ddraw.c 209 KB
Newer Older
1 2 3 4
/*
 * Copyright 1997-2000 Marcus Meissner
 * Copyright 1998-2000 Lionel Ulmer
 * Copyright 2000-2001 TransGaming Technologies Inc.
5
 * Copyright 2006 Stefan Dösinger
6
 * Copyright 2008 Denver Gingerich
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include "config.h"
#include "wine/port.h"

#include "ddraw_private.h"

WINE_DEFAULT_DEBUG_CHANNEL(ddraw);

/* Device identifier. Don't relay it to WineD3D */
static const DDDEVICEIDENTIFIER2 deviceidentifier =
{
    "display",
    "DirectDraw HAL",
    { { 0x00010001, 0x00010001 } },
    0, 0, 0, 0,
    /* a8373c10-7ac4-4deb-849a-009844d08b2d */
    {0xa8373c10,0x7ac4,0x4deb, {0x84,0x9a,0x00,0x98,0x44,0xd0,0x8b,0x2d}},
    0
};

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
static struct enum_device_entry
{
    char interface_name[100];
    char device_name[100];
    const GUID *device_guid;
} device_list7[] =
{
    /* T&L HAL device */
    {
        "WINE Direct3D7 Hardware Transform and Lighting acceleration using WineD3D",
        "Wine D3D7 T&L HAL",
        &IID_IDirect3DTnLHalDevice,
    },

    /* HAL device */
    {
        "WINE Direct3D7 Hardware acceleration using WineD3D",
        "Wine D3D7 HAL",
        &IID_IDirect3DHALDevice,
    },

    /* RGB device */
    {
        "WINE Direct3D7 RGB Software Emulation using WineD3D",
        "Wine D3D7 RGB",
        &IID_IDirect3DRGBDevice,
    },
};

71 72
static void STDMETHODCALLTYPE ddraw_null_wined3d_object_destroyed(void *parent) {}

73
const struct wined3d_parent_ops ddraw_null_wined3d_parent_ops =
74 75 76 77
{
    ddraw_null_wined3d_object_destroyed,
};

78
static inline IDirectDrawImpl *impl_from_IDirectDraw(IDirectDraw *iface)
79
{
80
    return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirectDraw_iface);
81 82
}

83
static inline IDirectDrawImpl *impl_from_IDirectDraw2(IDirectDraw2 *iface)
84
{
85
    return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirectDraw2_iface);
86 87
}

88
static inline IDirectDrawImpl *impl_from_IDirectDraw3(IDirectDraw3 *iface)
89
{
90
    return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirectDraw3_iface);
91 92
}

93
static inline IDirectDrawImpl *impl_from_IDirectDraw4(IDirectDraw4 *iface)
94
{
95
    return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirectDraw4_iface);
96 97
}

98 99 100 101 102
static inline IDirectDrawImpl *impl_from_IDirectDraw7(IDirectDraw7 *iface)
{
    return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirectDraw7_iface);
}

103 104 105 106 107
static inline IDirectDrawImpl *impl_from_IDirect3D(IDirect3D *iface)
{
    return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirect3D_iface);
}

108 109 110 111 112
static inline IDirectDrawImpl *impl_from_IDirect3D2(IDirect3D2 *iface)
{
    return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirect3D2_iface);
}

113 114 115 116 117
static inline IDirectDrawImpl *impl_from_IDirect3D3(IDirect3D3 *iface)
{
    return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirect3D3_iface);
}

118 119 120 121 122
static inline IDirectDrawImpl *impl_from_IDirect3D7(IDirect3D7 *iface)
{
    return CONTAINING_RECORD(iface, IDirectDrawImpl, IDirect3D7_iface);
}

123
/*****************************************************************************
124
 * IUnknown Methods
125 126 127 128 129 130 131 132 133
 *****************************************************************************/

/*****************************************************************************
 * IDirectDraw7::QueryInterface
 *
 * Queries different interfaces of the DirectDraw object. It can return
 * IDirectDraw interfaces in version 1, 2, 4 and 7, and IDirect3D interfaces
 * in version 1, 2, 3 and 7. An IDirect3DDevice can be created with this
 * method.
134
 * The returned interface is AddRef()-ed before it's returned
135 136 137 138 139 140 141 142 143 144 145 146
 *
 * Used for version 1, 2, 4 and 7
 *
 * Params:
 *  refiid: Interface ID asked for
 *  obj: Used to return the interface pointer
 *
 * Returns:
 *  S_OK if an interface was found
 *  E_NOINTERFACE if the requested interface wasn't found
 *
 *****************************************************************************/
147
static HRESULT WINAPI ddraw7_QueryInterface(IDirectDraw7 *iface, REFIID refiid, void **obj)
148
{
149
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
150

151
    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(refiid), obj);
152

153 154 155
    /* Can change surface impl type */
    EnterCriticalSection(&ddraw_cs);

156 157 158 159
    /* According to COM docs, if the QueryInterface fails, obj should be set to NULL */
    *obj = NULL;

    if(!refiid)
160 161
    {
        LeaveCriticalSection(&ddraw_cs);
162
        return DDERR_INVALIDPARAMS;
163
    }
164 165 166 167 168

    /* Check DirectDraw Interfaces */
    if ( IsEqualGUID( &IID_IUnknown, refiid ) ||
         IsEqualGUID( &IID_IDirectDraw7, refiid ) )
    {
169
        *obj = This;
170 171 172 173
        TRACE("(%p) Returning IDirectDraw7 interface at %p\n", This, *obj);
    }
    else if ( IsEqualGUID( &IID_IDirectDraw4, refiid ) )
    {
174
        *obj = &This->IDirectDraw4_iface;
175 176
        TRACE("(%p) Returning IDirectDraw4 interface at %p\n", This, *obj);
    }
177 178
    else if ( IsEqualGUID( &IID_IDirectDraw3, refiid ) )
    {
179 180 181 182 183
        /* This Interface exists in ddrawex.dll, it is implemented in a wrapper */
        WARN("IDirectDraw3 is not valid in ddraw.dll\n");
        *obj = NULL;
        LeaveCriticalSection(&ddraw_cs);
        return E_NOINTERFACE;
184
    }
185 186
    else if ( IsEqualGUID( &IID_IDirectDraw2, refiid ) )
    {
187
        *obj = &This->IDirectDraw2_iface;
188 189 190 191
        TRACE("(%p) Returning IDirectDraw2 interface at %p\n", This, *obj);
    }
    else if ( IsEqualGUID( &IID_IDirectDraw, refiid ) )
    {
192
        *obj = &This->IDirectDraw_iface;
193 194 195
        TRACE("(%p) Returning IDirectDraw interface at %p\n", This, *obj);
    }

196 197 198 199 200 201 202
    /* Direct3D
     * The refcount unit test revealed that an IDirect3D7 interface can only be queried
     * from a DirectDraw object that was created as an IDirectDraw7 interface. No idea
     * who had this idea and why. The older interfaces can query and IDirect3D version
     * because they are all created as IDirectDraw(1). This isn't really crucial behavior,
     * and messy to implement with the common creation function, so it has been left out here.
     */
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
    else if ( IsEqualGUID( &IID_IDirect3D  , refiid ) ||
              IsEqualGUID( &IID_IDirect3D2 , refiid ) ||
              IsEqualGUID( &IID_IDirect3D3 , refiid ) ||
              IsEqualGUID( &IID_IDirect3D7 , refiid ) )
    {
        /* Check the surface implementation */
        if(This->ImplType == SURFACE_UNKNOWN)
        {
            /* Apps may create the IDirect3D Interface before the primary surface.
             * set the surface implementation */
            This->ImplType = SURFACE_OPENGL;
            TRACE("(%p) Choosing OpenGL surfaces because a Direct3D interface was requested\n", This);
        }
        else if(This->ImplType != SURFACE_OPENGL && DefaultSurfaceType == SURFACE_UNKNOWN)
        {
            ERR("(%p) The App is requesting a D3D device, but a non-OpenGL surface type was choosen. Prepare for trouble!\n", This);
            ERR(" (%p) You may want to contact wine-devel for help\n", This);
            /* Should I assert(0) here??? */
        }
        else if(This->ImplType != SURFACE_OPENGL)
        {
            WARN("The app requests a Direct3D interface, but non-opengl surfaces where set in winecfg\n");
            /* Do not abort here, only reject 3D Device creation */
        }

        if ( IsEqualGUID( &IID_IDirect3D  , refiid ) )
        {
230
            This->d3dversion = 1;
231
            *obj = &This->IDirect3D_iface;
232 233 234 235
            TRACE(" returning Direct3D interface at %p.\n", *obj);
        }
        else if ( IsEqualGUID( &IID_IDirect3D2  , refiid ) )
        {
236
            This->d3dversion = 2;
237
            *obj = &This->IDirect3D2_iface;
238 239 240 241
            TRACE(" returning Direct3D2 interface at %p.\n", *obj);
        }
        else if ( IsEqualGUID( &IID_IDirect3D3  , refiid ) )
        {
242
            This->d3dversion = 3;
243
            *obj = &This->IDirect3D3_iface;
244 245 246 247
            TRACE(" returning Direct3D3 interface at %p.\n", *obj);
        }
        else if(IsEqualGUID( &IID_IDirect3D7  , refiid ))
        {
248
            This->d3dversion = 7;
249
            *obj = &This->IDirect3D7_iface;
250 251 252 253 254 255
            TRACE(" returning Direct3D7 interface at %p.\n", *obj);
        }
    }
    /* Unknown interface */
    else
    {
256
        ERR("(%p)->(%s, %p): No interface found\n", This, debugstr_guid(refiid), obj);
257
        LeaveCriticalSection(&ddraw_cs);
258 259 260 261
        return E_NOINTERFACE;
    }

    IUnknown_AddRef( (IUnknown *) *obj );
262
    LeaveCriticalSection(&ddraw_cs);
263 264 265
    return S_OK;
}

266 267
static HRESULT WINAPI ddraw4_QueryInterface(IDirectDraw4 *iface, REFIID riid, void **object)
{
268 269
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

270 271
    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);

272
    return ddraw7_QueryInterface(&This->IDirectDraw7_iface, riid, object);
273 274 275 276
}

static HRESULT WINAPI ddraw3_QueryInterface(IDirectDraw3 *iface, REFIID riid, void **object)
{
277 278
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);

279 280
    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);

281
    return ddraw7_QueryInterface(&This->IDirectDraw7_iface, riid, object);
282 283 284 285
}

static HRESULT WINAPI ddraw2_QueryInterface(IDirectDraw2 *iface, REFIID riid, void **object)
{
286 287
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);

288 289
    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);

290
    return ddraw7_QueryInterface(&This->IDirectDraw7_iface, riid, object);
291 292 293 294
}

static HRESULT WINAPI ddraw1_QueryInterface(IDirectDraw *iface, REFIID riid, void **object)
{
295 296
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);

297 298
    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);

299
    return ddraw7_QueryInterface(&This->IDirectDraw7_iface, riid, object);
300 301
}

302 303
static HRESULT WINAPI d3d7_QueryInterface(IDirect3D7 *iface, REFIID riid, void **object)
{
304 305
    IDirectDrawImpl *This = impl_from_IDirect3D7(iface);

306 307
    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);

308
    return ddraw7_QueryInterface(&This->IDirectDraw7_iface, riid, object);
309 310 311 312
}

static HRESULT WINAPI d3d3_QueryInterface(IDirect3D3 *iface, REFIID riid, void **object)
{
313 314
    IDirectDrawImpl *This = impl_from_IDirect3D3(iface);

315 316
    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);

317
    return ddraw7_QueryInterface(&This->IDirectDraw7_iface, riid, object);
318 319 320 321
}

static HRESULT WINAPI d3d2_QueryInterface(IDirect3D2 *iface, REFIID riid, void **object)
{
322 323
    IDirectDrawImpl *This = impl_from_IDirect3D2(iface);

324 325
    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);

326
    return ddraw7_QueryInterface(&This->IDirectDraw7_iface, riid, object);
327 328 329 330
}

static HRESULT WINAPI d3d1_QueryInterface(IDirect3D *iface, REFIID riid, void **object)
{
331 332
    IDirectDrawImpl *This = impl_from_IDirect3D(iface);

333 334
    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);

335
    return ddraw7_QueryInterface(&This->IDirectDraw7_iface, riid, object);
336 337
}

338 339 340
/*****************************************************************************
 * IDirectDraw7::AddRef
 *
341 342 343 344 345 346 347 348 349 350 351
 * Increases the interfaces refcount, basically
 *
 * DDraw refcounting is a bit tricky. The different DirectDraw interface
 * versions have individual refcounts, but the IDirect3D interfaces do not.
 * All interfaces are from one object, that means calling QueryInterface on an
 * IDirectDraw7 interface for an IDirectDraw4 interface does not create a new
 * IDirectDrawImpl object.
 *
 * That means all AddRef and Release implementations of IDirectDrawX work
 * with their own counter, and IDirect3DX::AddRef thunk to IDirectDraw (1),
 * except of IDirect3D7 which thunks to IDirectDraw7
352 353
 *
 * Returns: The new refcount
354
 *
355
 *****************************************************************************/
356
static ULONG WINAPI ddraw7_AddRef(IDirectDraw7 *iface)
357
{
358
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
359
    ULONG ref = InterlockedIncrement(&This->ref7);
360

361
    TRACE("%p increasing refcount to %u.\n", This, ref);
362 363

    if(ref == 1) InterlockedIncrement(&This->numIfaces);
364 365 366 367

    return ref;
}

368 369
static ULONG WINAPI ddraw4_AddRef(IDirectDraw4 *iface)
{
370 371
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
    ULONG ref = InterlockedIncrement(&This->ref4);
372

373
    TRACE("%p increasing refcount to %u.\n", This, ref);
374

375
    if (ref == 1) InterlockedIncrement(&This->numIfaces);
376 377 378 379 380 381

    return ref;
}

static ULONG WINAPI ddraw3_AddRef(IDirectDraw3 *iface)
{
382 383
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
    ULONG ref = InterlockedIncrement(&This->ref3);
384

385
    TRACE("%p increasing refcount to %u.\n", This, ref);
386

387
    if (ref == 1) InterlockedIncrement(&This->numIfaces);
388 389 390 391 392 393

    return ref;
}

static ULONG WINAPI ddraw2_AddRef(IDirectDraw2 *iface)
{
394 395
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
    ULONG ref = InterlockedIncrement(&This->ref2);
396

397
    TRACE("%p increasing refcount to %u.\n", This, ref);
398

399
    if (ref == 1) InterlockedIncrement(&This->numIfaces);
400 401 402 403 404 405

    return ref;
}

static ULONG WINAPI ddraw1_AddRef(IDirectDraw *iface)
{
406 407
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
    ULONG ref = InterlockedIncrement(&This->ref1);
408

409
    TRACE("%p increasing refcount to %u.\n", This, ref);
410

411
    if (ref == 1) InterlockedIncrement(&This->numIfaces);
412 413 414 415

    return ref;
}

416 417
static ULONG WINAPI d3d7_AddRef(IDirect3D7 *iface)
{
418 419
    IDirectDrawImpl *This = impl_from_IDirect3D7(iface);

420 421
    TRACE("iface %p.\n", iface);

422
    return ddraw7_AddRef(&This->IDirectDraw7_iface);
423 424 425 426
}

static ULONG WINAPI d3d3_AddRef(IDirect3D3 *iface)
{
427 428
    IDirectDrawImpl *This = impl_from_IDirect3D3(iface);

429 430
    TRACE("iface %p.\n", iface);

431
    return ddraw1_AddRef(&This->IDirectDraw_iface);
432 433 434 435
}

static ULONG WINAPI d3d2_AddRef(IDirect3D2 *iface)
{
436 437
    IDirectDrawImpl *This = impl_from_IDirect3D2(iface);

438 439
    TRACE("iface %p.\n", iface);

440
    return ddraw1_AddRef(&This->IDirectDraw_iface);
441 442 443 444
}

static ULONG WINAPI d3d1_AddRef(IDirect3D *iface)
{
445 446
    IDirectDrawImpl *This = impl_from_IDirect3D(iface);

447 448
    TRACE("iface %p.\n", iface);

449
    return ddraw1_AddRef(&This->IDirectDraw_iface);
450 451
}

452
/*****************************************************************************
453
 * ddraw_destroy
454
 *
455 456
 * Destroys a ddraw object if all refcounts are 0. This is to share code
 * between the IDirectDrawX::Release functions
457 458 459 460 461
 *
 * Params:
 *  This: DirectDraw object to destroy
 *
 *****************************************************************************/
462
static void ddraw_destroy(IDirectDrawImpl *This)
463
{
464 465
    IDirectDraw7_SetCooperativeLevel(&This->IDirectDraw7_iface, NULL, DDSCL_NORMAL);
    IDirectDraw7_RestoreDisplayMode(&This->IDirectDraw7_iface);
466

467 468 469 470 471 472 473
    /* Destroy the device window if we created one */
    if(This->devicewindow != 0)
    {
        TRACE(" (%p) Destroying the device window %p\n", This, This->devicewindow);
        DestroyWindow(This->devicewindow);
        This->devicewindow = 0;
    }
474

475 476 477
    EnterCriticalSection(&ddraw_cs);
    list_remove(&This->ddraw_list_entry);
    LeaveCriticalSection(&ddraw_cs);
478

479
    /* Release the attached WineD3D stuff */
480
    wined3d_device_decref(This->wined3d_device);
481
    wined3d_decref(This->wineD3D);
482

483 484
    /* Now free the object */
    HeapFree(GetProcessHeap(), 0, This);
485
}
486

487 488 489
/*****************************************************************************
 * IDirectDraw7::Release
 *
490
 * Decreases the refcount. If the refcount falls to 0, the object is destroyed
491 492 493
 *
 * Returns: The new refcount
 *****************************************************************************/
494
static ULONG WINAPI ddraw7_Release(IDirectDraw7 *iface)
495
{
496
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
497
    ULONG ref = InterlockedDecrement(&This->ref7);
498

499
    TRACE("%p decreasing refcount to %u.\n", This, ref);
500

501 502 503 504 505 506 507 508
    if (!ref && !InterlockedDecrement(&This->numIfaces))
        ddraw_destroy(This);

    return ref;
}

static ULONG WINAPI ddraw4_Release(IDirectDraw4 *iface)
{
509 510
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
    ULONG ref = InterlockedDecrement(&This->ref4);
511

512
    TRACE("%p decreasing refcount to %u.\n", This, ref);
513

514 515
    if (!ref && !InterlockedDecrement(&This->numIfaces))
        ddraw_destroy(This);
516 517 518 519 520 521

    return ref;
}

static ULONG WINAPI ddraw3_Release(IDirectDraw3 *iface)
{
522 523
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
    ULONG ref = InterlockedDecrement(&This->ref3);
524

525
    TRACE("%p decreasing refcount to %u.\n", This, ref);
526

527 528
    if (!ref && !InterlockedDecrement(&This->numIfaces))
        ddraw_destroy(This);
529 530 531 532 533 534

    return ref;
}

static ULONG WINAPI ddraw2_Release(IDirectDraw2 *iface)
{
535 536
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
    ULONG ref = InterlockedDecrement(&This->ref2);
537

538
    TRACE("%p decreasing refcount to %u.\n", This, ref);
539

540 541
    if (!ref && !InterlockedDecrement(&This->numIfaces))
        ddraw_destroy(This);
542 543 544 545 546 547

    return ref;
}

static ULONG WINAPI ddraw1_Release(IDirectDraw *iface)
{
548 549
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
    ULONG ref = InterlockedDecrement(&This->ref1);
550

551
    TRACE("%p decreasing refcount to %u.\n", This, ref);
552

553 554
    if (!ref && !InterlockedDecrement(&This->numIfaces))
        ddraw_destroy(This);
555 556 557 558

    return ref;
}

559 560
static ULONG WINAPI d3d7_Release(IDirect3D7 *iface)
{
561 562
    IDirectDrawImpl *This = impl_from_IDirect3D7(iface);

563 564
    TRACE("iface %p.\n", iface);

565
    return ddraw7_Release(&This->IDirectDraw7_iface);
566 567 568 569
}

static ULONG WINAPI d3d3_Release(IDirect3D3 *iface)
{
570 571
    IDirectDrawImpl *This = impl_from_IDirect3D3(iface);

572 573
    TRACE("iface %p.\n", iface);

574
    return ddraw1_Release(&This->IDirectDraw_iface);
575 576 577 578
}

static ULONG WINAPI d3d2_Release(IDirect3D2 *iface)
{
579 580
    IDirectDrawImpl *This = impl_from_IDirect3D2(iface);

581 582
    TRACE("iface %p.\n", iface);

583
    return ddraw1_Release(&This->IDirectDraw_iface);
584 585 586 587
}

static ULONG WINAPI d3d1_Release(IDirect3D *iface)
{
588 589
    IDirectDrawImpl *This = impl_from_IDirect3D(iface);

590 591
    TRACE("iface %p.\n", iface);

592
    return ddraw1_Release(&This->IDirectDraw_iface);
593 594
}

595 596 597 598 599 600 601
/*****************************************************************************
 * IDirectDraw methods
 *****************************************************************************/

/*****************************************************************************
 * IDirectDraw7::SetCooperativeLevel
 *
602
 * Sets the cooperative level for the DirectDraw object, and the window
603 604 605 606 607 608 609 610 611 612 613
 * assigned to it. The cooperative level determines the general behavior
 * of the DirectDraw application
 *
 * Warning: This is quite tricky, as it's not really documented which
 * cooperative levels can be combined with each other. If a game fails
 * after this function, try to check the cooperative levels passed on
 * Windows, and if it returns something different.
 *
 * If you think that this function caused the failure because it writes a
 * fixme, be sure to run again with a +ddraw trace.
 *
614
 * What is known about cooperative levels (See the ddraw modes test):
615 616 617 618 619 620 621
 * DDSCL_EXCLUSIVE and DDSCL_FULLSCREEN must be used with each other
 * DDSCL_NORMAL is not compatible with DDSCL_EXCLUSIVE or DDSCL_FULLSCREEN
 * DDSCL_SETFOCUSWINDOW can be passed only in DDSCL_NORMAL mode, but after that
 * DDSCL_FULLSCREEN can be activated
 * DDSCL_SETFOCUSWINDOW may only be used with DDSCL_NOWINDOWCHANGES
 *
 * Handled flags: DDSCL_NORMAL, DDSCL_FULLSCREEN, DDSCL_EXCLUSIVE,
622 623
 *                DDSCL_SETFOCUSWINDOW (partially),
 *                DDSCL_MULTITHREADED (work in progress)
624 625
 *
 * Unhandled flags, which should be implemented
626
 *  DDSCL_SETDEVICEWINDOW: Sets a window specially used for rendering (I don't
627
 *  expect any difference to a normal window for wine)
628
 *  DDSCL_CREATEDEVICEWINDOW: Tells ddraw to create its own window for
629
 *  rendering (Possible test case: Half-Life)
630 631 632
 *
 * Unsure about these: DDSCL_FPUSETUP DDSCL_FPURESERVE
 *
Austin English's avatar
Austin English committed
633
 * These don't seem very important for wine:
634
 *  DDSCL_ALLOWREBOOT, DDSCL_NOWINDOWCHANGES, DDSCL_ALLOWMODEX
635 636 637 638
 *
 * Returns:
 *  DD_OK if the cooperative level was set successfully
 *  DDERR_INVALIDPARAMS if the passed cooperative level combination is invalid
639 640
 *  DDERR_HWNDALREADYSET if DDSCL_SETFOCUSWINDOW is passed in exclusive mode
 *   (Probably others too, have to investigate)
641 642
 *
 *****************************************************************************/
643
static HRESULT WINAPI ddraw7_SetCooperativeLevel(IDirectDraw7 *iface, HWND hwnd, DWORD cooplevel)
644
{
645
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
646 647
    HWND window;

648
    TRACE("iface %p, window %p, flags %#x.\n", iface, hwnd, cooplevel);
649 650
    DDRAW_dump_cooperativelevel(cooplevel);

651 652
    EnterCriticalSection(&ddraw_cs);

653
    /* Get the old window */
654
    window = This->dest_window;
655 656 657 658 659 660 661

    /* Tests suggest that we need one of them: */
    if(!(cooplevel & (DDSCL_SETFOCUSWINDOW |
                      DDSCL_NORMAL         |
                      DDSCL_EXCLUSIVE      )))
    {
        TRACE("Incorrect cooplevel flags, returning DDERR_INVALIDPARAMS\n");
662
        LeaveCriticalSection(&ddraw_cs);
663 664 665
        return DDERR_INVALIDPARAMS;
    }

666
    /* Handle those levels first which set various hwnds */
667 668 669
    if(cooplevel & DDSCL_SETFOCUSWINDOW)
    {
        /* This isn't compatible with a lot of flags */
670 671 672 673 674 675 676 677 678 679
        if(cooplevel & ( DDSCL_MULTITHREADED      |
                         DDSCL_CREATEDEVICEWINDOW |
                         DDSCL_FPUSETUP           |
                         DDSCL_FPUPRESERVE        |
                         DDSCL_ALLOWREBOOT        |
                         DDSCL_ALLOWMODEX         |
                         DDSCL_SETDEVICEWINDOW    |
                         DDSCL_NORMAL             |
                         DDSCL_EXCLUSIVE          |
                         DDSCL_FULLSCREEN         ) )
680 681
        {
            TRACE("Called with incompatible flags, returning DDERR_INVALIDPARAMS\n");
682
            LeaveCriticalSection(&ddraw_cs);
683 684
            return DDERR_INVALIDPARAMS;
        }
685

686
        if( (This->cooperative_level & DDSCL_EXCLUSIVE) && window )
687 688
        {
            TRACE("Setting DDSCL_SETFOCUSWINDOW with an already set window, returning DDERR_HWNDALREADYSET\n");
689
            LeaveCriticalSection(&ddraw_cs);
690 691 692 693 694 695 696 697
            return DDERR_HWNDALREADYSET;
        }

        This->focuswindow = hwnd;
        /* Won't use the hwnd param for anything else */
        hwnd = NULL;

        /* Use the focus window for drawing too */
698
        This->dest_window = This->focuswindow;
699 700 701 702 703 704 705

        /* Destroy the device window, if we have one */
        if(This->devicewindow)
        {
            DestroyWindow(This->devicewindow);
            This->devicewindow = NULL;
        }
706

707
        LeaveCriticalSection(&ddraw_cs);
708
        return DD_OK;
709
    }
710

711
    if(cooplevel & DDSCL_EXCLUSIVE)
712
    {
713
        if( !(cooplevel & DDSCL_FULLSCREEN) || !hwnd )
714
        {
715
            TRACE("(%p) DDSCL_EXCLUSIVE needs DDSCL_FULLSCREEN and a window\n", This);
716
            LeaveCriticalSection(&ddraw_cs);
717 718 719
            return DDERR_INVALIDPARAMS;
        }
    }
720
    else if( !(cooplevel & DDSCL_NORMAL) )
721
    {
722
        TRACE("(%p) SetCooperativeLevel needs at least SetFocusWindow or Exclusive or Normal mode\n", This);
723
        LeaveCriticalSection(&ddraw_cs);
724
        return DDERR_INVALIDPARAMS;
725 726 727 728
    }

    if ((This->cooperative_level & DDSCL_EXCLUSIVE)
            && (hwnd != window || !(cooplevel & DDSCL_EXCLUSIVE)))
729
        wined3d_device_release_focus_window(This->wined3d_device);
730

731
    if ((cooplevel & DDSCL_FULLSCREEN) != (This->cooperative_level & DDSCL_FULLSCREEN) || hwnd != window)
732
    {
733
        if (This->cooperative_level & DDSCL_FULLSCREEN)
734 735
            wined3d_device_restore_fullscreen_window(This->wined3d_device, window);

736 737 738 739
        if (cooplevel & DDSCL_FULLSCREEN)
        {
            WINED3DDISPLAYMODE display_mode;

740
            wined3d_get_adapter_display_mode(This->wineD3D, WINED3DADAPTER_DEFAULT, &display_mode);
741 742
            wined3d_device_setup_fullscreen_window(This->wined3d_device, hwnd,
                    display_mode.Width, display_mode.Height);
743
        }
744 745
    }

746 747 748
    if ((cooplevel & DDSCL_EXCLUSIVE)
            && (hwnd != window || !(This->cooperative_level & DDSCL_EXCLUSIVE)))
    {
749
        HRESULT hr = wined3d_device_acquire_focus_window(This->wined3d_device, hwnd);
750 751 752 753 754 755 756 757
        if (FAILED(hr))
        {
            ERR("Failed to acquire focus window, hr %#x.\n", hr);
            LeaveCriticalSection(&ddraw_cs);
            return hr;
        }
    }

758 759 760 761
    /* Don't override focus windows or private device windows */
    if (hwnd && !This->focuswindow && !This->devicewindow && (hwnd != window))
        This->dest_window = hwnd;

762 763 764 765 766
    if(cooplevel & DDSCL_CREATEDEVICEWINDOW)
    {
        /* Don't create a device window if a focus window is set */
        if( !(This->focuswindow) )
        {
767 768 769 770 771 772 773 774 775
            HWND devicewindow = CreateWindowExA(0, DDRAW_WINDOW_CLASS_NAME, "DDraw device window",
                    WS_POPUP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
                    NULL, NULL, NULL, NULL);
            if (!devicewindow)
            {
                ERR("Failed to create window, last error %#x.\n", GetLastError());
                LeaveCriticalSection(&ddraw_cs);
                return E_FAIL;
            }
776 777 778 779 780

            ShowWindow(devicewindow, SW_SHOW);   /* Just to be sure */
            TRACE("(%p) Created a DDraw device window. HWND=%p\n", This, devicewindow);

            This->devicewindow = devicewindow;
781
            This->dest_window = devicewindow;
782 783 784
        }
    }

785 786
    if (cooplevel & DDSCL_MULTITHREADED && !(This->cooperative_level & DDSCL_MULTITHREADED))
        wined3d_device_set_multithreaded(This->wined3d_device);
787

788 789 790 791 792 793 794 795 796
    /* Unhandled flags */
    if(cooplevel & DDSCL_ALLOWREBOOT)
        WARN("(%p) Unhandled flag DDSCL_ALLOWREBOOT, harmless\n", This);
    if(cooplevel & DDSCL_ALLOWMODEX)
        WARN("(%p) Unhandled flag DDSCL_ALLOWMODEX, harmless\n", This);
    if(cooplevel & DDSCL_FPUSETUP)
        WARN("(%p) Unhandled flag DDSCL_FPUSETUP, harmless\n", This);

    /* Store the cooperative_level */
797
    This->cooperative_level = cooplevel;
798
    TRACE("SetCooperativeLevel retuning DD_OK\n");
799
    LeaveCriticalSection(&ddraw_cs);
800 801 802
    return DD_OK;
}

803 804
static HRESULT WINAPI ddraw4_SetCooperativeLevel(IDirectDraw4 *iface, HWND window, DWORD flags)
{
805 806
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

807 808
    TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);

809
    return ddraw7_SetCooperativeLevel(&This->IDirectDraw7_iface, window, flags);
810 811 812 813
}

static HRESULT WINAPI ddraw3_SetCooperativeLevel(IDirectDraw3 *iface, HWND window, DWORD flags)
{
814 815
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);

816 817
    TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);

818
    return ddraw7_SetCooperativeLevel(&This->IDirectDraw7_iface, window, flags);
819 820 821 822
}

static HRESULT WINAPI ddraw2_SetCooperativeLevel(IDirectDraw2 *iface, HWND window, DWORD flags)
{
823 824
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);

825 826
    TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);

827
    return ddraw7_SetCooperativeLevel(&This->IDirectDraw7_iface, window, flags);
828 829 830 831
}

static HRESULT WINAPI ddraw1_SetCooperativeLevel(IDirectDraw *iface, HWND window, DWORD flags)
{
832 833
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);

834 835
    TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);

836
    return ddraw7_SetCooperativeLevel(&This->IDirectDraw7_iface, window, flags);
837 838
}

839 840
/*****************************************************************************
 *
841
 * Helper function for SetDisplayMode and RestoreDisplayMode
842
 *
843 844
 * Implements DirectDraw's SetDisplayMode, but ignores the value of
 * ForceRefreshRate, since it is already handled by
845
 * ddraw7_SetDisplayMode.  RestoreDisplayMode can use this function
846 847
 * without worrying that ForceRefreshRate will override the refresh rate.  For
 * argument and return value documentation, see
848
 * ddraw7_SetDisplayMode.
849 850
 *
 *****************************************************************************/
851
static HRESULT ddraw_set_display_mode(IDirectDrawImpl *ddraw, DWORD Width, DWORD Height,
852
        DWORD BPP, DWORD RefreshRate, DWORD Flags)
853
{
854
    enum wined3d_format_id format;
855
    WINED3DDISPLAYMODE Mode;
856
    HRESULT hr;
857

858 859
    TRACE("ddraw %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n", ddraw, Width,
            Height, BPP, RefreshRate, Flags);
860

861
    EnterCriticalSection(&ddraw_cs);
862 863
    if( !Width || !Height )
    {
864
        ERR("Width %u, Height %u, what to do?\n", Width, Height);
865
        /* It looks like Need for Speed Porsche Unleashed expects DD_OK here */
866
        LeaveCriticalSection(&ddraw_cs);
867 868 869
        return DD_OK;
    }

870 871 872 873 874 875 876 877 878 879
    switch(BPP)
    {
        case 8:  format = WINED3DFMT_P8_UINT;          break;
        case 15: format = WINED3DFMT_B5G5R5X1_UNORM;   break;
        case 16: format = WINED3DFMT_B5G6R5_UNORM;     break;
        case 24: format = WINED3DFMT_B8G8R8_UNORM;     break;
        case 32: format = WINED3DFMT_B8G8R8X8_UNORM;   break;
        default: format = WINED3DFMT_UNKNOWN;          break;
    }

880
    if (FAILED(hr = wined3d_device_get_display_mode(ddraw->wined3d_device, 0, &Mode)))
881 882 883 884 885 886 887 888 889 890 891 892 893
    {
        ERR("Failed to get current display mode, hr %#x.\n", hr);
    }
    else if (Mode.Width == Width
            && Mode.Height == Height
            && Mode.Format == format
            && Mode.RefreshRate == RefreshRate)
    {
        TRACE("Skipping redundant mode setting call.\n");
        LeaveCriticalSection(&ddraw_cs);
        return DD_OK;
    }

894
    /* Check the exclusive mode
895
    if(!(ddraw->cooperative_level & DDSCL_EXCLUSIVE))
896 897
        return DDERR_NOEXCLUSIVEMODE;
     * This is WRONG. Don't know if the SDK is completely
898 899
     * wrong and if there are any conditions when DDERR_NOEXCLUSIVE
     * is returned, but Half-Life 1.1.1.1 (Steam version)
900 901 902 903 904 905
     * depends on this
     */

    Mode.Width = Width;
    Mode.Height = Height;
    Mode.RefreshRate = RefreshRate;
906
    Mode.Format = format;
907 908 909 910 911 912 913

    /* TODO: The possible return values from msdn suggest that
     * the screen mode can't be changed if a surface is locked
     * or some drawing is in progress
     */

    /* TODO: Lose the primary surface */
914
    hr = wined3d_device_set_display_mode(ddraw->wined3d_device, 0, &Mode);
915 916 917 918 919 920 921

    if (ddraw->cooperative_level & DDSCL_EXCLUSIVE)
    {
        wined3d_device_restore_fullscreen_window(ddraw->wined3d_device, ddraw->dest_window);
        wined3d_device_setup_fullscreen_window(ddraw->wined3d_device, ddraw->dest_window, Width, Height);
    }

922
    LeaveCriticalSection(&ddraw_cs);
923 924
    switch(hr)
    {
925
        case WINED3DERR_NOTAVAILABLE:       return DDERR_UNSUPPORTED;
926
        default:                            return hr;
927
    }
928 929
}

930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
/*****************************************************************************
 * IDirectDraw7::SetDisplayMode
 *
 * Sets the display screen resolution, color depth and refresh frequency
 * when in fullscreen mode (in theory).
 * Possible return values listed in the SDK suggest that this method fails
 * when not in fullscreen mode, but this is wrong. Windows 2000 happily sets
 * the display mode in DDSCL_NORMAL mode without an hwnd specified.
 * It seems to be valid to pass 0 for With and Height, this has to be tested
 * It could mean that the current video mode should be left as-is. (But why
 * call it then?)
 *
 * Params:
 *  Height, Width: Screen dimension
 *  BPP: Color depth in Bits per pixel
 *  Refreshrate: Screen refresh rate
 *  Flags: Other stuff
 *
 * Returns
 *  DD_OK on success
 *
 *****************************************************************************/
952 953
static HRESULT WINAPI ddraw7_SetDisplayMode(IDirectDraw7 *iface, DWORD Width, DWORD Height,
        DWORD BPP, DWORD RefreshRate, DWORD Flags)
954
{
955
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
956

957 958 959
    TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
            iface, Width, Height, BPP, RefreshRate, Flags);

960 961
    if (force_refresh_rate != 0)
    {
962 963
        TRACE("ForceRefreshRate overriding passed-in refresh rate (%u Hz) to %u Hz\n",
                RefreshRate, force_refresh_rate);
964 965 966
        RefreshRate = force_refresh_rate;
    }

967
    return ddraw_set_display_mode(This, Width, Height, BPP, RefreshRate, Flags);
968 969
}

970 971
static HRESULT WINAPI ddraw4_SetDisplayMode(IDirectDraw4 *iface, DWORD width, DWORD height,
        DWORD bpp, DWORD refresh_rate, DWORD flags)
972
{
973 974
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

975 976 977
    TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
            iface, width, height, bpp, refresh_rate, flags);

978
    return ddraw7_SetDisplayMode(&This->IDirectDraw7_iface, width, height, bpp, refresh_rate, flags);
979 980
}

981 982
static HRESULT WINAPI ddraw3_SetDisplayMode(IDirectDraw3 *iface, DWORD width, DWORD height,
        DWORD bpp, DWORD refresh_rate, DWORD flags)
983
{
984 985
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);

986 987 988
    TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
            iface, width, height, bpp, refresh_rate, flags);

989
    return ddraw7_SetDisplayMode(&This->IDirectDraw7_iface, width, height, bpp, refresh_rate, flags);
990 991 992 993 994
}

static HRESULT WINAPI ddraw2_SetDisplayMode(IDirectDraw2 *iface,
        DWORD width, DWORD height, DWORD bpp, DWORD refresh_rate, DWORD flags)
{
995 996
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);

997 998 999
    TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
            iface, width, height, bpp, refresh_rate, flags);

1000
    return ddraw7_SetDisplayMode(&This->IDirectDraw7_iface, width, height, bpp, refresh_rate, flags);
1001 1002 1003 1004
}

static HRESULT WINAPI ddraw1_SetDisplayMode(IDirectDraw *iface, DWORD width, DWORD height, DWORD bpp)
{
1005 1006
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);

1007 1008
    TRACE("iface %p, width %u, height %u, bpp %u.\n", iface, width, height, bpp);

1009
    return ddraw7_SetDisplayMode(&This->IDirectDraw7_iface, width, height, bpp, 0, 0);
1010 1011
}

1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
/*****************************************************************************
 * IDirectDraw7::RestoreDisplayMode
 *
 * Restores the display mode to what it was at creation time. Basically.
 *
 * A problem arises when there are 2 DirectDraw objects using the same hwnd:
 *  -> DD_1 finds the screen at 1400x1050x32 when created, sets it to 640x480x16
 *  -> DD_2 is created, finds the screen at 640x480x16, sets it to 1024x768x32
 *  -> DD_1 is released. The screen should be left at 1024x768x32.
 *  -> DD_2 is released. The screen should be set to 1400x1050x32
 * This case is unhandled right now, but Empire Earth does it this way.
 * (But perhaps there is something in SetCooperativeLevel to prevent this)
 *
 * The msdn says that this method resets the display mode to what it was before
 * SetDisplayMode was called. What if SetDisplayModes is called 2 times??
 *
 * Returns
 *  DD_OK on success
 *  DDERR_NOEXCLUSIVE mode if the device isn't in fullscreen mode
 *
 *****************************************************************************/
1033
static HRESULT WINAPI ddraw7_RestoreDisplayMode(IDirectDraw7 *iface)
1034
{
1035
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1036 1037

    TRACE("iface %p.\n", iface);
1038

1039
    return ddraw_set_display_mode(This, This->orig_width, This->orig_height, This->orig_bpp, 0, 0);
1040 1041 1042 1043
}

static HRESULT WINAPI ddraw4_RestoreDisplayMode(IDirectDraw4 *iface)
{
1044 1045
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

1046 1047
    TRACE("iface %p.\n", iface);

1048
    return ddraw7_RestoreDisplayMode(&This->IDirectDraw7_iface);
1049 1050 1051 1052
}

static HRESULT WINAPI ddraw3_RestoreDisplayMode(IDirectDraw3 *iface)
{
1053 1054
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);

1055 1056
    TRACE("iface %p.\n", iface);

1057
    return ddraw7_RestoreDisplayMode(&This->IDirectDraw7_iface);
1058 1059 1060 1061
}

static HRESULT WINAPI ddraw2_RestoreDisplayMode(IDirectDraw2 *iface)
{
1062 1063
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);

1064 1065
    TRACE("iface %p.\n", iface);

1066
    return ddraw7_RestoreDisplayMode(&This->IDirectDraw7_iface);
1067 1068 1069 1070
}

static HRESULT WINAPI ddraw1_RestoreDisplayMode(IDirectDraw *iface)
{
1071 1072
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);

1073 1074
    TRACE("iface %p.\n", iface);

1075
    return ddraw7_RestoreDisplayMode(&This->IDirectDraw7_iface);
1076 1077 1078 1079 1080
}

/*****************************************************************************
 * IDirectDraw7::GetCaps
 *
1081
 * Returns the drives capabilities
1082 1083 1084 1085
 *
 * Used for version 1, 2, 4 and 7
 *
 * Params:
1086
 *  DriverCaps: Structure to write the Hardware accelerated caps to
1087 1088 1089
 *  HelCaps: Structure to write the emulation caps to
 *
 * Returns
1090
 *  This implementation returns DD_OK only
1091 1092
 *
 *****************************************************************************/
1093
static HRESULT WINAPI ddraw7_GetCaps(IDirectDraw7 *iface, DDCAPS *DriverCaps, DDCAPS *HELCaps)
1094
{
1095
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1096 1097 1098 1099
    DDCAPS caps;
    WINED3DCAPS winecaps;
    HRESULT hr;
    DDSCAPS2 ddscaps = {0, 0, 0, 0};
1100 1101

    TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, DriverCaps, HELCaps);
1102 1103 1104 1105

    /* One structure must be != NULL */
    if( (!DriverCaps) && (!HELCaps) )
    {
1106
        ERR("(%p) Invalid params to ddraw7_GetCaps\n", This);
1107 1108 1109
        return DDERR_INVALIDPARAMS;
    }

1110 1111 1112 1113
    memset(&caps, 0, sizeof(caps));
    memset(&winecaps, 0, sizeof(winecaps));
    caps.dwSize = sizeof(caps);
    EnterCriticalSection(&ddraw_cs);
1114 1115 1116
    hr = wined3d_device_get_device_caps(This->wined3d_device, &winecaps);
    if (FAILED(hr))
    {
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
        WARN("IWineD3DDevice::GetDeviceCaps failed\n");
        LeaveCriticalSection(&ddraw_cs);
        return hr;
    }

    hr = IDirectDraw7_GetAvailableVidMem(iface, &ddscaps, &caps.dwVidMemTotal, &caps.dwVidMemFree);
    LeaveCriticalSection(&ddraw_cs);
    if(FAILED(hr)) {
        WARN("IDirectDraw7::GetAvailableVidMem failed\n");
        return hr;
    }

    caps.dwCaps = winecaps.DirectDrawCaps.Caps;
    caps.dwCaps2 = winecaps.DirectDrawCaps.Caps2;
    caps.dwCKeyCaps = winecaps.DirectDrawCaps.CKeyCaps;
    caps.dwFXCaps = winecaps.DirectDrawCaps.FXCaps;
    caps.dwPalCaps = winecaps.DirectDrawCaps.PalCaps;
    caps.ddsCaps.dwCaps = winecaps.DirectDrawCaps.ddsCaps;
    caps.dwSVBCaps = winecaps.DirectDrawCaps.SVBCaps;
    caps.dwSVBCKeyCaps = winecaps.DirectDrawCaps.SVBCKeyCaps;
    caps.dwSVBFXCaps = winecaps.DirectDrawCaps.SVBFXCaps;
    caps.dwVSBCaps = winecaps.DirectDrawCaps.VSBCaps;
    caps.dwVSBCKeyCaps = winecaps.DirectDrawCaps.VSBCKeyCaps;
    caps.dwVSBFXCaps = winecaps.DirectDrawCaps.VSBFXCaps;
    caps.dwSSBCaps = winecaps.DirectDrawCaps.SSBCaps;
    caps.dwSSBCKeyCaps = winecaps.DirectDrawCaps.SSBCKeyCaps;
    caps.dwSSBFXCaps = winecaps.DirectDrawCaps.SSBFXCaps;

    /* Even if WineD3D supports 3D rendering, remove the cap if ddraw is configured
     * not to use it
     */
    if(DefaultSurfaceType == SURFACE_GDI) {
        caps.dwCaps &= ~DDCAPS_3D;
        caps.ddsCaps.dwCaps &= ~(DDSCAPS_3DDEVICE | DDSCAPS_MIPMAP | DDSCAPS_TEXTURE | DDSCAPS_ZBUFFER);
    }
    if(winecaps.DirectDrawCaps.StrideAlign != 0) {
        caps.dwCaps |= DDCAPS_ALIGNSTRIDE;
        caps.dwAlignStrideAlign = winecaps.DirectDrawCaps.StrideAlign;
    }

1157 1158
    if(DriverCaps)
    {
1159
        DD_STRUCT_COPY_BYSIZE(DriverCaps, &caps);
1160 1161 1162 1163 1164 1165 1166 1167 1168
        if (TRACE_ON(ddraw))
        {
            TRACE("Driver Caps :\n");
            DDRAW_dump_DDCAPS(DriverCaps);
        }

    }
    if(HELCaps)
    {
1169
        DD_STRUCT_COPY_BYSIZE(HELCaps, &caps);
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
        if (TRACE_ON(ddraw))
        {
            TRACE("HEL Caps :\n");
            DDRAW_dump_DDCAPS(HELCaps);
        }
    }

    return DD_OK;
}

1180 1181
static HRESULT WINAPI ddraw4_GetCaps(IDirectDraw4 *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
{
1182 1183
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

1184 1185
    TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);

1186
    return ddraw7_GetCaps(&This->IDirectDraw7_iface, driver_caps, hel_caps);
1187 1188 1189 1190
}

static HRESULT WINAPI ddraw3_GetCaps(IDirectDraw3 *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
{
1191 1192
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);

1193 1194
    TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);

1195
    return ddraw7_GetCaps(&This->IDirectDraw7_iface, driver_caps, hel_caps);
1196 1197 1198 1199
}

static HRESULT WINAPI ddraw2_GetCaps(IDirectDraw2 *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
{
1200 1201
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);

1202 1203
    TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);

1204
    return ddraw7_GetCaps(&This->IDirectDraw7_iface, driver_caps, hel_caps);
1205 1206 1207 1208
}

static HRESULT WINAPI ddraw1_GetCaps(IDirectDraw *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
{
1209 1210
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);

1211 1212
    TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);

1213
    return ddraw7_GetCaps(&This->IDirectDraw7_iface, driver_caps, hel_caps);
1214 1215
}

1216 1217 1218 1219 1220 1221 1222 1223 1224
/*****************************************************************************
 * IDirectDraw7::Compact
 *
 * No idea what it does, MSDN says it's not implemented.
 *
 * Returns
 *  DD_OK, but this is unchecked
 *
 *****************************************************************************/
1225
static HRESULT WINAPI ddraw7_Compact(IDirectDraw7 *iface)
1226
{
1227
    TRACE("iface %p.\n", iface);
1228 1229 1230 1231

    return DD_OK;
}

1232 1233
static HRESULT WINAPI ddraw4_Compact(IDirectDraw4 *iface)
{
1234 1235
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

1236 1237
    TRACE("iface %p.\n", iface);

1238
    return ddraw7_Compact(&This->IDirectDraw7_iface);
1239 1240 1241 1242
}

static HRESULT WINAPI ddraw3_Compact(IDirectDraw3 *iface)
{
1243 1244
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);

1245 1246
    TRACE("iface %p.\n", iface);

1247
    return ddraw7_Compact(&This->IDirectDraw7_iface);
1248 1249 1250 1251
}

static HRESULT WINAPI ddraw2_Compact(IDirectDraw2 *iface)
{
1252 1253
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);

1254 1255
    TRACE("iface %p.\n", iface);

1256
    return ddraw7_Compact(&This->IDirectDraw7_iface);
1257 1258 1259 1260
}

static HRESULT WINAPI ddraw1_Compact(IDirectDraw *iface)
{
1261 1262
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);

1263 1264
    TRACE("iface %p.\n", iface);

1265
    return ddraw7_Compact(&This->IDirectDraw7_iface);
1266 1267
}

1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
/*****************************************************************************
 * IDirectDraw7::GetDisplayMode
 *
 * Returns information about the current display mode
 *
 * Exists in Version 1, 2, 4 and 7
 *
 * Params:
 *  DDSD: Address of a surface description structure to write the info to
 *
 * Returns
 *  DD_OK
 *
 *****************************************************************************/
1282
static HRESULT WINAPI ddraw7_GetDisplayMode(IDirectDraw7 *iface, DDSURFACEDESC2 *DDSD)
1283
{
1284
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1285 1286 1287
    HRESULT hr;
    WINED3DDISPLAYMODE Mode;
    DWORD Size;
1288 1289

    TRACE("iface %p, surface_desc %p.\n", iface, DDSD);
1290

1291
    EnterCriticalSection(&ddraw_cs);
1292
    /* This seems sane */
1293
    if (!DDSD)
1294
    {
1295
        LeaveCriticalSection(&ddraw_cs);
1296 1297 1298 1299
        return DDERR_INVALIDPARAMS;
    }

    /* The necessary members of LPDDSURFACEDESC and LPDDSURFACEDESC2 are equal,
1300 1301 1302
     * so one method can be used for all versions (Hopefully) */
    hr = wined3d_device_get_display_mode(This->wined3d_device, 0, &Mode);
    if (FAILED(hr))
1303
    {
1304
        ERR(" (%p) IWineD3DDevice::GetDisplayMode returned %08x\n", This, hr);
1305
        LeaveCriticalSection(&ddraw_cs);
1306 1307 1308 1309 1310 1311 1312 1313 1314
        return hr;
    }

    Size = DDSD->dwSize;
    memset(DDSD, 0, Size);

    DDSD->dwSize = Size;
    DDSD->dwFlags |= DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | DDSD_PITCH | DDSD_REFRESHRATE;
    DDSD->dwWidth = Mode.Width;
1315
    DDSD->dwHeight = Mode.Height;
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
    DDSD->u2.dwRefreshRate = 60;
    DDSD->ddsCaps.dwCaps = 0;
    DDSD->u4.ddpfPixelFormat.dwSize = sizeof(DDSD->u4.ddpfPixelFormat);
    PixelFormat_WineD3DtoDD(&DDSD->u4.ddpfPixelFormat, Mode.Format);
    DDSD->u1.lPitch = Mode.Width * DDSD->u4.ddpfPixelFormat.u1.dwRGBBitCount / 8;

    if(TRACE_ON(ddraw))
    {
        TRACE("Returning surface desc :\n");
        DDRAW_dump_surface_desc(DDSD);
    }

1328
    LeaveCriticalSection(&ddraw_cs);
1329 1330 1331
    return DD_OK;
}

1332 1333
static HRESULT WINAPI ddraw4_GetDisplayMode(IDirectDraw4 *iface, DDSURFACEDESC2 *surface_desc)
{
1334 1335
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

1336 1337
    TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);

1338
    return ddraw7_GetDisplayMode(&This->IDirectDraw7_iface, surface_desc);
1339 1340 1341 1342
}

static HRESULT WINAPI ddraw3_GetDisplayMode(IDirectDraw3 *iface, DDSURFACEDESC *surface_desc)
{
1343 1344
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);

1345 1346
    TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);

1347
    return ddraw7_GetDisplayMode(&This->IDirectDraw7_iface, (DDSURFACEDESC2 *)surface_desc);
1348 1349 1350 1351
}

static HRESULT WINAPI ddraw2_GetDisplayMode(IDirectDraw2 *iface, DDSURFACEDESC *surface_desc)
{
1352 1353
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);

1354 1355
    TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);

1356
    return ddraw7_GetDisplayMode(&This->IDirectDraw7_iface, (DDSURFACEDESC2 *)surface_desc);
1357 1358 1359 1360
}

static HRESULT WINAPI ddraw1_GetDisplayMode(IDirectDraw *iface, DDSURFACEDESC *surface_desc)
{
1361 1362
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);

1363 1364
    TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);

1365
    return ddraw7_GetDisplayMode(&This->IDirectDraw7_iface, (DDSURFACEDESC2 *)surface_desc);
1366 1367
}

1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
/*****************************************************************************
 * IDirectDraw7::GetFourCCCodes
 *
 * Returns an array of supported FourCC codes.
 *
 * Exists in Version 1, 2, 4 and 7
 *
 * Params:
 *  NumCodes: Contains the number of Codes that Codes can carry. Returns the number
 *            of enumerated codes
1378
 *  Codes: Pointer to an array of DWORDs where the supported codes are written
1379 1380 1381 1382 1383 1384
 *         to
 *
 * Returns
 *  Always returns DD_OK, as it's a stub for now
 *
 *****************************************************************************/
1385
static HRESULT WINAPI ddraw7_GetFourCCCodes(IDirectDraw7 *iface, DWORD *NumCodes, DWORD *Codes)
1386
{
1387
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1388
    static const enum wined3d_format_id formats[] =
1389
    {
1390
        WINED3DFMT_YUY2, WINED3DFMT_UYVY, WINED3DFMT_YV12,
1391
        WINED3DFMT_DXT1, WINED3DFMT_DXT2, WINED3DFMT_DXT3, WINED3DFMT_DXT4, WINED3DFMT_DXT5,
1392
        WINED3DFMT_ATI2N, WINED3DFMT_NVHU, WINED3DFMT_NVHS
1393 1394 1395 1396
    };
    DWORD count = 0, i, outsize;
    HRESULT hr;
    WINED3DDISPLAYMODE d3ddm;
1397
    WINED3DSURFTYPE type = This->ImplType;
1398 1399

    TRACE("iface %p, codes_count %p, codes %p.\n", iface, NumCodes, Codes);
1400

1401
    wined3d_device_get_display_mode(This->wined3d_device, 0, &d3ddm);
1402 1403 1404

    outsize = NumCodes && Codes ? *NumCodes : 0;

1405 1406
    if(type == SURFACE_UNKNOWN) type = SURFACE_GDI;

1407 1408 1409 1410 1411 1412 1413
    for (i = 0; i < (sizeof(formats) / sizeof(formats[0])); ++i)
    {
        hr = wined3d_check_device_format(This->wineD3D, WINED3DADAPTER_DEFAULT, WINED3DDEVTYPE_HAL,
                d3ddm.Format, 0, WINED3DRTYPE_SURFACE, formats[i], type);
        if (SUCCEEDED(hr))
        {
            if (count < outsize)
1414
                Codes[count] = formats[i];
1415
            ++count;
1416 1417 1418 1419 1420 1421
        }
    }
    if(NumCodes) {
        TRACE("Returning %u FourCC codes\n", count);
        *NumCodes = count;
    }
1422 1423 1424 1425

    return DD_OK;
}

1426 1427
static HRESULT WINAPI ddraw4_GetFourCCCodes(IDirectDraw4 *iface, DWORD *codes_count, DWORD *codes)
{
1428 1429
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

1430 1431
    TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);

1432
    return ddraw7_GetFourCCCodes(&This->IDirectDraw7_iface, codes_count, codes);
1433 1434 1435 1436
}

static HRESULT WINAPI ddraw3_GetFourCCCodes(IDirectDraw3 *iface, DWORD *codes_count, DWORD *codes)
{
1437 1438
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);

1439 1440
    TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);

1441
    return ddraw7_GetFourCCCodes(&This->IDirectDraw7_iface, codes_count, codes);
1442 1443 1444 1445
}

static HRESULT WINAPI ddraw2_GetFourCCCodes(IDirectDraw2 *iface, DWORD *codes_count, DWORD *codes)
{
1446 1447
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);

1448 1449
    TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);

1450
    return ddraw7_GetFourCCCodes(&This->IDirectDraw7_iface, codes_count, codes);
1451 1452 1453 1454
}

static HRESULT WINAPI ddraw1_GetFourCCCodes(IDirectDraw *iface, DWORD *codes_count, DWORD *codes)
{
1455 1456
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);

1457 1458
    TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);

1459
    return ddraw7_GetFourCCCodes(&This->IDirectDraw7_iface, codes_count, codes);
1460 1461
}

1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
/*****************************************************************************
 * IDirectDraw7::GetMonitorFrequency
 *
 * Returns the monitor's frequency
 *
 * Exists in Version 1, 2, 4 and 7
 *
 * Params:
 *  Freq: Pointer to a DWORD to write the frequency to
 *
 * Returns
 *  Always returns DD_OK
 *
 *****************************************************************************/
1476
static HRESULT WINAPI ddraw7_GetMonitorFrequency(IDirectDraw7 *iface, DWORD *Freq)
1477
{
1478
    FIXME("iface %p, frequency %p stub!\n", iface, Freq);
1479

1480
    /* Ideally this should be in WineD3D, as it concerns the screen setup,
1481 1482 1483 1484 1485 1486
     * but for now this should make the games happy
     */
    *Freq = 60;
    return DD_OK;
}

1487 1488
static HRESULT WINAPI ddraw4_GetMonitorFrequency(IDirectDraw4 *iface, DWORD *frequency)
{
1489 1490
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

1491 1492
    TRACE("iface %p, frequency %p.\n", iface, frequency);

1493
    return ddraw7_GetMonitorFrequency(&This->IDirectDraw7_iface, frequency);
1494 1495 1496 1497
}

static HRESULT WINAPI ddraw3_GetMonitorFrequency(IDirectDraw3 *iface, DWORD *frequency)
{
1498 1499
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);

1500 1501
    TRACE("iface %p, frequency %p.\n", iface, frequency);

1502
    return ddraw7_GetMonitorFrequency(&This->IDirectDraw7_iface, frequency);
1503 1504 1505 1506
}

static HRESULT WINAPI ddraw2_GetMonitorFrequency(IDirectDraw2 *iface, DWORD *frequency)
{
1507 1508
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);

1509 1510
    TRACE("iface %p, frequency %p.\n", iface, frequency);

1511
    return ddraw7_GetMonitorFrequency(&This->IDirectDraw7_iface, frequency);
1512 1513 1514 1515
}

static HRESULT WINAPI ddraw1_GetMonitorFrequency(IDirectDraw *iface, DWORD *frequency)
{
1516 1517
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);

1518 1519
    TRACE("iface %p, frequency %p.\n", iface, frequency);

1520
    return ddraw7_GetMonitorFrequency(&This->IDirectDraw7_iface, frequency);
1521 1522
}

1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
/*****************************************************************************
 * IDirectDraw7::GetVerticalBlankStatus
 *
 * Returns the Vertical blank status of the monitor. This should be in WineD3D
 * too basically, but as it's a semi stub, I didn't create a function there
 *
 * Params:
 *  status: Pointer to a BOOL to be filled with the vertical blank status
 *
 * Returns
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if status is NULL
 *
 *****************************************************************************/
1537
static HRESULT WINAPI ddraw7_GetVerticalBlankStatus(IDirectDraw7 *iface, BOOL *status)
1538
{
1539
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1540 1541

    TRACE("iface %p, status %p.\n", iface, status);
1542 1543

    /* This looks sane, the MSDN suggests it too */
1544 1545 1546 1547 1548 1549
    EnterCriticalSection(&ddraw_cs);
    if(!status)
    {
        LeaveCriticalSection(&ddraw_cs);
        return DDERR_INVALIDPARAMS;
    }
1550 1551 1552

    *status = This->fake_vblank;
    This->fake_vblank = !This->fake_vblank;
1553
    LeaveCriticalSection(&ddraw_cs);
1554 1555 1556
    return DD_OK;
}

1557 1558
static HRESULT WINAPI ddraw4_GetVerticalBlankStatus(IDirectDraw4 *iface, BOOL *status)
{
1559 1560
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

1561 1562
    TRACE("iface %p, status %p.\n", iface, status);

1563
    return ddraw7_GetVerticalBlankStatus(&This->IDirectDraw7_iface, status);
1564 1565 1566 1567
}

static HRESULT WINAPI ddraw3_GetVerticalBlankStatus(IDirectDraw3 *iface, BOOL *status)
{
1568 1569
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);

1570 1571
    TRACE("iface %p, status %p.\n", iface, status);

1572
    return ddraw7_GetVerticalBlankStatus(&This->IDirectDraw7_iface, status);
1573 1574 1575 1576
}

static HRESULT WINAPI ddraw2_GetVerticalBlankStatus(IDirectDraw2 *iface, BOOL *status)
{
1577 1578
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);

1579 1580
    TRACE("iface %p, status %p.\n", iface, status);

1581
    return ddraw7_GetVerticalBlankStatus(&This->IDirectDraw7_iface, status);
1582 1583 1584 1585
}

static HRESULT WINAPI ddraw1_GetVerticalBlankStatus(IDirectDraw *iface, BOOL *status)
{
1586 1587
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);

1588 1589
    TRACE("iface %p, status %p.\n", iface, status);

1590
    return ddraw7_GetVerticalBlankStatus(&This->IDirectDraw7_iface, status);
1591 1592
}

1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
/*****************************************************************************
 * IDirectDraw7::GetAvailableVidMem
 *
 * Returns the total and free video memory
 *
 * Params:
 *  Caps: Specifies the memory type asked for
 *  total: Pointer to a DWORD to be filled with the total memory
 *  free: Pointer to a DWORD to be filled with the free memory
 *
 * Returns
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS of free and total are NULL
 *
 *****************************************************************************/
1608 1609
static HRESULT WINAPI ddraw7_GetAvailableVidMem(IDirectDraw7 *iface, DDSCAPS2 *Caps, DWORD *total,
        DWORD *free)
1610
{
1611
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1612 1613

    TRACE("iface %p, caps %p, total %p, free %p.\n", iface, Caps, total, free);
1614 1615 1616 1617 1618 1619

    if(TRACE_ON(ddraw))
    {
        TRACE("(%p) Asked for memory with description: ", This);
        DDRAW_dump_DDSCAPS2(Caps);
    }
1620
    EnterCriticalSection(&ddraw_cs);
1621 1622

    /* Todo: System memory vs local video memory vs non-local video memory
1623
     * The MSDN also mentions differences between texture memory and other
1624 1625 1626
     * resources, but that's not important
     */

1627 1628 1629 1630 1631
    if( (!total) && (!free) )
    {
        LeaveCriticalSection(&ddraw_cs);
        return DDERR_INVALIDPARAMS;
    }
1632

1633 1634 1635 1636
    if (total)
        *total = This->total_vidmem;
    if (free)
        *free = wined3d_device_get_available_texture_mem(This->wined3d_device);
1637

1638
    LeaveCriticalSection(&ddraw_cs);
1639 1640 1641
    return DD_OK;
}

1642 1643 1644
static HRESULT WINAPI ddraw4_GetAvailableVidMem(IDirectDraw4 *iface,
        DDSCAPS2 *caps, DWORD *total, DWORD *free)
{
1645 1646
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

1647 1648
    TRACE("iface %p, caps %p, total %p, free %p.\n", iface, caps, total, free);

1649
    return ddraw7_GetAvailableVidMem(&This->IDirectDraw7_iface, caps, total, free);
1650 1651
}

1652 1653
static HRESULT WINAPI ddraw3_GetAvailableVidMem(IDirectDraw3 *iface, DDSCAPS *caps, DWORD *total,
        DWORD *free)
1654
{
1655
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
1656 1657 1658 1659 1660
    DDSCAPS2 caps2;

    TRACE("iface %p, caps %p, total %p, free %p.\n", iface, caps, total, free);

    DDRAW_Convert_DDSCAPS_1_To_2(caps, &caps2);
1661
    return ddraw7_GetAvailableVidMem(&This->IDirectDraw7_iface, &caps2, total, free);
1662 1663 1664 1665 1666
}

static HRESULT WINAPI ddraw2_GetAvailableVidMem(IDirectDraw2 *iface,
        DDSCAPS *caps, DWORD *total, DWORD *free)
{
1667
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
1668 1669 1670 1671 1672
    DDSCAPS2 caps2;

    TRACE("iface %p, caps %p, total %p, free %p.\n", iface, caps, total, free);

    DDRAW_Convert_DDSCAPS_1_To_2(caps, &caps2);
1673
    return ddraw7_GetAvailableVidMem(&This->IDirectDraw7_iface, &caps2, total, free);
1674 1675
}

1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
/*****************************************************************************
 * IDirectDraw7::Initialize
 *
 * Initializes a DirectDraw interface.
 *
 * Params:
 *  GUID: Interface identifier. Well, don't know what this is really good
 *   for
 *
 * Returns
 *  Returns DD_OK on the first call,
 *  DDERR_ALREADYINITIALIZED on repeated calls
 *
 *****************************************************************************/
1690
static HRESULT WINAPI ddraw7_Initialize(IDirectDraw7 *iface, GUID *Guid)
1691
{
1692
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1693 1694

    TRACE("iface %p, guid %s.\n", iface, debugstr_guid(Guid));
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705

    if(This->initialized)
    {
        return DDERR_ALREADYINITIALIZED;
    }
    else
    {
        return DD_OK;
    }
}

1706 1707
static HRESULT WINAPI ddraw4_Initialize(IDirectDraw4 *iface, GUID *guid)
{
1708 1709
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

1710 1711
    TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));

1712
    return ddraw7_Initialize(&This->IDirectDraw7_iface, guid);
1713 1714 1715 1716
}

static HRESULT WINAPI ddraw3_Initialize(IDirectDraw3 *iface, GUID *guid)
{
1717 1718
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);

1719 1720
    TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));

1721
    return ddraw7_Initialize(&This->IDirectDraw7_iface, guid);
1722 1723 1724 1725
}

static HRESULT WINAPI ddraw2_Initialize(IDirectDraw2 *iface, GUID *guid)
{
1726 1727
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);

1728 1729
    TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));

1730
    return ddraw7_Initialize(&This->IDirectDraw7_iface, guid);
1731 1732 1733 1734
}

static HRESULT WINAPI ddraw1_Initialize(IDirectDraw *iface, GUID *guid)
{
1735 1736
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);

1737 1738
    TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));

1739
    return ddraw7_Initialize(&This->IDirectDraw7_iface, guid);
1740 1741
}

1742 1743 1744 1745 1746 1747 1748
static HRESULT WINAPI d3d1_Initialize(IDirect3D *iface, REFIID riid)
{
    TRACE("iface %p, riid %s.\n", iface, debugstr_guid(riid));

    return D3D_OK;
}

1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
/*****************************************************************************
 * IDirectDraw7::FlipToGDISurface
 *
 * "Makes the surface that the GDI writes to the primary surface"
 * Looks like some windows specific thing we don't have to care about.
 * According to MSDN it permits GDI dialog boxes in FULLSCREEN mode. Good to
 * show error boxes ;)
 * Well, just return DD_OK.
 *
 * Returns:
 *  Always returns DD_OK
 *
 *****************************************************************************/
1762
static HRESULT WINAPI ddraw7_FlipToGDISurface(IDirectDraw7 *iface)
1763
{
1764
    FIXME("iface %p stub!\n", iface);
1765 1766 1767 1768

    return DD_OK;
}

1769 1770
static HRESULT WINAPI ddraw4_FlipToGDISurface(IDirectDraw4 *iface)
{
1771 1772
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

1773 1774
    TRACE("iface %p.\n", iface);

1775
    return ddraw7_FlipToGDISurface(&This->IDirectDraw7_iface);
1776 1777 1778 1779
}

static HRESULT WINAPI ddraw3_FlipToGDISurface(IDirectDraw3 *iface)
{
1780 1781
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);

1782 1783
    TRACE("iface %p.\n", iface);

1784
    return ddraw7_FlipToGDISurface(&This->IDirectDraw7_iface);
1785 1786 1787 1788
}

static HRESULT WINAPI ddraw2_FlipToGDISurface(IDirectDraw2 *iface)
{
1789 1790
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);

1791 1792
    TRACE("iface %p.\n", iface);

1793
    return ddraw7_FlipToGDISurface(&This->IDirectDraw7_iface);
1794 1795 1796 1797
}

static HRESULT WINAPI ddraw1_FlipToGDISurface(IDirectDraw *iface)
{
1798 1799
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);

1800 1801
    TRACE("iface %p.\n", iface);

1802
    return ddraw7_FlipToGDISurface(&This->IDirectDraw7_iface);
1803 1804
}

1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
/*****************************************************************************
 * IDirectDraw7::WaitForVerticalBlank
 *
 * This method allows applications to get in sync with the vertical blank
 * interval.
 * The wormhole demo in the DirectX 7 sdk uses this call, and it doesn't
 * redraw the screen, most likely because of this stub
 *
 * Parameters:
 *  Flags: one of DDWAITVB_BLOCKBEGIN, DDWAITVB_BLOCKBEGINEVENT
 *         or DDWAITVB_BLOCKEND
 *  h: Not used, according to MSDN
 *
 * Returns:
 *  Always returns DD_OK
 *
1821
 *****************************************************************************/
1822
static HRESULT WINAPI ddraw7_WaitForVerticalBlank(IDirectDraw7 *iface, DWORD Flags, HANDLE event)
1823
{
1824 1825 1826
    static BOOL hide;

    TRACE("iface %p, flags %#x, event %p.\n", iface, Flags, event);
1827 1828 1829 1830

    /* This function is called often, so print the fixme only once */
    if(!hide)
    {
1831
        FIXME("iface %p, flags %#x, event %p stub!\n", iface, Flags, event);
1832 1833
        hide = TRUE;
    }
1834 1835 1836 1837 1838 1839 1840 1841

    /* MSDN says DDWAITVB_BLOCKBEGINEVENT is not supported */
    if(Flags & DDWAITVB_BLOCKBEGINEVENT)
        return DDERR_UNSUPPORTED; /* unchecked */

    return DD_OK;
}

1842 1843
static HRESULT WINAPI ddraw4_WaitForVerticalBlank(IDirectDraw4 *iface, DWORD flags, HANDLE event)
{
1844 1845
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

1846 1847
    TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);

1848
    return ddraw7_WaitForVerticalBlank(&This->IDirectDraw7_iface, flags, event);
1849 1850 1851 1852
}

static HRESULT WINAPI ddraw3_WaitForVerticalBlank(IDirectDraw3 *iface, DWORD flags, HANDLE event)
{
1853 1854
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);

1855 1856
    TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);

1857
    return ddraw7_WaitForVerticalBlank(&This->IDirectDraw7_iface, flags, event);
1858 1859 1860 1861
}

static HRESULT WINAPI ddraw2_WaitForVerticalBlank(IDirectDraw2 *iface, DWORD flags, HANDLE event)
{
1862 1863
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);

1864 1865
    TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);

1866
    return ddraw7_WaitForVerticalBlank(&This->IDirectDraw7_iface, flags, event);
1867 1868 1869 1870
}

static HRESULT WINAPI ddraw1_WaitForVerticalBlank(IDirectDraw *iface, DWORD flags, HANDLE event)
{
1871 1872
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);

1873 1874
    TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);

1875
    return ddraw7_WaitForVerticalBlank(&This->IDirectDraw7_iface, flags, event);
1876 1877
}

1878 1879 1880
/*****************************************************************************
 * IDirectDraw7::GetScanLine
 *
1881
 * Returns the scan line that is being drawn on the monitor
1882 1883 1884 1885 1886 1887 1888
 *
 * Parameters:
 *  Scanline: Address to write the scan line value to
 *
 * Returns:
 *  Always returns DD_OK
 *
1889
 *****************************************************************************/
1890
static HRESULT WINAPI ddraw7_GetScanLine(IDirectDraw7 *iface, DWORD *Scanline)
1891
{
1892
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
1893 1894 1895
    static BOOL hide = FALSE;
    WINED3DDISPLAYMODE Mode;

1896 1897
    TRACE("iface %p, line %p.\n", iface, Scanline);

1898
    /* This function is called often, so print the fixme only once */
1899
    EnterCriticalSection(&ddraw_cs);
1900 1901
    if(!hide)
    {
1902
        FIXME("iface %p, line %p partial stub!\n", iface, Scanline);
1903 1904 1905
        hide = TRUE;
    }

1906
    wined3d_device_get_display_mode(This->wined3d_device, 0, &Mode);
1907 1908

    /* Fake the line sweeping of the monitor */
1909
    /* FIXME: We should synchronize with a source to keep the refresh rate */
1910 1911 1912 1913 1914
    *Scanline = This->cur_scanline++;
    /* Assume 20 scan lines in the vertical blank */
    if (This->cur_scanline >= Mode.Height + 20)
        This->cur_scanline = 0;

1915
    LeaveCriticalSection(&ddraw_cs);
1916 1917 1918
    return DD_OK;
}

1919 1920
static HRESULT WINAPI ddraw4_GetScanLine(IDirectDraw4 *iface, DWORD *line)
{
1921 1922
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

1923 1924
    TRACE("iface %p, line %p.\n", iface, line);

1925
    return ddraw7_GetScanLine(&This->IDirectDraw7_iface, line);
1926 1927 1928 1929
}

static HRESULT WINAPI ddraw3_GetScanLine(IDirectDraw3 *iface, DWORD *line)
{
1930 1931
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);

1932 1933
    TRACE("iface %p, line %p.\n", iface, line);

1934
    return ddraw7_GetScanLine(&This->IDirectDraw7_iface, line);
1935 1936 1937 1938
}

static HRESULT WINAPI ddraw2_GetScanLine(IDirectDraw2 *iface, DWORD *line)
{
1939 1940
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);

1941 1942
    TRACE("iface %p, line %p.\n", iface, line);

1943
    return ddraw7_GetScanLine(&This->IDirectDraw7_iface, line);
1944 1945 1946 1947
}

static HRESULT WINAPI ddraw1_GetScanLine(IDirectDraw *iface, DWORD *line)
{
1948 1949
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);

1950 1951
    TRACE("iface %p, line %p.\n", iface, line);

1952
    return ddraw7_GetScanLine(&This->IDirectDraw7_iface, line);
1953 1954
}

1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
/*****************************************************************************
 * IDirectDraw7::TestCooperativeLevel
 *
 * Informs the application about the state of the video adapter, depending
 * on the cooperative level
 *
 * Returns:
 *  DD_OK if the device is in a sane state
 *  DDERR_NOEXCLUSIVEMODE or DDERR_EXCLUSIVEMODEALREADYSET
 *  if the state is not correct(See below)
 *
1966
 *****************************************************************************/
1967
static HRESULT WINAPI ddraw7_TestCooperativeLevel(IDirectDraw7 *iface)
1968
{
1969
    TRACE("iface %p.\n", iface);
1970 1971 1972 1973

    return DD_OK;
}

1974 1975
static HRESULT WINAPI ddraw4_TestCooperativeLevel(IDirectDraw4 *iface)
{
1976 1977
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

1978 1979
    TRACE("iface %p.\n", iface);

1980
    return ddraw7_TestCooperativeLevel(&This->IDirectDraw7_iface);
1981 1982
}

1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
/*****************************************************************************
 * IDirectDraw7::GetGDISurface
 *
 * Returns the surface that GDI is treating as the primary surface.
 * For Wine this is the front buffer
 *
 * Params:
 *  GDISurface: Address to write the surface pointer to
 *
 * Returns:
 *  DD_OK if the surface was found
 *  DDERR_NOTFOUND if the GDI surface wasn't found
 *
1996
 *****************************************************************************/
1997
static HRESULT WINAPI ddraw7_GetGDISurface(IDirectDraw7 *iface, IDirectDrawSurface7 **GDISurface)
1998
{
1999
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
2000
    struct wined3d_surface *wined3d_surface;
2001 2002 2003
    IDirectDrawSurface7 *ddsurf;
    HRESULT hr;
    DDSCAPS2 ddsCaps;
2004 2005

    TRACE("iface %p, surface %p.\n", iface, GDISurface);
2006

2007
    /* Get the back buffer from the wineD3DDevice and search its
2008
     * attached surfaces for the front buffer. */
2009
    EnterCriticalSection(&ddraw_cs);
2010
    hr = wined3d_device_get_back_buffer(This->wined3d_device,
2011 2012
            0, 0, WINED3DBACKBUFFER_TYPE_MONO, &wined3d_surface);
    if (FAILED(hr) || !wined3d_surface)
2013 2014
    {
        ERR("IWineD3DDevice::GetBackBuffer failed\n");
2015
        LeaveCriticalSection(&ddraw_cs);
2016 2017 2018
        return DDERR_NOTFOUND;
    }

2019 2020
    ddsurf = wined3d_surface_get_parent(wined3d_surface);
    wined3d_surface_decref(wined3d_surface);
2021

2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
    /* Find the front buffer */
    ddsCaps.dwCaps = DDSCAPS_FRONTBUFFER;
    hr = IDirectDrawSurface7_GetAttachedSurface(ddsurf,
                                                &ddsCaps,
                                                GDISurface);
    if(hr != DD_OK)
    {
        ERR("IDirectDrawSurface7::GetAttachedSurface failed, hr = %x\n", hr);
    }

    /* The AddRef is OK this time */
    LeaveCriticalSection(&ddraw_cs);
    return hr;
}

static HRESULT WINAPI ddraw4_GetGDISurface(IDirectDraw4 *iface, IDirectDrawSurface4 **surface)
{
2039
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
2040 2041 2042
    IDirectDrawSurface7 *surface7;
    IDirectDrawSurfaceImpl *surface_impl;
    HRESULT hr;
2043

2044 2045
    TRACE("iface %p, surface %p.\n", iface, surface);

2046 2047 2048 2049 2050 2051 2052
    hr = ddraw7_GetGDISurface(&This->IDirectDraw7_iface, &surface7);
    if (FAILED(hr))
    {
        *surface = NULL;
        return hr;
    }
    surface_impl = impl_from_IDirectDrawSurface7(surface7);
2053
    *surface = &surface_impl->IDirectDrawSurface4_iface;
2054 2055

    return hr;
2056 2057 2058 2059
}

static HRESULT WINAPI ddraw3_GetGDISurface(IDirectDraw3 *iface, IDirectDrawSurface **surface)
{
2060
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
2061
    IDirectDrawSurface7 *surface7;
2062
    IDirectDrawSurfaceImpl *surface_impl;
2063 2064 2065 2066
    HRESULT hr;

    TRACE("iface %p, surface %p.\n", iface, surface);

2067
    hr = ddraw7_GetGDISurface(&This->IDirectDraw7_iface, &surface7);
2068 2069 2070 2071 2072
    if (FAILED(hr))
    {
        *surface = NULL;
        return hr;
    }
2073
    surface_impl = impl_from_IDirectDrawSurface7(surface7);
2074
    *surface = (IDirectDrawSurface *)&surface_impl->IDirectDrawSurface3_iface;
2075 2076 2077 2078 2079 2080

    return hr;
}

static HRESULT WINAPI ddraw2_GetGDISurface(IDirectDraw2 *iface, IDirectDrawSurface **surface)
{
2081
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
2082
    IDirectDrawSurface7 *surface7;
2083
    IDirectDrawSurfaceImpl *surface_impl;
2084 2085 2086 2087
    HRESULT hr;

    TRACE("iface %p, surface %p.\n", iface, surface);

2088
    hr = ddraw7_GetGDISurface(&This->IDirectDraw7_iface, &surface7);
2089 2090 2091 2092 2093
    if (FAILED(hr))
    {
        *surface = NULL;
        return hr;
    }
2094
    surface_impl = impl_from_IDirectDrawSurface7(surface7);
2095
    *surface = (IDirectDrawSurface *)&surface_impl->IDirectDrawSurface3_iface;
2096 2097 2098 2099 2100 2101

    return hr;
}

static HRESULT WINAPI ddraw1_GetGDISurface(IDirectDraw *iface, IDirectDrawSurface **surface)
{
2102
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
2103
    IDirectDrawSurface7 *surface7;
2104
    IDirectDrawSurfaceImpl *surface_impl;
2105 2106 2107 2108
    HRESULT hr;

    TRACE("iface %p, surface %p.\n", iface, surface);

2109
    hr = ddraw7_GetGDISurface(&This->IDirectDraw7_iface, &surface7);
2110 2111 2112 2113 2114
    if (FAILED(hr))
    {
        *surface = NULL;
        return hr;
    }
2115
    surface_impl = impl_from_IDirectDrawSurface7(surface7);
2116
    *surface = (IDirectDrawSurface *)&surface_impl->IDirectDrawSurface3_iface;
2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130

    return hr;
}

struct displaymodescallback_context
{
    LPDDENUMMODESCALLBACK func;
    void *context;
};

static HRESULT CALLBACK EnumDisplayModesCallbackThunk(DDSURFACEDESC2 *surface_desc, void *context)
{
    struct displaymodescallback_context *cbcontext = context;
    DDSURFACEDESC desc;
2131

2132 2133
    memcpy(&desc, surface_desc, sizeof(desc));
    desc.dwSize = sizeof(desc);
2134

2135
    return cbcontext->func(&desc, cbcontext->context);
2136 2137 2138 2139 2140 2141
}

/*****************************************************************************
 * IDirectDraw7::EnumDisplayModes
 *
 * Enumerates the supported Display modes. The modes can be filtered with
2142
 * the DDSD parameter.
2143 2144
 *
 * Params:
2145 2146
 *  Flags: can be DDEDM_REFRESHRATES and DDEDM_STANDARDVGAMODES. For old ddraw
 *         versions (3 and older?) this is reserved and must be 0.
2147 2148 2149 2150 2151 2152 2153 2154
 *  DDSD: Surface description to filter the modes
 *  Context: Pointer passed back to the callback function
 *  cb: Application-provided callback function
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if the callback wasn't set
 *
2155
 *****************************************************************************/
2156 2157
static HRESULT WINAPI ddraw7_EnumDisplayModes(IDirectDraw7 *iface, DWORD Flags,
        DDSURFACEDESC2 *DDSD, void *Context, LPDDENUMMODESCALLBACK2 cb)
2158
{
2159
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
2160
    unsigned int modenum, fmt;
2161 2162
    WINED3DDISPLAYMODE mode;
    DDSURFACEDESC2 callback_sd;
2163 2164
    WINED3DDISPLAYMODE *enum_modes = NULL;
    unsigned enum_mode_count = 0, enum_mode_array_size = 0;
2165
    DDPIXELFORMAT pixelformat;
2166

2167
    static const enum wined3d_format_id checkFormatList[] =
2168
    {
2169 2170 2171
        WINED3DFMT_B8G8R8X8_UNORM,
        WINED3DFMT_B5G6R5_UNORM,
        WINED3DFMT_P8_UINT,
2172 2173
    };

2174 2175
    TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
            iface, Flags, DDSD, Context, cb);
2176

2177
    EnterCriticalSection(&ddraw_cs);
2178
    /* This looks sane */
2179 2180 2181 2182 2183
    if(!cb)
    {
        LeaveCriticalSection(&ddraw_cs);
        return DDERR_INVALIDPARAMS;
    }
2184

2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
    if(!(Flags & DDEDM_REFRESHRATES))
    {
        enum_mode_array_size = 16;
        enum_modes = HeapAlloc(GetProcessHeap(), 0, sizeof(WINED3DDISPLAYMODE) * enum_mode_array_size);
        if (!enum_modes)
        {
            ERR("Out of memory\n");
            LeaveCriticalSection(&ddraw_cs);
            return DDERR_OUTOFMEMORY;
        }
    }

2197
    pixelformat.dwSize = sizeof(pixelformat);
2198 2199 2200
    for(fmt = 0; fmt < (sizeof(checkFormatList) / sizeof(checkFormatList[0])); fmt++)
    {
        modenum = 0;
2201 2202
        while (wined3d_enum_adapter_modes(This->wineD3D, WINED3DADAPTER_DEFAULT,
                checkFormatList[fmt], modenum++, &mode) == WINED3D_OK)
2203
        {
2204
            PixelFormat_WineD3DtoDD(&pixelformat, mode.Format);
2205 2206 2207 2208
            if(DDSD)
            {
                if(DDSD->dwFlags & DDSD_WIDTH && mode.Width != DDSD->dwWidth) continue;
                if(DDSD->dwFlags & DDSD_HEIGHT && mode.Height != DDSD->dwHeight) continue;
2209 2210 2211
                if(DDSD->dwFlags & DDSD_REFRESHRATE && mode.RefreshRate != DDSD->u2.dwRefreshRate) continue;
                if (DDSD->dwFlags & DDSD_PIXELFORMAT &&
                        pixelformat.u1.dwRGBBitCount != DDSD->u4.ddpfPixelFormat.u1.dwRGBBitCount) continue;
2212 2213
            }

2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
            if(!(Flags & DDEDM_REFRESHRATES))
            {
                /* DX docs state EnumDisplayMode should return only unique modes. If DDEDM_REFRESHRATES is not set, refresh
                 * rate doesn't matter when determining if the mode is unique. So modes only differing in refresh rate have
                 * to be reduced to a single unique result in such case.
                 */
                BOOL found = FALSE;
                unsigned i;

                for (i = 0; i < enum_mode_count; i++)
                {
                    if(enum_modes[i].Width == mode.Width && enum_modes[i].Height == mode.Height &&
                       enum_modes[i].Format == mode.Format)
                    {
                        found = TRUE;
                        break;
                    }
                }

                if(found) continue;
            }

2236 2237 2238
            memset(&callback_sd, 0, sizeof(callback_sd));
            callback_sd.dwSize = sizeof(callback_sd);
            callback_sd.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
2239

2240
            callback_sd.dwFlags = DDSD_HEIGHT|DDSD_WIDTH|DDSD_PIXELFORMAT|DDSD_PITCH|DDSD_REFRESHRATE;
2241 2242 2243 2244
            if(Flags & DDEDM_REFRESHRATES)
            {
                callback_sd.u2.dwRefreshRate = mode.RefreshRate;
            }
2245

2246 2247
            callback_sd.dwWidth = mode.Width;
            callback_sd.dwHeight = mode.Height;
2248

2249
            callback_sd.u4.ddpfPixelFormat=pixelformat;
2250

2251 2252 2253 2254 2255 2256
            /* Calc pitch and DWORD align like MSDN says */
            callback_sd.u1.lPitch = (callback_sd.u4.ddpfPixelFormat.u1.dwRGBBitCount / 8) * mode.Width;
            callback_sd.u1.lPitch = (callback_sd.u1.lPitch + 3) & ~3;

            TRACE("Enumerating %dx%dx%d @%d\n", callback_sd.dwWidth, callback_sd.dwHeight, callback_sd.u4.ddpfPixelFormat.u1.dwRGBBitCount,
              callback_sd.u2.dwRefreshRate);
2257 2258 2259 2260

            if(cb(&callback_sd, Context) == DDENUMRET_CANCEL)
            {
                TRACE("Application asked to terminate the enumeration\n");
2261
                HeapFree(GetProcessHeap(), 0, enum_modes);
2262
                LeaveCriticalSection(&ddraw_cs);
2263 2264
                return DD_OK;
            }
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287

            if(!(Flags & DDEDM_REFRESHRATES))
            {
                if (enum_mode_count == enum_mode_array_size)
                {
                    WINED3DDISPLAYMODE *new_enum_modes;

                    enum_mode_array_size *= 2;
                    new_enum_modes = HeapReAlloc(GetProcessHeap(), 0, enum_modes, sizeof(WINED3DDISPLAYMODE) * enum_mode_array_size);

                    if (!new_enum_modes)
                    {
                        ERR("Out of memory\n");
                        HeapFree(GetProcessHeap(), 0, enum_modes);
                        LeaveCriticalSection(&ddraw_cs);
                        return DDERR_OUTOFMEMORY;
                    }

                    enum_modes = new_enum_modes;
                }

                enum_modes[enum_mode_count++] = mode;
            }
2288 2289
        }
    }
2290

2291
    TRACE("End of enumeration\n");
2292
    HeapFree(GetProcessHeap(), 0, enum_modes);
2293
    LeaveCriticalSection(&ddraw_cs);
2294
    return DD_OK;
2295 2296
}

2297 2298 2299
static HRESULT WINAPI ddraw4_EnumDisplayModes(IDirectDraw4 *iface, DWORD flags,
        DDSURFACEDESC2 *surface_desc, void *context, LPDDENUMMODESCALLBACK2 callback)
{
2300 2301
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

2302 2303 2304
    TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
            iface, flags, surface_desc, context, callback);

2305
    return ddraw7_EnumDisplayModes(&This->IDirectDraw7_iface, flags, surface_desc, context, callback);
2306 2307 2308 2309 2310
}

static HRESULT WINAPI ddraw3_EnumDisplayModes(IDirectDraw3 *iface, DWORD flags,
        DDSURFACEDESC *surface_desc, void *context, LPDDENUMMODESCALLBACK callback)
{
2311
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
2312 2313 2314 2315 2316 2317 2318 2319
    struct displaymodescallback_context cbcontext;

    TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
            iface, flags, surface_desc, context, callback);

    cbcontext.func = callback;
    cbcontext.context = context;

2320 2321
    return ddraw7_EnumDisplayModes(&This->IDirectDraw7_iface, flags, (DDSURFACEDESC2 *)surface_desc,
            &cbcontext, EnumDisplayModesCallbackThunk);
2322 2323 2324 2325 2326
}

static HRESULT WINAPI ddraw2_EnumDisplayModes(IDirectDraw2 *iface, DWORD flags,
        DDSURFACEDESC *surface_desc, void *context, LPDDENUMMODESCALLBACK callback)
{
2327
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
2328 2329 2330 2331 2332 2333 2334 2335
    struct displaymodescallback_context cbcontext;

    TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
            iface, flags, surface_desc, context, callback);

    cbcontext.func = callback;
    cbcontext.context = context;

2336 2337
    return ddraw7_EnumDisplayModes(&This->IDirectDraw7_iface, flags, (DDSURFACEDESC2 *)surface_desc,
            &cbcontext, EnumDisplayModesCallbackThunk);
2338 2339 2340 2341 2342
}

static HRESULT WINAPI ddraw1_EnumDisplayModes(IDirectDraw *iface, DWORD flags,
        DDSURFACEDESC *surface_desc, void *context, LPDDENUMMODESCALLBACK callback)
{
2343
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
2344 2345 2346 2347 2348 2349 2350 2351
    struct displaymodescallback_context cbcontext;

    TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
            iface, flags, surface_desc, context, callback);

    cbcontext.func = callback;
    cbcontext.context = context;

2352
    return ddraw7_EnumDisplayModes(&This->IDirectDraw7_iface, flags, (DDSURFACEDESC2 *)surface_desc,
2353
            &cbcontext, EnumDisplayModesCallbackThunk);
2354 2355
}

2356 2357 2358 2359 2360 2361 2362 2363 2364
/*****************************************************************************
 * IDirectDraw7::EvaluateMode
 *
 * Used with IDirectDraw7::StartModeTest to test video modes.
 * EvaluateMode is used to pass or fail a mode, and continue with the next
 * mode
 *
 * Params:
 *  Flags: DDEM_MODEPASSED or DDEM_MODEFAILED
2365
 *  Timeout: Returns the amount of seconds left before the mode would have
2366 2367 2368 2369 2370 2371
 *           been failed automatically
 *
 * Returns:
 *  This implementation always DD_OK, because it's a stub
 *
 *****************************************************************************/
2372
static HRESULT WINAPI ddraw7_EvaluateMode(IDirectDraw7 *iface, DWORD Flags, DWORD *Timeout)
2373
{
2374
    FIXME("iface %p, flags %#x, timeout %p stub!\n", iface, Flags, Timeout);
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392

    /* When implementing this, implement it in WineD3D */

    return DD_OK;
}

/*****************************************************************************
 * IDirectDraw7::GetDeviceIdentifier
 *
 * Returns the device identifier, which gives information about the driver
 * Our device identifier is defined at the beginning of this file.
 *
 * Params:
 *  DDDI: Address for the returned structure
 *  Flags: Can be DDGDI_GETHOSTIDENTIFIER
 *
 * Returns:
 *  On success it returns DD_OK
2393
 *  DDERR_INVALIDPARAMS if DDDI is NULL
2394 2395
 *
 *****************************************************************************/
2396 2397
static HRESULT WINAPI ddraw7_GetDeviceIdentifier(IDirectDraw7 *iface,
        DDDEVICEIDENTIFIER2 *DDDI, DWORD Flags)
2398
{
2399
    TRACE("iface %p, device_identifier %p, flags %#x.\n", iface, DDDI, Flags);
2400 2401 2402 2403 2404 2405

    if(!DDDI)
        return DDERR_INVALIDPARAMS;

    /* The DDGDI_GETHOSTIDENTIFIER returns the information about the 2D
     * host adapter, if there's a secondary 3D adapter. This doesn't apply
2406 2407 2408
     * to any modern hardware, nor is it interesting for Wine, so ignore it.
     * Size of DDDEVICEIDENTIFIER2 may be aligned to 8 bytes and thus 4
     * bytes too long. So only copy the relevant part of the structure
2409 2410
     */

2411
    memcpy(DDDI, &deviceidentifier, FIELD_OFFSET(DDDEVICEIDENTIFIER2, dwWHQLLevel) + sizeof(DWORD));
2412 2413 2414
    return DD_OK;
}

2415 2416 2417
static HRESULT WINAPI ddraw4_GetDeviceIdentifier(IDirectDraw4 *iface,
        DDDEVICEIDENTIFIER *identifier, DWORD flags)
{
2418
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
2419 2420 2421 2422 2423
    DDDEVICEIDENTIFIER2 identifier2;
    HRESULT hr;

    TRACE("iface %p, identifier %p, flags %#x.\n", iface, identifier, flags);

2424
    hr = ddraw7_GetDeviceIdentifier(&This->IDirectDraw7_iface, &identifier2, flags);
2425 2426 2427 2428 2429
    DDRAW_Convert_DDDEVICEIDENTIFIER_2_To_1(&identifier2, identifier);

    return hr;
}

2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443
/*****************************************************************************
 * IDirectDraw7::GetSurfaceFromDC
 *
 * Returns the Surface for a GDI device context handle.
 * Is this related to IDirectDrawSurface::GetDC ???
 *
 * Params:
 *  hdc: hdc to return the surface for
 *  Surface: Address to write the surface pointer to
 *
 * Returns:
 *  Always returns DD_OK because it's a stub
 *
 *****************************************************************************/
2444 2445
static HRESULT WINAPI ddraw7_GetSurfaceFromDC(IDirectDraw7 *iface, HDC hdc,
        IDirectDrawSurface7 **Surface)
2446
{
2447
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
2448
    struct wined3d_surface *wined3d_surface;
2449 2450 2451 2452 2453 2454
    HRESULT hr;

    TRACE("iface %p, dc %p, surface %p.\n", iface, hdc, Surface);

    if (!Surface) return E_INVALIDARG;

2455
    hr = wined3d_device_get_surface_from_dc(This->wined3d_device, hdc, &wined3d_surface);
2456 2457 2458 2459 2460 2461
    if (FAILED(hr))
    {
        TRACE("No surface found for dc %p.\n", hdc);
        *Surface = NULL;
        return DDERR_NOTFOUND;
    }
2462

2463
    *Surface = wined3d_surface_get_parent(wined3d_surface);
2464
    IDirectDrawSurface7_AddRef(*Surface);
2465 2466
    TRACE("Returning surface %p.\n", Surface);
    return DD_OK;
2467 2468
}

2469 2470
static HRESULT WINAPI ddraw4_GetSurfaceFromDC(IDirectDraw4 *iface, HDC dc,
        IDirectDrawSurface4 **surface)
2471
{
2472
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
2473
    IDirectDrawSurface7 *surface7;
2474
    IDirectDrawSurfaceImpl *surface_impl;
2475 2476 2477 2478 2479 2480
    HRESULT hr;

    TRACE("iface %p, dc %p, surface %p.\n", iface, dc, surface);

    if (!surface) return E_INVALIDARG;

2481
    hr = ddraw7_GetSurfaceFromDC(&This->IDirectDraw7_iface, dc, &surface7);
2482 2483 2484 2485 2486
    if (FAILED(hr))
    {
        *surface = NULL;
        return hr;
    }
2487
    surface_impl = impl_from_IDirectDrawSurface7(surface7);
2488 2489
    /* Tests say this is true */
    *surface = (IDirectDrawSurface4 *)&surface_impl->IDirectDrawSurface3_iface;
2490 2491 2492 2493

    return hr;
}

2494 2495
static HRESULT WINAPI ddraw3_GetSurfaceFromDC(IDirectDraw3 *iface, HDC dc,
        IDirectDrawSurface **surface)
2496
{
2497
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
2498 2499 2500
    IDirectDrawSurface7 *surface7;
    IDirectDrawSurfaceImpl *surface_impl;
    HRESULT hr;
2501

2502 2503
    TRACE("iface %p, dc %p, surface %p.\n", iface, dc, surface);

2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
    if (!surface) return E_INVALIDARG;

    hr = ddraw7_GetSurfaceFromDC(&This->IDirectDraw7_iface, dc, &surface7);
    if (FAILED(hr))
    {
        *surface = NULL;
        return hr;
    }

    surface_impl = impl_from_IDirectDrawSurface7(surface7);
    *surface = (IDirectDrawSurface *)&surface_impl->IDirectDrawSurface3_iface;

    return hr;
2517 2518
}

2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
/*****************************************************************************
 * IDirectDraw7::RestoreAllSurfaces
 *
 * Calls the restore method of all surfaces
 *
 * Params:
 *
 * Returns:
 *  Always returns DD_OK because it's a stub
 *
 *****************************************************************************/
2530
static HRESULT WINAPI ddraw7_RestoreAllSurfaces(IDirectDraw7 *iface)
2531
{
2532
    FIXME("iface %p stub!\n", iface);
2533 2534 2535 2536 2537 2538 2539 2540 2541

    /* This isn't hard to implement: Enumerate all WineD3D surfaces,
     * get their parent and call their restore method. Do not implement
     * it in WineD3D, as restoring a surface means re-creating the
     * WineD3DDSurface
     */
    return DD_OK;
}

2542 2543
static HRESULT WINAPI ddraw4_RestoreAllSurfaces(IDirectDraw4 *iface)
{
2544 2545
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

2546 2547
    TRACE("iface %p.\n", iface);

2548
    return ddraw7_RestoreAllSurfaces(&This->IDirectDraw7_iface);
2549 2550
}

2551 2552 2553 2554 2555 2556
/*****************************************************************************
 * IDirectDraw7::StartModeTest
 *
 * Tests the specified video modes to update the system registry with
 * refresh rate information. StartModeTest starts the mode test,
 * EvaluateMode is used to fail or pass a mode. If EvaluateMode
2557
 * isn't called within 15 seconds, the mode is failed automatically
2558 2559
 *
 * As refresh rates are handled by the X server, I don't think this
2560
 * Method is important
2561 2562 2563 2564 2565 2566 2567 2568 2569
 *
 * Params:
 *  Modes: An array of mode specifications
 *  NumModes: The number of modes in Modes
 *  Flags: Some flags...
 *
 * Returns:
 *  Returns DDERR_TESTFINISHED if flags contains DDSMT_ISTESTREQUIRED,
 *  if no modes are passed, DDERR_INVALIDPARAMS is returned,
2570
 *  otherwise DD_OK
2571 2572
 *
 *****************************************************************************/
2573
static HRESULT WINAPI ddraw7_StartModeTest(IDirectDraw7 *iface, SIZE *Modes, DWORD NumModes, DWORD Flags)
2574
{
2575 2576
    FIXME("iface %p, modes %p, mode_count %u, flags %#x partial stub!\n",
            iface, Modes, NumModes, Flags);
2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592

    /* This looks sane */
    if( (!Modes) || (NumModes == 0) ) return DDERR_INVALIDPARAMS;

    /* DDSMT_ISTESTREQUIRED asks if a mode test is necessary.
     * As it is not, DDERR_TESTFINISHED is returned
     * (hopefully that's correct
     *
    if(Flags & DDSMT_ISTESTREQUIRED) return DDERR_TESTFINISHED;
     * well, that value doesn't (yet) exist in the wine headers, so ignore it
     */

    return DD_OK;
}

/*****************************************************************************
2593
 * ddraw_recreate_surfaces_cb
2594
 *
2595
 * Enumeration callback for ddraw_recreate_surface.
2596
 * It re-recreates the WineD3DSurface. It's pretty straightforward
2597 2598
 *
 *****************************************************************************/
2599
HRESULT WINAPI ddraw_recreate_surfaces_cb(IDirectDrawSurface7 *surf, DDSURFACEDESC2 *desc, void *Context)
2600
{
2601
    IDirectDrawSurfaceImpl *surfImpl = impl_from_IDirectDrawSurface7(surf);
2602
    struct wined3d_resource_desc wined3d_desc;
2603
    struct wined3d_resource *wined3d_resource;
2604
    IDirectDrawImpl *This = surfImpl->ddraw;
2605
    struct wined3d_surface *wined3d_surface;
2606
    struct wined3d_swapchain *swapchain;
2607
    struct wined3d_clipper *clipper;
2608
    void *parent;
2609 2610
    HRESULT hr;

2611 2612
    TRACE("surface %p, surface_desc %p, context %p.\n",
            surf, desc, Context);
2613 2614 2615 2616 2617 2618 2619

    /* For the enumeration */
    IDirectDrawSurface7_Release(surf);

    if(surfImpl->ImplType == This->ImplType) return DDENUMRET_OK; /* Continue */

    /* Get the objects */
2620 2621
    swapchain = surfImpl->wined3d_swapchain;
    surfImpl->wined3d_swapchain = NULL;
2622
    wined3d_surface = surfImpl->wined3d_surface;
2623

2624
    /* get the clipper */
2625
    clipper = wined3d_surface_get_clipper(wined3d_surface);
2626 2627

    /* Get the surface properties */
2628
    wined3d_resource = wined3d_surface_get_resource(wined3d_surface);
2629
    wined3d_resource_get_desc(wined3d_resource, &wined3d_desc);
2630

2631
    parent = wined3d_surface_get_parent(wined3d_surface);
2632
    hr = wined3d_surface_create(This->wined3d_device, wined3d_desc.width, wined3d_desc.height,
2633 2634
            wined3d_desc.format, TRUE, FALSE, surfImpl->mipmap_level, wined3d_desc.usage, wined3d_desc.pool,
            wined3d_desc.multisample_type, wined3d_desc.multisample_quality, This->ImplType,
2635
            parent, &ddraw_surface_wined3d_parent_ops, &surfImpl->wined3d_surface);
2636 2637
    if (FAILED(hr))
    {
2638
        surfImpl->wined3d_surface = wined3d_surface;
2639
        return hr;
2640
    }
2641

2642
    wined3d_surface_set_clipper(surfImpl->wined3d_surface, clipper);
2643

2644 2645
    /* TODO: Copy the surface content, except for render targets */

2646 2647 2648
    /* If there's a swapchain, it owns the wined3d surfaces. So Destroy
     * the swapchain
     */
2649 2650
    if (swapchain)
    {
2651
        /* The backbuffers have the swapchain set as well, but the primary
2652 2653
         * owns it and destroys it. */
        if (surfImpl->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
2654
            wined3d_device_uninit_gdi(This->wined3d_device);
2655
        surfImpl->isRenderTarget = FALSE;
2656 2657 2658 2659
    }
    else
    {
        if (!wined3d_surface_decref(wined3d_surface))
2660 2661 2662 2663
            TRACE("Surface released successful, next surface\n");
        else
            ERR("Something's still holding the old WineD3DSurface\n");
    }
2664 2665 2666 2667 2668 2669 2670

    surfImpl->ImplType = This->ImplType;

    return DDENUMRET_OK;
}

/*****************************************************************************
2671
 * ddraw_recreate_surfaces
2672 2673 2674
 *
 * A function, that converts all wineD3DSurfaces to the new implementation type
 * It enumerates all surfaces with IWineD3DDevice::EnumSurfaces, creates a
2675
 * new WineD3DSurface, copies the content and releases the old surface
2676 2677
 *
 *****************************************************************************/
2678
static HRESULT ddraw_recreate_surfaces(IDirectDrawImpl *This)
2679 2680 2681 2682 2683 2684 2685 2686 2687
{
    DDSURFACEDESC2 desc;
    TRACE("(%p): Switch to implementation %d\n", This, This->ImplType);

    if(This->ImplType != SURFACE_OPENGL && This->d3d_initialized)
    {
        /* Should happen almost never */
        FIXME("(%p) Switching to non-opengl surfaces with d3d started. Is this a bug?\n", This);
        /* Shutdown d3d */
2688
        wined3d_device_uninit_3d(This->wined3d_device);
2689 2690 2691 2692 2693 2694
    }
    /* Contrary: D3D starting is handled by the caller, because it knows the render target */

    memset(&desc, 0, sizeof(desc));
    desc.dwSize = sizeof(desc);

2695 2696
    return IDirectDraw7_EnumSurfaces(&This->IDirectDraw7_iface, 0, &desc, This,
            ddraw_recreate_surfaces_cb);
2697 2698 2699
}

/*****************************************************************************
2700
 * ddraw_create_surface
2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712
 *
 * A helper function for IDirectDraw7::CreateSurface. It creates a new surface
 * with the passed parameters.
 *
 * Params:
 *  DDSD: Description of the surface to create
 *  Surf: Address to store the interface pointer at
 *
 * Returns:
 *  DD_OK on success
 *
 *****************************************************************************/
2713 2714
static HRESULT ddraw_create_surface(IDirectDrawImpl *This, DDSURFACEDESC2 *pDDSD,
        IDirectDrawSurfaceImpl **ppSurf, UINT level)
2715 2716
{
    WINED3DSURFTYPE ImplType = This->ImplType;
2717
    HRESULT hr;
2718

2719 2720 2721
    TRACE("ddraw %p, surface_desc %p, surface %p, level %u.\n",
            This, pDDSD, ppSurf, level);

2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747
    if (TRACE_ON(ddraw))
    {
        TRACE(" (%p) Requesting surface desc :\n", This);
        DDRAW_dump_surface_desc(pDDSD);
    }

    /* Select the surface type, if it wasn't choosen yet */
    if(ImplType == SURFACE_UNKNOWN)
    {
        /* Use GL Surfaces if a D3DDEVICE Surface is requested */
        if(pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
        {
            TRACE("(%p) Choosing GL surfaces because a 3DDEVICE Surface was requested\n", This);
            ImplType = SURFACE_OPENGL;
        }

        /* Otherwise use GDI surfaces for now */
        else
        {
            TRACE("(%p) Choosing GDI surfaces for 2D rendering\n", This);
            ImplType = SURFACE_GDI;
        }

        /* Policy if all surface implementations are available:
         * First, check if a default type was set with winecfg. If not,
         * try Xrender surfaces, and use them if they work. Next, check if
2748 2749
         * accelerated OpenGL is available, and use GL surfaces in this
         * case. If all else fails, use GDI surfaces. If a 3DDEVICE surface
2750 2751
         * was created, always use OpenGL surfaces.
         *
2752 2753
         * (Note: Xrender surfaces are not implemented for now, the
         * unaccelerated implementation uses GDI to render in Software)
2754 2755 2756 2757 2758 2759 2760 2761 2762
         */

        /* Store the type. If it needs to be changed, all WineD3DSurfaces have to
         * be re-created. This could be done with IDirectDrawSurface7::Restore
         */
        This->ImplType = ImplType;
    }
    else
    {
2763 2764 2765
        if ((pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
                && (This->ImplType != SURFACE_OPENGL)
                && DefaultSurfaceType == SURFACE_UNKNOWN)
2766 2767 2768 2769 2770 2771 2772
        {
            /* We have to change to OpenGL,
             * and re-create all WineD3DSurfaces
             */
            ImplType = SURFACE_OPENGL;
            This->ImplType = ImplType;
            TRACE("(%p) Re-creating all surfaces\n", This);
2773
            ddraw_recreate_surfaces(This);
2774 2775
            TRACE("(%p) Done recreating all surfaces\n", This);
        }
2776
        else if(This->ImplType != SURFACE_OPENGL && pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789
        {
            WARN("The application requests a 3D capable surface, but a non-opengl surface was set in the registry\n");
            /* Do not fail surface creation, only fail 3D device creation */
        }
    }

    /* Create the Surface object */
    *ppSurf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirectDrawSurfaceImpl));
    if(!*ppSurf)
    {
        ERR("(%p) Error allocating memory for a surface\n", This);
        return DDERR_OUTOFVIDEOMEMORY;
    }
2790 2791 2792

    hr = ddraw_surface_init(*ppSurf, This, pDDSD, level, ImplType);
    if (FAILED(hr))
2793
    {
2794 2795
        WARN("Failed to initialize surface, hr %#x.\n", hr);
        HeapFree(GetProcessHeap(), 0, *ppSurf);
2796 2797 2798 2799 2800
        return hr;
    }

    /* Increase the surface counter, and attach the surface */
    InterlockedIncrement(&This->surfaces);
2801
    list_add_head(&This->surface_list, &(*ppSurf)->surface_list_entry);
2802

2803
    TRACE("Created surface %p.\n", *ppSurf);
2804 2805 2806

    return DD_OK;
}
2807 2808 2809 2810 2811 2812 2813 2814 2815 2816
/*****************************************************************************
 * CreateAdditionalSurfaces
 *
 * Creates a new mipmap chain.
 *
 * Params:
 *  root: Root surface to attach the newly created chain to
 *  count: number of surfaces to create
 *  DDSD: Description of the surface. Intentionally not a pointer to avoid side
 *        effects on the caller
2817
 *  CubeFaceRoot: Whether the new surface is a root of a cube map face. This
2818 2819 2820
 *                creates an additional surface without the mipmapping flags
 *
 *****************************************************************************/
2821 2822 2823 2824
static HRESULT
CreateAdditionalSurfaces(IDirectDrawImpl *This,
                         IDirectDrawSurfaceImpl *root,
                         UINT count,
2825 2826
                         DDSURFACEDESC2 DDSD,
                         BOOL CubeFaceRoot)
2827
{
2828
    UINT i, j, level = 0;
2829
    HRESULT hr;
2830
    IDirectDrawSurfaceImpl *last = root;
2831

2832 2833 2834 2835 2836 2837 2838
    for(i = 0; i < count; i++)
    {
        IDirectDrawSurfaceImpl *object2 = NULL;

        /* increase the mipmap level, but only if a mipmap is created
         * In this case, also halve the size
         */
2839
        if(DDSD.ddsCaps.dwCaps & DDSCAPS_MIPMAP && !CubeFaceRoot)
2840 2841
        {
            level++;
2842 2843 2844 2845
            if(DDSD.dwWidth > 1) DDSD.dwWidth /= 2;
            if(DDSD.dwHeight > 1) DDSD.dwHeight /= 2;
            /* Set the mipmap sublevel flag according to msdn */
            DDSD.ddsCaps.dwCaps2 |= DDSCAPS2_MIPMAPSUBLEVEL;
2846
        }
2847 2848 2849 2850 2851
        else
        {
            DDSD.ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
        }
        CubeFaceRoot = FALSE;
2852

2853
        hr = ddraw_create_surface(This, &DDSD, &object2, level);
2854 2855 2856 2857 2858
        if(hr != DD_OK)
        {
            return hr;
        }

2859
        /* Add the new surface to the complex attachment array */
2860 2861 2862 2863 2864 2865
        for(j = 0; j < MAX_COMPLEX_ATTACHED; j++)
        {
            if(last->complex_array[j]) continue;
            last->complex_array[j] = object2;
            break;
        }
2866
        last = object2;
2867 2868 2869 2870 2871

        /* Remove the (possible) back buffer cap from the new surface description,
         * because only one surface in the flipping chain is a back buffer, one
         * is a front buffer, the others are just primary surfaces.
         */
2872
        DDSD.ddsCaps.dwCaps &= ~DDSCAPS_BACKBUFFER;
2873 2874 2875 2876
    }
    return DD_OK;
}

2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895
/* Must set all attached surfaces (e.g. mipmaps) versions as well */
static void ddraw_set_surface_version(IDirectDrawSurfaceImpl *surface, UINT version)
{
    unsigned int i;

    TRACE("surface %p, version %u -> %u.\n", surface, surface->version, version);

    surface->version = version;
    for (i = 0; i < MAX_COMPLEX_ATTACHED; ++i)
    {
        if (!surface->complex_array[i]) break;
        ddraw_set_surface_version(surface->complex_array[i], version);
    }
    while ((surface = surface->next_attached))
    {
        ddraw_set_surface_version(surface, version);
    }
}

2896
/*****************************************************************************
2897
 * ddraw_attach_d3d_device
2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908
 *
 * Initializes the D3D capabilities of WineD3D
 *
 * Params:
 *  primary: The primary surface for D3D
 *
 * Returns
 *  DD_OK on success,
 *  DDERR_* otherwise
 *
 *****************************************************************************/
2909
static HRESULT ddraw_attach_d3d_device(IDirectDrawImpl *ddraw, IDirectDrawSurfaceImpl *primary)
2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956
{
    WINED3DPRESENT_PARAMETERS localParameters;
    HWND window = ddraw->dest_window;
    HRESULT hr;

    TRACE("ddraw %p, primary %p.\n", ddraw, primary);

    if (!window || window == GetDesktopWindow())
    {
        window = CreateWindowExA(0, DDRAW_WINDOW_CLASS_NAME, "Hidden D3D Window",
                WS_DISABLED, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
                NULL, NULL, NULL, NULL);
        if (!window)
        {
            ERR("Failed to create window, last error %#x.\n", GetLastError());
            return E_FAIL;
        }

        ShowWindow(window, SW_HIDE);   /* Just to be sure */
        WARN("No window for the Direct3DDevice, created hidden window %p.\n", window);
    }
    else
    {
        TRACE("Using existing window %p for Direct3D rendering.\n", window);
    }
    ddraw->d3d_window = window;

    /* Store the future Render Target surface */
    ddraw->d3d_target = primary;

    /* Use the surface description for the device parameters, not the device
     * settings. The application might render to an offscreen surface. */
    localParameters.BackBufferWidth = primary->surface_desc.dwWidth;
    localParameters.BackBufferHeight = primary->surface_desc.dwHeight;
    localParameters.BackBufferFormat = PixelFormat_DD2WineD3D(&primary->surface_desc.u4.ddpfPixelFormat);
    localParameters.BackBufferCount = (primary->surface_desc.dwFlags & DDSD_BACKBUFFERCOUNT)
            ? primary->surface_desc.dwBackBufferCount : 0;
    localParameters.MultiSampleType = WINED3DMULTISAMPLE_NONE;
    localParameters.MultiSampleQuality = 0;
    localParameters.SwapEffect = WINED3DSWAPEFFECT_COPY;
    localParameters.hDeviceWindow = window;
    localParameters.Windowed = !(ddraw->cooperative_level & DDSCL_FULLSCREEN);
    localParameters.EnableAutoDepthStencil = TRUE;
    localParameters.AutoDepthStencilFormat = WINED3DFMT_D16_UNORM;
    localParameters.Flags = 0;
    localParameters.FullScreen_RefreshRateInHz = WINED3DPRESENT_RATE_DEFAULT;
    localParameters.PresentationInterval = WINED3DPRESENT_INTERVAL_DEFAULT;
2957
    localParameters.AutoRestoreDisplayMode = FALSE;
2958 2959 2960 2961

    /* Set this NOW, otherwise creating the depth stencil surface will cause a
     * recursive loop until ram or emulated video memory is full. */
    ddraw->d3d_initialized = TRUE;
2962
    hr = wined3d_device_init_3d(ddraw->wined3d_device, &localParameters);
2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975
    if (FAILED(hr))
    {
        ddraw->d3d_target = NULL;
        ddraw->d3d_initialized = FALSE;
        return hr;
    }

    ddraw->declArraySize = 2;
    ddraw->decls = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ddraw->decls) * ddraw->declArraySize);
    if (!ddraw->decls)
    {
        ERR("Error allocating an array for the converted vertex decls.\n");
        ddraw->declArraySize = 0;
2976
        hr = wined3d_device_uninit_3d(ddraw->wined3d_device);
2977 2978 2979 2980 2981 2982 2983 2984
        return E_OUTOFMEMORY;
    }

    TRACE("Successfully initialized 3D.\n");

    return DD_OK;
}

2985
static HRESULT ddraw_create_gdi_swapchain(IDirectDrawImpl *ddraw, IDirectDrawSurfaceImpl *primary)
2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011
{
    WINED3DPRESENT_PARAMETERS presentation_parameters;
    HWND window;
    HRESULT hr;

    window = ddraw->dest_window;

    memset(&presentation_parameters, 0, sizeof(presentation_parameters));

    /* Use the surface description for the device parameters, not the device
     * settings. The application might render to an offscreen surface. */
    presentation_parameters.BackBufferWidth = primary->surface_desc.dwWidth;
    presentation_parameters.BackBufferHeight = primary->surface_desc.dwHeight;
    presentation_parameters.BackBufferFormat = PixelFormat_DD2WineD3D(&primary->surface_desc.u4.ddpfPixelFormat);
    presentation_parameters.BackBufferCount = (primary->surface_desc.dwFlags & DDSD_BACKBUFFERCOUNT)
            ? primary->surface_desc.dwBackBufferCount : 0;
    presentation_parameters.MultiSampleType = WINED3DMULTISAMPLE_NONE;
    presentation_parameters.MultiSampleQuality = 0;
    presentation_parameters.SwapEffect = WINED3DSWAPEFFECT_FLIP;
    presentation_parameters.hDeviceWindow = window;
    presentation_parameters.Windowed = !(ddraw->cooperative_level & DDSCL_FULLSCREEN);
    presentation_parameters.EnableAutoDepthStencil = FALSE; /* Not on GDI swapchains */
    presentation_parameters.AutoDepthStencilFormat = 0;
    presentation_parameters.Flags = 0;
    presentation_parameters.FullScreen_RefreshRateInHz = WINED3DPRESENT_RATE_DEFAULT;
    presentation_parameters.PresentationInterval = WINED3DPRESENT_INTERVAL_DEFAULT;
3012
    presentation_parameters.AutoRestoreDisplayMode = FALSE;
3013 3014

    ddraw->d3d_target = primary;
3015
    hr = wined3d_device_init_gdi(ddraw->wined3d_device, &presentation_parameters);
3016 3017 3018 3019
    ddraw->d3d_target = NULL;
    if (FAILED(hr))
    {
        WARN("Failed to initialize GDI ddraw implementation, hr %#x.\n", hr);
3020
        primary->wined3d_swapchain = NULL;
3021 3022 3023 3024 3025
    }

    return hr;
}

3026 3027 3028
/*****************************************************************************
 * IDirectDraw7::CreateSurface
 *
3029
 * Creates a new IDirectDrawSurface object and returns its interface.
3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044
 *
 * The surface connections with wined3d are a bit tricky. Basically it works
 * like this:
 *
 * |------------------------|               |-----------------|
 * | DDraw surface          |               | WineD3DSurface  |
 * |                        |               |                 |
 * |        WineD3DSurface  |-------------->|                 |
 * |        Child           |<------------->| Parent          |
 * |------------------------|               |-----------------|
 *
 * The DDraw surface is the parent of the wined3d surface, and it releases
 * the WineD3DSurface when the ddraw surface is destroyed.
 *
 * However, for all surfaces which can be in a container in WineD3D,
Austin English's avatar
Austin English committed
3045
 * we have to do this. These surfaces are usually complex surfaces,
3046 3047
 * so this concerns primary surfaces with a front and a back buffer,
 * and textures.
3048 3049
 *
 * |------------------------|               |-----------------|
Austin English's avatar
Austin English committed
3050
 * | DDraw surface          |               | Container       |
3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102
 * |                        |               |                 |
 * |                  Child |<------------->| Parent          |
 * |                Texture |<------------->|                 |
 * |         WineD3DSurface |<----|         |          Levels |<--|
 * | Complex connection     |     |         |                 |   |
 * |------------------------|     |         |-----------------|   |
 *  ^                             |                               |
 *  |                             |                               |
 *  |                             |                               |
 *  |    |------------------|     |         |-----------------|   |
 *  |    | IParent          |     |-------->| WineD3DSurface  |   |
 *  |    |                  |               |                 |   |
 *  |    |            Child |<------------->| Parent          |   |
 *  |    |                  |               |       Container |<--|
 *  |    |------------------|               |-----------------|   |
 *  |                                                             |
 *  |   |----------------------|                                  |
 *  |   | DDraw surface 2      |                                  |
 *  |   |                      |                                  |
 *  |<->| Complex root   Child |                                  |
 *  |   |              Texture |                                  |
 *  |   |       WineD3DSurface |<----|                            |
 *  |   |----------------------|     |                            |
 *  |                                |                            |
 *  |    |---------------------|     |      |-----------------|   |
 *  |    | IParent             |     |----->| WineD3DSurface  |   |
 *  |    |                     |            |                 |   |
 *  |    |               Child |<---------->| Parent          |   |
 *  |    |---------------------|            |       Container |<--|
 *  |                                       |-----------------|   |
 *  |                                                             |
 *  |             ---More surfaces can follow---                  |
 *
 * The reason is that the IWineD3DSwapchain(render target container)
 * and the IWineD3DTexure(Texture container) release the parents
 * of their surface's children, but by releasing the complex root
 * the surfaces which are complexly attached to it are destroyed
 * too. See IDirectDrawSurface::Release for a more detailed
 * explanation.
 *
 * Params:
 *  DDSD: Description of the surface to create
 *  Surf: Address to store the interface pointer at
 *  UnkOuter: Basically for aggregation support, but ddraw doesn't support
 *            aggregation, so it has to be NULL
 *
 * Returns:
 *  DD_OK on success
 *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
 *  DDERR_* if an error occurs
 *
 *****************************************************************************/
3103
static HRESULT CreateSurface(IDirectDrawImpl *ddraw, DDSURFACEDESC2 *DDSD,
3104
        IDirectDrawSurfaceImpl **Surf, IUnknown *UnkOuter)
3105 3106 3107
{
    IDirectDrawSurfaceImpl *object = NULL;
    HRESULT hr;
3108
    LONG extra_surfaces = 0;
3109 3110
    DDSURFACEDESC2 desc2;
    WINED3DDISPLAYMODE Mode;
3111
    const DWORD sysvidmem = DDSCAPS_VIDEOMEMORY | DDSCAPS_SYSTEMMEMORY;
3112

3113
    TRACE("ddraw %p, surface_desc %p, surface %p, outer_unknown %p.\n", ddraw, DDSD, Surf, UnkOuter);
3114 3115 3116 3117

    /* Some checks before we start */
    if (TRACE_ON(ddraw))
    {
3118
        TRACE(" (%p) Requesting surface desc :\n", ddraw);
3119 3120
        DDRAW_dump_surface_desc(DDSD);
    }
3121
    EnterCriticalSection(&ddraw_cs);
3122 3123 3124

    if (UnkOuter != NULL)
    {
3125
        FIXME("(%p) : outer != NULL?\n", ddraw);
3126
        LeaveCriticalSection(&ddraw_cs);
3127 3128 3129
        return CLASS_E_NOAGGREGATION; /* unchecked */
    }

3130 3131
    if (Surf == NULL)
    {
3132
        FIXME("(%p) You want to get back a surface? Don't give NULL ptrs!\n", ddraw);
3133
        LeaveCriticalSection(&ddraw_cs);
3134 3135 3136
        return E_POINTER; /* unchecked */
    }

3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151
    if (!(DDSD->dwFlags & DDSD_CAPS))
    {
        /* DVIDEO.DLL does forget the DDSD_CAPS flag ... *sigh* */
        DDSD->dwFlags |= DDSD_CAPS;
    }

    if (DDSD->ddsCaps.dwCaps & DDSCAPS_ALLOCONLOAD)
    {
        /* If the surface is of the 'alloconload' type, ignore the LPSURFACE field */
        DDSD->dwFlags &= ~DDSD_LPSURFACE;
    }

    if ((DDSD->dwFlags & DDSD_LPSURFACE) && (DDSD->lpSurface == NULL))
    {
        /* Frank Herbert's Dune specifies a null pointer for the surface, ignore the LPSURFACE field */
3152
        WARN("(%p) Null surface pointer specified, ignore it!\n", ddraw);
3153 3154 3155
        DDSD->dwFlags &= ~DDSD_LPSURFACE;
    }

3156
    if((DDSD->ddsCaps.dwCaps & (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE)) == (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE) &&
3157
       !(ddraw->cooperative_level & DDSCL_EXCLUSIVE))
3158
    {
3159 3160
        TRACE("(%p): Attempt to create a flipable primary surface without DDSCL_EXCLUSIVE set\n",
                ddraw);
3161
        *Surf = NULL;
3162
        LeaveCriticalSection(&ddraw_cs);
3163 3164 3165
        return DDERR_NOEXCLUSIVEMODE;
    }

3166 3167 3168
    if((DDSD->ddsCaps.dwCaps & (DDSCAPS_BACKBUFFER | DDSCAPS_PRIMARYSURFACE)) == (DDSCAPS_BACKBUFFER | DDSCAPS_PRIMARYSURFACE))
    {
        WARN("Application wanted to create back buffer primary surface\n");
3169
        LeaveCriticalSection(&ddraw_cs);
3170
        return DDERR_INVALIDCAPS;
3171
    }
3172 3173 3174 3175 3176 3177 3178 3179 3180 3181

    if((DDSD->ddsCaps.dwCaps & sysvidmem) == sysvidmem)
    {
        /* This is a special switch in ddrawex.dll, but not allowed in ddraw.dll */
        WARN("Application tries to put the surface in both system and video memory\n");
        LeaveCriticalSection(&ddraw_cs);
        *Surf = NULL;
        return DDERR_INVALIDCAPS;
    }

3182 3183 3184 3185 3186 3187 3188
    /* Check cube maps but only if the size includes them */
    if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
    {
        if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES &&
           !(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP))
        {
            WARN("Cube map faces requested without cube map flag\n");
3189
            LeaveCriticalSection(&ddraw_cs);
3190 3191 3192 3193 3194 3195
            return DDERR_INVALIDCAPS;
        }
        if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
           (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) == 0)
        {
            WARN("Cube map without faces requested\n");
3196
            LeaveCriticalSection(&ddraw_cs);
3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207
            return DDERR_INVALIDPARAMS;
        }

        /* Quick tests confirm those can be created, but we don't do that yet */
        if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
           (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) != DDSCAPS2_CUBEMAP_ALLFACES)
        {
            FIXME("Partial cube maps not supported yet\n");
        }
    }

3208
    /* According to the msdn this flag is ignored by CreateSurface */
3209 3210
    if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
        DDSD->ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
3211

3212
    /* Modify some flags */
3213
    copy_to_surfacedesc2(&desc2, DDSD);
3214 3215 3216
    desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT); /* Just to be sure */

    /* Get the video mode from WineD3D - we will need it */
3217 3218
    hr = wined3d_device_get_display_mode(ddraw->wined3d_device, 0, &Mode);
    if (FAILED(hr))
3219 3220
    {
        ERR("Failed to read display mode from wined3d\n");
3221
        switch(ddraw->orig_bpp)
3222 3223
        {
            case 8:
3224
                Mode.Format = WINED3DFMT_P8_UINT;
3225 3226 3227
                break;

            case 15:
3228
                Mode.Format = WINED3DFMT_B5G5R5X1_UNORM;
3229 3230 3231
                break;

            case 16:
3232
                Mode.Format = WINED3DFMT_B5G6R5_UNORM;
3233 3234 3235
                break;

            case 24:
3236
                Mode.Format = WINED3DFMT_B8G8R8_UNORM;
3237 3238 3239
                break;

            case 32:
3240
                Mode.Format = WINED3DFMT_B8G8R8X8_UNORM;
3241 3242
                break;
        }
3243 3244
        Mode.Width = ddraw->orig_width;
        Mode.Height = ddraw->orig_height;
3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255
    }

    /* No pixelformat given? Use the current screen format */
    if(!(desc2.dwFlags & DDSD_PIXELFORMAT))
    {
        desc2.dwFlags |= DDSD_PIXELFORMAT;
        desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT);

        /* Wait: It could be a Z buffer */
        if(desc2.ddsCaps.dwCaps & DDSCAPS_ZBUFFER)
        {
3256
            switch(desc2.u2.dwMipMapCount) /* Who had this glorious idea? */
3257 3258
            {
                case 15:
3259
                    PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_S1_UINT_D15_UNORM);
3260 3261
                    break;
                case 16:
3262
                    PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D16_UNORM);
3263 3264
                    break;
                case 24:
3265
                    PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_X8D24_UNORM);
3266 3267
                    break;
                case 32:
3268
                    PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D32_UNORM);
3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279
                    break;
                default:
                    ERR("Unknown Z buffer bit depth\n");
            }
        }
        else
        {
            PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, Mode.Format);
        }
    }

3280
    /* No Width or no Height? Use the original screen size
3281 3282 3283 3284
     */
    if(!(desc2.dwFlags & DDSD_WIDTH) ||
       !(desc2.dwFlags & DDSD_HEIGHT) )
    {
3285 3286 3287 3288 3289
        /* Invalid for non-render targets */
        if(!(desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE))
        {
            WARN("Creating a non-Primary surface without Width or Height info, returning DDERR_INVALIDPARAMS\n");
            *Surf = NULL;
3290
            LeaveCriticalSection(&ddraw_cs);
3291 3292
            return DDERR_INVALIDPARAMS;
        }
3293 3294 3295 3296 3297 3298

        desc2.dwFlags |= DDSD_WIDTH | DDSD_HEIGHT;
        desc2.dwWidth = Mode.Width;
        desc2.dwHeight = Mode.Height;
    }

3299 3300 3301 3302 3303 3304
    if (!desc2.dwWidth || !desc2.dwHeight)
    {
        LeaveCriticalSection(&ddraw_cs);
        return DDERR_INVALIDPARAMS;
    }

3305 3306 3307 3308 3309 3310 3311
    /* Mipmap count fixes */
    if(desc2.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
    {
        if(desc2.ddsCaps.dwCaps & DDSCAPS_COMPLEX)
        {
            if(desc2.dwFlags & DDSD_MIPMAPCOUNT)
            {
3312 3313 3314 3315 3316 3317
                /* Mipmap count is given, should not be 0 */
                if( desc2.u2.dwMipMapCount == 0 )
                {
                    LeaveCriticalSection(&ddraw_cs);
                    return DDERR_INVALIDPARAMS;
                }
3318 3319 3320 3321
            }
            else
            {
                /* Undocumented feature: Create sublevels until
3322
                 * either the width or the height is 1
3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351
                 */
                DWORD min = desc2.dwWidth < desc2.dwHeight ?
                            desc2.dwWidth : desc2.dwHeight;
                desc2.u2.dwMipMapCount = 0;
                while( min )
                {
                    desc2.u2.dwMipMapCount += 1;
                    min >>= 1;
                }
            }
        }
        else
        {
            /* Not-complex mipmap -> Mipmapcount = 1 */
            desc2.u2.dwMipMapCount = 1;
        }
        extra_surfaces = desc2.u2.dwMipMapCount - 1;

        /* There's a mipmap count in the created surface in any case */
        desc2.dwFlags |= DDSD_MIPMAPCOUNT;
    }
    /* If no mipmap is given, the texture has only one level */

    /* The first surface is a front buffer, the back buffer is created afterwards */
    if( (desc2.dwFlags & DDSD_CAPS) && (desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) )
    {
        desc2.ddsCaps.dwCaps |= DDSCAPS_FRONTBUFFER;
    }

3352 3353 3354 3355 3356 3357 3358
    /* The root surface in a cube map is positive x */
    if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
    {
        desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
        desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
    }

3359
    /* Create the first surface */
3360
    hr = ddraw_create_surface(ddraw, &desc2, &object, 0);
3361
    if (FAILED(hr))
3362
    {
3363
        WARN("ddraw_create_surface failed, hr %#x.\n", hr);
3364
        LeaveCriticalSection(&ddraw_cs);
3365 3366
        return hr;
    }
3367
    object->is_complex_root = TRUE;
3368

3369
    *Surf = object;
3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380

    /* Create Additional surfaces if necessary
     * This applies to Primary surfaces which have a back buffer count
     * set, but not to mipmap textures. In case of Mipmap textures,
     * wineD3D takes care of the creation of additional surfaces
     */
    if(DDSD->dwFlags & DDSD_BACKBUFFERCOUNT)
    {
        extra_surfaces = DDSD->dwBackBufferCount;
        desc2.ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER; /* It's not a front buffer */
        desc2.ddsCaps.dwCaps |= DDSCAPS_BACKBUFFER;
3381
        desc2.dwBackBufferCount = 0;
3382 3383
    }

3384 3385 3386 3387 3388
    hr = DD_OK;
    if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
    {
        desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
        desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEZ;
3389
        hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE);
3390 3391
        desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEZ;
        desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEZ;
3392
        hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE);
3393 3394
        desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_POSITIVEZ;
        desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEY;
3395
        hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE);
3396 3397
        desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEY;
        desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEY;
3398
        hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE);
3399 3400
        desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_POSITIVEY;
        desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEX;
3401
        hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces + 1, desc2, TRUE);
3402 3403 3404 3405
        desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEX;
        desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
    }

3406
    hr |= CreateAdditionalSurfaces(ddraw, object, extra_surfaces, desc2, FALSE);
3407
    if(hr != DD_OK)
3408
    {
3409
        /* This destroys and possibly created surfaces too */
3410
        IDirectDrawSurface7_Release(&object->IDirectDrawSurface7_iface);
3411
        LeaveCriticalSection(&ddraw_cs);
3412
        return hr;
3413 3414 3415 3416
    }

    /* If the implementation is OpenGL and there's no d3ddevice, attach a d3ddevice
     * But attach the d3ddevice only if the currently created surface was
3417
     * a primary surface (2D app in 3D mode) or a 3DDEVICE surface (3D app)
3418 3419 3420 3421 3422
     * The only case I can think of where this doesn't apply is when a
     * 2D app was configured by the user to run with OpenGL and it didn't create
     * the render target as first surface. In this case the render target creation
     * will cause the 3D init.
     */
3423
    if( (ddraw->ImplType == SURFACE_OPENGL) && !(ddraw->d3d_initialized) &&
3424 3425
        desc2.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_3DDEVICE) )
    {
3426 3427
        IDirectDrawSurfaceImpl *target = object, *surface;
        struct list *entry;
3428 3429

        /* Search for the primary to use as render target */
3430
        LIST_FOR_EACH(entry, &ddraw->surface_list)
3431
        {
3432
            surface = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
3433 3434
            if((surface->surface_desc.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_FRONTBUFFER)) ==
               (DDSCAPS_PRIMARYSURFACE | DDSCAPS_FRONTBUFFER))
3435 3436
            {
                /* found */
3437
                target = surface;
3438 3439 3440 3441 3442
                TRACE("Using primary %p as render target\n", target);
                break;
            }
        }

3443 3444
        TRACE("(%p) Attaching a D3DDevice, rendertarget = %p\n", ddraw, target);
        hr = ddraw_attach_d3d_device(ddraw, target);
3445
        if (hr != D3D_OK)
3446
        {
3447
            IDirectDrawSurfaceImpl *release_surf;
3448
            ERR("ddraw_attach_d3d_device failed, hr %#x\n", hr);
3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461
            *Surf = NULL;

            /* The before created surface structures are in an incomplete state here.
             * WineD3D holds the reference on the IParents, and it released them on the failure
             * already. So the regular release method implementation would fail on the attempt
             * to destroy either the IParents or the swapchain. So free the surface here.
             * The surface structure here is a list, not a tree, because onscreen targets
             * cannot be cube textures
             */
            while(object)
            {
                release_surf = object;
                object = object->complex_array[0];
3462
                ddraw_surface_destroy(release_surf);
3463 3464 3465
            }
            LeaveCriticalSection(&ddraw_cs);
            return hr;
3466
        }
3467
    }
3468
    else if(!(ddraw->d3d_initialized) && desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
3469
    {
3470
        ddraw_create_gdi_swapchain(ddraw, object);
3471 3472
    }

3473
    /* Addref the ddraw interface to keep an reference for each surface */
3474 3475
    IDirectDraw7_AddRef(&ddraw->IDirectDraw7_iface);
    object->ifaceToRelease = (IUnknown *)&ddraw->IDirectDraw7_iface;
3476

3477
    /* Create a WineD3DTexture if a texture was requested */
3478
    if (desc2.ddsCaps.dwCaps & DDSCAPS_TEXTURE)
3479
    {
3480
        ddraw->tex_root = object;
3481
        ddraw_surface_create_texture(object);
3482
        ddraw->tex_root = NULL;
3483 3484
    }

3485
    LeaveCriticalSection(&ddraw_cs);
3486 3487 3488
    return hr;
}

3489 3490
static HRESULT WINAPI ddraw7_CreateSurface(IDirectDraw7 *iface, DDSURFACEDESC2 *surface_desc,
        IDirectDrawSurface7 **surface, IUnknown *outer_unknown)
3491
{
3492
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
3493 3494
    IDirectDrawSurfaceImpl *impl;
    HRESULT hr;
3495

3496 3497 3498
    TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
            iface, surface_desc, surface, outer_unknown);

3499 3500 3501 3502 3503 3504
    if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC2))
    {
        WARN("Application supplied invalid surface descriptor\n");
        return DDERR_INVALIDPARAMS;
    }

3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516
    if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
    {
        if (TRACE_ON(ddraw))
        {
            TRACE(" (%p) Requesting surface desc :\n", iface);
            DDRAW_dump_surface_desc(surface_desc);
        }

        WARN("Application tried to create an explicit front or back buffer\n");
        return DDERR_INVALIDCAPS;
    }

3517 3518 3519 3520 3521 3522 3523
    hr = CreateSurface(This, surface_desc, &impl, outer_unknown);
    if (FAILED(hr))
    {
        *surface = NULL;
        return hr;
    }

3524
    *surface = &impl->IDirectDrawSurface7_iface;
3525 3526

    return hr;
3527 3528
}

3529 3530 3531
static HRESULT WINAPI ddraw4_CreateSurface(IDirectDraw4 *iface,
        DDSURFACEDESC2 *surface_desc, IDirectDrawSurface4 **surface, IUnknown *outer_unknown)
{
3532
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
3533 3534 3535 3536 3537 3538
    IDirectDrawSurfaceImpl *impl;
    HRESULT hr;

    TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
            iface, surface_desc, surface, outer_unknown);

3539 3540 3541 3542 3543 3544
    if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC2))
    {
        WARN("Application supplied invalid surface descriptor\n");
        return DDERR_INVALIDPARAMS;
    }

3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556
    if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
    {
        if (TRACE_ON(ddraw))
        {
            TRACE(" (%p) Requesting surface desc :\n", iface);
            DDRAW_dump_surface_desc(surface_desc);
        }

        WARN("Application tried to create an explicit front or back buffer\n");
        return DDERR_INVALIDCAPS;
    }

3557 3558
    hr = CreateSurface(This, surface_desc, &impl, outer_unknown);
    if (FAILED(hr))
3559
    {
3560 3561
        *surface = NULL;
        return hr;
3562 3563
    }

3564
    *surface = &impl->IDirectDrawSurface4_iface;
3565 3566 3567 3568 3569
    ddraw_set_surface_version(impl, 4);
    IDirectDraw7_Release(&This->IDirectDraw7_iface);
    IDirectDraw4_AddRef(iface);
    impl->ifaceToRelease = (IUnknown *)iface;

3570 3571 3572
    return hr;
}

3573 3574
static HRESULT WINAPI ddraw3_CreateSurface(IDirectDraw3 *iface, DDSURFACEDESC *surface_desc,
        IDirectDrawSurface **surface, IUnknown *outer_unknown)
3575
{
3576
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
3577 3578 3579 3580 3581 3582
    IDirectDrawSurfaceImpl *impl;
    HRESULT hr;

    TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
            iface, surface_desc, surface, outer_unknown);

3583 3584 3585 3586 3587 3588
    if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC))
    {
        WARN("Application supplied invalid surface descriptor\n");
        return DDERR_INVALIDPARAMS;
    }

3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600
    if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
    {
        if (TRACE_ON(ddraw))
        {
            TRACE(" (%p) Requesting surface desc :\n", iface);
            DDRAW_dump_surface_desc((LPDDSURFACEDESC2)surface_desc);
        }

        WARN("Application tried to create an explicit front or back buffer\n");
        return DDERR_INVALIDCAPS;
    }

3601
    hr = CreateSurface(This, (DDSURFACEDESC2 *)surface_desc, &impl, outer_unknown);
3602 3603 3604 3605 3606 3607
    if (FAILED(hr))
    {
        *surface = NULL;
        return hr;
    }

3608
    *surface = (IDirectDrawSurface *)&impl->IDirectDrawSurface3_iface;
3609
    ddraw_set_surface_version(impl, 3);
3610
    IDirectDraw7_Release(&This->IDirectDraw7_iface);
3611 3612 3613 3614 3615 3616 3617 3618 3619
    IDirectDraw3_AddRef(iface);
    impl->ifaceToRelease = (IUnknown *)iface;

    return hr;
}

static HRESULT WINAPI ddraw2_CreateSurface(IDirectDraw2 *iface,
        DDSURFACEDESC *surface_desc, IDirectDrawSurface **surface, IUnknown *outer_unknown)
{
3620
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
3621 3622 3623 3624 3625 3626
    IDirectDrawSurfaceImpl *impl;
    HRESULT hr;

    TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
            iface, surface_desc, surface, outer_unknown);

3627 3628 3629 3630 3631 3632
    if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC))
    {
        WARN("Application supplied invalid surface descriptor\n");
        return DDERR_INVALIDPARAMS;
    }

3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644
    if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
    {
        if (TRACE_ON(ddraw))
        {
            TRACE(" (%p) Requesting surface desc :\n", iface);
            DDRAW_dump_surface_desc((LPDDSURFACEDESC2)surface_desc);
        }

        WARN("Application tried to create an explicit front or back buffer\n");
        return DDERR_INVALIDCAPS;
    }

3645
    hr = CreateSurface(This, (DDSURFACEDESC2 *)surface_desc, &impl, outer_unknown);
3646 3647 3648 3649 3650 3651
    if (FAILED(hr))
    {
        *surface = NULL;
        return hr;
    }

3652
    *surface = (IDirectDrawSurface *)&impl->IDirectDrawSurface3_iface;
3653
    ddraw_set_surface_version(impl, 2);
3654
    IDirectDraw7_Release(&This->IDirectDraw7_iface);
3655 3656 3657 3658 3659 3660 3661 3662
    impl->ifaceToRelease = NULL;

    return hr;
}

static HRESULT WINAPI ddraw1_CreateSurface(IDirectDraw *iface,
        DDSURFACEDESC *surface_desc, IDirectDrawSurface **surface, IUnknown *outer_unknown)
{
3663
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
3664 3665 3666 3667 3668 3669
    IDirectDrawSurfaceImpl *impl;
    HRESULT hr;

    TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
            iface, surface_desc, surface, outer_unknown);

3670 3671 3672 3673 3674 3675
    if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC))
    {
        WARN("Application supplied invalid surface descriptor\n");
        return DDERR_INVALIDPARAMS;
    }

3676 3677 3678
    /* Remove front buffer flag, this causes failure in v7, and its added to normal
     * primaries anyway. */
    surface_desc->ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER;
3679
    hr = CreateSurface(This, (DDSURFACEDESC2 *)surface_desc, &impl, outer_unknown);
3680 3681 3682 3683 3684 3685
    if (FAILED(hr))
    {
        *surface = NULL;
        return hr;
    }

3686
    *surface = (IDirectDrawSurface *)&impl->IDirectDrawSurface3_iface;
3687
    ddraw_set_surface_version(impl, 1);
3688
    IDirectDraw7_Release(&This->IDirectDraw7_iface);
3689 3690 3691 3692 3693
    impl->ifaceToRelease = NULL;

    return hr;
}

3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742
#define DDENUMSURFACES_SEARCHTYPE (DDENUMSURFACES_CANBECREATED|DDENUMSURFACES_DOESEXIST)
#define DDENUMSURFACES_MATCHTYPE (DDENUMSURFACES_ALL|DDENUMSURFACES_MATCH|DDENUMSURFACES_NOMATCH)

static BOOL
Main_DirectDraw_DDPIXELFORMAT_Match(const DDPIXELFORMAT *requested,
                                    const DDPIXELFORMAT *provided)
{
    /* Some flags must be present in both or neither for a match. */
    static const DWORD must_match = DDPF_PALETTEINDEXED1 | DDPF_PALETTEINDEXED2
        | DDPF_PALETTEINDEXED4 | DDPF_PALETTEINDEXED8 | DDPF_FOURCC
        | DDPF_ZBUFFER | DDPF_STENCILBUFFER;

    if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
        return FALSE;

    if ((requested->dwFlags & must_match) != (provided->dwFlags & must_match))
        return FALSE;

    if (requested->dwFlags & DDPF_FOURCC)
        if (requested->dwFourCC != provided->dwFourCC)
            return FALSE;

    if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_ALPHA
                              |DDPF_LUMINANCE|DDPF_BUMPDUDV))
        if (requested->u1.dwRGBBitCount != provided->u1.dwRGBBitCount)
            return FALSE;

    if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
                              |DDPF_LUMINANCE|DDPF_BUMPDUDV))
        if (requested->u2.dwRBitMask != provided->u2.dwRBitMask)
            return FALSE;

    if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_BUMPDUDV))
        if (requested->u3.dwGBitMask != provided->u3.dwGBitMask)
            return FALSE;

    /* I could be wrong about the bumpmapping. MSDN docs are vague. */
    if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
                              |DDPF_BUMPDUDV))
        if (requested->u4.dwBBitMask != provided->u4.dwBBitMask)
            return FALSE;

    if (requested->dwFlags & (DDPF_ALPHAPIXELS|DDPF_ZPIXELS))
        if (requested->u5.dwRGBAlphaBitMask != provided->u5.dwRGBAlphaBitMask)
            return FALSE;

    return TRUE;
}

3743
static BOOL ddraw_match_surface_desc(const DDSURFACEDESC2 *requested, const DDSURFACEDESC2 *provided)
3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805
{
    struct compare_info
    {
        DWORD flag;
        ptrdiff_t offset;
        size_t size;
    };

#define CMP(FLAG, FIELD)                                \
        { DDSD_##FLAG, offsetof(DDSURFACEDESC2, FIELD), \
          sizeof(((DDSURFACEDESC2 *)(NULL))->FIELD) }

    static const struct compare_info compare[] =
    {
        CMP(ALPHABITDEPTH, dwAlphaBitDepth),
        CMP(BACKBUFFERCOUNT, dwBackBufferCount),
        CMP(CAPS, ddsCaps),
        CMP(CKDESTBLT, ddckCKDestBlt),
        CMP(CKDESTOVERLAY, u3 /* ddckCKDestOverlay */),
        CMP(CKSRCBLT, ddckCKSrcBlt),
        CMP(CKSRCOVERLAY, ddckCKSrcOverlay),
        CMP(HEIGHT, dwHeight),
        CMP(LINEARSIZE, u1 /* dwLinearSize */),
        CMP(LPSURFACE, lpSurface),
        CMP(MIPMAPCOUNT, u2 /* dwMipMapCount */),
        CMP(PITCH, u1 /* lPitch */),
        /* PIXELFORMAT: manual */
        CMP(REFRESHRATE, u2 /* dwRefreshRate */),
        CMP(TEXTURESTAGE, dwTextureStage),
        CMP(WIDTH, dwWidth),
        /* ZBUFFERBITDEPTH: "obsolete" */
    };

#undef CMP

    unsigned int i;

    if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
        return FALSE;

    for (i=0; i < sizeof(compare)/sizeof(compare[0]); i++)
    {
        if (requested->dwFlags & compare[i].flag
            && memcmp((const char *)provided + compare[i].offset,
                      (const char *)requested + compare[i].offset,
                      compare[i].size) != 0)
            return FALSE;
    }

    if (requested->dwFlags & DDSD_PIXELFORMAT)
    {
        if (!Main_DirectDraw_DDPIXELFORMAT_Match(&requested->u4.ddpfPixelFormat,
                                                &provided->u4.ddpfPixelFormat))
            return FALSE;
    }

    return TRUE;
}

#undef DDENUMSURFACES_SEARCHTYPE
#undef DDENUMSURFACES_MATCHTYPE

3806 3807 3808 3809 3810 3811 3812 3813 3814
struct surfacescallback_context
{
    LPDDENUMSURFACESCALLBACK func;
    void *context;
};

static HRESULT CALLBACK EnumSurfacesCallbackThunk(IDirectDrawSurface7 *surface,
        DDSURFACEDESC2 *surface_desc, void *context)
{
3815
    IDirectDrawSurfaceImpl *surface_impl = impl_from_IDirectDrawSurface7(surface);
3816 3817
    struct surfacescallback_context *cbcontext = context;

3818
    return cbcontext->func((IDirectDrawSurface *)&surface_impl->IDirectDrawSurface3_iface,
3819 3820 3821
            (DDSURFACEDESC *)surface_desc, cbcontext->context);
}

3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840
/*****************************************************************************
 * IDirectDraw7::EnumSurfaces
 *
 * Loops through all surfaces attached to this device and calls the
 * application callback. This can't be relayed to WineD3DDevice,
 * because some WineD3DSurfaces' parents are IParent objects
 *
 * Params:
 *  Flags: Some filtering flags. See IDirectDrawImpl_EnumSurfacesCallback
 *  DDSD: Description to filter for
 *  Context: Application-provided pointer, it's passed unmodified to the
 *           Callback function
 *  Callback: Address to call for each surface
 *
 * Returns:
 *  DDERR_INVALIDPARAMS if the callback is NULL
 *  DD_OK on success
 *
 *****************************************************************************/
3841 3842
static HRESULT WINAPI ddraw7_EnumSurfaces(IDirectDraw7 *iface, DWORD Flags,
        DDSURFACEDESC2 *DDSD, void *Context, LPDDENUMSURFACESCALLBACK7 Callback)
3843 3844 3845 3846 3847 3848 3849
{
    /* The surface enumeration is handled by WineDDraw,
     * because it keeps track of all surfaces attached to
     * it. The filtering is done by our callback function,
     * because WineDDraw doesn't handle ddraw-like surface
     * caps structures
     */
3850
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
3851 3852 3853
    IDirectDrawSurfaceImpl *surf;
    BOOL all, nomatch;
    DDSURFACEDESC2 desc;
3854
    struct list *entry, *entry2;
3855

3856 3857 3858
    TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
            iface, Flags, DDSD, Context, Callback);

3859 3860 3861
    all = Flags & DDENUMSURFACES_ALL;
    nomatch = Flags & DDENUMSURFACES_NOMATCH;

3862
    EnterCriticalSection(&ddraw_cs);
3863 3864

    if(!Callback)
3865 3866
    {
        LeaveCriticalSection(&ddraw_cs);
3867
        return DDERR_INVALIDPARAMS;
3868
    }
3869

3870 3871
    /* Use the _SAFE enumeration, the app may destroy enumerated surfaces */
    LIST_FOR_EACH_SAFE(entry, entry2, &This->surface_list)
3872
    {
3873
        surf = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
3874
        if (all || (nomatch != ddraw_match_surface_desc(DDSD, &surf->surface_desc)))
3875 3876
        {
            desc = surf->surface_desc;
3877 3878
            IDirectDrawSurface7_AddRef(&surf->IDirectDrawSurface7_iface);
            if (Callback(&surf->IDirectDrawSurface7_iface, &desc, Context) != DDENUMRET_OK)
3879 3880
            {
                LeaveCriticalSection(&ddraw_cs);
3881
                return DD_OK;
3882
            }
3883 3884
        }
    }
3885
    LeaveCriticalSection(&ddraw_cs);
3886 3887 3888
    return DD_OK;
}

3889 3890 3891
static HRESULT WINAPI ddraw4_EnumSurfaces(IDirectDraw4 *iface, DWORD flags,
        DDSURFACEDESC2 *surface_desc, void *context, LPDDENUMSURFACESCALLBACK2 callback)
{
3892 3893
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

3894 3895 3896
    TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
            iface, flags, surface_desc, context, callback);

3897
    return ddraw7_EnumSurfaces(&This->IDirectDraw7_iface, flags, surface_desc, context,
3898
            (LPDDENUMSURFACESCALLBACK7)callback);
3899 3900 3901 3902 3903
}

static HRESULT WINAPI ddraw3_EnumSurfaces(IDirectDraw3 *iface, DWORD flags,
        DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
{
3904
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
3905 3906 3907 3908 3909 3910 3911 3912
    struct surfacescallback_context cbcontext;

    TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
            iface, flags, surface_desc, context, callback);

    cbcontext.func = callback;
    cbcontext.context = context;

3913 3914
    return ddraw7_EnumSurfaces(&This->IDirectDraw7_iface, flags, (DDSURFACEDESC2 *)surface_desc,
            &cbcontext, EnumSurfacesCallbackThunk);
3915 3916 3917 3918 3919
}

static HRESULT WINAPI ddraw2_EnumSurfaces(IDirectDraw2 *iface, DWORD flags,
        DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
{
3920
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
3921 3922 3923 3924 3925 3926 3927 3928
    struct surfacescallback_context cbcontext;

    TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
            iface, flags, surface_desc, context, callback);

    cbcontext.func = callback;
    cbcontext.context = context;

3929 3930
    return ddraw7_EnumSurfaces(&This->IDirectDraw7_iface, flags, (DDSURFACEDESC2 *)surface_desc,
            &cbcontext, EnumSurfacesCallbackThunk);
3931 3932 3933 3934 3935
}

static HRESULT WINAPI ddraw1_EnumSurfaces(IDirectDraw *iface, DWORD flags,
        DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
{
3936
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
3937 3938 3939 3940 3941 3942 3943 3944
    struct surfacescallback_context cbcontext;

    TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
            iface, flags, surface_desc, context, callback);

    cbcontext.func = callback;
    cbcontext.context = context;

3945
    return ddraw7_EnumSurfaces(&This->IDirectDraw7_iface, flags, (DDSURFACEDESC2 *)surface_desc,
3946
            &cbcontext, EnumSurfacesCallbackThunk);
3947 3948
}

3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965
/*****************************************************************************
 * DirectDrawCreateClipper (DDRAW.@)
 *
 * Creates a new IDirectDrawClipper object.
 *
 * Params:
 *  Clipper: Address to write the interface pointer to
 *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
 *            NULL
 *
 * Returns:
 *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
 *  E_OUTOFMEMORY if allocating the object failed
 *
 *****************************************************************************/
HRESULT WINAPI
DirectDrawCreateClipper(DWORD Flags,
3966
                        LPDIRECTDRAWCLIPPER *Clipper,
3967 3968 3969
                        IUnknown *UnkOuter)
{
    IDirectDrawClipperImpl* object;
3970 3971
    HRESULT hr;

3972 3973
    TRACE("flags %#x, clipper %p, outer_unknown %p.\n",
            Flags, Clipper, UnkOuter);
3974

3975 3976 3977 3978 3979 3980
    EnterCriticalSection(&ddraw_cs);
    if (UnkOuter != NULL)
    {
        LeaveCriticalSection(&ddraw_cs);
        return CLASS_E_NOAGGREGATION;
    }
3981 3982 3983

    object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
                     sizeof(IDirectDrawClipperImpl));
3984 3985 3986 3987 3988
    if (object == NULL)
    {
        LeaveCriticalSection(&ddraw_cs);
        return E_OUTOFMEMORY;
    }
3989

3990 3991
    hr = ddraw_clipper_init(object);
    if (FAILED(hr))
3992
    {
3993
        WARN("Failed to initialize clipper, hr %#x.\n", hr);
3994
        HeapFree(GetProcessHeap(), 0, object);
3995
        LeaveCriticalSection(&ddraw_cs);
3996
        return hr;
3997
    }
3998

3999
    TRACE("Created clipper %p.\n", object);
4000
    *Clipper = (IDirectDrawClipper *) object;
4001
    LeaveCriticalSection(&ddraw_cs);
4002 4003 4004 4005 4006 4007 4008 4009 4010
    return DD_OK;
}

/*****************************************************************************
 * IDirectDraw7::CreateClipper
 *
 * Creates a DDraw clipper. See DirectDrawCreateClipper for details
 *
 *****************************************************************************/
4011 4012
static HRESULT WINAPI ddraw7_CreateClipper(IDirectDraw7 *iface, DWORD Flags,
        IDirectDrawClipper **Clipper, IUnknown *UnkOuter)
4013
{
4014 4015 4016
    TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
            iface, Flags, Clipper, UnkOuter);

4017 4018 4019
    return DirectDrawCreateClipper(Flags, Clipper, UnkOuter);
}

4020 4021
static HRESULT WINAPI ddraw4_CreateClipper(IDirectDraw4 *iface, DWORD flags,
        IDirectDrawClipper **clipper, IUnknown *outer_unknown)
4022
{
4023 4024
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);

4025 4026 4027
    TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
            iface, flags, clipper, outer_unknown);

4028
    return ddraw7_CreateClipper(&This->IDirectDraw7_iface, flags, clipper, outer_unknown);
4029 4030
}

4031 4032
static HRESULT WINAPI ddraw3_CreateClipper(IDirectDraw3 *iface, DWORD flags,
        IDirectDrawClipper **clipper, IUnknown *outer_unknown)
4033
{
4034 4035
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);

4036 4037 4038
    TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
            iface, flags, clipper, outer_unknown);

4039
    return ddraw7_CreateClipper(&This->IDirectDraw7_iface, flags, clipper, outer_unknown);
4040 4041 4042 4043 4044
}

static HRESULT WINAPI ddraw2_CreateClipper(IDirectDraw2 *iface,
        DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
{
4045 4046
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);

4047 4048 4049
    TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
            iface, flags, clipper, outer_unknown);

4050
    return ddraw7_CreateClipper(&This->IDirectDraw7_iface, flags, clipper, outer_unknown);
4051 4052 4053 4054 4055
}

static HRESULT WINAPI ddraw1_CreateClipper(IDirectDraw *iface,
        DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
{
4056 4057
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);

4058 4059 4060
    TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
            iface, flags, clipper, outer_unknown);

4061
    return ddraw7_CreateClipper(&This->IDirectDraw7_iface, flags, clipper, outer_unknown);
4062 4063
}

4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080
/*****************************************************************************
 * IDirectDraw7::CreatePalette
 *
 * Creates a new IDirectDrawPalette object
 *
 * Params:
 *  Flags: The flags for the new clipper
 *  ColorTable: Color table to assign to the new clipper
 *  Palette: Address to write the interface pointer to
 *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
 *            NULL
 *
 * Returns:
 *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
 *  E_OUTOFMEMORY if allocating the object failed
 *
 *****************************************************************************/
4081 4082
static HRESULT WINAPI ddraw7_CreatePalette(IDirectDraw7 *iface, DWORD Flags,
        PALETTEENTRY *ColorTable, IDirectDrawPalette **Palette, IUnknown *pUnkOuter)
4083
{
4084
    IDirectDrawImpl *This = impl_from_IDirectDraw7(iface);
4085
    IDirectDrawPaletteImpl *object;
4086 4087
    HRESULT hr;

4088 4089
    TRACE("iface %p, flags %#x, color_table %p, palette %p, outer_unknown %p.\n",
            iface, Flags, ColorTable, Palette, pUnkOuter);
4090

4091
    EnterCriticalSection(&ddraw_cs);
4092 4093 4094
    if(pUnkOuter != NULL)
    {
        WARN("pUnkOuter is %p, returning CLASS_E_NOAGGREGATION\n", pUnkOuter);
4095
        LeaveCriticalSection(&ddraw_cs);
4096 4097 4098 4099 4100 4101 4102
        return CLASS_E_NOAGGREGATION;
    }

    /* The refcount test shows that a cooplevel is required for this */
    if(!This->cooperative_level)
    {
        WARN("No cooperative level set, returning DDERR_NOCOOPERATIVELEVELSET\n");
4103
        LeaveCriticalSection(&ddraw_cs);
4104 4105
        return DDERR_NOCOOPERATIVELEVELSET;
    }
4106 4107

    object = HeapAlloc(GetProcessHeap(), 0, sizeof(IDirectDrawPaletteImpl));
4108 4109 4110
    if(!object)
    {
        ERR("Out of memory when allocating memory for a palette implementation\n");
4111
        LeaveCriticalSection(&ddraw_cs);
4112 4113
        return E_OUTOFMEMORY;
    }
4114

4115 4116
    hr = ddraw_palette_init(object, This, Flags, ColorTable);
    if (FAILED(hr))
4117
    {
4118
        WARN("Failed to initialize palette, hr %#x.\n", hr);
4119
        HeapFree(GetProcessHeap(), 0, object);
4120
        LeaveCriticalSection(&ddraw_cs);
4121 4122 4123
        return hr;
    }

4124
    TRACE("Created palette %p.\n", object);
4125
    *Palette = (IDirectDrawPalette *)object;
4126
    LeaveCriticalSection(&ddraw_cs);
4127 4128 4129
    return DD_OK;
}

4130 4131
static HRESULT WINAPI ddraw4_CreatePalette(IDirectDraw4 *iface, DWORD flags, PALETTEENTRY *entries,
        IDirectDrawPalette **palette, IUnknown *outer_unknown)
4132
{
4133
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
4134 4135 4136 4137 4138
    HRESULT hr;

    TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
            iface, flags, entries, palette, outer_unknown);

4139
    hr = ddraw7_CreatePalette(&This->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
4140 4141 4142
    if (SUCCEEDED(hr) && *palette)
    {
        IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
4143
        IDirectDraw7_Release(&This->IDirectDraw7_iface);
4144 4145 4146 4147 4148 4149 4150 4151 4152
        IDirectDraw4_AddRef(iface);
        impl->ifaceToRelease = (IUnknown *)iface;
    }
    return hr;
}

static HRESULT WINAPI ddraw3_CreatePalette(IDirectDraw3 *iface, DWORD flags,
        PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
{
4153
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
4154 4155 4156 4157 4158
    HRESULT hr;

    TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
            iface, flags, entries, palette, outer_unknown);

4159
    hr = ddraw7_CreatePalette(&This->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
4160 4161 4162
    if (SUCCEEDED(hr) && *palette)
    {
        IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
4163
        IDirectDraw7_Release(&This->IDirectDraw7_iface);
4164 4165 4166 4167 4168 4169 4170 4171 4172 4173
        IDirectDraw4_AddRef(iface);
        impl->ifaceToRelease = (IUnknown *)iface;
    }

    return hr;
}

static HRESULT WINAPI ddraw2_CreatePalette(IDirectDraw2 *iface, DWORD flags,
        PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
{
4174
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
4175 4176 4177 4178 4179
    HRESULT hr;

    TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
            iface, flags, entries, palette, outer_unknown);

4180
    hr = ddraw7_CreatePalette(&This->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
4181 4182 4183
    if (SUCCEEDED(hr) && *palette)
    {
        IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
4184
        IDirectDraw7_Release(&This->IDirectDraw7_iface);
4185 4186 4187 4188 4189 4190 4191 4192 4193
        impl->ifaceToRelease = NULL;
    }

    return hr;
}

static HRESULT WINAPI ddraw1_CreatePalette(IDirectDraw *iface, DWORD flags,
        PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
{
4194
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
4195 4196 4197 4198 4199
    HRESULT hr;

    TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
            iface, flags, entries, palette, outer_unknown);

4200
    hr = ddraw7_CreatePalette(&This->IDirectDraw7_iface, flags, entries, palette, outer_unknown);
4201 4202 4203
    if (SUCCEEDED(hr) && *palette)
    {
        IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
4204
        IDirectDraw7_Release(&This->IDirectDraw7_iface);
4205 4206 4207 4208 4209 4210
        impl->ifaceToRelease = NULL;
    }

    return hr;
}

4211 4212 4213 4214
/*****************************************************************************
 * IDirectDraw7::DuplicateSurface
 *
 * Duplicates a surface. The surface memory points to the same memory as
4215 4216
 * the original surface, and it's released when the last surface referencing
 * it is released. I guess that's beyond Wine's surface management right now
4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227
 * (Idea: create a new DDraw surface with the same WineD3DSurface. I need a
 * test application to implement this)
 *
 * Params:
 *  Src: Address of the source surface
 *  Dest: Address to write the new surface pointer to
 *
 * Returns:
 *  See IDirectDraw7::CreateSurface
 *
 *****************************************************************************/
4228 4229
static HRESULT WINAPI ddraw7_DuplicateSurface(IDirectDraw7 *iface,
        IDirectDrawSurface7 *Src, IDirectDrawSurface7 **Dest)
4230
{
4231
    IDirectDrawSurfaceImpl *Surf = unsafe_impl_from_IDirectDrawSurface7(Src);
4232

4233
    FIXME("iface %p, src %p, dst %p partial stub!\n", iface, Src, Dest);
4234 4235 4236 4237 4238 4239 4240 4241

    /* For now, simply create a new, independent surface */
    return IDirectDraw7_CreateSurface(iface,
                                      &Surf->surface_desc,
                                      Dest,
                                      NULL);
}

4242 4243
static HRESULT WINAPI ddraw4_DuplicateSurface(IDirectDraw4 *iface, IDirectDrawSurface4 *src,
        IDirectDrawSurface4 **dst)
4244
{
4245
    IDirectDrawImpl *This = impl_from_IDirectDraw4(iface);
4246
    IDirectDrawSurfaceImpl *src_impl = unsafe_impl_from_IDirectDrawSurface4(src);
4247 4248 4249
    IDirectDrawSurface7 *dst7;
    IDirectDrawSurfaceImpl *dst_impl;
    HRESULT hr;
4250

4251
    TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4252
    hr = ddraw7_DuplicateSurface(&This->IDirectDraw7_iface,
4253
            src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, &dst7);
4254 4255 4256 4257 4258 4259
    if (FAILED(hr))
    {
        *dst = NULL;
        return hr;
    }
    dst_impl = impl_from_IDirectDrawSurface7(dst7);
4260
    *dst = &dst_impl->IDirectDrawSurface4_iface;
4261

4262
    return hr;
4263 4264
}

4265 4266
static HRESULT WINAPI ddraw3_DuplicateSurface(IDirectDraw3 *iface, IDirectDrawSurface *src,
        IDirectDrawSurface **dst)
4267
{
4268
    IDirectDrawImpl *This = impl_from_IDirectDraw3(iface);
4269 4270
    IDirectDrawSurfaceImpl *src_impl = unsafe_impl_from_IDirectDrawSurface3((IDirectDrawSurface3 *)src);
    IDirectDrawSurface7 *dst7;
4271
    IDirectDrawSurfaceImpl *dst_impl;
4272 4273 4274
    HRESULT hr;

    TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4275 4276
    hr = ddraw7_DuplicateSurface(&This->IDirectDraw7_iface,
            src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, &dst7);
4277
    if (FAILED(hr))
4278
        return hr;
4279
    dst_impl = impl_from_IDirectDrawSurface7(dst7);
4280
    *dst = (IDirectDrawSurface *)&dst_impl->IDirectDrawSurface3_iface;
4281

4282 4283 4284 4285 4286 4287
    return hr;
}

static HRESULT WINAPI ddraw2_DuplicateSurface(IDirectDraw2 *iface,
        IDirectDrawSurface *src, IDirectDrawSurface **dst)
{
4288
    IDirectDrawImpl *This = impl_from_IDirectDraw2(iface);
4289 4290
    IDirectDrawSurfaceImpl *src_impl = unsafe_impl_from_IDirectDrawSurface3((IDirectDrawSurface3 *)src);
    IDirectDrawSurface7 *dst7;
4291
    IDirectDrawSurfaceImpl *dst_impl;
4292 4293 4294
    HRESULT hr;

    TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4295 4296
    hr = ddraw7_DuplicateSurface(&This->IDirectDraw7_iface,
            src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, &dst7);
4297
    if (FAILED(hr))
4298
        return hr;
4299
    dst_impl = impl_from_IDirectDrawSurface7(dst7);
4300
    *dst = (IDirectDrawSurface *)&dst_impl->IDirectDrawSurface3_iface;
4301

4302 4303 4304
    return hr;
}

4305 4306
static HRESULT WINAPI ddraw1_DuplicateSurface(IDirectDraw *iface, IDirectDrawSurface *src,
        IDirectDrawSurface **dst)
4307
{
4308
    IDirectDrawImpl *This = impl_from_IDirectDraw(iface);
4309 4310
    IDirectDrawSurfaceImpl *src_impl = unsafe_impl_from_IDirectDrawSurface3((IDirectDrawSurface3 *)src);
    IDirectDrawSurface7 *dst7;
4311
    IDirectDrawSurfaceImpl *dst_impl;
4312 4313 4314
    HRESULT hr;

    TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4315 4316
    hr = ddraw7_DuplicateSurface(&This->IDirectDraw7_iface,
            src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, &dst7);
4317
    if (FAILED(hr))
4318
        return hr;
4319
    dst_impl = impl_from_IDirectDrawSurface7(dst7);
4320
    *dst = (IDirectDrawSurface *)&dst_impl->IDirectDrawSurface3_iface;
4321

4322 4323 4324
    return hr;
}

4325
/*****************************************************************************
4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337
 * IDirect3D7::EnumDevices
 *
 * The EnumDevices method for IDirect3D7. It enumerates all supported
 * D3D7 devices. Currently the T&L, HAL and RGB devices are enumerated.
 *
 * Params:
 *  callback: Function to call for each enumerated device
 *  context: Pointer to pass back to the app
 *
 * Returns:
 *  D3D_OK, or the return value of the GetCaps call
 *
4338
 *****************************************************************************/
4339 4340
static HRESULT WINAPI d3d7_EnumDevices(IDirect3D7 *iface, LPD3DENUMDEVICESCALLBACK7 callback, void *context)
{
4341
    IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
4342 4343 4344
    D3DDEVICEDESC7 device_desc7;
    D3DDEVICEDESC device_desc1;
    HRESULT hr;
4345
    size_t i;
4346 4347 4348

    TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);

4349 4350 4351
    if (!callback)
        return DDERR_INVALIDPARAMS;

4352 4353
    EnterCriticalSection(&ddraw_cs);

4354
    hr = IDirect3DImpl_GetCaps(This->wineD3D, &device_desc1, &device_desc7);
4355 4356 4357 4358 4359 4360
    if (hr != D3D_OK)
    {
        LeaveCriticalSection(&ddraw_cs);
        return hr;
    }

4361 4362
    for (i = 0; i < sizeof(device_list7)/sizeof(device_list7[0]); i++)
    {
4363 4364
        HRESULT ret;

4365
        device_desc7.deviceGUID = *device_list7[i].device_guid;
4366 4367 4368 4369 4370 4371 4372
        ret = callback(device_list7[i].interface_name, device_list7[i].device_name, &device_desc7, context);
        if (ret != DDENUMRET_OK)
        {
            TRACE("Application cancelled the enumeration.\n");
            LeaveCriticalSection(&ddraw_cs);
            return D3D_OK;
        }
4373
    }
4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399

    TRACE("End of enumeration.\n");

    LeaveCriticalSection(&ddraw_cs);

    return D3D_OK;
}

/*****************************************************************************
 * IDirect3D3::EnumDevices
 *
 * Enumerates all supported Direct3DDevice interfaces. This is the
 * implementation for Direct3D 1 to Direc3D 3, Version 7 has its own.
 *
 * Version 1, 2 and 3
 *
 * Params:
 *  callback: Application-provided routine to call for each enumerated device
 *  Context: Pointer to pass to the callback
 *
 * Returns:
 *  D3D_OK on success,
 *  The result of IDirect3DImpl_GetCaps if it failed
 *
 *****************************************************************************/
static HRESULT WINAPI d3d3_EnumDevices(IDirect3D3 *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4400
{
4401
    static CHAR wined3d_description[] = "Wine D3DDevice using WineD3D and OpenGL";
4402

4403
    IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415
    D3DDEVICEDESC device_desc1, hal_desc, hel_desc;
    D3DDEVICEDESC7 device_desc7;
    HRESULT hr;

    /* Some games (Motoracer 2 demo) have the bad idea to modify the device
     * name string. Let's put the string in a sufficiently sized array in
     * writable memory. */
    char device_name[50];
    strcpy(device_name,"Direct3D HEL");

    TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);

4416 4417 4418
    if (!callback)
        return DDERR_INVALIDPARAMS;

4419 4420
    EnterCriticalSection(&ddraw_cs);

4421
    hr = IDirect3DImpl_GetCaps(This->wineD3D, &device_desc1, &device_desc7);
4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446
    if (hr != D3D_OK)
    {
        LeaveCriticalSection(&ddraw_cs);
        return hr;
    }

    /* Do I have to enumerate the reference id? Note from old d3d7:
     * "It seems that enumerating the reference IID on Direct3D 1 games
     * (AvP / Motoracer2) breaks them". So do not enumerate this iid in V1
     *
     * There's a registry key HKLM\Software\Microsoft\Direct3D\Drivers,
     * EnumReference which enables / disables enumerating the reference
     * rasterizer. It's a DWORD, 0 means disabled, 2 means enabled. The
     * enablerefrast.reg and disablerefrast.reg files in the DirectX 7.0 sdk
     * demo directory suggest this.
     *
     * Some games(GTA 2) seem to use the second enumerated device, so I have
     * to enumerate at least 2 devices. So enumerate the reference device to
     * have 2 devices.
     *
     * Other games (Rollcage) tell emulation and hal device apart by certain
     * flags. Rollcage expects D3DPTEXTURECAPS_POW2 to be set (yeah, it is a
     * limitation flag), and it refuses all devices that have the perspective
     * flag set. This way it refuses the emulation device, and HAL devices
     * never have POW2 unset in d3d7 on windows. */
4447
    if (This->d3dversion != 1)
4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494
    {
        static CHAR reference_description[] = "RGB Direct3D emulation";

        TRACE("Enumerating WineD3D D3DDevice interface.\n");
        hal_desc = device_desc1;
        hel_desc = device_desc1;
        /* The rgb device has the pow2 flag set in the hel caps, but not in the hal caps. */
        hal_desc.dpcLineCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
                | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
        hal_desc.dpcTriCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
                | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
        hr = callback((GUID *)&IID_IDirect3DRGBDevice, reference_description,
                device_name, &hal_desc, &hel_desc, context);
        if (hr != D3DENUMRET_OK)
        {
            TRACE("Application cancelled the enumeration.\n");
            LeaveCriticalSection(&ddraw_cs);
            return D3D_OK;
        }
    }

    strcpy(device_name,"Direct3D HAL");

    TRACE("Enumerating HAL Direct3D device.\n");
    hal_desc = device_desc1;
    hel_desc = device_desc1;
    /* The hal device does not have the pow2 flag set in hel, but in hal. */
    hel_desc.dpcLineCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
            | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
    hel_desc.dpcTriCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
            | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
    hr = callback((GUID *)&IID_IDirect3DHALDevice, wined3d_description,
            device_name, &hal_desc, &hel_desc, context);
    if (hr != D3DENUMRET_OK)
    {
        TRACE("Application cancelled the enumeration.\n");
        LeaveCriticalSection(&ddraw_cs);
        return D3D_OK;
    }

    TRACE("End of enumeration.\n");

    LeaveCriticalSection(&ddraw_cs);
    return D3D_OK;
}

static HRESULT WINAPI d3d2_EnumDevices(IDirect3D2 *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4495
{
4496 4497
    IDirectDrawImpl *This = impl_from_IDirect3D2(iface);

4498
    TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4499

4500
    return d3d3_EnumDevices(&This->IDirect3D3_iface, callback, context);
4501 4502 4503
}

static HRESULT WINAPI d3d1_EnumDevices(IDirect3D *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4504
{
4505 4506
    IDirectDrawImpl *This = impl_from_IDirect3D(iface);

4507
    TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4508

4509
    return d3d3_EnumDevices(&This->IDirect3D3_iface, callback, context);
4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532
}

/*****************************************************************************
 * IDirect3D3::CreateLight
 *
 * Creates an IDirect3DLight interface. This interface is used in
 * Direct3D3 or earlier for lighting. In Direct3D7 it has been replaced
 * by the DIRECT3DLIGHT7 structure. Wine's Direct3DLight implementation
 * uses the IDirect3DDevice7 interface with D3D7 lights.
 *
 * Version 1, 2 and 3
 *
 * Params:
 *  light: Address to store the new interface pointer
 *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
 *                 Must be NULL
 *
 * Returns:
 *  D3D_OK on success
 *  DDERR_OUTOFMEMORY if memory allocation failed
 *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
 *
 *****************************************************************************/
4533 4534
static HRESULT WINAPI d3d3_CreateLight(IDirect3D3 *iface, IDirect3DLight **light,
        IUnknown *outer_unknown)
4535
{
4536
    IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549
    IDirect3DLightImpl *object;

    TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);

    if (outer_unknown) return CLASS_E_NOAGGREGATION;

    object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
    if (!object)
    {
        ERR("Failed to allocate light memory.\n");
        return DDERR_OUTOFMEMORY;
    }

4550
    d3d_light_init(object, This);
4551 4552 4553 4554 4555 4556 4557 4558 4559

    TRACE("Created light %p.\n", object);
    *light = (IDirect3DLight *)object;

    return D3D_OK;
}

static HRESULT WINAPI d3d2_CreateLight(IDirect3D2 *iface, IDirect3DLight **light, IUnknown *outer_unknown)
{
4560 4561
    IDirectDrawImpl *This = impl_from_IDirect3D2(iface);

4562 4563
    TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);

4564
    return d3d3_CreateLight(&This->IDirect3D3_iface, light, outer_unknown);
4565 4566 4567 4568
}

static HRESULT WINAPI d3d1_CreateLight(IDirect3D *iface, IDirect3DLight **light, IUnknown *outer_unknown)
{
4569 4570
    IDirectDrawImpl *This = impl_from_IDirect3D(iface);

4571 4572
    TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);

4573
    return d3d3_CreateLight(&This->IDirect3D3_iface, light, outer_unknown);
4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595
}

/*****************************************************************************
 * IDirect3D3::CreateMaterial
 *
 * Creates an IDirect3DMaterial interface. This interface is used by Direct3D3
 * and older versions. The IDirect3DMaterial implementation wraps its
 * functionality to IDirect3DDevice7::SetMaterial and friends.
 *
 * Version 1, 2 and 3
 *
 * Params:
 *  material: Address to store the new interface's pointer to
 *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
 *                 Must be NULL
 *
 * Returns:
 *  D3D_OK on success
 *  DDERR_OUTOFMEMORY if memory allocation failed
 *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
 *
 *****************************************************************************/
4596 4597
static HRESULT WINAPI d3d3_CreateMaterial(IDirect3D3 *iface, IDirect3DMaterial3 **material,
        IUnknown *outer_unknown)
4598
{
4599
    IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4600 4601 4602 4603 4604 4605
    IDirect3DMaterialImpl *object;

    TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);

    if (outer_unknown) return CLASS_E_NOAGGREGATION;

4606
    object = d3d_material_create(This);
4607 4608 4609 4610 4611 4612 4613
    if (!object)
    {
        ERR("Failed to allocate material memory.\n");
        return DDERR_OUTOFMEMORY;
    }

    TRACE("Created material %p.\n", object);
4614
    *material = &object->IDirect3DMaterial3_iface;
4615 4616 4617 4618

    return D3D_OK;
}

4619 4620
static HRESULT WINAPI d3d2_CreateMaterial(IDirect3D2 *iface, IDirect3DMaterial2 **material,
        IUnknown *outer_unknown)
4621
{
4622
    IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4623
    IDirect3DMaterialImpl *object;
4624 4625 4626

    TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);

4627 4628 4629 4630 4631 4632
    object = d3d_material_create(This);
    if (!object)
    {
        ERR("Failed to allocate material memory.\n");
        return DDERR_OUTOFMEMORY;
    }
4633

4634 4635
    TRACE("Created material %p.\n", object);
    *material = &object->IDirect3DMaterial2_iface;
4636

4637
    return D3D_OK;
4638 4639
}

4640 4641
static HRESULT WINAPI d3d1_CreateMaterial(IDirect3D *iface, IDirect3DMaterial **material,
        IUnknown *outer_unknown)
4642
{
4643
    IDirectDrawImpl *This = impl_from_IDirect3D(iface);
4644
    IDirect3DMaterialImpl *object;
4645

4646 4647
    TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);

4648 4649 4650 4651 4652 4653
    object = d3d_material_create(This);
    if (!object)
    {
        ERR("Failed to allocate material memory.\n");
        return DDERR_OUTOFMEMORY;
    }
4654

4655 4656
    TRACE("Created material %p.\n", object);
    *material = &object->IDirect3DMaterial_iface;
4657

4658
    return D3D_OK;
4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680
}

/*****************************************************************************
 * IDirect3D3::CreateViewport
 *
 * Creates an IDirect3DViewport interface. This interface is used
 * by Direct3D and earlier versions for Viewport management. In Direct3D7
 * it has been replaced by a viewport structure and
 * IDirect3DDevice7::*Viewport. Wine's IDirect3DViewport implementation
 * uses the IDirect3DDevice7 methods for its functionality
 *
 * Params:
 *  Viewport: Address to store the new interface pointer
 *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
 *                 Must be NULL
 *
 * Returns:
 *  D3D_OK on success
 *  DDERR_OUTOFMEMORY if memory allocation failed
 *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
 *
 *****************************************************************************/
4681 4682
static HRESULT WINAPI d3d3_CreateViewport(IDirect3D3 *iface, IDirect3DViewport3 **viewport,
        IUnknown *outer_unknown)
4683
{
4684
    IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697
    IDirect3DViewportImpl *object;

    TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);

    if (outer_unknown) return CLASS_E_NOAGGREGATION;

    object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
    if (!object)
    {
        ERR("Failed to allocate viewport memory.\n");
        return DDERR_OUTOFMEMORY;
    }

4698
    d3d_viewport_init(object, This);
4699 4700 4701 4702 4703 4704 4705 4706 4707

    TRACE("Created viewport %p.\n", object);
    *viewport = (IDirect3DViewport3 *)object;

    return D3D_OK;
}

static HRESULT WINAPI d3d2_CreateViewport(IDirect3D2 *iface, IDirect3DViewport2 **viewport, IUnknown *outer_unknown)
{
4708 4709
    IDirectDrawImpl *This = impl_from_IDirect3D2(iface);

4710 4711
    TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);

4712 4713
    return d3d3_CreateViewport(&This->IDirect3D3_iface, (IDirect3DViewport3 **)viewport,
            outer_unknown);
4714 4715 4716 4717
}

static HRESULT WINAPI d3d1_CreateViewport(IDirect3D *iface, IDirect3DViewport **viewport, IUnknown *outer_unknown)
{
4718 4719
    IDirectDrawImpl *This = impl_from_IDirect3D(iface);

4720 4721
    TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);

4722 4723
    return d3d3_CreateViewport(&This->IDirect3D3_iface, (IDirect3DViewport3 **)viewport,
            outer_unknown);
4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743
}

/*****************************************************************************
 * IDirect3D3::FindDevice
 *
 * This method finds a device with the requested properties and returns a
 * device description
 *
 * Verion 1, 2 and 3
 * Params:
 *  fds: Describes the requested device characteristics
 *  fdr: Returns the device description
 *
 * Returns:
 *  D3D_OK on success
 *  DDERR_INVALIDPARAMS if no device was found
 *
 *****************************************************************************/
static HRESULT WINAPI d3d3_FindDevice(IDirect3D3 *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
{
4744
    IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776
    D3DDEVICEDESC7 desc7;
    D3DDEVICEDESC desc1;
    HRESULT hr;

    TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);

    if (!fds || !fdr) return DDERR_INVALIDPARAMS;

    if (fds->dwSize != sizeof(D3DFINDDEVICESEARCH)
            || fdr->dwSize != sizeof(D3DFINDDEVICERESULT))
        return DDERR_INVALIDPARAMS;

    if ((fds->dwFlags & D3DFDS_COLORMODEL)
            && fds->dcmColorModel != D3DCOLOR_RGB)
    {
        WARN("Trying to request a non-RGB D3D color model. Not supported.\n");
        return DDERR_INVALIDPARAMS; /* No real idea what to return here :-) */
    }

    if (fds->dwFlags & D3DFDS_GUID)
    {
        TRACE("Trying to match guid %s.\n", debugstr_guid(&(fds->guid)));
        if (!IsEqualGUID(&IID_D3DDEVICE_WineD3D, &fds->guid)
                && !IsEqualGUID(&IID_IDirect3DHALDevice, &fds->guid)
                && !IsEqualGUID(&IID_IDirect3DRGBDevice, &fds->guid))
        {
            WARN("No match for this GUID.\n");
            return DDERR_NOTFOUND;
        }
    }

    /* Get the caps */
4777
    hr = IDirect3DImpl_GetCaps(This->wineD3D, &desc1, &desc7);
4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791
    if (hr != D3D_OK) return hr;

    /* Now return our own GUID */
    fdr->guid = IID_D3DDEVICE_WineD3D;
    fdr->ddHwDesc = desc1;
    fdr->ddSwDesc = desc1;

    TRACE("Returning Wine's wined3d device with (undumped) capabilities.\n");

    return D3D_OK;
}

static HRESULT WINAPI d3d2_FindDevice(IDirect3D2 *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
{
4792 4793
    IDirectDrawImpl *This = impl_from_IDirect3D2(iface);

4794 4795
    TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);

4796
    return d3d3_FindDevice(&This->IDirect3D3_iface, fds, fdr);
4797 4798 4799 4800
}

static HRESULT WINAPI d3d1_FindDevice(IDirect3D *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
{
4801 4802
    IDirectDrawImpl *This = impl_from_IDirect3D(iface);

4803 4804
    TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);

4805
    return d3d3_FindDevice(&This->IDirect3D3_iface, fds, fdr);
4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831
}

/*****************************************************************************
 * IDirect3D7::CreateDevice
 *
 * Creates an IDirect3DDevice7 interface.
 *
 * Version 2, 3 and 7. IDirect3DDevice 1 interfaces are interfaces to
 * DirectDraw surfaces and are created with
 * IDirectDrawSurface::QueryInterface. This method uses CreateDevice to
 * create the device object and QueryInterfaces for IDirect3DDevice
 *
 * Params:
 *  refiid: IID of the device to create
 *  Surface: Initial rendertarget
 *  Device: Address to return the interface pointer
 *
 * Returns:
 *  D3D_OK on success
 *  DDERR_OUTOFMEMORY if memory allocation failed
 *  DDERR_INVALIDPARAMS if a device exists already
 *
 *****************************************************************************/
static HRESULT WINAPI d3d7_CreateDevice(IDirect3D7 *iface, REFCLSID riid,
        IDirectDrawSurface7 *surface, IDirect3DDevice7 **device)
{
4832
    IDirectDrawSurfaceImpl *target = unsafe_impl_from_IDirectDrawSurface7(surface);
4833
    IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
4834 4835 4836 4837 4838 4839 4840 4841 4842
    IDirect3DDeviceImpl *object;
    HRESULT hr;

    TRACE("iface %p, riid %s, surface %p, device %p.\n", iface, debugstr_guid(riid), surface, device);

    EnterCriticalSection(&ddraw_cs);
    *device = NULL;

    /* Fail device creation if non-opengl surfaces are used. */
4843
    if (This->ImplType != SURFACE_OPENGL)
4844 4845 4846 4847 4848 4849 4850 4851 4852 4853
    {
        ERR("The application wants to create a Direct3D device, but non-opengl surfaces are set in the registry.\n");
        ERR("Please set the surface implementation to opengl or autodetection to allow 3D rendering.\n");

        /* We only hit this path if a default surface is set in the registry. Incorrect autodetection
         * is caught in CreateSurface or QueryInterface. */
        LeaveCriticalSection(&ddraw_cs);
        return DDERR_NO3D;
    }

4854
    if (This->d3ddevice)
4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868
    {
        FIXME("Only one Direct3D device per DirectDraw object supported.\n");
        LeaveCriticalSection(&ddraw_cs);
        return DDERR_INVALIDPARAMS;
    }

    object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
    if (!object)
    {
        ERR("Failed to allocate device memory.\n");
        LeaveCriticalSection(&ddraw_cs);
        return DDERR_OUTOFMEMORY;
    }

4869
    hr = d3d_device_init(object, This, target);
4870 4871
    if (FAILED(hr))
    {
4872
        WARN("Failed to initialize device, hr %#x.\n", hr);
4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887
        HeapFree(GetProcessHeap(), 0, object);
        LeaveCriticalSection(&ddraw_cs);
        return hr;
    }

    TRACE("Created device %p.\n", object);
    *device = (IDirect3DDevice7 *)object;

    LeaveCriticalSection(&ddraw_cs);
    return D3D_OK;
}

static HRESULT WINAPI d3d3_CreateDevice(IDirect3D3 *iface, REFCLSID riid,
        IDirectDrawSurface4 *surface, IDirect3DDevice3 **device, IUnknown *outer_unknown)
{
4888
    IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4889
    IDirectDrawSurfaceImpl *surface_impl = unsafe_impl_from_IDirectDrawSurface4(surface);
4890 4891 4892 4893 4894 4895 4896
    HRESULT hr;

    TRACE("iface %p, riid %s, surface %p, device %p, outer_unknown %p.\n",
            iface, debugstr_guid(riid), surface, device, outer_unknown);

    if (outer_unknown) return CLASS_E_NOAGGREGATION;

4897 4898
    hr = d3d7_CreateDevice(&This->IDirect3D7_iface, riid,
            surface_impl ? &surface_impl->IDirectDrawSurface7_iface : NULL,
4899
            (IDirect3DDevice7 **)device);
4900 4901 4902 4903 4904 4905 4906 4907
    if (*device) *device = (IDirect3DDevice3 *)&((IDirect3DDeviceImpl *)*device)->IDirect3DDevice3_vtbl;

    return hr;
}

static HRESULT WINAPI d3d2_CreateDevice(IDirect3D2 *iface, REFCLSID riid,
        IDirectDrawSurface *surface, IDirect3DDevice2 **device)
{
4908
    IDirectDrawImpl *This = impl_from_IDirect3D2(iface);
4909
    IDirectDrawSurfaceImpl *surface_impl = unsafe_impl_from_IDirectDrawSurface3((IDirectDrawSurface3 *)surface);
4910 4911 4912 4913 4914
    HRESULT hr;

    TRACE("iface %p, riid %s, surface %p, device %p.\n",
            iface, debugstr_guid(riid), surface, device);

4915
    hr = d3d7_CreateDevice(&This->IDirect3D7_iface, riid,
4916
            surface_impl ? &surface_impl->IDirectDrawSurface7_iface : NULL,
4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945
            (IDirect3DDevice7 **)device);
    if (*device) *device = (IDirect3DDevice2 *)&((IDirect3DDeviceImpl *)*device)->IDirect3DDevice2_vtbl;

    return hr;
}

/*****************************************************************************
 * IDirect3D7::CreateVertexBuffer
 *
 * Creates a new vertex buffer object and returns a IDirect3DVertexBuffer7
 * interface.
 *
 * Version 3 and 7
 *
 * Params:
 *  desc: Requested Vertex buffer properties
 *  vertex_buffer: Address to return the interface pointer at
 *  flags: Some flags, should be 0
 *
 * Returns
 *  D3D_OK on success
 *  DDERR_OUTOFMEMORY if memory allocation failed
 *  The return value of IWineD3DDevice::CreateVertexBuffer if this call fails
 *  DDERR_INVALIDPARAMS if desc or vertex_buffer are NULL
 *
 *****************************************************************************/
static HRESULT WINAPI d3d7_CreateVertexBuffer(IDirect3D7 *iface, D3DVERTEXBUFFERDESC *desc,
        IDirect3DVertexBuffer7 **vertex_buffer, DWORD flags)
{
4946
    IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968
    IDirect3DVertexBufferImpl *object;
    HRESULT hr;

    TRACE("iface %p, desc %p, vertex_buffer %p, flags %#x.\n",
            iface, desc, vertex_buffer, flags);

    if (!vertex_buffer || !desc) return DDERR_INVALIDPARAMS;

    TRACE("Vertex buffer description:\n");
    TRACE("    dwSize %u\n", desc->dwSize);
    TRACE("    dwCaps %#x\n", desc->dwCaps);
    TRACE("    FVF %#x\n", desc->dwFVF);
    TRACE("    dwNumVertices %u\n", desc->dwNumVertices);

    /* Now create the vertex buffer */
    object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
    if (!object)
    {
        ERR("Failed to allocate vertex buffer memory.\n");
        return DDERR_OUTOFMEMORY;
    }

4969
    hr = d3d_vertex_buffer_init(object, This, desc);
4970 4971
    if (FAILED(hr))
    {
4972
        WARN("Failed to initialize vertex buffer, hr %#x.\n", hr);
4973
        HeapFree(GetProcessHeap(), 0, object);
4974
        return hr;
4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985
    }

    TRACE("Created vertex buffer %p.\n", object);
    *vertex_buffer = (IDirect3DVertexBuffer7 *)object;

    return D3D_OK;
}

static HRESULT WINAPI d3d3_CreateVertexBuffer(IDirect3D3 *iface, D3DVERTEXBUFFERDESC *desc,
        IDirect3DVertexBuffer **vertex_buffer, DWORD flags, IUnknown *outer_unknown)
{
4986
    IDirectDrawImpl *This = impl_from_IDirect3D3(iface);
4987 4988 4989 4990 4991 4992 4993
    HRESULT hr;

    TRACE("iface %p, desc %p, vertex_buffer %p, flags %#x, outer_unknown %p.\n",
            iface, desc, vertex_buffer, flags, outer_unknown);

    if (outer_unknown) return CLASS_E_NOAGGREGATION;

4994 4995
    hr = d3d7_CreateVertexBuffer(&This->IDirect3D7_iface, desc,
            (IDirect3DVertexBuffer7 **)vertex_buffer, flags);
4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022
    if (*vertex_buffer)
        *vertex_buffer = (IDirect3DVertexBuffer *)&((IDirect3DVertexBufferImpl *)*vertex_buffer)->IDirect3DVertexBuffer_vtbl;

    return hr;
}

/*****************************************************************************
 * IDirect3D7::EnumZBufferFormats
 *
 * Enumerates all supported Z buffer pixel formats
 *
 * Version 3 and 7
 *
 * Params:
 *  device_iid:
 *  callback: callback to call for each pixel format
 *  context: Pointer to pass back to the callback
 *
 * Returns:
 *  D3D_OK on success
 *  DDERR_INVALIDPARAMS if callback is NULL
 *  For details, see IWineD3DDevice::EnumZBufferFormats
 *
 *****************************************************************************/
static HRESULT WINAPI d3d7_EnumZBufferFormats(IDirect3D7 *iface, REFCLSID device_iid,
        LPD3DENUMPIXELFORMATSCALLBACK callback, void *context)
{
5023
    IDirectDrawImpl *This = impl_from_IDirect3D7(iface);
5024 5025 5026 5027 5028 5029 5030
    WINED3DDISPLAYMODE d3ddm;
    WINED3DDEVTYPE type;
    unsigned int i;
    HRESULT hr;

    /* Order matters. Specifically, BattleZone II (full version) expects the
     * 16-bit depth formats to be listed before the 24 and 32 ones. */
5031
    static const enum wined3d_format_id formats[] =
5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081
    {
        WINED3DFMT_S1_UINT_D15_UNORM,
        WINED3DFMT_D16_UNORM,
        WINED3DFMT_X8D24_UNORM,
        WINED3DFMT_S4X4_UINT_D24_UNORM,
        WINED3DFMT_D24_UNORM_S8_UINT,
        WINED3DFMT_D32_UNORM,
    };

    TRACE("iface %p, device_iid %s, callback %p, context %p.\n",
            iface, debugstr_guid(device_iid), callback, context);

    if (!callback) return DDERR_INVALIDPARAMS;

    if (IsEqualGUID(device_iid, &IID_IDirect3DHALDevice)
            || IsEqualGUID(device_iid, &IID_IDirect3DTnLHalDevice)
            || IsEqualGUID(device_iid, &IID_D3DDEVICE_WineD3D))
    {
        TRACE("Asked for HAL device.\n");
        type = WINED3DDEVTYPE_HAL;
    }
    else if (IsEqualGUID(device_iid, &IID_IDirect3DRGBDevice)
            || IsEqualGUID(device_iid, &IID_IDirect3DMMXDevice))
    {
        TRACE("Asked for SW device.\n");
        type = WINED3DDEVTYPE_SW;
    }
    else if (IsEqualGUID(device_iid, &IID_IDirect3DRefDevice))
    {
        TRACE("Asked for REF device.\n");
        type = WINED3DDEVTYPE_REF;
    }
    else if (IsEqualGUID(device_iid, &IID_IDirect3DNullDevice))
    {
        TRACE("Asked for NULLREF device.\n");
        type = WINED3DDEVTYPE_NULLREF;
    }
    else
    {
        FIXME("Unexpected device GUID %s.\n", debugstr_guid(device_iid));
        type = WINED3DDEVTYPE_HAL;
    }

    EnterCriticalSection(&ddraw_cs);
    /* We need an adapter format from somewhere to please wined3d and WGL.
     * Use the current display mode. So far all cards offer the same depth
     * stencil format for all modes, but if some do not and applications do
     * not like that we'll have to find some workaround, like iterating over
     * all imaginable formats and collecting all the depth stencil formats we
     * can get. */
5082
    hr = wined3d_device_get_display_mode(This->wined3d_device, 0, &d3ddm);
5083 5084 5085

    for (i = 0; i < (sizeof(formats) / sizeof(*formats)); ++i)
    {
5086
        hr = wined3d_check_device_format(This->wineD3D, WINED3DADAPTER_DEFAULT, type, d3ddm.Format,
5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114
                WINED3DUSAGE_DEPTHSTENCIL, WINED3DRTYPE_SURFACE, formats[i], SURFACE_OPENGL);
        if (SUCCEEDED(hr))
        {
            DDPIXELFORMAT pformat;

            memset(&pformat, 0, sizeof(pformat));
            pformat.dwSize = sizeof(pformat);
            PixelFormat_WineD3DtoDD(&pformat, formats[i]);

            TRACE("Enumerating wined3d format %#x.\n", formats[i]);
            hr = callback(&pformat, context);
            if (hr != DDENUMRET_OK)
            {
                TRACE("Format enumeration cancelled by application.\n");
                LeaveCriticalSection(&ddraw_cs);
                return D3D_OK;
            }
        }
    }
    TRACE("End of enumeration.\n");

    LeaveCriticalSection(&ddraw_cs);
    return D3D_OK;
}

static HRESULT WINAPI d3d3_EnumZBufferFormats(IDirect3D3 *iface, REFCLSID device_iid,
        LPD3DENUMPIXELFORMATSCALLBACK callback, void *context)
{
5115 5116
    IDirectDrawImpl *This = impl_from_IDirect3D3(iface);

5117 5118 5119
    TRACE("iface %p, device_iid %s, callback %p, context %p.\n",
            iface, debugstr_guid(device_iid), callback, context);

5120
    return d3d7_EnumZBufferFormats(&This->IDirect3D7_iface, device_iid, callback, context);
5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146
}

/*****************************************************************************
 * IDirect3D7::EvictManagedTextures
 *
 * Removes all managed textures (=surfaces with DDSCAPS2_TEXTUREMANAGE or
 * DDSCAPS2_D3DTEXTUREMANAGE caps) to be removed from video memory.
 *
 * Version 3 and 7
 *
 * Returns:
 *  D3D_OK, because it's a stub
 *
 *****************************************************************************/
static HRESULT WINAPI d3d7_EvictManagedTextures(IDirect3D7 *iface)
{
    FIXME("iface %p stub!\n", iface);

    /* TODO: Just enumerate resources using IWineD3DDevice_EnumResources(),
     * then unload surfaces / textures. */

    return D3D_OK;
}

static HRESULT WINAPI d3d3_EvictManagedTextures(IDirect3D3 *iface)
{
5147 5148
    IDirectDrawImpl *This = impl_from_IDirect3D3(iface);

5149 5150
    TRACE("iface %p.\n", iface);

5151
    return d3d7_EvictManagedTextures(&This->IDirect3D7_iface);
5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169
}

/*****************************************************************************
 * IDirect3DImpl_GetCaps
 *
 * This function retrieves the device caps from wined3d
 * and converts it into a D3D7 and D3D - D3D3 structure
 * This is a helper function called from various places in ddraw
 *
 * Params:
 *  wined3d: The interface to get the caps from
 *  desc1: Old D3D <3 structure to fill (needed)
 *  desc7: D3D7 device desc structure to fill (needed)
 *
 * Returns
 *  D3D_OK on success, or the return value of IWineD3D::GetCaps
 *
 *****************************************************************************/
5170
HRESULT IDirect3DImpl_GetCaps(const struct wined3d *wined3d, D3DDEVICEDESC *desc1, D3DDEVICEDESC7 *desc7)
5171 5172 5173 5174 5175 5176 5177 5178 5179
{
    WINED3DCAPS wined3d_caps;
    HRESULT hr;

    TRACE("wined3d %p, desc1 %p, desc7 %p.\n", wined3d, desc1, desc7);

    memset(&wined3d_caps, 0, sizeof(wined3d_caps));

    EnterCriticalSection(&ddraw_cs);
5180
    hr = wined3d_get_device_caps(wined3d, 0, WINED3DDEVTYPE_HAL, &wined3d_caps);
5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368
    LeaveCriticalSection(&ddraw_cs);
    if (FAILED(hr))
    {
        WARN("Failed to get device caps, hr %#x.\n", hr);
        return hr;
    }

    /* Copy the results into the d3d7 and d3d3 structures */
    desc7->dwDevCaps = wined3d_caps.DevCaps;
    desc7->dpcLineCaps.dwMiscCaps = wined3d_caps.PrimitiveMiscCaps;
    desc7->dpcLineCaps.dwRasterCaps = wined3d_caps.RasterCaps;
    desc7->dpcLineCaps.dwZCmpCaps = wined3d_caps.ZCmpCaps;
    desc7->dpcLineCaps.dwSrcBlendCaps = wined3d_caps.SrcBlendCaps;
    desc7->dpcLineCaps.dwDestBlendCaps = wined3d_caps.DestBlendCaps;
    desc7->dpcLineCaps.dwAlphaCmpCaps = wined3d_caps.AlphaCmpCaps;
    desc7->dpcLineCaps.dwShadeCaps = wined3d_caps.ShadeCaps;
    desc7->dpcLineCaps.dwTextureCaps = wined3d_caps.TextureCaps;
    desc7->dpcLineCaps.dwTextureFilterCaps = wined3d_caps.TextureFilterCaps;
    desc7->dpcLineCaps.dwTextureAddressCaps = wined3d_caps.TextureAddressCaps;

    desc7->dwMaxTextureWidth = wined3d_caps.MaxTextureWidth;
    desc7->dwMaxTextureHeight = wined3d_caps.MaxTextureHeight;

    desc7->dwMaxTextureRepeat = wined3d_caps.MaxTextureRepeat;
    desc7->dwMaxTextureAspectRatio = wined3d_caps.MaxTextureAspectRatio;
    desc7->dwMaxAnisotropy = wined3d_caps.MaxAnisotropy;
    desc7->dvMaxVertexW = wined3d_caps.MaxVertexW;

    desc7->dvGuardBandLeft = wined3d_caps.GuardBandLeft;
    desc7->dvGuardBandTop = wined3d_caps.GuardBandTop;
    desc7->dvGuardBandRight = wined3d_caps.GuardBandRight;
    desc7->dvGuardBandBottom = wined3d_caps.GuardBandBottom;

    desc7->dvExtentsAdjust = wined3d_caps.ExtentsAdjust;
    desc7->dwStencilCaps = wined3d_caps.StencilCaps;

    desc7->dwFVFCaps = wined3d_caps.FVFCaps;
    desc7->dwTextureOpCaps = wined3d_caps.TextureOpCaps;

    desc7->dwVertexProcessingCaps = wined3d_caps.VertexProcessingCaps;
    desc7->dwMaxActiveLights = wined3d_caps.MaxActiveLights;

    /* Remove all non-d3d7 caps */
    desc7->dwDevCaps &= (
        D3DDEVCAPS_FLOATTLVERTEX         | D3DDEVCAPS_SORTINCREASINGZ          | D3DDEVCAPS_SORTDECREASINGZ          |
        D3DDEVCAPS_SORTEXACT             | D3DDEVCAPS_EXECUTESYSTEMMEMORY      | D3DDEVCAPS_EXECUTEVIDEOMEMORY       |
        D3DDEVCAPS_TLVERTEXSYSTEMMEMORY  | D3DDEVCAPS_TLVERTEXVIDEOMEMORY      | D3DDEVCAPS_TEXTURESYSTEMMEMORY      |
        D3DDEVCAPS_TEXTUREVIDEOMEMORY    | D3DDEVCAPS_DRAWPRIMTLVERTEX         | D3DDEVCAPS_CANRENDERAFTERFLIP       |
        D3DDEVCAPS_TEXTURENONLOCALVIDMEM | D3DDEVCAPS_DRAWPRIMITIVES2          | D3DDEVCAPS_SEPARATETEXTUREMEMORIES  |
        D3DDEVCAPS_DRAWPRIMITIVES2EX     | D3DDEVCAPS_HWTRANSFORMANDLIGHT      | D3DDEVCAPS_CANBLTSYSTONONLOCAL      |
        D3DDEVCAPS_HWRASTERIZATION);

    desc7->dwStencilCaps &= (
        D3DSTENCILCAPS_KEEP              | D3DSTENCILCAPS_ZERO                 | D3DSTENCILCAPS_REPLACE              |
        D3DSTENCILCAPS_INCRSAT           | D3DSTENCILCAPS_DECRSAT              | D3DSTENCILCAPS_INVERT               |
        D3DSTENCILCAPS_INCR              | D3DSTENCILCAPS_DECR);

    /* FVF caps ?*/

    desc7->dwTextureOpCaps &= (
        D3DTEXOPCAPS_DISABLE             | D3DTEXOPCAPS_SELECTARG1             | D3DTEXOPCAPS_SELECTARG2             |
        D3DTEXOPCAPS_MODULATE            | D3DTEXOPCAPS_MODULATE2X             | D3DTEXOPCAPS_MODULATE4X             |
        D3DTEXOPCAPS_ADD                 | D3DTEXOPCAPS_ADDSIGNED              | D3DTEXOPCAPS_ADDSIGNED2X            |
        D3DTEXOPCAPS_SUBTRACT            | D3DTEXOPCAPS_ADDSMOOTH              | D3DTEXOPCAPS_BLENDTEXTUREALPHA      |
        D3DTEXOPCAPS_BLENDFACTORALPHA    | D3DTEXOPCAPS_BLENDTEXTUREALPHAPM    | D3DTEXOPCAPS_BLENDCURRENTALPHA      |
        D3DTEXOPCAPS_PREMODULATE         | D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR | D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA |
        D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR | D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA | D3DTEXOPCAPS_BUMPENVMAP    |
        D3DTEXOPCAPS_BUMPENVMAPLUMINANCE | D3DTEXOPCAPS_DOTPRODUCT3);

    desc7->dwVertexProcessingCaps &= (
        D3DVTXPCAPS_TEXGEN               | D3DVTXPCAPS_MATERIALSOURCE7         | D3DVTXPCAPS_VERTEXFOG               |
        D3DVTXPCAPS_DIRECTIONALLIGHTS    | D3DVTXPCAPS_POSITIONALLIGHTS        | D3DVTXPCAPS_LOCALVIEWER);

    desc7->dpcLineCaps.dwMiscCaps &= (
        D3DPMISCCAPS_MASKPLANES          | D3DPMISCCAPS_MASKZ                  | D3DPMISCCAPS_LINEPATTERNREP         |
        D3DPMISCCAPS_CONFORMANT          | D3DPMISCCAPS_CULLNONE               | D3DPMISCCAPS_CULLCW                 |
        D3DPMISCCAPS_CULLCCW);

    desc7->dpcLineCaps.dwRasterCaps &= (
        D3DPRASTERCAPS_DITHER            | D3DPRASTERCAPS_ROP2                 | D3DPRASTERCAPS_XOR                  |
        D3DPRASTERCAPS_PAT               | D3DPRASTERCAPS_ZTEST                | D3DPRASTERCAPS_SUBPIXEL             |
        D3DPRASTERCAPS_SUBPIXELX         | D3DPRASTERCAPS_FOGVERTEX            | D3DPRASTERCAPS_FOGTABLE             |
        D3DPRASTERCAPS_STIPPLE           | D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT | D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT |
        D3DPRASTERCAPS_ANTIALIASEDGES    | D3DPRASTERCAPS_MIPMAPLODBIAS        | D3DPRASTERCAPS_ZBIAS                |
        D3DPRASTERCAPS_ZBUFFERLESSHSR    | D3DPRASTERCAPS_FOGRANGE             | D3DPRASTERCAPS_ANISOTROPY           |
        D3DPRASTERCAPS_WBUFFER           | D3DPRASTERCAPS_TRANSLUCENTSORTINDEPENDENT | D3DPRASTERCAPS_WFOG           |
        D3DPRASTERCAPS_ZFOG);

    desc7->dpcLineCaps.dwZCmpCaps &= (
        D3DPCMPCAPS_NEVER                | D3DPCMPCAPS_LESS                    | D3DPCMPCAPS_EQUAL                   |
        D3DPCMPCAPS_LESSEQUAL            | D3DPCMPCAPS_GREATER                 | D3DPCMPCAPS_NOTEQUAL                |
        D3DPCMPCAPS_GREATEREQUAL         | D3DPCMPCAPS_ALWAYS);

    desc7->dpcLineCaps.dwSrcBlendCaps &= (
        D3DPBLENDCAPS_ZERO               | D3DPBLENDCAPS_ONE                   | D3DPBLENDCAPS_SRCCOLOR              |
        D3DPBLENDCAPS_INVSRCCOLOR        | D3DPBLENDCAPS_SRCALPHA              | D3DPBLENDCAPS_INVSRCALPHA           |
        D3DPBLENDCAPS_DESTALPHA          | D3DPBLENDCAPS_INVDESTALPHA          | D3DPBLENDCAPS_DESTCOLOR             |
        D3DPBLENDCAPS_INVDESTCOLOR       | D3DPBLENDCAPS_SRCALPHASAT           | D3DPBLENDCAPS_BOTHSRCALPHA          |
        D3DPBLENDCAPS_BOTHINVSRCALPHA);

    desc7->dpcLineCaps.dwDestBlendCaps &= (
        D3DPBLENDCAPS_ZERO               | D3DPBLENDCAPS_ONE                   | D3DPBLENDCAPS_SRCCOLOR              |
        D3DPBLENDCAPS_INVSRCCOLOR        | D3DPBLENDCAPS_SRCALPHA              | D3DPBLENDCAPS_INVSRCALPHA           |
        D3DPBLENDCAPS_DESTALPHA          | D3DPBLENDCAPS_INVDESTALPHA          | D3DPBLENDCAPS_DESTCOLOR             |
        D3DPBLENDCAPS_INVDESTCOLOR       | D3DPBLENDCAPS_SRCALPHASAT           | D3DPBLENDCAPS_BOTHSRCALPHA          |
        D3DPBLENDCAPS_BOTHINVSRCALPHA);

    desc7->dpcLineCaps.dwAlphaCmpCaps &= (
        D3DPCMPCAPS_NEVER                | D3DPCMPCAPS_LESS                    | D3DPCMPCAPS_EQUAL                   |
        D3DPCMPCAPS_LESSEQUAL            | D3DPCMPCAPS_GREATER                 | D3DPCMPCAPS_NOTEQUAL                |
        D3DPCMPCAPS_GREATEREQUAL         | D3DPCMPCAPS_ALWAYS);

    desc7->dpcLineCaps.dwShadeCaps &= (
        D3DPSHADECAPS_COLORFLATMONO      | D3DPSHADECAPS_COLORFLATRGB          | D3DPSHADECAPS_COLORGOURAUDMONO      |
        D3DPSHADECAPS_COLORGOURAUDRGB    | D3DPSHADECAPS_COLORPHONGMONO        | D3DPSHADECAPS_COLORPHONGRGB         |
        D3DPSHADECAPS_SPECULARFLATMONO   | D3DPSHADECAPS_SPECULARFLATRGB       | D3DPSHADECAPS_SPECULARGOURAUDMONO   |
        D3DPSHADECAPS_SPECULARGOURAUDRGB | D3DPSHADECAPS_SPECULARPHONGMONO     | D3DPSHADECAPS_SPECULARPHONGRGB      |
        D3DPSHADECAPS_ALPHAFLATBLEND     | D3DPSHADECAPS_ALPHAFLATSTIPPLED     | D3DPSHADECAPS_ALPHAGOURAUDBLEND     |
        D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED | D3DPSHADECAPS_ALPHAPHONGBLEND     | D3DPSHADECAPS_ALPHAPHONGSTIPPLED    |
        D3DPSHADECAPS_FOGFLAT            | D3DPSHADECAPS_FOGGOURAUD            | D3DPSHADECAPS_FOGPHONG);

    desc7->dpcLineCaps.dwTextureCaps &= (
        D3DPTEXTURECAPS_PERSPECTIVE      | D3DPTEXTURECAPS_POW2                | D3DPTEXTURECAPS_ALPHA               |
        D3DPTEXTURECAPS_TRANSPARENCY     | D3DPTEXTURECAPS_BORDER              | D3DPTEXTURECAPS_SQUAREONLY          |
        D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE | D3DPTEXTURECAPS_ALPHAPALETTE| D3DPTEXTURECAPS_NONPOW2CONDITIONAL  |
        D3DPTEXTURECAPS_PROJECTED        | D3DPTEXTURECAPS_CUBEMAP             | D3DPTEXTURECAPS_COLORKEYBLEND);

    desc7->dpcLineCaps.dwTextureFilterCaps &= (
        D3DPTFILTERCAPS_NEAREST          | D3DPTFILTERCAPS_LINEAR              | D3DPTFILTERCAPS_MIPNEAREST          |
        D3DPTFILTERCAPS_MIPLINEAR        | D3DPTFILTERCAPS_LINEARMIPNEAREST    | D3DPTFILTERCAPS_LINEARMIPLINEAR     |
        D3DPTFILTERCAPS_MINFPOINT        | D3DPTFILTERCAPS_MINFLINEAR          | D3DPTFILTERCAPS_MINFANISOTROPIC     |
        D3DPTFILTERCAPS_MIPFPOINT        | D3DPTFILTERCAPS_MIPFLINEAR          | D3DPTFILTERCAPS_MAGFPOINT           |
        D3DPTFILTERCAPS_MAGFLINEAR       | D3DPTFILTERCAPS_MAGFANISOTROPIC     | D3DPTFILTERCAPS_MAGFAFLATCUBIC      |
        D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC);

    desc7->dpcLineCaps.dwTextureBlendCaps &= (
        D3DPTBLENDCAPS_DECAL             | D3DPTBLENDCAPS_MODULATE             | D3DPTBLENDCAPS_DECALALPHA           |
        D3DPTBLENDCAPS_MODULATEALPHA     | D3DPTBLENDCAPS_DECALMASK            | D3DPTBLENDCAPS_MODULATEMASK         |
        D3DPTBLENDCAPS_COPY              | D3DPTBLENDCAPS_ADD);

    desc7->dpcLineCaps.dwTextureAddressCaps &= (
        D3DPTADDRESSCAPS_WRAP            | D3DPTADDRESSCAPS_MIRROR             | D3DPTADDRESSCAPS_CLAMP              |
        D3DPTADDRESSCAPS_BORDER          | D3DPTADDRESSCAPS_INDEPENDENTUV);

    if (!(desc7->dpcLineCaps.dwTextureCaps & D3DPTEXTURECAPS_POW2))
    {
        /* DirectX7 always has the np2 flag set, no matter what the card
         * supports. Some old games (Rollcage) check the caps incorrectly.
         * If wined3d supports nonpow2 textures it also has np2 conditional
         * support. */
        desc7->dpcLineCaps.dwTextureCaps |= D3DPTEXTURECAPS_POW2 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL;
    }

    /* Fill the missing members, and do some fixup */
    desc7->dpcLineCaps.dwSize = sizeof(desc7->dpcLineCaps);
    desc7->dpcLineCaps.dwTextureBlendCaps = D3DPTBLENDCAPS_ADD | D3DPTBLENDCAPS_MODULATEMASK |
                                            D3DPTBLENDCAPS_COPY | D3DPTBLENDCAPS_DECAL |
                                            D3DPTBLENDCAPS_DECALALPHA | D3DPTBLENDCAPS_DECALMASK |
                                            D3DPTBLENDCAPS_MODULATE | D3DPTBLENDCAPS_MODULATEALPHA;
    desc7->dpcLineCaps.dwStippleWidth = 32;
    desc7->dpcLineCaps.dwStippleHeight = 32;
    /* Use the same for the TriCaps */
    desc7->dpcTriCaps = desc7->dpcLineCaps;

    desc7->dwDeviceRenderBitDepth = DDBD_16 | DDBD_24 | DDBD_32;
    desc7->dwDeviceZBufferBitDepth = DDBD_16 | DDBD_24;
    desc7->dwMinTextureWidth = 1;
    desc7->dwMinTextureHeight = 1;

    /* Convert DWORDs safely to WORDs */
    if (wined3d_caps.MaxTextureBlendStages > 0xffff) desc7->wMaxTextureBlendStages = 0xffff;
    else desc7->wMaxTextureBlendStages = (WORD)wined3d_caps.MaxTextureBlendStages;
    if (wined3d_caps.MaxSimultaneousTextures > 0xffff) desc7->wMaxSimultaneousTextures = 0xffff;
    else desc7->wMaxSimultaneousTextures = (WORD)wined3d_caps.MaxSimultaneousTextures;

    if (wined3d_caps.MaxUserClipPlanes > 0xffff) desc7->wMaxUserClipPlanes = 0xffff;
    else desc7->wMaxUserClipPlanes = (WORD)wined3d_caps.MaxUserClipPlanes;
    if (wined3d_caps.MaxVertexBlendMatrices > 0xffff) desc7->wMaxVertexBlendMatrices = 0xffff;
    else desc7->wMaxVertexBlendMatrices = (WORD)wined3d_caps.MaxVertexBlendMatrices;

    desc7->deviceGUID = IID_IDirect3DTnLHalDevice;

    desc7->dwReserved1 = 0;
    desc7->dwReserved2 = 0;
    desc7->dwReserved3 = 0;
    desc7->dwReserved4 = 0;

    /* Fill the old structure */
5369
    memset(desc1, 0, sizeof(*desc1));
5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456
    desc1->dwSize = sizeof(D3DDEVICEDESC);
    desc1->dwFlags = D3DDD_COLORMODEL
            | D3DDD_DEVCAPS
            | D3DDD_TRANSFORMCAPS
            | D3DDD_BCLIPPING
            | D3DDD_LIGHTINGCAPS
            | D3DDD_LINECAPS
            | D3DDD_TRICAPS
            | D3DDD_DEVICERENDERBITDEPTH
            | D3DDD_DEVICEZBUFFERBITDEPTH
            | D3DDD_MAXBUFFERSIZE
            | D3DDD_MAXVERTEXCOUNT;

    desc1->dcmColorModel = D3DCOLOR_RGB;
    desc1->dwDevCaps = desc7->dwDevCaps;
    desc1->dtcTransformCaps.dwSize = sizeof(D3DTRANSFORMCAPS);
    desc1->dtcTransformCaps.dwCaps = D3DTRANSFORMCAPS_CLIP;
    desc1->bClipping = TRUE;
    desc1->dlcLightingCaps.dwSize = sizeof(D3DLIGHTINGCAPS);
    desc1->dlcLightingCaps.dwCaps = D3DLIGHTCAPS_DIRECTIONAL
            | D3DLIGHTCAPS_PARALLELPOINT
            | D3DLIGHTCAPS_POINT
            | D3DLIGHTCAPS_SPOT;

    desc1->dlcLightingCaps.dwLightingModel = D3DLIGHTINGMODEL_RGB;
    desc1->dlcLightingCaps.dwNumLights = desc7->dwMaxActiveLights;

    desc1->dpcLineCaps.dwSize = sizeof(D3DPRIMCAPS);
    desc1->dpcLineCaps.dwMiscCaps = desc7->dpcLineCaps.dwMiscCaps;
    desc1->dpcLineCaps.dwRasterCaps = desc7->dpcLineCaps.dwRasterCaps;
    desc1->dpcLineCaps.dwZCmpCaps = desc7->dpcLineCaps.dwZCmpCaps;
    desc1->dpcLineCaps.dwSrcBlendCaps = desc7->dpcLineCaps.dwSrcBlendCaps;
    desc1->dpcLineCaps.dwDestBlendCaps = desc7->dpcLineCaps.dwDestBlendCaps;
    desc1->dpcLineCaps.dwShadeCaps = desc7->dpcLineCaps.dwShadeCaps;
    desc1->dpcLineCaps.dwTextureCaps = desc7->dpcLineCaps.dwTextureCaps;
    desc1->dpcLineCaps.dwTextureFilterCaps = desc7->dpcLineCaps.dwTextureFilterCaps;
    desc1->dpcLineCaps.dwTextureBlendCaps = desc7->dpcLineCaps.dwTextureBlendCaps;
    desc1->dpcLineCaps.dwTextureAddressCaps = desc7->dpcLineCaps.dwTextureAddressCaps;
    desc1->dpcLineCaps.dwStippleWidth = desc7->dpcLineCaps.dwStippleWidth;
    desc1->dpcLineCaps.dwAlphaCmpCaps = desc7->dpcLineCaps.dwAlphaCmpCaps;

    desc1->dpcTriCaps.dwSize = sizeof(D3DPRIMCAPS);
    desc1->dpcTriCaps.dwMiscCaps = desc7->dpcTriCaps.dwMiscCaps;
    desc1->dpcTriCaps.dwRasterCaps = desc7->dpcTriCaps.dwRasterCaps;
    desc1->dpcTriCaps.dwZCmpCaps = desc7->dpcTriCaps.dwZCmpCaps;
    desc1->dpcTriCaps.dwSrcBlendCaps = desc7->dpcTriCaps.dwSrcBlendCaps;
    desc1->dpcTriCaps.dwDestBlendCaps = desc7->dpcTriCaps.dwDestBlendCaps;
    desc1->dpcTriCaps.dwShadeCaps = desc7->dpcTriCaps.dwShadeCaps;
    desc1->dpcTriCaps.dwTextureCaps = desc7->dpcTriCaps.dwTextureCaps;
    desc1->dpcTriCaps.dwTextureFilterCaps = desc7->dpcTriCaps.dwTextureFilterCaps;
    desc1->dpcTriCaps.dwTextureBlendCaps = desc7->dpcTriCaps.dwTextureBlendCaps;
    desc1->dpcTriCaps.dwTextureAddressCaps = desc7->dpcTriCaps.dwTextureAddressCaps;
    desc1->dpcTriCaps.dwStippleWidth = desc7->dpcTriCaps.dwStippleWidth;
    desc1->dpcTriCaps.dwAlphaCmpCaps = desc7->dpcTriCaps.dwAlphaCmpCaps;

    desc1->dwDeviceRenderBitDepth = desc7->dwDeviceRenderBitDepth;
    desc1->dwDeviceZBufferBitDepth = desc7->dwDeviceZBufferBitDepth;
    desc1->dwMaxBufferSize = 0;
    desc1->dwMaxVertexCount = 65536;
    desc1->dwMinTextureWidth  = desc7->dwMinTextureWidth;
    desc1->dwMinTextureHeight = desc7->dwMinTextureHeight;
    desc1->dwMaxTextureWidth  = desc7->dwMaxTextureWidth;
    desc1->dwMaxTextureHeight = desc7->dwMaxTextureHeight;
    desc1->dwMinStippleWidth  = 1;
    desc1->dwMinStippleHeight = 1;
    desc1->dwMaxStippleWidth  = 32;
    desc1->dwMaxStippleHeight = 32;
    desc1->dwMaxTextureRepeat = desc7->dwMaxTextureRepeat;
    desc1->dwMaxTextureAspectRatio = desc7->dwMaxTextureAspectRatio;
    desc1->dwMaxAnisotropy = desc7->dwMaxAnisotropy;
    desc1->dvGuardBandLeft = desc7->dvGuardBandLeft;
    desc1->dvGuardBandRight = desc7->dvGuardBandRight;
    desc1->dvGuardBandTop = desc7->dvGuardBandTop;
    desc1->dvGuardBandBottom = desc7->dvGuardBandBottom;
    desc1->dvExtentsAdjust = desc7->dvExtentsAdjust;
    desc1->dwStencilCaps = desc7->dwStencilCaps;
    desc1->dwFVFCaps = desc7->dwFVFCaps;
    desc1->dwTextureOpCaps = desc7->dwTextureOpCaps;
    desc1->wMaxTextureBlendStages = desc7->wMaxTextureBlendStages;
    desc1->wMaxSimultaneousTextures = desc7->wMaxSimultaneousTextures;

    return DD_OK;
}

/*****************************************************************************
 * IDirectDraw7 VTable
 *****************************************************************************/
5457
static const struct IDirectDraw7Vtbl ddraw7_vtbl =
5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496
{
    /* IUnknown */
    ddraw7_QueryInterface,
    ddraw7_AddRef,
    ddraw7_Release,
    /* IDirectDraw */
    ddraw7_Compact,
    ddraw7_CreateClipper,
    ddraw7_CreatePalette,
    ddraw7_CreateSurface,
    ddraw7_DuplicateSurface,
    ddraw7_EnumDisplayModes,
    ddraw7_EnumSurfaces,
    ddraw7_FlipToGDISurface,
    ddraw7_GetCaps,
    ddraw7_GetDisplayMode,
    ddraw7_GetFourCCCodes,
    ddraw7_GetGDISurface,
    ddraw7_GetMonitorFrequency,
    ddraw7_GetScanLine,
    ddraw7_GetVerticalBlankStatus,
    ddraw7_Initialize,
    ddraw7_RestoreDisplayMode,
    ddraw7_SetCooperativeLevel,
    ddraw7_SetDisplayMode,
    ddraw7_WaitForVerticalBlank,
    /* IDirectDraw2 */
    ddraw7_GetAvailableVidMem,
    /* IDirectDraw3 */
    ddraw7_GetSurfaceFromDC,
    /* IDirectDraw4 */
    ddraw7_RestoreAllSurfaces,
    ddraw7_TestCooperativeLevel,
    ddraw7_GetDeviceIdentifier,
    /* IDirectDraw7 */
    ddraw7_StartModeTest,
    ddraw7_EvaluateMode
};

5497
static const struct IDirectDraw4Vtbl ddraw4_vtbl =
5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533
{
    /* IUnknown */
    ddraw4_QueryInterface,
    ddraw4_AddRef,
    ddraw4_Release,
    /* IDirectDraw */
    ddraw4_Compact,
    ddraw4_CreateClipper,
    ddraw4_CreatePalette,
    ddraw4_CreateSurface,
    ddraw4_DuplicateSurface,
    ddraw4_EnumDisplayModes,
    ddraw4_EnumSurfaces,
    ddraw4_FlipToGDISurface,
    ddraw4_GetCaps,
    ddraw4_GetDisplayMode,
    ddraw4_GetFourCCCodes,
    ddraw4_GetGDISurface,
    ddraw4_GetMonitorFrequency,
    ddraw4_GetScanLine,
    ddraw4_GetVerticalBlankStatus,
    ddraw4_Initialize,
    ddraw4_RestoreDisplayMode,
    ddraw4_SetCooperativeLevel,
    ddraw4_SetDisplayMode,
    ddraw4_WaitForVerticalBlank,
    /* IDirectDraw2 */
    ddraw4_GetAvailableVidMem,
    /* IDirectDraw3 */
    ddraw4_GetSurfaceFromDC,
    /* IDirectDraw4 */
    ddraw4_RestoreAllSurfaces,
    ddraw4_TestCooperativeLevel,
    ddraw4_GetDeviceIdentifier,
};

5534
static const struct IDirectDraw3Vtbl ddraw3_vtbl =
5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566
{
    /* IUnknown */
    ddraw3_QueryInterface,
    ddraw3_AddRef,
    ddraw3_Release,
    /* IDirectDraw */
    ddraw3_Compact,
    ddraw3_CreateClipper,
    ddraw3_CreatePalette,
    ddraw3_CreateSurface,
    ddraw3_DuplicateSurface,
    ddraw3_EnumDisplayModes,
    ddraw3_EnumSurfaces,
    ddraw3_FlipToGDISurface,
    ddraw3_GetCaps,
    ddraw3_GetDisplayMode,
    ddraw3_GetFourCCCodes,
    ddraw3_GetGDISurface,
    ddraw3_GetMonitorFrequency,
    ddraw3_GetScanLine,
    ddraw3_GetVerticalBlankStatus,
    ddraw3_Initialize,
    ddraw3_RestoreDisplayMode,
    ddraw3_SetCooperativeLevel,
    ddraw3_SetDisplayMode,
    ddraw3_WaitForVerticalBlank,
    /* IDirectDraw2 */
    ddraw3_GetAvailableVidMem,
    /* IDirectDraw3 */
    ddraw3_GetSurfaceFromDC,
};

5567
static const struct IDirectDraw2Vtbl ddraw2_vtbl =
5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581
{
    /* IUnknown */
    ddraw2_QueryInterface,
    ddraw2_AddRef,
    ddraw2_Release,
    /* IDirectDraw */
    ddraw2_Compact,
    ddraw2_CreateClipper,
    ddraw2_CreatePalette,
    ddraw2_CreateSurface,
    ddraw2_DuplicateSurface,
    ddraw2_EnumDisplayModes,
    ddraw2_EnumSurfaces,
    ddraw2_FlipToGDISurface,
5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597
    ddraw2_GetCaps,
    ddraw2_GetDisplayMode,
    ddraw2_GetFourCCCodes,
    ddraw2_GetGDISurface,
    ddraw2_GetMonitorFrequency,
    ddraw2_GetScanLine,
    ddraw2_GetVerticalBlankStatus,
    ddraw2_Initialize,
    ddraw2_RestoreDisplayMode,
    ddraw2_SetCooperativeLevel,
    ddraw2_SetDisplayMode,
    ddraw2_WaitForVerticalBlank,
    /* IDirectDraw2 */
    ddraw2_GetAvailableVidMem,
};

5598
static const struct IDirectDrawVtbl ddraw1_vtbl =
5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624
{
    /* IUnknown */
    ddraw1_QueryInterface,
    ddraw1_AddRef,
    ddraw1_Release,
    /* IDirectDraw */
    ddraw1_Compact,
    ddraw1_CreateClipper,
    ddraw1_CreatePalette,
    ddraw1_CreateSurface,
    ddraw1_DuplicateSurface,
    ddraw1_EnumDisplayModes,
    ddraw1_EnumSurfaces,
    ddraw1_FlipToGDISurface,
    ddraw1_GetCaps,
    ddraw1_GetDisplayMode,
    ddraw1_GetFourCCCodes,
    ddraw1_GetGDISurface,
    ddraw1_GetMonitorFrequency,
    ddraw1_GetScanLine,
    ddraw1_GetVerticalBlankStatus,
    ddraw1_Initialize,
    ddraw1_RestoreDisplayMode,
    ddraw1_SetCooperativeLevel,
    ddraw1_SetDisplayMode,
    ddraw1_WaitForVerticalBlank,
5625
};
5626

5627
static const struct IDirect3D7Vtbl d3d7_vtbl =
5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640
{
    /* IUnknown methods */
    d3d7_QueryInterface,
    d3d7_AddRef,
    d3d7_Release,
    /* IDirect3D7 methods */
    d3d7_EnumDevices,
    d3d7_CreateDevice,
    d3d7_CreateVertexBuffer,
    d3d7_EnumZBufferFormats,
    d3d7_EvictManagedTextures
};

5641
static const struct IDirect3D3Vtbl d3d3_vtbl =
5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658
{
    /* IUnknown methods */
    d3d3_QueryInterface,
    d3d3_AddRef,
    d3d3_Release,
    /* IDirect3D3 methods */
    d3d3_EnumDevices,
    d3d3_CreateLight,
    d3d3_CreateMaterial,
    d3d3_CreateViewport,
    d3d3_FindDevice,
    d3d3_CreateDevice,
    d3d3_CreateVertexBuffer,
    d3d3_EnumZBufferFormats,
    d3d3_EvictManagedTextures
};

5659
static const struct IDirect3D2Vtbl d3d2_vtbl =
5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673
{
    /* IUnknown methods */
    d3d2_QueryInterface,
    d3d2_AddRef,
    d3d2_Release,
    /* IDirect3D2 methods */
    d3d2_EnumDevices,
    d3d2_CreateLight,
    d3d2_CreateMaterial,
    d3d2_CreateViewport,
    d3d2_FindDevice,
    d3d2_CreateDevice
};

5674
static const struct IDirect3DVtbl d3d1_vtbl =
5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688
{
    /* IUnknown methods */
    d3d1_QueryInterface,
    d3d1_AddRef,
    d3d1_Release,
    /* IDirect3D methods */
    d3d1_Initialize,
    d3d1_EnumDevices,
    d3d1_CreateLight,
    d3d1_CreateMaterial,
    d3d1_CreateViewport,
    d3d1_FindDevice
};

5689
/*****************************************************************************
5690
 * ddraw_find_decl
5691 5692 5693 5694 5695 5696
 *
 * Finds the WineD3D vertex declaration for a specific fvf, and creates one
 * if none was found.
 *
 * This function is in ddraw.c and the DDraw object space because D3D7
 * vertex buffers are created using the IDirect3D interface to the ddraw
5697
 * object, so they can be valid across D3D devices(theoretically. The ddraw
5698 5699 5700 5701 5702 5703 5704
 * object also owns the wined3d device
 *
 * Parameters:
 *  This: Device
 *  fvf: Fvf to find the decl for
 *
 * Returns:
5705
 *  NULL in case of an error, the vertex declaration for the FVF otherwise.
5706 5707
 *
 *****************************************************************************/
5708
struct wined3d_vertex_declaration *ddraw_find_decl(IDirectDrawImpl *This, DWORD fvf)
5709
{
5710
    struct wined3d_vertex_declaration *pDecl = NULL;
5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732
    HRESULT hr;
    int p, low, high; /* deliberately signed */
    struct FvfToDecl *convertedDecls = This->decls;

    TRACE("Searching for declaration for fvf %08x... ", fvf);

    low = 0;
    high = This->numConvertedDecls - 1;
    while(low <= high) {
        p = (low + high) >> 1;
        TRACE("%d ", p);
        if(convertedDecls[p].fvf == fvf) {
            TRACE("found %p\n", convertedDecls[p].decl);
            return convertedDecls[p].decl;
        } else if(convertedDecls[p].fvf < fvf) {
            low = p + 1;
        } else {
            high = p - 1;
        }
    }
    TRACE("not found. Creating and inserting at position %d.\n", low);

5733
    hr = wined3d_vertex_declaration_create_from_fvf(This->wined3d_device,
5734
            fvf, This, &ddraw_null_wined3d_parent_ops, &pDecl);
5735 5736 5737 5738 5739 5740
    if (hr != S_OK) return NULL;

    if(This->declArraySize == This->numConvertedDecls) {
        int grow = max(This->declArraySize / 2, 8);
        convertedDecls = HeapReAlloc(GetProcessHeap(), 0, convertedDecls,
                                     sizeof(convertedDecls[0]) * (This->numConvertedDecls + grow));
5741 5742 5743
        if (!convertedDecls)
        {
            wined3d_vertex_declaration_decref(pDecl);
5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757
            return NULL;
        }
        This->decls = convertedDecls;
        This->declArraySize += grow;
    }

    memmove(convertedDecls + low + 1, convertedDecls + low, sizeof(convertedDecls[0]) * (This->numConvertedDecls - low));
    convertedDecls[low].decl = pDecl;
    convertedDecls[low].fvf = fvf;
    This->numConvertedDecls++;

    TRACE("Returning %p. %d decls in array\n", pDecl, This->numConvertedDecls);
    return pDecl;
}
5758

5759
static inline struct IDirectDrawImpl *ddraw_from_device_parent(struct wined3d_device_parent *device_parent)
5760
{
5761
    return CONTAINING_RECORD(device_parent, struct IDirectDrawImpl, device_parent);
5762 5763
}

5764
static void CDECL device_parent_wined3d_device_created(struct wined3d_device_parent *device_parent,
5765
        struct wined3d_device *device)
5766
{
5767
    TRACE("device_parent %p, device %p.\n", device_parent, device);
5768 5769
}

5770
static HRESULT CDECL device_parent_create_surface(struct wined3d_device_parent *device_parent,
5771
        void *container_parent, UINT width, UINT height, enum wined3d_format_id format, DWORD usage,
5772
        WINED3DPOOL pool, UINT level, WINED3DCUBEMAP_FACES face, struct wined3d_surface **surface)
5773
{
5774
    struct IDirectDrawImpl *ddraw = ddraw_from_device_parent(device_parent);
5775 5776
    IDirectDrawSurfaceImpl *surf = NULL;
    UINT i = 0;
5777
    DDSCAPS2 searchcaps = ddraw->tex_root->surface_desc.ddsCaps;
5778

5779 5780 5781
    TRACE("device_parent %p, container_parent %p, width %u, height %u, format %#x, usage %#x,\n"
            "\tpool %#x, level %u, face %u, surface %p.\n",
            device_parent, container_parent, width, height, format, usage, pool, level, face, surface);
5782 5783 5784 5785 5786 5787 5788 5789 5790 5791

    searchcaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
    switch(face)
    {
        case WINED3DCUBEMAP_FACE_POSITIVE_X:
            TRACE("Asked for positive x\n");
            if (searchcaps.dwCaps2 & DDSCAPS2_CUBEMAP)
            {
                searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEX;
            }
5792
            surf = ddraw->tex_root; break;
5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813
        case WINED3DCUBEMAP_FACE_NEGATIVE_X:
            TRACE("Asked for negative x\n");
            searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEX; break;
        case WINED3DCUBEMAP_FACE_POSITIVE_Y:
            TRACE("Asked for positive y\n");
            searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEY; break;
        case WINED3DCUBEMAP_FACE_NEGATIVE_Y:
            TRACE("Asked for negative y\n");
            searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEY; break;
        case WINED3DCUBEMAP_FACE_POSITIVE_Z:
            TRACE("Asked for positive z\n");
            searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEZ; break;
        case WINED3DCUBEMAP_FACE_NEGATIVE_Z:
            TRACE("Asked for negative z\n");
            searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEZ; break;
        default: {ERR("Unexpected cube face\n");} /* Stupid compiler */
    }

    if (!surf)
    {
        IDirectDrawSurface7 *attached;
5814
        IDirectDrawSurface7_GetAttachedSurface(&ddraw->tex_root->IDirectDrawSurface7_iface, &searchcaps, &attached);
5815
        surf = unsafe_impl_from_IDirectDrawSurface7(attached);
5816 5817 5818 5819 5820 5821 5822 5823
        IDirectDrawSurface7_Release(attached);
    }
    if (!surf) ERR("root search surface not found\n");

    /* Find the wanted mipmap. There are enough mipmaps in the chain */
    while (i < level)
    {
        IDirectDrawSurface7 *attached;
5824
        IDirectDrawSurface7_GetAttachedSurface(&surf->IDirectDrawSurface7_iface, &searchcaps, &attached);
5825
        if(!attached) ERR("Surface not found\n");
5826
        surf = impl_from_IDirectDrawSurface7(attached);
5827 5828 5829 5830 5831
        IDirectDrawSurface7_Release(attached);
        ++i;
    }

    /* Return the surface */
5832 5833
    *surface = surf->wined3d_surface;
    wined3d_surface_incref(*surface);
5834 5835 5836 5837 5838 5839

    TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *surface, surf);

    return D3D_OK;
}

5840 5841
static HRESULT WINAPI findRenderTarget(IDirectDrawSurface7 *surface, DDSURFACEDESC2 *surface_desc, void *ctx)
{
5842
    IDirectDrawSurfaceImpl *s = impl_from_IDirectDrawSurface7(surface);
5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860
    IDirectDrawSurfaceImpl **target = ctx;

    if (!s->isRenderTarget)
    {
        *target = s;
        IDirectDrawSurface7_Release(surface);
        return DDENUMRET_CANCEL;
    }

    /* Recurse into the surface tree */
    IDirectDrawSurface7_EnumAttachedSurfaces(surface, ctx, findRenderTarget);

    IDirectDrawSurface7_Release(surface);
    if (*target) return DDENUMRET_CANCEL;

    return DDENUMRET_OK;
}

5861
static HRESULT CDECL device_parent_create_rendertarget(struct wined3d_device_parent *device_parent,
5862
        void *container_parent, UINT width, UINT height, enum wined3d_format_id format,
5863
        WINED3DMULTISAMPLE_TYPE multisample_type, DWORD multisample_quality, BOOL lockable,
5864
        struct wined3d_surface **surface)
5865
{
5866 5867
    struct IDirectDrawImpl *ddraw = ddraw_from_device_parent(device_parent);
    IDirectDrawSurfaceImpl *d3d_surface = ddraw->d3d_target;
5868 5869
    IDirectDrawSurfaceImpl *target = NULL;

5870 5871 5872 5873
    TRACE("device_parent %p, container_parent %p, width %u, height %u, format %#x, multisample_type %#x,\n"
            "\tmultisample_quality %u, lockable %u, surface %p.\n",
            device_parent, container_parent, width, height, format, multisample_type,
            multisample_quality, lockable, surface);
5874 5875 5876

    if (d3d_surface->isRenderTarget)
    {
5877
        IDirectDrawSurface7_EnumAttachedSurfaces(&d3d_surface->IDirectDrawSurface7_iface, &target, findRenderTarget);
5878 5879 5880 5881 5882 5883 5884 5885
    }
    else
    {
        target = d3d_surface;
    }

    if (!target)
    {
5886 5887
        target = ddraw->d3d_target;
        ERR(" (%p) : No DirectDrawSurface found to create the back buffer. Using the front buffer as back buffer. Uncertain consequences\n", ddraw);
5888 5889 5890 5891
    }

    /* TODO: Return failure if the dimensions do not match, but this shouldn't happen */

5892 5893
    *surface = target->wined3d_surface;
    wined3d_surface_incref(*surface);
5894 5895 5896 5897 5898 5899 5900
    target->isRenderTarget = TRUE;

    TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *surface, d3d_surface);

    return D3D_OK;
}

5901
static HRESULT CDECL device_parent_create_depth_stencil(struct wined3d_device_parent *device_parent,
5902
        UINT width, UINT height, enum wined3d_format_id format, WINED3DMULTISAMPLE_TYPE multisample_type,
5903
        DWORD multisample_quality, BOOL discard, struct wined3d_surface **surface)
5904
{
5905
    struct IDirectDrawImpl *ddraw = ddraw_from_device_parent(device_parent);
5906
    IDirectDrawSurface7 *ddraw7;
5907
    IDirectDrawSurfaceImpl *ddraw_surface;
5908 5909 5910
    DDSURFACEDESC2 ddsd;
    HRESULT hr;

5911 5912 5913
    TRACE("device_parent %p, width %u, height %u, format %#x, multisample_type %#x,\n"
            "\tmultisample_quality %u, discard %u, surface %p.\n",
            device_parent, width, height, format, multisample_type, multisample_quality, discard, surface);
5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933

    *surface = NULL;

    /* Create a DirectDraw surface */
    memset(&ddsd, 0, sizeof(ddsd));
    ddsd.dwSize = sizeof(ddsd);
    ddsd.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
    ddsd.dwFlags = DDSD_PIXELFORMAT | DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS;
    ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
    ddsd.dwHeight = height;
    ddsd.dwWidth = width;
    if (format)
    {
        PixelFormat_WineD3DtoDD(&ddsd.u4.ddpfPixelFormat, format);
    }
    else
    {
        ddsd.dwFlags ^= DDSD_PIXELFORMAT;
    }

5934
    ddraw->depthstencil = TRUE;
5935
    hr = IDirectDraw7_CreateSurface(&ddraw->IDirectDraw7_iface, &ddsd, &ddraw7, NULL);
5936 5937
    ddraw->depthstencil = FALSE;
    if (FAILED(hr))
5938
    {
5939
        WARN("Failed to create depth/stencil surface, hr %#x.\n", hr);
5940 5941 5942
        return hr;
    }

5943
    ddraw_surface = impl_from_IDirectDrawSurface7(ddraw7);
5944 5945
    *surface = ddraw_surface->wined3d_surface;
    wined3d_surface_incref(*surface);
5946
    IDirectDrawSurface7_Release(&ddraw_surface->IDirectDrawSurface7_iface);
5947 5948 5949 5950

    return D3D_OK;
}

5951
static HRESULT CDECL device_parent_create_volume(struct wined3d_device_parent *device_parent,
5952
        void *container_parent, UINT width, UINT height, UINT depth, enum wined3d_format_id format,
5953
        WINED3DPOOL pool, DWORD usage, struct wined3d_volume **volume)
5954
{
5955 5956 5957 5958
    TRACE("device_parent %p, container_parent %p, width %u, height %u, depth %u, "
            "format %#x, pool %#x, usage %#x, volume %p.\n",
            device_parent, container_parent, width, height, depth,
            format, pool, usage, volume);
5959 5960 5961 5962 5963 5964

    ERR("Not implemented!\n");

    return E_NOTIMPL;
}

5965
static HRESULT CDECL device_parent_create_swapchain(struct wined3d_device_parent *device_parent,
5966
        WINED3DPRESENT_PARAMETERS *present_parameters, struct wined3d_swapchain **swapchain)
5967
{
5968
    struct IDirectDrawImpl *ddraw = ddraw_from_device_parent(device_parent);
5969 5970 5971
    IDirectDrawSurfaceImpl *iterator;
    HRESULT hr;

5972
    TRACE("device_parent %p, present_parameters %p, swapchain %p.\n", device_parent, present_parameters, swapchain);
5973

5974 5975
    hr = wined3d_swapchain_create(ddraw->wined3d_device, present_parameters,
            ddraw->ImplType, NULL, &ddraw_null_wined3d_parent_ops, swapchain);
5976 5977
    if (FAILED(hr))
    {
5978
        WARN("Failed to create swapchain, hr %#x.\n", hr);
5979 5980 5981 5982
        *swapchain = NULL;
        return hr;
    }

5983 5984
    ddraw->d3d_target->wined3d_swapchain = *swapchain;
    iterator = ddraw->d3d_target->complex_array[0];
5985 5986
    while (iterator)
    {
5987
        iterator->wined3d_swapchain = *swapchain;
5988 5989 5990 5991 5992 5993
        iterator = iterator->complex_array[0];
    }

    return hr;
}

5994
static const struct wined3d_device_parent_ops ddraw_wined3d_device_parent_ops =
5995
{
5996 5997 5998 5999 6000 6001
    device_parent_wined3d_device_created,
    device_parent_create_surface,
    device_parent_create_rendertarget,
    device_parent_create_depth_stencil,
    device_parent_create_volume,
    device_parent_create_swapchain,
6002
};
6003 6004 6005 6006 6007 6008

HRESULT ddraw_init(IDirectDrawImpl *ddraw, WINED3DDEVTYPE device_type)
{
    HRESULT hr;
    HDC hDC;

6009
    ddraw->IDirectDraw7_iface.lpVtbl = &ddraw7_vtbl;
6010
    ddraw->IDirectDraw_iface.lpVtbl = &ddraw1_vtbl;
6011
    ddraw->IDirectDraw2_iface.lpVtbl = &ddraw2_vtbl;
6012
    ddraw->IDirectDraw3_iface.lpVtbl = &ddraw3_vtbl;
6013
    ddraw->IDirectDraw4_iface.lpVtbl = &ddraw4_vtbl;
6014
    ddraw->IDirect3D_iface.lpVtbl = &d3d1_vtbl;
6015
    ddraw->IDirect3D2_iface.lpVtbl = &d3d2_vtbl;
6016
    ddraw->IDirect3D3_iface.lpVtbl = &d3d3_vtbl;
6017
    ddraw->IDirect3D7_iface.lpVtbl = &d3d7_vtbl;
6018
    ddraw->device_parent.ops = &ddraw_wined3d_device_parent_ops;
6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032
    ddraw->numIfaces = 1;
    ddraw->ref7 = 1;

    /* See comments in IDirectDrawImpl_CreateNewSurface for a description of
     * this field. */
    ddraw->ImplType = DefaultSurfaceType;

    /* Get the current screen settings. */
    hDC = GetDC(0);
    ddraw->orig_bpp = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
    ReleaseDC(0, hDC);
    ddraw->orig_width = GetSystemMetrics(SM_CXSCREEN);
    ddraw->orig_height = GetSystemMetrics(SM_CYSCREEN);

6033
    ddraw->wineD3D = wined3d_create(7, &ddraw->IDirectDraw7_iface);
6034 6035 6036 6037 6038 6039
    if (!ddraw->wineD3D)
    {
        WARN("Failed to create a wined3d object.\n");
        return E_OUTOFMEMORY;
    }

6040 6041
    hr = wined3d_device_create(ddraw->wineD3D, WINED3DADAPTER_DEFAULT, device_type,
            NULL, 0, &ddraw->device_parent, &ddraw->wined3d_device);
6042 6043 6044
    if (FAILED(hr))
    {
        WARN("Failed to create a wined3d device, hr %#x.\n", hr);
6045
        wined3d_decref(ddraw->wineD3D);
6046 6047 6048 6049
        return hr;
    }

    /* Get the amount of video memory */
6050
    ddraw->total_vidmem = wined3d_device_get_available_texture_mem(ddraw->wined3d_device);
6051 6052 6053 6054 6055

    list_init(&ddraw->surface_list);

    return DD_OK;
}