surface.c 205 KB
Newer Older
1 2 3
/*
 * IWineD3DSurface Implementation
 *
4
 * Copyright 1998 Lionel Ulmer
5
 * Copyright 2000-2001 TransGaming Technologies Inc.
6 7 8
 * Copyright 2002-2005 Jason Edmeades
 * Copyright 2002-2003 Raphael Junqueira
 * Copyright 2004 Christian Costa
9
 * Copyright 2005 Oliver Stieber
10
 * Copyright 2006-2008 Stefan Dösinger for CodeWeavers
11
 * Copyright 2007-2008 Henri Verbeet
12
 * Copyright 2006-2008 Roderick Colenbrander
13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * 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
26
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 28 29
 */

#include "config.h"
30
#include "wine/port.h"
31 32 33
#include "wined3d_private.h"

WINE_DEFAULT_DEBUG_CHANNEL(d3d_surface);
34
WINE_DECLARE_DEBUG_CHANNEL(d3d);
35 36

#define GLINFO_LOCATION (*gl_info)
37

38 39 40
static void surface_cleanup(IWineD3DSurfaceImpl *This)
{
    IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
41
    const WineD3D_GL_Info *gl_info = &device->adapter->gl_info;
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    renderbuffer_entry_t *entry, *entry2;

    TRACE("(%p) : Cleaning up.\n", This);

    /* Need a context to destroy the texture. Use the currently active render
     * target, but only if the primary render target exists. Otherwise
     * lastActiveRenderTarget is garbage. When destroying the primary render
     * target, Uninit3D() will activate a context before doing anything. */
    if (device->render_targets && device->render_targets[0])
    {
        ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
    }

    ENTER_GL();

57
    if (This->texture_name)
58 59
    {
        /* Release the OpenGL texture. */
60 61
        TRACE("Deleting texture %u.\n", This->texture_name);
        glDeleteTextures(1, &This->texture_name);
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
    }

    if (This->Flags & SFLAG_PBO)
    {
        /* Delete the PBO. */
        GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
    }

    LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry)
    {
        GL_EXTCALL(glDeleteRenderbuffersEXT(1, &entry->id));
        HeapFree(GetProcessHeap(), 0, entry);
    }

    LEAVE_GL();

    if (This->Flags & SFLAG_DIBSECTION)
    {
        /* Release the DC. */
        SelectObject(This->hDC, This->dib.holdbitmap);
        DeleteDC(This->hDC);
        /* Release the DIB section. */
        DeleteObject(This->dib.DIBsection);
        This->dib.bitmap_data = NULL;
        This->resource.allocatedMemory = NULL;
    }

    if (This->Flags & SFLAG_USERPTR) IWineD3DSurface_SetMem((IWineD3DSurface *)This, NULL);
    if (This->overlay_dest) list_remove(&This->overlay_entry);

    HeapFree(GetProcessHeap(), 0, This->palette9);

    resource_cleanup((IWineD3DResource *)This);
}

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
UINT surface_calculate_size(const struct GlPixelFormatDesc *format_desc, UINT alignment, UINT width, UINT height)
{
    UINT size;

    if (format_desc->format == WINED3DFMT_UNKNOWN)
    {
        size = 0;
    }
    else if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
    {
        UINT row_block_count = (width + format_desc->block_width - 1) / format_desc->block_width;
        UINT row_count = (height + format_desc->block_height - 1) / format_desc->block_height;
        size = row_count * row_block_count * format_desc->block_byte_count;
    }
    else
    {
        /* The pitch is a multiple of 4 bytes. */
        size = height * (((width * format_desc->byte_count) + alignment - 1) & ~(alignment - 1));
    }

117
    if (format_desc->heightscale != 0.0f) size *= format_desc->heightscale;
118 119 120 121

    return size;
}

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
HRESULT surface_init(IWineD3DSurfaceImpl *surface, WINED3DSURFTYPE surface_type, UINT alignment,
        UINT width, UINT height, UINT level, BOOL lockable, BOOL discard, WINED3DMULTISAMPLE_TYPE multisample_type,
        UINT multisample_quality, IWineD3DDeviceImpl *device, DWORD usage, WINED3DFORMAT format,
        WINED3DPOOL pool, IUnknown *parent)
{
    const WineD3D_GL_Info *gl_info = &device->adapter->gl_info;
    const struct GlPixelFormatDesc *format_desc = getFormatDescEntry(format, &GLINFO_LOCATION);
    void (*cleanup)(IWineD3DSurfaceImpl *This);
    unsigned int resource_size;
    HRESULT hr;

    if (multisample_quality > 0)
    {
        FIXME("multisample_quality set to %u, substituting 0\n", multisample_quality);
        multisample_quality = 0;
    }

    /* FIXME: Check that the format is supported by the device. */

141
    resource_size = surface_calculate_size(format_desc, alignment, width, height);
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175

    /* Look at the implementation and set the correct Vtable. */
    switch (surface_type)
    {
        case SURFACE_OPENGL:
            surface->lpVtbl = &IWineD3DSurface_Vtbl;
            cleanup = surface_cleanup;
            break;

        case SURFACE_GDI:
            surface->lpVtbl = &IWineGDISurface_Vtbl;
            cleanup = surface_gdi_cleanup;
            break;

        default:
            ERR("Requested unknown surface implementation %#x.\n", surface_type);
            return WINED3DERR_INVALIDCALL;
    }

    hr = resource_init((IWineD3DResource *)surface, WINED3DRTYPE_SURFACE,
            device, resource_size, usage, format_desc, pool, parent);
    if (FAILED(hr))
    {
        WARN("Failed to initialize resource, returning %#x.\n", hr);
        return hr;
    }

    /* "Standalone" surface. */
    IWineD3DSurface_SetContainer((IWineD3DSurface *)surface, NULL);

    surface->currentDesc.Width = width;
    surface->currentDesc.Height = height;
    surface->currentDesc.MultiSampleType = multisample_type;
    surface->currentDesc.MultiSampleQuality = multisample_quality;
176
    surface->texture_level = level;
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 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 230 231 232 233 234 235 236 237 238 239 240 241
    list_init(&surface->overlays);

    /* Flags */
    surface->Flags = SFLAG_NORMCOORD; /* Default to normalized coords. */
    if (discard) surface->Flags |= SFLAG_DISCARD;
    if (lockable || format == WINED3DFMT_D16_LOCKABLE) surface->Flags |= SFLAG_LOCKABLE;

    /* Quick lockable sanity check.
     * TODO: remove this after surfaces, usage and lockability have been debugged properly
     * this function is too deep to need to care about things like this.
     * Levels need to be checked too, since they all affect what can be done. */
    switch (pool)
    {
        case WINED3DPOOL_SCRATCH:
            if(!lockable)
            {
                FIXME("Called with a pool of SCRATCH and a lockable of FALSE "
                        "which are mutually exclusive, setting lockable to TRUE.\n");
                lockable = TRUE;
            }
            break;

        case WINED3DPOOL_SYSTEMMEM:
            if (!lockable)
                FIXME("Called with a pool of SYSTEMMEM and a lockable of FALSE, this is acceptable but unexpected.\n");
            break;

        case WINED3DPOOL_MANAGED:
            if (usage & WINED3DUSAGE_DYNAMIC)
                FIXME("Called with a pool of MANAGED and a usage of DYNAMIC which are mutually exclusive.\n");
            break;

        case WINED3DPOOL_DEFAULT:
            if (lockable && !(usage & (WINED3DUSAGE_DYNAMIC | WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL)))
                WARN("Creating a lockable surface with a POOL of DEFAULT, that doesn't specify DYNAMIC usage.\n");
            break;

        default:
            FIXME("Unknown pool %#x.\n", pool);
            break;
    };

    if (usage & WINED3DUSAGE_RENDERTARGET && pool != WINED3DPOOL_DEFAULT)
    {
        FIXME("Trying to create a render target that isn't in the default pool.\n");
    }

    /* Mark the texture as dirty so that it gets loaded first time around. */
    surface_add_dirty_rect((IWineD3DSurface *)surface, NULL);
    list_init(&surface->renderbuffers);

    TRACE("surface %p, memory %p, size %u\n", surface, surface->resource.allocatedMemory, surface->resource.size);

    /* Call the private setup routine */
    hr = IWineD3DSurface_PrivateSetup((IWineD3DSurface *)surface);
    if (FAILED(hr))
    {
        ERR("Private setup failed, returning %#x\n", hr);
        cleanup(surface);
        return hr;
    }

    return hr;
}

242
static void surface_force_reload(IWineD3DSurface *iface)
243 244 245
{
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;

246
    This->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
247 248
}

249
void surface_set_texture_name(IWineD3DSurface *iface, GLuint new_name, BOOL srgb)
250 251
{
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
252 253
    GLuint *name;
    DWORD flag;
254

255 256
    if(srgb)
    {
257
        name = &This->texture_name_srgb;
258 259 260 261
        flag = SFLAG_INSRGBTEX;
    }
    else
    {
262
        name = &This->texture_name;
263 264 265 266
        flag = SFLAG_INTEXTURE;
    }

    TRACE("(%p) : setting texture name %u\n", This, new_name);
267

268
    if (!*name && new_name)
269 270 271
    {
        /* FIXME: We shouldn't need to remove SFLAG_INTEXTURE if the
         * surface has no texture name yet. See if we can get rid of this. */
272
        if (This->Flags & flag)
273
            ERR("Surface has SFLAG_INTEXTURE set, but no texture name\n");
274
        IWineD3DSurface_ModifyLocation(iface, flag, FALSE);
275 276
    }

277
    *name = new_name;
278 279 280 281 282 283 284 285 286
    surface_force_reload(iface);
}

void surface_set_texture_target(IWineD3DSurface *iface, GLenum target)
{
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;

    TRACE("(%p) : setting target %#x\n", This, target);

287
    if (This->texture_target != target)
288 289 290 291 292
    {
        if (target == GL_TEXTURE_RECTANGLE_ARB)
        {
            This->Flags &= ~SFLAG_NORMCOORD;
        }
293
        else if (This->texture_target == GL_TEXTURE_RECTANGLE_ARB)
294 295 296 297
        {
            This->Flags |= SFLAG_NORMCOORD;
        }
    }
298
    This->texture_target = target;
299 300 301
    surface_force_reload(iface);
}

302
/* Context activation is done by the caller. */
303
static void surface_bind_and_dirtify(IWineD3DSurfaceImpl *This, BOOL srgb) {
304
    int active_sampler;
305 306 307 308 309

    /* We don't need a specific texture unit, but after binding the texture the current unit is dirty.
     * Read the unit back instead of switching to 0, this avoids messing around with the state manager's
     * gl states. The current texture unit should always be a valid one.
     *
310 311 312 313 314
     * To be more specific, this is tricky because we can implicitly be called
     * from sampler() in state.c. This means we can't touch anything other than
     * whatever happens to be the currently active texture, or we would risk
     * marking already applied sampler states dirty again.
     *
315 316
     * TODO: Track the current active texture per GL context instead of using glGet
     */
317 318 319 320 321
    GLint active_texture;
    ENTER_GL();
    glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
    LEAVE_GL();
    active_sampler = This->resource.wineD3DDevice->rev_tex_unit_map[active_texture - GL_TEXTURE0_ARB];
322 323 324

    if (active_sampler != -1) {
        IWineD3DDeviceImpl_MarkStateDirty(This->resource.wineD3DDevice, STATE_SAMPLER(active_sampler));
325
    }
326
    IWineD3DSurface_BindTexture((IWineD3DSurface *)This, srgb);
327 328
}

329 330 331 332 333
/* This function checks if the primary render target uses the 8bit paletted format. */
static BOOL primary_render_target_is_p8(IWineD3DDeviceImpl *device)
{
    if (device->render_targets && device->render_targets[0]) {
        IWineD3DSurfaceImpl* render_target = (IWineD3DSurfaceImpl*)device->render_targets[0];
334 335
        if ((render_target->resource.usage & WINED3DUSAGE_RENDERTARGET)
                && (render_target->resource.format_desc->format == WINED3DFMT_P8))
336 337 338 339 340
            return TRUE;
    }
    return FALSE;
}

341 342 343 344
#undef GLINFO_LOCATION

#define GLINFO_LOCATION This->resource.wineD3DDevice->adapter->gl_info

345 346 347
/* This call just downloads data, the caller is responsible for binding the
 * correct texture. */
/* Context activation is done by the caller. */
348
static void surface_download_data(IWineD3DSurfaceImpl *This) {
349
    const struct GlPixelFormatDesc *format_desc = This->resource.format_desc;
350

351
    /* Only support read back of converted P8 surfaces */
352 353 354
    if (This->Flags & SFLAG_CONVERTED && format_desc->format != WINED3DFMT_P8)
    {
        FIXME("Read back converted textures unsupported, format=%s\n", debug_d3dformat(format_desc->format));
355 356
        return;
    }
357 358

    ENTER_GL();
359

360
    if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
361
    {
362
        TRACE("(%p) : Calling glGetCompressedTexImageARB level %d, format %#x, type %#x, data %p.\n",
363
                This, This->texture_level, format_desc->glFormat, format_desc->glType,
364 365 366 367 368 369
                This->resource.allocatedMemory);

        if (This->Flags & SFLAG_PBO)
        {
            GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
            checkGLcall("glBindBufferARB");
370
            GL_EXTCALL(glGetCompressedTexImageARB(This->texture_target, This->texture_level, NULL));
371 372 373
            checkGLcall("glGetCompressedTexImageARB()");
            GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
            checkGLcall("glBindBufferARB");
374
        }
375 376
        else
        {
377 378
            GL_EXTCALL(glGetCompressedTexImageARB(This->texture_target,
                    This->texture_level, This->resource.allocatedMemory));
379 380 381
            checkGLcall("glGetCompressedTexImageARB()");
        }

382
        LEAVE_GL();
383
    } else {
384
        void *mem;
385 386
        GLenum format = format_desc->glFormat;
        GLenum type = format_desc->glType;
387 388 389
        int src_pitch = 0;
        int dst_pitch = 0;

390
        /* In case of P8 the index is stored in the alpha component if the primary render target uses P8 */
391 392
        if (format_desc->format == WINED3DFMT_P8 && primary_render_target_is_p8(This->resource.wineD3DDevice))
        {
393 394 395 396
            format = GL_ALPHA;
            type = GL_UNSIGNED_BYTE;
        }

397
        if (This->Flags & SFLAG_NONPOW2) {
398
            unsigned char alignment = This->resource.wineD3DDevice->surface_alignment;
399
            src_pitch = format_desc->byte_count * This->pow2Width;
400
            dst_pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This);
401
            src_pitch = (src_pitch + alignment - 1) & ~(alignment - 1);
402 403 404 405 406
            mem = HeapAlloc(GetProcessHeap(), 0, src_pitch * This->pow2Height);
        } else {
            mem = This->resource.allocatedMemory;
        }

407 408
        TRACE("(%p) : Calling glGetTexImage level %d, format %#x, type %#x, data %p\n",
                This, This->texture_level, format, type, mem);
409

410 411 412 413
        if(This->Flags & SFLAG_PBO) {
            GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
            checkGLcall("glBindBufferARB");

414
            glGetTexImage(This->texture_target, This->texture_level, format, type, NULL);
415 416 417 418 419
            checkGLcall("glGetTexImage()");

            GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
            checkGLcall("glBindBufferARB");
        } else {
420
            glGetTexImage(This->texture_target, This->texture_level, format, type, mem);
421 422
            checkGLcall("glGetTexImage()");
        }
423
        LEAVE_GL();
424

425
        if (This->Flags & SFLAG_NONPOW2) {
426 427
            const BYTE *src_data;
            BYTE *dst_data;
428
            UINT y;
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
            /*
             * Some games (e.g. warhammer 40k) don't work properly with the odd pitches, preventing
             * the surface pitch from being used to box non-power2 textures. Instead we have to use a hack to
             * repack the texture so that the bpp * width pitch can be used instead of bpp * pow2width.
             *
             * We're doing this...
             *
             * instead of boxing the texture :
             * |<-texture width ->|  -->pow2width|   /\
             * |111111111111111111|              |   |
             * |222 Texture 222222| boxed empty  | texture height
             * |3333 Data 33333333|              |   |
             * |444444444444444444|              |   \/
             * -----------------------------------   |
             * |     boxed  empty | boxed empty  | pow2height
             * |                  |              |   \/
             * -----------------------------------
             *
             *
             * we're repacking the data to the expected texture width
             *
             * |<-texture width ->|  -->pow2width|   /\
             * |111111111111111111222222222222222|   |
             * |222333333333333333333444444444444| texture height
             * |444444                           |   |
             * |                                 |   \/
             * |                                 |   |
             * |            empty                | pow2height
             * |                                 |   \/
             * -----------------------------------
             *
             * == is the same as
             *
             * |<-texture width ->|    /\
             * |111111111111111111|
             * |222222222222222222|texture height
             * |333333333333333333|
             * |444444444444444444|    \/
             * --------------------
             *
             * this also means that any references to allocatedMemory should work with the data as if were a
             * standard texture with a non-power2 width instead of texture boxed up to be a power2 texture.
             *
             * internally the texture is still stored in a boxed format so any references to textureName will
             * get a boxed texture with width pow2width and not a texture of width currentDesc.Width.
474 475 476 477
             *
             * Performance should not be an issue, because applications normally do not lock the surfaces when
             * rendering. If an app does, the SFLAG_DYNLOCK flag will kick in and the memory copy won't be released,
             * and doesn't have to be re-read.
478
             */
479 480 481 482 483 484 485 486
            src_data = mem;
            dst_data = This->resource.allocatedMemory;
            TRACE("(%p) : Repacking the surface data from pitch %d to pitch %d\n", This, src_pitch, dst_pitch);
            for (y = 1 ; y < This->currentDesc.Height; y++) {
                /* skip the first row */
                src_data += src_pitch;
                dst_data += dst_pitch;
                memcpy(dst_data, src_data, dst_pitch);
487
            }
488 489

            HeapFree(GetProcessHeap(), 0, mem);
490 491
        }
    }
492

493 494
    /* Surface has now been downloaded */
    This->Flags |= SFLAG_INSYSMEM;
495 496
}

497 498 499
/* This call just uploads data, the caller is responsible for binding the
 * correct texture. */
/* Context activation is done by the caller. */
500
static void surface_upload_data(IWineD3DSurfaceImpl *This, GLenum internal, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *data) {
501
    const struct GlPixelFormatDesc *format_desc = This->resource.format_desc;
502

503
    if (format_desc->heightscale != 1.0f && format_desc->heightscale != 0.0f) height *= format_desc->heightscale;
504

505
    if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
506
    {
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
        /* glCompressedTexSubImage2D() for uploading and glTexImage2D() for
         * allocating does not work well on some drivers (r200 dri, MacOS ATI
         * driver). glCompressedTexImage2D() does not accept NULL pointers. So
         * for compressed textures surface_allocate_surface() does nothing,
         * and this function uses glCompressedTexImage2D() instead of
         * glCompressedTexSubImage2D(). */
        TRACE("(%p) : Calling glCompressedTexImage2DARB w %u, h %u, data %p.\n", This, width, height, data);

        ENTER_GL();

        if (This->Flags & SFLAG_PBO)
        {
            GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
            checkGLcall("glBindBufferARB");

            TRACE("(%p) pbo: %#x, data: %p.\n", This, This->pbo, data);

524
            GL_EXTCALL(glCompressedTexImage2DARB(This->texture_target, This->texture_level,
525 526 527 528 529
                    internal, width, height, 0 /* border */, This->resource.size, NULL));
            checkGLcall("glCompressedTexImage2DARB");

            GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
            checkGLcall("glBindBufferARB");
530
        }
531 532
        else
        {
533
            GL_EXTCALL(glCompressedTexImage2DARB(This->texture_target, This->texture_level,
534 535 536 537 538 539 540 541
                    internal, width, height, 0 /* border */, This->resource.size, data));
            checkGLcall("glCompressedTexSubImage2D");
        }

        LEAVE_GL();
    }
    else
    {
542 543
        TRACE("(%p) : Calling glTexSubImage2D w %d,  h %d, data, %p\n", This, width, height, data);
        ENTER_GL();
544 545 546 547 548 549

        if(This->Flags & SFLAG_PBO) {
            GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
            checkGLcall("glBindBufferARB");
            TRACE("(%p) pbo: %#x, data: %p\n", This, This->pbo, data);

550
            glTexSubImage2D(This->texture_target, This->texture_level, 0, 0, width, height, format, type, NULL);
551 552 553 554 555 556
            checkGLcall("glTexSubImage2D");

            GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
            checkGLcall("glBindBufferARB");
        }
        else {
557
            glTexSubImage2D(This->texture_target, This->texture_level, 0, 0, width, height, format, type, data);
558 559 560
            checkGLcall("glTexSubImage2D");
        }

561 562 563 564
        LEAVE_GL();
    }
}

565 566 567
/* This call just allocates the texture, the caller is responsible for binding
 * the correct texture. */
/* Context activation is done by the caller. */
568
static void surface_allocate_surface(IWineD3DSurfaceImpl *This, GLenum internal, GLsizei width, GLsizei height, GLenum format, GLenum type) {
569
    const struct GlPixelFormatDesc *format_desc = This->resource.format_desc;
570
    BOOL enable_client_storage = FALSE;
571
    const BYTE *mem = NULL;
572

573
    if (format_desc->heightscale != 1.0f && format_desc->heightscale != 0.0f) height *= format_desc->heightscale;
574

575
    TRACE("(%p) : Creating surface (target %#x)  level %d, d3d format %s, internal format %#x, width %d, height %d, gl format %#x, gl type=%#x\n",
576
            This, This->texture_target, This->texture_level, debug_d3dformat(format_desc->format),
577
            internal, width, height, format, type);
578

579
    if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
580
    {
581 582
        /* glCompressedTexImage2D does not accept NULL pointers, so we cannot allocate a compressed texture without uploading data */
        TRACE("Not allocating compressed surfaces, surface_upload_data will specify them\n");
583 584 585 586 587 588 589 590

        /* We have to point GL to the client storage memory here, because upload_data might use a PBO. This means a double upload
         * once, unfortunately
         */
        if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
            /* Neither NONPOW2, DIBSECTION nor OVERSIZE flags can be set on compressed textures */
            This->Flags |= SFLAG_CLIENT;
            mem = (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
591
            ENTER_GL();
592 593
            GL_EXTCALL(glCompressedTexImage2DARB(This->texture_target, This->texture_level, internal,
                    width, height, 0 /* border */, This->resource.size, mem));
594
            LEAVE_GL();
595 596
        }

597 598 599
        return;
    }

600 601
    ENTER_GL();

602 603 604 605 606 607 608 609 610 611 612
    if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
        if(This->Flags & (SFLAG_NONPOW2 | SFLAG_DIBSECTION | SFLAG_OVERSIZE | SFLAG_CONVERTED) || This->resource.allocatedMemory == NULL) {
            /* In some cases we want to disable client storage.
             * SFLAG_NONPOW2 has a bigger opengl texture than the client memory, and different pitches
             * SFLAG_DIBSECTION: Dibsections may have read / write protections on the memory. Avoid issues...
             * SFLAG_OVERSIZE: The gl texture is smaller than the allocated memory
             * SFLAG_CONVERTED: The conversion destination memory is freed after loading the surface
             * allocatedMemory == NULL: Not defined in the extension. Seems to disable client storage effectively
             */
            glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
            checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
613
            This->Flags &= ~SFLAG_CLIENT;
614 615 616
            enable_client_storage = TRUE;
        } else {
            This->Flags |= SFLAG_CLIENT;
617 618 619 620 621

            /* Point opengl to our allocated texture memory. Do not use resource.allocatedMemory here because
             * it might point into a pbo. Instead use heapMemory, but get the alignment right.
             */
            mem = (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
622 623
        }
    }
624
    glTexImage2D(This->texture_target, This->texture_level, internal, width, height, 0, format, type, mem);
625 626
    checkGLcall("glTexImage2D");

627 628 629 630
    if(enable_client_storage) {
        glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
        checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
    }
631 632 633
    LEAVE_GL();
}

634 635 636
/* In D3D the depth stencil dimensions have to be greater than or equal to the
 * render target dimensions. With FBOs, the dimensions have to be an exact match. */
/* TODO: We should synchronize the renderbuffer's content with the texture's content. */
637
/* GL locking is done by the caller */
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
void surface_set_compatible_renderbuffer(IWineD3DSurface *iface, unsigned int width, unsigned int height) {
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
    renderbuffer_entry_t *entry;
    GLuint renderbuffer = 0;
    unsigned int src_width, src_height;

    src_width = This->pow2Width;
    src_height = This->pow2Height;

    /* A depth stencil smaller than the render target is not valid */
    if (width > src_width || height > src_height) return;

    /* Remove any renderbuffer set if the sizes match */
    if (width == src_width && height == src_height) {
        This->current_renderbuffer = NULL;
        return;
    }

    /* Look if we've already got a renderbuffer of the correct dimensions */
    LIST_FOR_EACH_ENTRY(entry, &This->renderbuffers, renderbuffer_entry_t, entry) {
        if (entry->width == width && entry->height == height) {
            renderbuffer = entry->id;
            This->current_renderbuffer = entry;
            break;
        }
    }

    if (!renderbuffer) {
        GL_EXTCALL(glGenRenderbuffersEXT(1, &renderbuffer));
        GL_EXTCALL(glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, renderbuffer));
668 669
        GL_EXTCALL(glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT,
                This->resource.format_desc->glInternal, width, height));
670 671 672 673 674 675 676 677 678 679 680 681 682

        entry = HeapAlloc(GetProcessHeap(), 0, sizeof(renderbuffer_entry_t));
        entry->width = width;
        entry->height = height;
        entry->id = renderbuffer;
        list_add_head(&This->renderbuffers, &entry->entry);

        This->current_renderbuffer = entry;
    }

    checkGLcall("set_compatible_renderbuffer");
}

683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
GLenum surface_get_gl_buffer(IWineD3DSurface *iface, IWineD3DSwapChain *swapchain) {
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
    IWineD3DSwapChainImpl *swapchain_impl = (IWineD3DSwapChainImpl *)swapchain;

    TRACE("(%p) : swapchain %p\n", This, swapchain);

    if (swapchain_impl->backBuffer && swapchain_impl->backBuffer[0] == iface) {
        TRACE("Returning GL_BACK\n");
        return GL_BACK;
    } else if (swapchain_impl->frontBuffer == iface) {
        TRACE("Returning GL_FRONT\n");
        return GL_FRONT;
    }

    FIXME("Higher back buffer, returning GL_BACK\n");
    return GL_BACK;
}
700

701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
/* Slightly inefficient way to handle multiple dirty rects but it works :) */
void surface_add_dirty_rect(IWineD3DSurface *iface, const RECT *dirty_rect)
{
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
    IWineD3DBaseTexture *baseTexture = NULL;

    if (!(This->Flags & SFLAG_INSYSMEM) && (This->Flags & SFLAG_INTEXTURE))
        IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL /* no partial locking for textures yet */);

    IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
    if (dirty_rect)
    {
        This->dirtyRect.left = min(This->dirtyRect.left, dirty_rect->left);
        This->dirtyRect.top = min(This->dirtyRect.top, dirty_rect->top);
        This->dirtyRect.right = max(This->dirtyRect.right, dirty_rect->right);
        This->dirtyRect.bottom = max(This->dirtyRect.bottom, dirty_rect->bottom);
    }
    else
    {
        This->dirtyRect.left = 0;
        This->dirtyRect.top = 0;
        This->dirtyRect.right = This->currentDesc.Width;
        This->dirtyRect.bottom = This->currentDesc.Height;
    }

    TRACE("(%p) : Dirty: yes, Rect:(%d, %d, %d, %d)\n", This, This->dirtyRect.left,
            This->dirtyRect.top, This->dirtyRect.right, This->dirtyRect.bottom);

    /* if the container is a basetexture then mark it dirty. */
    if (SUCCEEDED(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture)))
    {
        TRACE("Passing to container\n");
        IWineD3DBaseTexture_SetDirty(baseTexture, TRUE);
        IWineD3DBaseTexture_Release(baseTexture);
    }
}

738 739 740 741 742 743 744 745 746 747 748
static inline BOOL surface_can_stretch_rect(IWineD3DSurfaceImpl *src, IWineD3DSurfaceImpl *dst)
{
    return ((src->resource.format_desc->Flags & WINED3DFMT_FLAG_FBO_ATTACHABLE)
            || (src->resource.usage & WINED3DUSAGE_RENDERTARGET))
            && ((dst->resource.format_desc->Flags & WINED3DFMT_FLAG_FBO_ATTACHABLE)
            || (dst->resource.usage & WINED3DUSAGE_RENDERTARGET))
            && (src->resource.format_desc->format == dst->resource.format_desc->format
            || (is_identity_fixup(src->resource.format_desc->color_fixup)
            && is_identity_fixup(dst->resource.format_desc->color_fixup)));
}

749 750
static ULONG WINAPI IWineD3DSurfaceImpl_Release(IWineD3DSurface *iface)
{
751
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
752
    ULONG ref = InterlockedDecrement(&This->resource.ref);
753
    TRACE("(%p) : Releasing from %d\n", This, ref + 1);
754

755 756 757
    if (!ref)
    {
        surface_cleanup(This);
758

759
        TRACE("(%p) Released.\n", This);
760 761
        HeapFree(GetProcessHeap(), 0, This);
    }
762

763 764 765 766 767 768 769
    return ref;
}

/* ****************************************************
   IWineD3DSurface IWineD3DResource parts follow
   **************************************************** */

770
void surface_internal_preload(IWineD3DSurface *iface, enum WINED3DSRGB srgb)
771
{
772 773 774
    /* TODO: check for locks */
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
    IWineD3DBaseTexture *baseTexture = NULL;
775 776
    IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;

777
    TRACE("(%p)Checking to see if the container is a base texture\n", This);
778
    if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
779
        IWineD3DBaseTextureImpl *tex_impl = (IWineD3DBaseTextureImpl *) baseTexture;
780
        TRACE("Passing to container\n");
781
        tex_impl->baseTexture.internal_preload(baseTexture, SRGB_RGB);
782
        IWineD3DBaseTexture_Release(baseTexture);
783
    } else {
784
        TRACE("(%p) : About to load surface\n", This);
785

786 787 788
        if(!device->isInDraw) {
            ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
        }
789

790 791 792
        if (This->resource.format_desc->format == WINED3DFMT_P8
                || This->resource.format_desc->format == WINED3DFMT_A8P8)
        {
793 794 795 796 797 798 799 800
            if(palette9_changed(This)) {
                TRACE("Reloading surface because the d3d8/9 palette was changed\n");
                /* TODO: This is not necessarily needed with hw palettized texture support */
                IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
                /* Make sure the texture is reloaded because of the palette change, this kills performance though :( */
                IWineD3DSurface_ModifyLocation(iface, SFLAG_INTEXTURE, FALSE);
            }
        }
801

802
        IWineD3DSurface_LoadTexture(iface, srgb == SRGB_SRGB ? TRUE : FALSE);
803

804 805 806 807
        if (This->resource.pool == WINED3DPOOL_DEFAULT) {
            /* Tell opengl to try and keep this texture in video ram (well mostly) */
            GLclampf tmp;
            tmp = 0.9f;
808
            ENTER_GL();
809
            glPrioritizeTextures(1, &This->texture_name, &tmp);
810
            LEAVE_GL();
811
        }
812 813
    }
    return;
814 815
}

816 817 818 819
static void WINAPI IWineD3DSurfaceImpl_PreLoad(IWineD3DSurface *iface) {
    surface_internal_preload(iface, SRGB_ANY);
}

820
/* Context activation is done by the caller. */
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
static void surface_remove_pbo(IWineD3DSurfaceImpl *This) {
    This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
    This->resource.allocatedMemory =
            (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));

    ENTER_GL();
    GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
    checkGLcall("glBindBuffer(GL_PIXEL_UNPACK_BUFFER, This->pbo)");
    GL_EXTCALL(glGetBufferSubDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0, This->resource.size, This->resource.allocatedMemory));
    checkGLcall("glGetBufferSubData");
    GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
    checkGLcall("glDeleteBuffers");
    LEAVE_GL();

    This->pbo = 0;
    This->Flags &= ~SFLAG_PBO;
}

static void WINAPI IWineD3DSurfaceImpl_UnLoad(IWineD3DSurface *iface) {
    IWineD3DBaseTexture *texture = NULL;
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
842
    IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
843
    renderbuffer_entry_t *entry, *entry2;
844 845 846
    TRACE("(%p)\n", iface);

    if(This->resource.pool == WINED3DPOOL_DEFAULT) {
847 848 849 850
        /* Default pool resources are supposed to be destroyed before Reset is called.
         * Implicit resources stay however. So this means we have an implicit render target
         * or depth stencil. The content may be destroyed, but we still have to tear down
         * opengl resources, so we cannot leave early.
851 852 853 854 855 856 857
         *
         * Put the most up to date surface location into the drawable. D3D-wise this content
         * is undefined, so it would be nowhere, but that would make the location management
         * more complicated. The drawable is a sane location, because if we mark sysmem or
         * texture up to date, drawPrim will copy the uninitialized texture or sysmem to the
         * uninitialized drawable. That's pointless and we'd have to allocate the texture /
         * sysmem copy here.
858
         */
859 860 861 862 863
        if (This->resource.usage & WINED3DUSAGE_DEPTHSTENCIL) {
            IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
        } else {
            IWineD3DSurface_ModifyLocation(iface, SFLAG_INDRAWABLE, TRUE);
        }
864 865 866
    } else {
        /* Load the surface into system memory */
        IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
867
        IWineD3DSurface_ModifyLocation(iface, SFLAG_INDRAWABLE, FALSE);
868
    }
869
    IWineD3DSurface_ModifyLocation(iface, SFLAG_INTEXTURE, FALSE);
870
    IWineD3DSurface_ModifyLocation(iface, SFLAG_INSRGBTEX, FALSE);
871
    This->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
872

873 874
    ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);

875 876 877 878 879
    /* Destroy PBOs, but load them into real sysmem before */
    if(This->Flags & SFLAG_PBO) {
        surface_remove_pbo(This);
    }

880 881 882 883 884 885 886 887 888 889 890 891 892 893
    /* Destroy fbo render buffers. This is needed for implicit render targets, for
     * all application-created targets the application has to release the surface
     * before calling _Reset
     */
    LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry) {
        ENTER_GL();
        GL_EXTCALL(glDeleteRenderbuffersEXT(1, &entry->id));
        LEAVE_GL();
        list_remove(&entry->entry);
        HeapFree(GetProcessHeap(), 0, entry);
    }
    list_init(&This->renderbuffers);
    This->current_renderbuffer = NULL;

894 895 896 897 898 899
    /* If we're in a texture, the texture name belongs to the texture. Otherwise,
     * destroy it
     */
    IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **) &texture);
    if(!texture) {
        ENTER_GL();
900 901 902 903
        glDeleteTextures(1, &This->texture_name);
        This->texture_name = 0;
        glDeleteTextures(1, &This->texture_name_srgb);
        This->texture_name_srgb = 0;
904 905 906 907
        LEAVE_GL();
    } else {
        IWineD3DBaseTexture_Release(texture);
    }
908 909 910
    return;
}

911 912 913 914
/* ******************************************************
   IWineD3DSurface IWineD3DSurface parts follow
   ****************************************************** */

915
/* Read the framebuffer back into the surface */
916 917 918
static void read_from_framebuffer(IWineD3DSurfaceImpl *This, CONST RECT *rect, void *dest, UINT pitch) {
    IWineD3DSwapChainImpl *swapchain;
    IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
919
    BYTE *mem;
920 921
    GLint fmt;
    GLint type;
922 923 924
    BYTE *row, *top, *bottom;
    int i;
    BOOL bpp;
925 926
    RECT local_rect;
    BOOL srcIsUpsideDown;
927 928 929
    GLint rowLen = 0;
    GLint skipPix = 0;
    GLint skipRow = 0;
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951

    if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
        static BOOL warned = FALSE;
        if(!warned) {
            ERR("The application tries to lock the render target, but render target locking is disabled\n");
            warned = TRUE;
        }
        return;
    }

    /* Activate the surface. Set it up for blitting now, although not necessarily needed for LockRect.
     * Certain graphics drivers seem to dislike some enabled states when reading from opengl, the blitting usage
     * should help here. Furthermore unlockrect will need the context set up for blitting. The context manager will find
     * context->last_was_blit set on the unlock.
     */
    ActivateContext(myDevice, (IWineD3DSurface *) This, CTXUSAGE_BLIT);
    ENTER_GL();

    /* Select the correct read buffer, and give some debug output.
     * There is no need to keep track of the current read buffer or reset it, every part of the code
     * that reads sets the read buffer as desired.
     */
952 953
    if (SUCCEEDED(IWineD3DSurface_GetContainer((IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&swapchain)))
    {
954 955 956 957 958 959 960
        GLenum buffer = surface_get_gl_buffer((IWineD3DSurface *) This, (IWineD3DSwapChain *)swapchain);
        TRACE("Locking %#x buffer\n", buffer);
        glReadBuffer(buffer);
        checkGLcall("glReadBuffer");

        IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
        srcIsUpsideDown = FALSE;
961 962 963 964 965 966 967
    } else {
        /* Locking the primary render target which is not on a swapchain(=offscreen render target).
         * Read from the back buffer
         */
        TRACE("Locking offscreen render target\n");
        glReadBuffer(myDevice->offscreenBuffer);
        srcIsUpsideDown = TRUE;
968 969 970 971 972 973 974 975 976 977 978 979
    }

    /* TODO: Get rid of the extra rectangle comparison and construction of a full surface rectangle */
    if(!rect) {
        local_rect.left = 0;
        local_rect.top = 0;
        local_rect.right = This->currentDesc.Width;
        local_rect.bottom = This->currentDesc.Height;
    } else {
        local_rect = *rect;
    }
    /* TODO: Get rid of the extra GetPitch call, LockRect does that too. Cache the pitch */
980

981
    switch(This->resource.format_desc->format)
982 983 984
    {
        case WINED3DFMT_P8:
        {
985
            if(primary_render_target_is_p8(myDevice)) {
986 987 988 989
                /* In case of P8 render targets the index is stored in the alpha component */
                fmt = GL_ALPHA;
                type = GL_UNSIGNED_BYTE;
                mem = dest;
990
                bpp = This->resource.format_desc->byte_count;
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
            } else {
                /* GL can't return palettized data, so read ARGB pixels into a
                 * separate block of memory and convert them into palettized format
                 * in software. Slow, but if the app means to use palettized render
                 * targets and locks it...
                 *
                 * Use GL_RGB, GL_UNSIGNED_BYTE to read the surface for performance reasons
                 * Don't use GL_BGR as in the WINED3DFMT_R8G8B8 case, instead watch out
                 * for the color channels when palettizing the colors.
                 */
                fmt = GL_RGB;
                type = GL_UNSIGNED_BYTE;
                pitch *= 3;
                mem = HeapAlloc(GetProcessHeap(), 0, This->resource.size * 3);
                if(!mem) {
                    ERR("Out of memory\n");
1007
                    LEAVE_GL();
1008 1009
                    return;
                }
1010
                bpp = This->resource.format_desc->byte_count * 3;
1011 1012 1013 1014 1015 1016
            }
        }
        break;

        default:
            mem = dest;
1017 1018
            fmt = This->resource.format_desc->glFormat;
            type = This->resource.format_desc->glType;
1019
            bpp = This->resource.format_desc->byte_count;
1020 1021
    }

1022 1023 1024
    if(This->Flags & SFLAG_PBO) {
        GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
        checkGLcall("glBindBufferARB");
1025 1026 1027 1028
        if(mem != NULL) {
            ERR("mem not null for pbo -- unexpected\n");
            mem = NULL;
        }
1029 1030
    }

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
    /* Save old pixel store pack state */
    glGetIntegerv(GL_PACK_ROW_LENGTH, &rowLen);
    checkGLcall("glIntegerv");
    glGetIntegerv(GL_PACK_SKIP_PIXELS, &skipPix);
    checkGLcall("glIntegerv");
    glGetIntegerv(GL_PACK_SKIP_ROWS, &skipRow);
    checkGLcall("glIntegerv");

    /* Setup pixel store pack state -- to glReadPixels into the correct place */
    glPixelStorei(GL_PACK_ROW_LENGTH, This->currentDesc.Width);
    checkGLcall("glPixelStorei");
    glPixelStorei(GL_PACK_SKIP_PIXELS, local_rect.left);
    checkGLcall("glPixelStorei");
    glPixelStorei(GL_PACK_SKIP_ROWS, local_rect.top);
    checkGLcall("glPixelStorei");

    glReadPixels(local_rect.left, (!srcIsUpsideDown) ? (This->currentDesc.Height - local_rect.bottom) : local_rect.top ,
1048 1049
                 local_rect.right - local_rect.left,
                 local_rect.bottom - local_rect.top,
1050
                 fmt, type, mem);
1051
    checkGLcall("glReadPixels");
1052

1053 1054 1055 1056 1057 1058 1059 1060
    /* Reset previous pixel store pack state */
    glPixelStorei(GL_PACK_ROW_LENGTH, rowLen);
    checkGLcall("glPixelStorei");
    glPixelStorei(GL_PACK_SKIP_PIXELS, skipPix);
    checkGLcall("glPixelStorei");
    glPixelStorei(GL_PACK_SKIP_ROWS, skipRow);
    checkGLcall("glPixelStorei");

1061 1062 1063 1064 1065 1066 1067 1068
    if(This->Flags & SFLAG_PBO) {
        GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
        checkGLcall("glBindBufferARB");

        /* Check if we need to flip the image. If we need to flip use glMapBufferARB
         * to get a pointer to it and perform the flipping in software. This is a lot
         * faster than calling glReadPixels for each line. In case we want more speed
         * we should rerender it flipped in a FBO and read the data back from the FBO. */
1069
        if(!srcIsUpsideDown) {
1070 1071
            GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
            checkGLcall("glBindBufferARB");
1072

1073 1074 1075 1076 1077 1078
            mem = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
            checkGLcall("glMapBufferARB");
        }
    }

    /* TODO: Merge this with the palettization loop below for P8 targets */
1079
    if(!srcIsUpsideDown) {
1080 1081 1082
        UINT len, off;
        /* glReadPixels returns the image upside down, and there is no way to prevent this.
            Flip the lines in software */
1083 1084
        len = (local_rect.right - local_rect.left) * bpp;
        off = local_rect.left * bpp;
1085 1086

        row = HeapAlloc(GetProcessHeap(), 0, len);
1087 1088
        if(!row) {
            ERR("Out of memory\n");
1089
            if (This->resource.format_desc->format == WINED3DFMT_P8) HeapFree(GetProcessHeap(), 0, mem);
1090
            LEAVE_GL();
1091 1092
            return;
        }
1093

1094
        top = mem + pitch * local_rect.top;
1095
        bottom = mem + pitch * (local_rect.bottom - 1);
1096
        for(i = 0; i < (local_rect.bottom - local_rect.top) / 2; i++) {
1097 1098 1099
            memcpy(row, top + off, len);
            memcpy(top + off, bottom + off, len);
            memcpy(bottom + off, row, len);
1100 1101 1102 1103
            top += pitch;
            bottom -= pitch;
        }
        HeapFree(GetProcessHeap(), 0, row);
1104 1105 1106 1107 1108 1109

        /* Unmap the temp PBO buffer */
        if(This->Flags & SFLAG_PBO) {
            GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
            GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
        }
1110 1111
    }

1112 1113
    LEAVE_GL();

1114 1115 1116
    /* For P8 textures we need to perform an inverse palette lookup. This is done by searching for a palette
     * index which matches the RGB value. Note this isn't guaranteed to work when there are multiple entries for
     * the same color but we have no choice.
1117
     * In case of P8 render targets, the index is stored in the alpha component so no conversion is needed.
1118
     */
1119 1120
    if ((This->resource.format_desc->format == WINED3DFMT_P8) && !primary_render_target_is_p8(myDevice))
    {
1121
        const PALETTEENTRY *pal = NULL;
1122 1123
        DWORD width = pitch / 3;
        int x, y, c;
1124

1125 1126 1127
        if(This->palette) {
            pal = This->palette->palents;
        } else {
1128 1129 1130
            ERR("Palette is missing, cannot perform inverse palette lookup\n");
            HeapFree(GetProcessHeap(), 0, mem);
            return ;
1131 1132
        }

1133 1134
        for(y = local_rect.top; y < local_rect.bottom; y++) {
            for(x = local_rect.left; x < local_rect.right; x++) {
1135
                /*                      start              lines            pixels      */
1136 1137 1138
                const BYTE *blue = mem + y * pitch + x * (sizeof(BYTE) * 3);
                const BYTE *green = blue  + 1;
                const BYTE *red = green + 1;
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154

                for(c = 0; c < 256; c++) {
                    if(*red   == pal[c].peRed   &&
                       *green == pal[c].peGreen &&
                       *blue  == pal[c].peBlue)
                    {
                        *((BYTE *) dest + y * width + x) = c;
                        break;
                    }
                }
            }
        }
        HeapFree(GetProcessHeap(), 0, mem);
    }
}

1155
/* Read the framebuffer contents into a texture */
1156
static void read_from_framebuffer_texture(IWineD3DSurfaceImpl *This, BOOL srgb)
1157 1158 1159 1160 1161 1162 1163
{
    IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
    IWineD3DSwapChainImpl *swapchain;
    int bpp;
    GLenum format, internal, type;
    CONVERT_TYPES convert;
    GLint prevRead;
1164
    BOOL alloc_flag = srgb ? SFLAG_SRGBALLOCATED : SFLAG_ALLOCATED;
1165

1166
    d3dfmt_get_conv(This, TRUE /* We need color keying */, TRUE /* We will use textures */, &format, &internal, &type, &convert, &bpp, srgb);
1167

1168 1169 1170
    /* Activate the surface to read from. In some situations it isn't the currently active target(e.g. backbuffer
     * locking during offscreen rendering). RESOURCELOAD is ok because glCopyTexSubImage2D isn't affected by any
     * states in the stateblock, and no driver was found yet that had bugs in that regard.
1171
     */
1172
    ActivateContext(device, (IWineD3DSurface *) This, CTXUSAGE_RESOURCELOAD);
1173
    surface_bind_and_dirtify(This, srgb);
1174

1175
    ENTER_GL();
1176
    glGetIntegerv(GL_READ_BUFFER, &prevRead);
1177
    LEAVE_GL();
1178 1179 1180 1181 1182

    /* Select the correct read buffer, and give some debug output.
     * There is no need to keep track of the current read buffer or reset it, every part of the code
     * that reads sets the read buffer as desired.
     */
1183 1184
    if (SUCCEEDED(IWineD3DSurface_GetContainer((IWineD3DSurface *)This, &IID_IWineD3DSwapChain, (void **)&swapchain)))
    {
1185 1186
        GLenum buffer = surface_get_gl_buffer((IWineD3DSurface *) This, (IWineD3DSwapChain *)swapchain);
        TRACE("Locking %#x buffer\n", buffer);
1187 1188

        ENTER_GL();
1189 1190
        glReadBuffer(buffer);
        checkGLcall("glReadBuffer");
1191
        LEAVE_GL();
1192 1193

        IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
1194 1195 1196 1197 1198
    } else {
        /* Locking the primary render target which is not on a swapchain(=offscreen render target).
         * Read from the back buffer
         */
        TRACE("Locking offscreen render target\n");
1199
        ENTER_GL();
1200
        glReadBuffer(device->offscreenBuffer);
1201
        checkGLcall("glReadBuffer");
1202
        LEAVE_GL();
1203 1204
    }

1205
    if(!(This->Flags & alloc_flag)) {
1206 1207
        surface_allocate_surface(This, internal, This->pow2Width,
                                 This->pow2Height, format, type);
1208
        This->Flags |= alloc_flag;
1209 1210
    }

1211
    ENTER_GL();
1212 1213 1214 1215 1216 1217
    /* If !SrcIsUpsideDown we should flip the surface.
     * This can be done using glCopyTexSubImage2D but this
     * is VERY slow, so don't do that. We should prevent
     * this code from getting called in such cases or perhaps
     * we can use FBOs */

1218 1219
    glCopyTexSubImage2D(This->texture_target, This->texture_level,
            0, 0, 0, 0, This->currentDesc.Width, This->currentDesc.Height);
1220 1221 1222
    checkGLcall("glCopyTexSubImage2D");

    glReadBuffer(prevRead);
1223
    checkGLcall("glReadBuffer");
1224 1225

    LEAVE_GL();
1226
    TRACE("Updated target %d\n", This->texture_target);
1227 1228
}

1229 1230 1231 1232
static void surface_prepare_system_memory(IWineD3DSurfaceImpl *This) {
    /* Performance optimization: Count how often a surface is locked, if it is locked regularly do not throw away the system memory copy.
     * This avoids the need to download the surface from opengl all the time. The surface is still downloaded if the opengl texture is
     * changed
1233
     */
1234 1235 1236 1237 1238 1239
    if(!(This->Flags & SFLAG_DYNLOCK)) {
        This->lockCount++;
        /* MAXLOCKCOUNT is defined in wined3d_private.h */
        if(This->lockCount > MAXLOCKCOUNT) {
            TRACE("Surface is locked regularly, not freeing the system memory copy any more\n");
            This->Flags |= SFLAG_DYNLOCK;
1240
        }
1241 1242
    }

1243
    /* Create a PBO for dynamically locked surfaces but don't do it for converted or non-pow2 surfaces.
1244 1245
     * Also don't create a PBO for systemmem surfaces.
     */
1246
    if(GL_SUPPORT(ARB_PIXEL_BUFFER_OBJECT) && (This->Flags & SFLAG_DYNLOCK) && !(This->Flags & (SFLAG_PBO | SFLAG_CONVERTED | SFLAG_NONPOW2)) && (This->resource.pool != WINED3DPOOL_SYSTEMMEM)) {
1247
        GLenum error;
1248 1249 1250
        IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;

        ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
        ENTER_GL();

        GL_EXTCALL(glGenBuffersARB(1, &This->pbo));
        error = glGetError();
        if(This->pbo == 0 || error != GL_NO_ERROR) {
            ERR("Failed to bind the PBO with error %s (%#x)\n", debug_glerror(error), error);
        }

        TRACE("Attaching pbo=%#x to (%p)\n", This->pbo, This);

        GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
        checkGLcall("glBindBufferARB");

        GL_EXTCALL(glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->resource.size + 4, This->resource.allocatedMemory, GL_STREAM_DRAW_ARB));
        checkGLcall("glBufferDataARB");

        GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
        checkGLcall("glBindBufferARB");

        /* We don't need the system memory anymore and we can't even use it for PBOs */
1271 1272 1273 1274
        if(!(This->Flags & SFLAG_CLIENT)) {
            HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
            This->resource.heapMemory = NULL;
        }
1275 1276 1277
        This->resource.allocatedMemory = NULL;
        This->Flags |= SFLAG_PBO;
        LEAVE_GL();
1278 1279 1280 1281
    } else if(!(This->resource.allocatedMemory || This->Flags & SFLAG_PBO)) {
        /* Whatever surface we have, make sure that there is memory allocated for the downloaded copy,
         * or a pbo to map
         */
1282 1283 1284
        if(!This->resource.heapMemory) {
            This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
        }
1285 1286
        This->resource.allocatedMemory =
                (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1287 1288 1289 1290 1291 1292 1293 1294 1295
        if(This->Flags & SFLAG_INSYSMEM) {
            ERR("Surface without memory or pbo has SFLAG_INSYSMEM set!\n");
        }
    }
}

static HRESULT WINAPI IWineD3DSurfaceImpl_LockRect(IWineD3DSurface *iface, WINED3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags) {
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
    IWineD3DDeviceImpl  *myDevice = This->resource.wineD3DDevice;
1296
    const RECT *pass_rect = pRect;
1297 1298 1299

    TRACE("(%p) : rect@%p flags(%08x), output lockedRect@%p, memory@%p\n", This, pRect, Flags, pLockedRect, This->resource.allocatedMemory);

1300 1301 1302 1303
    /* This is also done in the base class, but we have to verify this before loading any data from
     * gl into the sysmem copy. The PBO may be mapped, a different rectangle locked, the discard flag
     * may interfere, and all other bad things may happen
     */
1304 1305 1306 1307
    if (This->Flags & SFLAG_LOCKED) {
        WARN("Surface is already locked, returning D3DERR_INVALIDCALL\n");
        return WINED3DERR_INVALIDCALL;
    }
1308 1309 1310 1311 1312 1313
    This->Flags |= SFLAG_LOCKED;

    if (!(This->Flags & SFLAG_LOCKABLE))
    {
        TRACE("Warning: trying to lock unlockable surf@%p\n", This);
    }
1314

1315 1316 1317
    if (Flags & WINED3DLOCK_DISCARD) {
        /* Set SFLAG_INSYSMEM, so we'll never try to download the data from the texture. */
        TRACE("WINED3DLOCK_DISCARD flag passed, marking local copy as up to date\n");
1318
        surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1319
        This->Flags |= SFLAG_INSYSMEM;
1320
        goto lock_end;
1321 1322 1323 1324
    }

    if (This->Flags & SFLAG_INSYSMEM) {
        TRACE("Local copy is up to date, not downloading data\n");
1325
        surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1326 1327
        goto lock_end;
    }
1328

1329 1330 1331 1332 1333
    /* IWineD3DSurface_LoadLocation() does not check if the rectangle specifies
     * the full surface. Most callers don't need that, so do it here. */
    if (pRect && pRect->top == 0 && pRect->left == 0
            && pRect->right == This->currentDesc.Width
            && pRect->bottom == This->currentDesc.Height)
1334
    {
1335 1336
        pass_rect = NULL;
    }
1337

1338 1339 1340 1341
    if (!(wined3d_settings.rendertargetlock_mode == RTL_DISABLE
            && ((This->Flags & SFLAG_SWAPCHAIN) || iface == myDevice->render_targets[0])))
    {
        IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, pass_rect);
1342 1343
    }

1344
lock_end:
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
    if(This->Flags & SFLAG_PBO) {
        ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
        ENTER_GL();
        GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
        checkGLcall("glBindBufferARB");

        /* This shouldn't happen but could occur if some other function didn't handle the PBO properly */
        if(This->resource.allocatedMemory) {
            ERR("The surface already has PBO memory allocated!\n");
        }

        This->resource.allocatedMemory = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
        checkGLcall("glMapBufferARB");

        /* Make sure the pbo isn't set anymore in order not to break non-pbo calls */
        GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
        checkGLcall("glBindBufferARB");

        LEAVE_GL();
    }

1366
    if (Flags & (WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY)) {
1367 1368
        /* Don't dirtify */
    } else {
1369
        IWineD3DBaseTexture *pBaseTexture;
1370 1371 1372 1373
        /**
         * Dirtify on lock
         * as seen in msdn docs
         */
1374
        surface_add_dirty_rect(iface, pRect);
1375

1376
        /** Dirtify Container if needed */
1377
        if (SUCCEEDED(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&pBaseTexture))) {
1378
            TRACE("Making container dirty\n");
1379
            IWineD3DBaseTexture_SetDirty(pBaseTexture, TRUE);
1380
            IWineD3DBaseTexture_Release(pBaseTexture);
1381
        } else {
1382
            TRACE("Surface is standalone, no need to dirty the container\n");
1383 1384 1385
        }
    }

1386
    return IWineD3DBaseSurfaceImpl_LockRect(iface, pLockedRect, pRect, Flags);
1387 1388
}

1389
static void flush_to_framebuffer_drawpixels(IWineD3DSurfaceImpl *This, GLenum fmt, GLenum type, UINT bpp, const BYTE *mem) {
1390 1391
    GLint  prev_store;
    GLint  prev_rasterpos[4];
1392
    GLint skipBytes = 0;
1393
    UINT pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This);    /* target is argb, 4 byte */
1394
    IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
1395 1396 1397 1398 1399 1400
    IWineD3DSwapChainImpl *swapchain;

    /* Activate the correct context for the render target */
    ActivateContext(myDevice, (IWineD3DSurface *) This, CTXUSAGE_BLIT);
    ENTER_GL();

1401
    if (SUCCEEDED(IWineD3DSurface_GetContainer((IWineD3DSurface *)This, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
1402 1403 1404 1405 1406 1407
        GLenum buffer = surface_get_gl_buffer((IWineD3DSurface *) This, (IWineD3DSwapChain *)swapchain);
        TRACE("Unlocking %#x buffer\n", buffer);
        glDrawBuffer(buffer);
        checkGLcall("glDrawBuffer");

        IWineD3DSwapChain_Release((IWineD3DSwapChain *)swapchain);
1408 1409 1410 1411 1412
    } else {
        /* Primary offscreen render target */
        TRACE("Offscreen render target\n");
        glDrawBuffer(myDevice->offscreenBuffer);
        checkGLcall("glDrawBuffer(myDevice->offscreenBuffer)");
1413
    }
1414 1415

    glGetIntegerv(GL_PACK_SWAP_BYTES, &prev_store);
1416
    checkGLcall("glIntegerv");
1417
    glGetIntegerv(GL_CURRENT_RASTER_POSITION, &prev_rasterpos[0]);
1418
    checkGLcall("glIntegerv");
1419
    glPixelZoom(1.0f, -1.0f);
1420
    checkGLcall("glPixelZoom");
1421 1422 1423 1424 1425 1426

    /* If not fullscreen, we need to skip a number of bytes to find the next row of data */
    glGetIntegerv(GL_UNPACK_ROW_LENGTH, &skipBytes);
    glPixelStorei(GL_UNPACK_ROW_LENGTH, This->currentDesc.Width);

    glRasterPos3i(This->lockedRect.left, This->lockedRect.top, 1);
1427
    checkGLcall("glRasterPos2f");
1428 1429 1430 1431 1432 1433 1434

    /* Some drivers(radeon dri, others?) don't like exceptions during
     * glDrawPixels. If the surface is a DIB section, it might be in GDIMode
     * after ReleaseDC. Reading it will cause an exception, which x11drv will
     * catch to put the dib section in InSync mode, which leads to a crash
     * and a blocked x server on my radeon card.
     *
Austin English's avatar
Austin English committed
1435
     * The following lines read the dib section so it is put in InSync mode
1436 1437 1438 1439
     * before glDrawPixels is called and the crash is prevented. There won't
     * be any interfering gdi accesses, because UnlockRect is called from
     * ReleaseDC, and the app won't use the dc any more afterwards.
     */
1440
    if((This->Flags & SFLAG_DIBSECTION) && !(This->Flags & SFLAG_PBO)) {
1441 1442 1443 1444
        volatile BYTE read;
        read = This->resource.allocatedMemory[0];
    }

1445 1446 1447 1448 1449
    if(This->Flags & SFLAG_PBO) {
        GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
        checkGLcall("glBindBufferARB");
    }

1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
    /* When the surface is locked we only have to refresh the locked part else we need to update the whole image */
    if(This->Flags & SFLAG_LOCKED) {
        glDrawPixels(This->lockedRect.right - This->lockedRect.left,
                     (This->lockedRect.bottom - This->lockedRect.top)-1,
                     fmt, type,
                     mem + bpp * This->lockedRect.left + pitch * This->lockedRect.top);
        checkGLcall("glDrawPixels");
    } else {
        glDrawPixels(This->currentDesc.Width,
                     This->currentDesc.Height,
                     fmt, type, mem);
        checkGLcall("glDrawPixels");
    }
1463 1464 1465 1466 1467 1468

    if(This->Flags & SFLAG_PBO) {
        GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
        checkGLcall("glBindBufferARB");
    }

1469
    glPixelZoom(1.0f, 1.0f);
1470
    checkGLcall("glPixelZoom");
1471 1472

    glRasterPos3iv(&prev_rasterpos[0]);
1473
    checkGLcall("glRasterPos3iv");
1474 1475 1476

    /* Reset to previous pack row length */
    glPixelStorei(GL_UNPACK_ROW_LENGTH, skipBytes);
1477
    checkGLcall("glPixelStorei GL_UNPACK_ROW_LENGTH");
1478

1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
    if(!swapchain) {
        glDrawBuffer(myDevice->offscreenBuffer);
        checkGLcall("glDrawBuffer(myDevice->offscreenBuffer)");
    } else if(swapchain->backBuffer) {
        glDrawBuffer(GL_BACK);
        checkGLcall("glDrawBuffer(GL_BACK)");
    } else {
        glDrawBuffer(GL_FRONT);
        checkGLcall("glDrawBuffer(GL_FRONT)");
    }
    LEAVE_GL();

1491 1492 1493 1494
    return;
}

static HRESULT WINAPI IWineD3DSurfaceImpl_UnlockRect(IWineD3DSurface *iface) {
1495
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1496
    IWineD3DDeviceImpl  *myDevice = This->resource.wineD3DDevice;
1497
    BOOL fullsurface;
1498

1499
    if (!(This->Flags & SFLAG_LOCKED)) {
1500
        WARN("trying to Unlock an unlocked surf@%p\n", This);
1501
        return WINEDDERR_NOTLOCKED;
1502 1503
    }

1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
    if (This->Flags & SFLAG_PBO) {
        TRACE("Freeing PBO memory\n");
        ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
        ENTER_GL();
        GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
        GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
        GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
        checkGLcall("glUnmapBufferARB");
        LEAVE_GL();
        This->resource.allocatedMemory = NULL;
    }

1516
    TRACE("(%p) : dirtyfied(%d)\n", This, This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE) ? 0 : 1);
1517

1518
    if (This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE)) {
1519 1520 1521 1522
        TRACE("(%p) : Not Dirtified so nothing to do, return now\n", This);
        goto unlock_end;
    }

1523 1524
    if ((This->Flags & SFLAG_SWAPCHAIN) || (myDevice->render_targets && iface == myDevice->render_targets[0]))
    {
1525 1526 1527 1528 1529
        if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
            static BOOL warned = FALSE;
            if(!warned) {
                ERR("The application tries to write to the render target, but render target locking is disabled\n");
                warned = TRUE;
1530
            }
1531
            goto unlock_end;
1532
        }
1533

1534 1535 1536 1537 1538
        if(This->dirtyRect.left   == 0 &&
           This->dirtyRect.top    == 0 &&
           This->dirtyRect.right  == This->currentDesc.Width &&
           This->dirtyRect.bottom == This->currentDesc.Height) {
            fullsurface = TRUE;
1539
        } else {
1540 1541 1542
            /* TODO: Proper partial rectangle tracking */
            fullsurface = FALSE;
            This->Flags |= SFLAG_INSYSMEM;
1543 1544
        }

1545
        switch(wined3d_settings.rendertargetlock_mode) {
1546 1547 1548
            case RTL_READTEX:
            case RTL_TEXTEX:
                IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL /* partial texture loading not supported yet */);
1549 1550
                /* drop through */

1551 1552 1553
            case RTL_AUTO:
            case RTL_READDRAW:
            case RTL_TEXDRAW:
1554
                IWineD3DSurface_LoadLocation(iface, SFLAG_INDRAWABLE, fullsurface ? NULL : &This->dirtyRect);
1555 1556
                break;
        }
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566

        if(!fullsurface) {
            /* Partial rectangle tracking is not commonly implemented, it is only done for render targets. Overwrite
             * the flags to bring them back into a sane state. INSYSMEM was set before to tell LoadLocation where
             * to read the rectangle from. Indrawable is set because all modifications from the partial sysmem copy
             * are written back to the drawable, thus the surface is merged again in the drawable. The sysmem copy is
             * not fully up to date because only a subrectangle was read in LockRect.
             */
            This->Flags &= ~SFLAG_INSYSMEM;
            This->Flags |= SFLAG_INDRAWABLE;
1567 1568
        }

1569 1570 1571 1572
        This->dirtyRect.left   = This->currentDesc.Width;
        This->dirtyRect.top    = This->currentDesc.Height;
        This->dirtyRect.right  = 0;
        This->dirtyRect.bottom = 0;
1573 1574
    } else if(iface == myDevice->stencilBufferTarget) {
        FIXME("Depth Stencil buffer locking is not implemented\n");
1575
    } else {
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
        /* The rest should be a normal texture */
        IWineD3DBaseTextureImpl *impl;
        /* Check if the texture is bound, if yes dirtify the sampler to force a re-upload of the texture
         * Can't load the texture here because PreLoad may destroy and recreate the gl texture, so sampler
         * states need resetting
         */
        if(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&impl) == WINED3D_OK) {
            if(impl->baseTexture.bindCount) {
                IWineD3DDeviceImpl_MarkStateDirty(myDevice, STATE_SAMPLER(impl->baseTexture.sampler));
            }
            IWineD3DBaseTexture_Release((IWineD3DBaseTexture *) impl);
        }
1588 1589 1590
    }

    unlock_end:
1591
    This->Flags &= ~SFLAG_LOCKED;
1592
    memset(&This->lockedRect, 0, sizeof(RECT));
1593 1594 1595 1596 1597

    /* Overlays have to be redrawn manually after changes with the GL implementation */
    if(This->overlay_dest) {
        IWineD3DSurface_DrawOverlay(iface);
    }
1598
    return WINED3D_OK;
1599 1600
}

1601 1602
static HRESULT WINAPI IWineD3DSurfaceImpl_GetDC(IWineD3DSurface *iface, HDC *pHDC)
{
1603
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1604 1605
    WINED3DLOCKED_RECT lock;
    HRESULT hr;
1606
    RGBQUAD col[256];
1607 1608 1609

    TRACE("(%p)->(%p)\n",This,pHDC);

1610 1611
    if(This->Flags & SFLAG_USERPTR) {
        ERR("Not supported on surfaces with an application-provided surfaces\n");
1612
        return WINEDDERR_NODC;
1613 1614
    }

1615 1616
    /* Give more detailed info for ddraw */
    if (This->Flags & SFLAG_DCINUSE)
1617
        return WINEDDERR_DCALREADYCREATED;
1618 1619 1620 1621 1622

    /* Can't GetDC if the surface is locked */
    if (This->Flags & SFLAG_LOCKED)
        return WINED3DERR_INVALIDCALL;

1623 1624
    /* According to Direct3D9 docs, only these formats are supported */
    if (((IWineD3DImpl *)This->resource.wineD3DDevice->wineD3D)->dxVersion > 7) {
1625 1626 1627 1628 1629
        if (This->resource.format_desc->format != WINED3DFMT_R5G6B5
                && This->resource.format_desc->format != WINED3DFMT_X1R5G5B5
                && This->resource.format_desc->format != WINED3DFMT_R8G8B8
                && This->resource.format_desc->format != WINED3DFMT_X8R8G8B8)
            return WINED3DERR_INVALIDCALL;
1630 1631
    }

1632 1633 1634
    memset(&lock, 0, sizeof(lock)); /* To be sure */

    /* Create a DIB section if there isn't a hdc yet */
1635
    if(!This->hDC) {
1636 1637
        IWineD3DBaseSurfaceImpl_CreateDIBSection(iface);
        if(This->Flags & SFLAG_CLIENT) {
1638
            surface_internal_preload(iface, SRGB_RGB);
1639
        }
1640

1641 1642 1643
        /* Use the dib section from now on if we are not using a PBO */
        if(!(This->Flags & SFLAG_PBO))
            This->resource.allocatedMemory = This->dib.bitmap_data;
1644 1645 1646 1647 1648 1649 1650
    }

    /* Lock the surface */
    hr = IWineD3DSurface_LockRect(iface,
                                  &lock,
                                  NULL,
                                  0);
1651 1652 1653 1654 1655 1656

    if(This->Flags & SFLAG_PBO) {
        /* Sync the DIB with the PBO. This can't be done earlier because LockRect activates the allocatedMemory */
        memcpy(This->dib.bitmap_data, This->resource.allocatedMemory, This->dib.bitmap_size);
    }

1657
    if(FAILED(hr)) {
1658
        ERR("IWineD3DSurface_LockRect failed with hr = %08x\n", hr);
1659 1660 1661 1662
        /* keep the dib section */
        return hr;
    }

1663 1664 1665
    if (This->resource.format_desc->format == WINED3DFMT_P8
            || This->resource.format_desc->format == WINED3DFMT_A8P8)
    {
1666 1667
        /* GetDC on palettized formats is unsupported in D3D9, and the method is missing in
            D3D8, so this should only be used for DX <=7 surfaces (with non-device palettes) */
1668
        unsigned int n;
1669
        const PALETTEENTRY *pal = NULL;
1670

1671 1672
        if(This->palette) {
            pal = This->palette->palents;
1673
        } else {
1674 1675 1676 1677
            IWineD3DSurfaceImpl *dds_primary;
            IWineD3DSwapChainImpl *swapchain;
            swapchain = (IWineD3DSwapChainImpl *)This->resource.wineD3DDevice->swapchains[0];
            dds_primary = (IWineD3DSurfaceImpl *)swapchain->frontBuffer;
1678 1679 1680
            if (dds_primary && dds_primary->palette)
                pal = dds_primary->palette->palents;
        }
1681

1682
        if (pal) {
1683
            for (n=0; n<256; n++) {
1684 1685 1686
                col[n].rgbRed   = pal[n].peRed;
                col[n].rgbGreen = pal[n].peGreen;
                col[n].rgbBlue  = pal[n].peBlue;
1687 1688
                col[n].rgbReserved = 0;
            }
1689
            SetDIBColorTable(This->hDC, 0, 256, col);
1690 1691 1692
        }
    }

1693 1694 1695 1696 1697
    *pHDC = This->hDC;
    TRACE("returning %p\n",*pHDC);
    This->Flags |= SFLAG_DCINUSE;

    return WINED3D_OK;
1698 1699
}

1700 1701
static HRESULT WINAPI IWineD3DSurfaceImpl_ReleaseDC(IWineD3DSurface *iface, HDC hDC)
{
1702
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1703 1704 1705 1706

    TRACE("(%p)->(%p)\n",This,hDC);

    if (!(This->Flags & SFLAG_DCINUSE))
1707
        return WINEDDERR_NODC;
1708

1709 1710
    if (This->hDC !=hDC) {
        WARN("Application tries to release an invalid DC(%p), surface dc is %p\n", hDC, This->hDC);
1711
        return WINEDDERR_NODC;
1712 1713
    }

1714 1715 1716 1717 1718
    if((This->Flags & SFLAG_PBO) && This->resource.allocatedMemory) {
        /* Copy the contents of the DIB over to the PBO */
        memcpy(This->resource.allocatedMemory, This->dib.bitmap_data, This->dib.bitmap_size);
    }

1719 1720 1721 1722 1723 1724
    /* we locked first, so unlock now */
    IWineD3DSurface_UnlockRect(iface);

    This->Flags &= ~SFLAG_DCINUSE;

    return WINED3D_OK;
1725 1726 1727 1728 1729
}

/* ******************************************************
   IWineD3DSurface Internal (No mapping to directx api) parts follow
   ****************************************************** */
1730

1731
HRESULT d3dfmt_get_conv(IWineD3DSurfaceImpl *This, BOOL need_alpha_ck, BOOL use_texturing, GLenum *format, GLenum *internal, GLenum *type, CONVERT_TYPES *convert, int *target_bpp, BOOL srgb_mode) {
1732
    BOOL colorkey_active = need_alpha_ck && (This->CKeyFlags & WINEDDSD_CKSRCBLT);
1733
    const struct GlPixelFormatDesc *glDesc = This->resource.format_desc;
1734
    IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
1735 1736

    /* Default values: From the surface */
1737 1738
    *format = glDesc->glFormat;
    *type = glDesc->glType;
1739
    *convert = NO_CONVERSION;
1740
    *target_bpp = glDesc->byte_count;
1741

1742 1743
    if(srgb_mode) {
        *internal = glDesc->glGammaInternal;
1744 1745 1746 1747
    }
    else if (This->resource.usage & WINED3DUSAGE_RENDERTARGET
            && !(This->Flags & SFLAG_SWAPCHAIN))
    {
1748 1749 1750 1751 1752
        *internal = glDesc->rtInternal;
    } else {
        *internal = glDesc->glInternal;
    }

1753
    /* Ok, now look if we have to do any conversion */
1754 1755
    switch(This->resource.format_desc->format)
    {
1756 1757 1758 1759
        case WINED3DFMT_P8:
            /* ****************
                Paletted Texture
                **************** */
1760

1761
             /* Use conversion when the paletted texture extension OR fragment shaders are available. When either
1762 1763 1764 1765 1766
             * of the two is available make sure texturing is requested as neither of the two works in
             * conjunction with calls like glDraw-/glReadPixels. Further also use conversion in case of color keying.
             * Paletted textures can be emulated using shaders but only do that for 2D purposes e.g. situations
             * in which the main render target uses p8. Some games like GTA Vice City use P8 for texturing which
             * conflicts with this.
1767
             */
1768 1769 1770 1771 1772
            if( !(GL_SUPPORT(EXT_PALETTED_TEXTURE) ||
                  (GL_SUPPORT(ARB_FRAGMENT_PROGRAM) &&
                   device->render_targets &&
                   This == (IWineD3DSurfaceImpl*)device->render_targets[0])) ||
                colorkey_active || !use_texturing ) {
1773 1774 1775 1776 1777 1778
                *format = GL_RGBA;
                *internal = GL_RGBA;
                *type = GL_UNSIGNED_BYTE;
                *target_bpp = 4;
                if(colorkey_active) {
                    *convert = CONVERT_PALETTED_CK;
1779 1780
                } else {
                    *convert = CONVERT_PALETTED;
1781 1782
                }
            }
1783
            else if(!GL_SUPPORT(EXT_PALETTED_TEXTURE) && GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
1784
                *format = GL_ALPHA;
1785 1786 1787
                *type = GL_UNSIGNED_BYTE;
                *target_bpp = 1;
            }
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805

            break;

        case WINED3DFMT_R3G3B2:
            /* **********************
                GL_UNSIGNED_BYTE_3_3_2
                ********************** */
            if (colorkey_active) {
                /* This texture format will never be used.. So do not care about color keying
                    up until the point in time it will be needed :-) */
                FIXME(" ColorKeying not supported in the RGB 332 format !\n");
            }
            break;

        case WINED3DFMT_R5G6B5:
            if (colorkey_active) {
                *convert = CONVERT_CK_565;
                *format = GL_RGBA;
1806
                *internal = GL_RGB5_A1;
1807 1808 1809 1810
                *type = GL_UNSIGNED_SHORT_5_5_5_1;
            }
            break;

1811 1812 1813 1814
        case WINED3DFMT_X1R5G5B5:
            if (colorkey_active) {
                *convert = CONVERT_CK_5551;
                *format = GL_BGRA;
1815
                *internal = GL_RGB5_A1;
1816 1817 1818 1819
                *type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
            }
            break;

1820 1821 1822 1823
        case WINED3DFMT_R8G8B8:
            if (colorkey_active) {
                *convert = CONVERT_CK_RGB24;
                *format = GL_RGBA;
1824
                *internal = GL_RGBA8;
1825 1826 1827 1828 1829 1830 1831 1832 1833
                *type = GL_UNSIGNED_INT_8_8_8_8;
                *target_bpp = 4;
            }
            break;

        case WINED3DFMT_X8R8G8B8:
            if (colorkey_active) {
                *convert = CONVERT_RGB32_888;
                *format = GL_RGBA;
1834
                *internal = GL_RGBA8;
1835 1836 1837 1838
                *type = GL_UNSIGNED_INT_8_8_8_8;
            }
            break;

1839
        case WINED3DFMT_R8G8_SNORM:
1840
            if (GL_SUPPORT(NV_TEXTURE_SHADER)) break;
1841 1842
            *convert = CONVERT_V8U8;
            *format = GL_BGR;
1843
            *type = GL_UNSIGNED_BYTE;
1844 1845 1846
            *target_bpp = 3;
            break;

1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
        case WINED3DFMT_L6V5U5:
            *convert = CONVERT_L6V5U5;
            if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
                *target_bpp = 3;
                /* Use format and types from table */
            } else {
                /* Load it into unsigned R5G6B5, swap L and V channels, and revert that in the shader */
                *target_bpp = 2;
                *format = GL_RGB;
                *type = GL_UNSIGNED_SHORT_5_6_5;
            }
            break;

1860
        case WINED3DFMT_X8L8V8U8:
1861
            *convert = CONVERT_X8L8V8U8;
1862
            *target_bpp = 4;
1863 1864 1865 1866 1867 1868 1869 1870 1871
            if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
                /* Use formats from gl table. It is a bit unfortunate, but the conversion
                 * is needed to set the X format to 255 to get 1.0 for alpha when sampling
                 * the texture. OpenGL can't use GL_DSDT8_MAG8_NV as internal format with
                 * the needed type and format parameter, so the internal format contains a
                 * 4th component, which is returned as alpha
                 */
            } else {
                *format = GL_BGRA;
1872
                *type = GL_UNSIGNED_INT_8_8_8_8_REV;
1873
            }
1874 1875
            break;

1876
        case WINED3DFMT_R8G8B8A8_SNORM:
1877
            if (GL_SUPPORT(NV_TEXTURE_SHADER)) break;
1878
            *convert = CONVERT_Q8W8V8U8;
1879
            *format = GL_BGRA;
1880
            *type = GL_UNSIGNED_BYTE;
1881 1882 1883
            *target_bpp = 4;
            break;

1884
        case WINED3DFMT_R16G16_SNORM:
1885
            if (GL_SUPPORT(NV_TEXTURE_SHADER)) break;
1886 1887
            *convert = CONVERT_V16U16;
            *format = GL_BGR;
1888
            *type = GL_UNSIGNED_SHORT;
1889
            *target_bpp = 6;
1890 1891
            break;

1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
        case WINED3DFMT_A4L4:
            /* A4L4 exists as an internal gl format, but for some reason there is not
             * format+type combination to load it. Thus convert it to A8L8, then load it
             * with A4L4 internal, but A8L8 format+type
             */
            *convert = CONVERT_A4L4;
            *format = GL_LUMINANCE_ALPHA;
            *type = GL_UNSIGNED_BYTE;
            *target_bpp = 2;
            break;

1903
        case WINED3DFMT_R16G16_UNORM:
1904 1905 1906 1907 1908 1909
            *convert = CONVERT_G16R16;
            *format = GL_RGB;
            *type = GL_UNSIGNED_SHORT;
            *target_bpp = 6;
            break;

1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
        case WINED3DFMT_R16G16_FLOAT:
            *convert = CONVERT_R16G16F;
            *format = GL_RGB;
            *type = GL_HALF_FLOAT_ARB;
            *target_bpp = 6;
            break;

        case WINED3DFMT_R32G32_FLOAT:
            *convert = CONVERT_R32G32F;
            *format = GL_RGB;
            *type = GL_FLOAT;
            *target_bpp = 12;
            break;

1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
        case WINED3DFMT_D15S1:
            if (GL_SUPPORT(EXT_PACKED_DEPTH_STENCIL))
            {
                *convert = CONVERT_D15S1;
                *target_bpp = 4;
            }
            break;

        case WINED3DFMT_D24X4S4:
            if (GL_SUPPORT(EXT_PACKED_DEPTH_STENCIL))
            {
                *convert = CONVERT_D24X4S4;
            }
            break;

        case WINED3DFMT_D24FS8:
            if (GL_SUPPORT(ARB_DEPTH_BUFFER_FLOAT))
            {
                *convert = CONVERT_D24FS8;
                *target_bpp = 8;
            }
            break;

1947 1948 1949 1950 1951 1952 1953
        default:
            break;
    }

    return WINED3D_OK;
}

1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
static void d3dfmt_p8_init_palette(IWineD3DSurfaceImpl *This, BYTE table[256][4], BOOL colorkey)
{
    IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
    IWineD3DPaletteImpl *pal = This->palette;
    BOOL index_in_alpha = FALSE;
    unsigned int i;

    /* Old games like StarCraft, C&C, Red Alert and others use P8 render targets.
     * Reading back the RGB output each lockrect (each frame as they lock the whole screen)
     * is slow. Further RGB->P8 conversion is not possible because palettes can have
     * duplicate entries. Store the color key in the unused alpha component to speed the
     * download up and to make conversion unneeded. */
    index_in_alpha = primary_render_target_is_p8(device);

    if (!pal)
    {
        UINT dxVersion = ((IWineD3DImpl *)device->wineD3D)->dxVersion;

        /* In DirectDraw the palette is a property of the surface, there are no such things as device palettes. */
        if (dxVersion <= 7)
        {
            ERR("This code should never get entered for DirectDraw!, expect problems\n");
            if (index_in_alpha)
            {
                /* Guarantees that memory representation remains correct after sysmem<->texture transfers even if
                 * there's no palette at this time. */
                for (i = 0; i < 256; i++) table[i][3] = i;
            }
        }
        else
        {
            /* Direct3D >= 8 palette usage style: P8 textures use device palettes, palette entry format is A8R8G8B8,
             * alpha is stored in peFlags and may be used by the app if D3DPTEXTURECAPS_ALPHAPALETTE device
             * capability flag is present (wine does advertise this capability) */
            for (i = 0; i < 256; ++i)
            {
                table[i][0] = device->palettes[device->currentPalette][i].peRed;
                table[i][1] = device->palettes[device->currentPalette][i].peGreen;
                table[i][2] = device->palettes[device->currentPalette][i].peBlue;
                table[i][3] = device->palettes[device->currentPalette][i].peFlags;
            }
        }
    }
    else
    {
        TRACE("Using surface palette %p\n", pal);
        /* Get the surface's palette */
        for (i = 0; i < 256; ++i)
        {
            table[i][0] = pal->palents[i].peRed;
            table[i][1] = pal->palents[i].peGreen;
            table[i][2] = pal->palents[i].peBlue;

            /* When index_in_alpha is set the palette index is stored in the
             * alpha component. In case of a readback we can then read
             * GL_ALPHA. Color keying is handled in BltOverride using a
             * GL_ALPHA_TEST using GL_NOT_EQUAL. In case of index_in_alpha the
             * color key itself is passed to glAlphaFunc in other cases the
             * alpha component of pixels that should be masked away is set to 0. */
            if (index_in_alpha)
            {
                table[i][3] = i;
            }
            else if (colorkey && (i >= This->SrcBltCKey.dwColorSpaceLowValue)
                    && (i <= This->SrcBltCKey.dwColorSpaceHighValue))
            {
                table[i][3] = 0x00;
            }
            else if(pal->Flags & WINEDDPCAPS_ALPHA)
            {
                table[i][3] = pal->palents[i].peFlags;
            }
            else
            {
                table[i][3] = 0xFF;
            }
        }
    }
}

2034
static HRESULT d3dfmt_convert_surface(const BYTE *src, BYTE *dst, UINT pitch, UINT width,
2035 2036
        UINT height, UINT outpitch, CONVERT_TYPES convert, IWineD3DSurfaceImpl *This)
{
2037 2038
    const BYTE *source;
    BYTE *dest;
2039
    TRACE("(%p)->(%p),(%d,%d,%d,%d,%p)\n", src, dst, pitch, height, outpitch, convert,This);
2040 2041 2042 2043

    switch (convert) {
        case NO_CONVERSION:
        {
2044
            memcpy(dst, src, pitch * height);
2045 2046 2047 2048 2049
            break;
        }
        case CONVERT_PALETTED:
        case CONVERT_PALETTED_CK:
        {
2050
            IWineD3DPaletteImpl* pal = This->palette;
2051
            BYTE table[256][4];
2052
            unsigned int x, y;
2053 2054 2055 2056 2057

            if( pal == NULL) {
                /* TODO: If we are a sublevel, try to get the palette from level 0 */
            }

2058
            d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
2059

2060 2061
            for (y = 0; y < height; y++)
            {
2062
                source = src + pitch * y;
2063
                dest = dst + outpitch * y;
2064 2065 2066
                /* This is an 1 bpp format, using the width here is fine */
                for (x = 0; x < width; x++) {
                    BYTE color = *source++;
2067 2068 2069 2070 2071
                    *dest++ = table[color][0];
                    *dest++ = table[color][1];
                    *dest++ = table[color][2];
                    *dest++ = table[color][3];
                }
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
            }
        }
        break;

        case CONVERT_CK_565:
        {
            /* Converting the 565 format in 5551 packed to emulate color-keying.

              Note : in all these conversion, it would be best to average the averaging
                      pixels to get the color of the pixel that will be color-keyed to
                      prevent 'color bleeding'. This will be done later on if ever it is
                      too visible.

2085 2086
              Note2: Nvidia documents say that their driver does not support alpha + color keying
                     on the same surface and disables color keying in such a case
2087
            */
2088
            unsigned int x, y;
2089
            const WORD *Source;
2090
            WORD *Dest;
2091 2092 2093

            TRACE("Color keyed 565\n");

2094
            for (y = 0; y < height; y++) {
2095
                Source = (const WORD *)(src + y * pitch);
2096
                Dest = (WORD *) (dst + y * outpitch);
2097
                for (x = 0; x < width; x++ ) {
2098 2099
                    WORD color = *Source++;
                    *Dest = ((color & 0xFFC0) | ((color & 0x1F) << 1));
2100 2101
                    if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
                        (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2102 2103 2104
                        *Dest |= 0x0001;
                    }
                    Dest++;
2105 2106 2107 2108 2109
                }
            }
        }
        break;

2110 2111 2112 2113
        case CONVERT_CK_5551:
        {
            /* Converting X1R5G5B5 format to R5G5B5A1 to emulate color-keying. */
            unsigned int x, y;
2114
            const WORD *Source;
2115 2116 2117
            WORD *Dest;
            TRACE("Color keyed 5551\n");
            for (y = 0; y < height; y++) {
2118
                Source = (const WORD *)(src + y * pitch);
2119 2120 2121
                Dest = (WORD *) (dst + y * outpitch);
                for (x = 0; x < width; x++ ) {
                    WORD color = *Source++;
2122
                    *Dest = color;
2123 2124
                    if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
                        (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2125 2126 2127 2128 2129 2130 2131
                        *Dest |= (1 << 15);
                    }
                    else {
                        *Dest &= ~(1 << 15);
                    }
                    Dest++;
                }
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154
            }
        }
        break;

        case CONVERT_CK_RGB24:
        {
            /* Converting R8G8B8 format to R8G8B8A8 with color-keying. */
            unsigned int x, y;
            for (y = 0; y < height; y++)
            {
                source = src + pitch * y;
                dest = dst + outpitch * y;
                for (x = 0; x < width; x++) {
                    DWORD color = ((DWORD)source[0] << 16) + ((DWORD)source[1] << 8) + (DWORD)source[2] ;
                    DWORD dstcolor = color << 8;
                    if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
                        (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
                        dstcolor |= 0xff;
                    }
                    *(DWORD*)dest = dstcolor;
                    source += 3;
                    dest += 4;
                }
2155 2156 2157 2158
            }
        }
        break;

2159 2160 2161 2162 2163 2164 2165 2166 2167
        case CONVERT_RGB32_888:
        {
            /* Converting X8R8G8B8 format to R8G8B8A8 with color-keying. */
            unsigned int x, y;
            for (y = 0; y < height; y++)
            {
                source = src + pitch * y;
                dest = dst + outpitch * y;
                for (x = 0; x < width; x++) {
2168
                    DWORD color = 0xffffff & *(const DWORD*)source;
2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181
                    DWORD dstcolor = color << 8;
                    if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
                        (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
                        dstcolor |= 0xff;
                    }
                    *(DWORD*)dest = dstcolor;
                    source += 4;
                    dest += 4;
                }
            }
        }
        break;

2182 2183 2184
        case CONVERT_V8U8:
        {
            unsigned int x, y;
2185
            const short *Source;
2186
            unsigned char *Dest;
2187
            for(y = 0; y < height; y++) {
2188
                Source = (const short *)(src + y * pitch);
2189
                Dest = dst + y * outpitch;
2190 2191
                for (x = 0; x < width; x++ ) {
                    long color = (*Source++);
2192 2193 2194
                    /* B */ Dest[0] = 0xff;
                    /* G */ Dest[1] = (color >> 8) + 128; /* V */
                    /* R */ Dest[2] = (color) + 128;      /* U */
2195 2196 2197 2198 2199 2200
                    Dest += 3;
                }
            }
            break;
        }

2201 2202 2203
        case CONVERT_V16U16:
        {
            unsigned int x, y;
2204
            const DWORD *Source;
2205 2206
            unsigned short *Dest;
            for(y = 0; y < height; y++) {
2207
                Source = (const DWORD *)(src + y * pitch);
2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219
                Dest = (unsigned short *) (dst + y * outpitch);
                for (x = 0; x < width; x++ ) {
                    DWORD color = (*Source++);
                    /* B */ Dest[0] = 0xffff;
                    /* G */ Dest[1] = (color >> 16) + 32768; /* V */
                    /* R */ Dest[2] = (color      ) + 32768; /* U */
                    Dest += 3;
                }
            }
            break;
        }

2220 2221 2222
        case CONVERT_Q8W8V8U8:
        {
            unsigned int x, y;
2223
            const DWORD *Source;
2224 2225
            unsigned char *Dest;
            for(y = 0; y < height; y++) {
2226
                Source = (const DWORD *)(src + y * pitch);
2227
                Dest = dst + y * outpitch;
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
                for (x = 0; x < width; x++ ) {
                    long color = (*Source++);
                    /* B */ Dest[0] = ((color >> 16) & 0xff) + 128; /* W */
                    /* G */ Dest[1] = ((color >> 8 ) & 0xff) + 128; /* V */
                    /* R */ Dest[2] = (color         & 0xff) + 128; /* U */
                    /* A */ Dest[3] = ((color >> 24) & 0xff) + 128; /* Q */
                    Dest += 4;
                }
            }
            break;
        }

2240 2241 2242
        case CONVERT_L6V5U5:
        {
            unsigned int x, y;
2243
            const WORD *Source;
2244 2245 2246 2247 2248 2249 2250 2251
            unsigned char *Dest;

            if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
                /* This makes the gl surface bigger(24 bit instead of 16), but it works with
                 * fixed function and shaders without further conversion once the surface is
                 * loaded
                 */
                for(y = 0; y < height; y++) {
2252
                    Source = (const WORD *)(src + y * pitch);
2253
                    Dest = dst + y * outpitch;
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
                    for (x = 0; x < width; x++ ) {
                        short color = (*Source++);
                        unsigned char l = ((color >> 10) & 0xfc);
                                  char v = ((color >>  5) & 0x3e);
                                  char u = ((color      ) & 0x1f);

                        /* 8 bits destination, 6 bits source, 8th bit is the sign. gl ignores the sign
                         * and doubles the positive range. Thus shift left only once, gl does the 2nd
                         * shift. GL reads a signed value and converts it into an unsigned value.
                         */
                        /* M */ Dest[2] = l << 1;

                        /* Those are read as signed, but kept signed. Just left-shift 3 times to scale
                         * from 5 bit values to 8 bit values.
                         */
                        /* V */ Dest[1] = v << 3;
                        /* U */ Dest[0] = u << 3;
                        Dest += 3;
                    }
                }
            } else {
2275 2276
                for(y = 0; y < height; y++) {
                    unsigned short *Dest_s = (unsigned short *) (dst + y * outpitch);
2277
                    Source = (const WORD *)(src + y * pitch);
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
                    for (x = 0; x < width; x++ ) {
                        short color = (*Source++);
                        unsigned char l = ((color >> 10) & 0xfc);
                                 short v = ((color >>  5) & 0x3e);
                                 short u = ((color      ) & 0x1f);
                        short v_conv = v + 16;
                        short u_conv = u + 16;

                        *Dest_s = ((v_conv << 11) & 0xf800) | ((l << 5) & 0x7e0) | (u_conv & 0x1f);
                        Dest_s += 1;
                    }
                }
2290 2291 2292 2293
            }
            break;
        }

2294 2295 2296
        case CONVERT_X8L8V8U8:
        {
            unsigned int x, y;
2297
            const DWORD *Source;
2298 2299 2300 2301 2302 2303 2304
            unsigned char *Dest;

            if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
                /* This implementation works with the fixed function pipeline and shaders
                 * without further modification after converting the surface.
                 */
                for(y = 0; y < height; y++) {
2305
                    Source = (const DWORD *)(src + y * pitch);
2306
                    Dest = dst + y * outpitch;
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
                    for (x = 0; x < width; x++ ) {
                        long color = (*Source++);
                        /* L */ Dest[2] = ((color >> 16) & 0xff);   /* L */
                        /* V */ Dest[1] = ((color >> 8 ) & 0xff);   /* V */
                        /* U */ Dest[0] = (color         & 0xff);   /* U */
                        /* I */ Dest[3] = 255;                      /* X */
                        Dest += 4;
                    }
                }
            } else {
                /* Doesn't work correctly with the fixed function pipeline, but can work in
                 * shaders if the shader is adjusted. (There's no use for this format in gl's
                 * standard fixed function pipeline anyway).
                 */
2321
                for(y = 0; y < height; y++) {
2322
                    Source = (const DWORD *)(src + y * pitch);
2323
                    Dest = dst + y * outpitch;
2324 2325 2326 2327 2328 2329 2330 2331
                    for (x = 0; x < width; x++ ) {
                        long color = (*Source++);
                        /* B */ Dest[0] = ((color >> 16) & 0xff);       /* L */
                        /* G */ Dest[1] = ((color >> 8 ) & 0xff) + 128; /* V */
                        /* R */ Dest[2] = (color         & 0xff) + 128;  /* U */
                        Dest += 4;
                    }
                }
2332 2333 2334 2335
            }
            break;
        }

2336 2337 2338
        case CONVERT_A4L4:
        {
            unsigned int x, y;
2339
            const unsigned char *Source;
2340 2341
            unsigned char *Dest;
            for(y = 0; y < height; y++) {
2342 2343
                Source = src + y * pitch;
                Dest = dst + y * outpitch;
2344 2345 2346 2347 2348 2349 2350 2351 2352
                for (x = 0; x < width; x++ ) {
                    unsigned char color = (*Source++);
                    /* A */ Dest[1] = (color & 0xf0) << 0;
                    /* L */ Dest[0] = (color & 0x0f) << 4;
                    Dest += 2;
                }
            }
            break;
        }
2353

2354
        case CONVERT_G16R16:
2355
        case CONVERT_R16G16F:
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368
        {
            unsigned int x, y;
            const WORD *Source;
            WORD *Dest;

            for(y = 0; y < height; y++) {
                Source = (const WORD *)(src + y * pitch);
                Dest = (WORD *) (dst + y * outpitch);
                for (x = 0; x < width; x++ ) {
                    WORD green = (*Source++);
                    WORD red = (*Source++);
                    Dest[0] = green;
                    Dest[1] = red;
2369 2370 2371
                    /* Strictly speaking not correct for R16G16F, but it doesn't matter because the
                     * shader overwrites it anyway
                     */
2372 2373 2374 2375 2376 2377 2378
                    Dest[2] = 0xffff;
                    Dest += 3;
                }
            }
            break;
        }

2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391
        case CONVERT_R32G32F:
        {
            unsigned int x, y;
            const float *Source;
            float *Dest;
            for(y = 0; y < height; y++) {
                Source = (const float *)(src + y * pitch);
                Dest = (float *) (dst + y * outpitch);
                for (x = 0; x < width; x++ ) {
                    float green = (*Source++);
                    float red = (*Source++);
                    Dest[0] = green;
                    Dest[1] = red;
2392
                    Dest[2] = 1.0f;
2393 2394
                    Dest += 3;
                }
2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
            }
            break;
        }

        case CONVERT_D15S1:
        {
            unsigned int x, y;

            for (y = 0; y < height; ++y)
            {
                const WORD *source = (const WORD *)(src + y * pitch);
                DWORD *dest = (DWORD *)(dst + y * outpitch);

                for (x = 0; x < width; ++x)
                {
2410 2411 2412 2413 2414
                    /* The depth data is normalized, so needs to be scaled,
                     * the stencil data isn't.  Scale depth data by
                     *      (2^24-1)/(2^15-1) ~~ (2^9 + 2^-6). */
                    WORD d15 = source[x] >> 1;
                    DWORD d24 = (d15 << 9) + (d15 >> 6);
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
                    dest[x] = (d24 << 8) | (source[x] & 0x1);
                }
            }
            break;
        }

        case CONVERT_D24X4S4:
        {
            unsigned int x, y;

            for (y = 0; y < height; ++y)
            {
                const DWORD *source = (const DWORD *)(src + y * pitch);
                DWORD *dest = (DWORD *)(dst + y * outpitch);

                for (x = 0; x < width; ++x)
                {
                    /* Just need to clear out the X4 part. */
                    dest[x] = source[x] & ~0xf0;
                }
            }
            break;
        }

        case CONVERT_D24FS8:
        {
            unsigned int x, y;

            for (y = 0; y < height; ++y)
            {
                const DWORD *source = (const DWORD *)(src + y * pitch);
                float *dest_f = (float *)(dst + y * outpitch);
                DWORD *dest_s = (DWORD *)(dst + y * outpitch);

                for (x = 0; x < width; ++x)
                {
                    dest_f[x * 2] = float_24_to_32((source[x] & 0xffffff00) >> 8);
                    dest_s[x * 2 + 1] = source[x] & 0xff;
                }
2454 2455 2456 2457
            }
            break;
        }

2458
        default:
Henri Verbeet's avatar
Henri Verbeet committed
2459
            ERR("Unsupported conversion type %#x.\n", convert);
2460 2461 2462 2463
    }
    return WINED3D_OK;
}

2464
/* This function is used in case of 8bit paletted textures to upload the palette.
2465 2466
   It supports GL_EXT_paletted_texture and GL_ARB_fragment_program, support for other
   extensions like ATI_fragment_shaders is possible.
2467
*/
2468
/* Context activation is done by the caller. */
2469 2470 2471
static void d3dfmt_p8_upload_palette(IWineD3DSurface *iface, CONVERT_TYPES convert) {
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
    BYTE table[256][4];
2472
    IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2473 2474

    d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
2475 2476 2477 2478 2479

    /* Try to use the paletted texture extension */
    if(GL_SUPPORT(EXT_PALETTED_TEXTURE))
    {
        TRACE("Using GL_EXT_PALETTED_TEXTURE for 8-bit paletted texture support\n");
2480
        ENTER_GL();
2481
        GL_EXTCALL(glColorTableEXT(This->texture_target, GL_RGBA, 256, GL_RGBA, GL_UNSIGNED_BYTE, table));
2482
        LEAVE_GL();
2483 2484 2485 2486 2487 2488 2489
    }
    else
    {
        /* Let a fragment shader do the color conversion by uploading the palette to a 1D texture.
         * The 8bit pixel data will be used as an index in this palette texture to retrieve the final color. */
        TRACE("Using fragment shaders for emulating 8-bit paletted texture support\n");

2490 2491
        ENTER_GL();

2492 2493 2494
        /* Create the fragment program if we don't have it */
        if(!device->paletteConversionShader)
        {
2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
            const char *fragment_palette_conversion =
                "!!ARBfp1.0\n"
                "TEMP index;\n"
                /* { 255/256, 0.5/255*255/256, 0, 0 } */
                "PARAM constants = { 0.996, 0.00195, 0, 0 };\n"
                /* The alpha-component contains the palette index */
                "TEX index, fragment.texcoord[0], texture[0], 2D;\n"
                /* Scale the index by 255/256 and add a bias of '0.5' in order to sample in the middle */
                "MAD index.a, index.a, constants.x, constants.y;\n"
                /* Use the alpha-component as an index in the palette to get the final color */
                "TEX result.color, index.a, texture[1], 1D;\n"
                "END";

2508 2509 2510
            glEnable(GL_FRAGMENT_PROGRAM_ARB);
            GL_EXTCALL(glGenProgramsARB(1, &device->paletteConversionShader));
            GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, device->paletteConversionShader));
2511
            GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(fragment_palette_conversion), fragment_palette_conversion));
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
            glDisable(GL_FRAGMENT_PROGRAM_ARB);
        }

        glEnable(GL_FRAGMENT_PROGRAM_ARB);
        GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, device->paletteConversionShader));

        GL_EXTCALL(glActiveTextureARB(GL_TEXTURE1));
        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

        glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); /* Make sure we have discrete color levels. */
        glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, table); /* Upload the palette */

        /* Switch back to unit 0 in which the 2D texture will be stored. */
        GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0));
2528 2529

        /* Rebind the texture because it isn't bound anymore */
2530
        glBindTexture(This->texture_target, This->texture_name);
2531 2532

        LEAVE_GL();
2533
    }
2534 2535
}

2536
BOOL palette9_changed(IWineD3DSurfaceImpl *This) {
2537 2538
    IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;

2539 2540 2541
    if (This->palette || (This->resource.format_desc->format != WINED3DFMT_P8
            && This->resource.format_desc->format != WINED3DFMT_A8P8))
    {
2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552
        /* If a ddraw-style palette is attached assume no d3d9 palette change.
         * Also the palette isn't interesting if the surface format isn't P8 or A8P8
         */
        return FALSE;
    }

    if(This->palette9) {
        if(memcmp(This->palette9, &device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256) == 0) {
            return FALSE;
        }
    } else {
2553
        This->palette9 = HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY) * 256);
2554 2555 2556 2557 2558
    }
    memcpy(This->palette9, &device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256);
    return TRUE;
}

2559
static HRESULT WINAPI IWineD3DSurfaceImpl_LoadTexture(IWineD3DSurface *iface, BOOL srgb_mode) {
2560
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2561
    DWORD flag = srgb_mode ? SFLAG_INSRGBTEX : SFLAG_INTEXTURE;
2562

2563
    if (!(This->Flags & flag)) {
2564 2565
        TRACE("Reloading because surface is dirty\n");
    } else if(/* Reload: gl texture has ck, now no ckey is set OR */
2566
              ((This->Flags & SFLAG_GLCKEY) && (!(This->CKeyFlags & WINEDDSD_CKSRCBLT))) ||
2567
              /* Reload: vice versa  OR */
2568
              ((!(This->Flags & SFLAG_GLCKEY)) && (This->CKeyFlags & WINEDDSD_CKSRCBLT)) ||
2569
              /* Also reload: Color key is active AND the color key has changed */
2570
              ((This->CKeyFlags & WINEDDSD_CKSRCBLT) && (
2571 2572
                (This->glCKey.dwColorSpaceLowValue != This->SrcBltCKey.dwColorSpaceLowValue) ||
                (This->glCKey.dwColorSpaceHighValue != This->SrcBltCKey.dwColorSpaceHighValue)))) {
2573
        TRACE("Reloading because of color keying\n");
2574 2575 2576
        /* To perform the color key conversion we need a sysmem copy of
         * the surface. Make sure we have it
         */
2577

2578
        IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
2579 2580
        /* Make sure the texture is reloaded because of the color key change, this kills performance though :( */
        /* TODO: This is not necessarily needed with hw palettized texture support */
2581
        IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2582
    } else {
2583
        TRACE("surface is already in texture\n");
2584
        return WINED3D_OK;
2585 2586
    }

2587
    /* Resources are placed in system RAM and do not need to be recreated when a device is lost.
2588 2589 2590 2591
     *  These resources are not bound by device size or format restrictions. Because of this,
     *  these resources cannot be accessed by the Direct3D device nor set as textures or render targets.
     *  However, these resources can always be created, locked, and copied.
     */
2592
    if (This->resource.pool == WINED3DPOOL_SCRATCH )
2593
    {
2594
        FIXME("(%p) Operation not supported for scratch textures\n",This);
2595
        return WINED3DERR_INVALIDCALL;
2596
    }
2597

2598
    IWineD3DSurface_LoadLocation(iface, flag, NULL /* no partial locking for textures yet */);
2599 2600

#if 0
2601 2602 2603 2604 2605
    {
        static unsigned int gen = 0;
        char buffer[4096];
        ++gen;
        if ((gen % 10) == 0) {
2606 2607
            snprintf(buffer, sizeof(buffer), "/tmp/surface%p_type%u_level%u_%u.ppm",
                    This, This->texture_target, This->texture_level, gen);
2608
            IWineD3DSurfaceImpl_SaveSnapshot(iface, buffer);
2609
        }
2610 2611 2612 2613 2614 2615 2616 2617
        /*
         * debugging crash code
         if (gen == 250) {
         void** test = NULL;
         *test = 0;
         }
         */
    }
2618
#endif
2619

2620
    if (!(This->Flags & SFLAG_DONOTFREE)) {
2621
        HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
2622
        This->resource.allocatedMemory = NULL;
2623
        This->resource.heapMemory = NULL;
2624
        IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, FALSE);
2625 2626
    }

2627
    return WINED3D_OK;
2628 2629
}

2630
/* Context activation is done by the caller. */
2631
static void WINAPI IWineD3DSurfaceImpl_BindTexture(IWineD3DSurface *iface, BOOL srgb) {
2632 2633 2634 2635 2636 2637 2638 2639
    /* TODO: check for locks */
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
    IWineD3DBaseTexture *baseTexture = NULL;
    IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;

    TRACE("(%p)Checking to see if the container is a base texture\n", This);
    if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
        TRACE("Passing to container\n");
2640
        IWineD3DBaseTexture_BindTexture(baseTexture, srgb);
2641 2642
        IWineD3DBaseTexture_Release(baseTexture);
    } else {
2643
        GLuint *name;
2644 2645
        TRACE("(%p) : Binding surface\n", This);

2646
        name = srgb ? &This->texture_name_srgb : &This->texture_name;
2647 2648 2649
        if(!device->isInDraw) {
            ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
        }
2650

2651
        ENTER_GL();
2652

2653 2654
        if (!This->texture_level)
        {
2655 2656
            if (!*name) {
                glGenTextures(1, name);
2657
                checkGLcall("glGenTextures");
2658
                TRACE("Surface %p given name %d\n", This, *name);
2659

2660
                glBindTexture(This->texture_target, *name);
2661
                checkGLcall("glBindTexture");
2662
                glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2663
                checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)");
2664
                glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2665
                checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)");
2666
                glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
2667
                checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE)");
2668
                glTexParameteri(This->texture_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2669
                checkGLcall("glTexParameteri(dimension, GL_TEXTURE_MIN_FILTER, GL_NEAREST)");
2670
                glTexParameteri(This->texture_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2671
                checkGLcall("glTexParameteri(dimension, GL_TEXTURE_MAG_FILTER, GL_NEAREST)");
2672 2673
            }
            /* This is where we should be reducing the amount of GLMemoryUsed */
2674
        } else if (*name) {
2675 2676 2677 2678
            /* Mipmap surfaces should have a base texture container */
            ERR("Mipmap surface has a glTexture bound to it!\n");
        }

2679
        glBindTexture(This->texture_target, *name);
2680 2681
        checkGLcall("glBindTexture");

2682 2683 2684 2685 2686
        LEAVE_GL();
    }
    return;
}

2687 2688
#include <errno.h>
#include <stdio.h>
2689 2690
static HRESULT WINAPI IWineD3DSurfaceImpl_SaveSnapshot(IWineD3DSurface *iface, const char* filename)
{
2691 2692
    FILE* f = NULL;
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2693
    char *allocatedMemory;
2694
    const char *textureRow;
2695
    IWineD3DSwapChain *swapChain = NULL;
2696
    int width, height, i, y;
2697
    GLuint tmpTexture = 0;
2698 2699
    DWORD color;
    /*FIXME:
2700
    Textures may not be stored in ->allocatedgMemory and a GlTexture
2701
    so we should lock the surface before saving a snapshot, or at least check that
2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713
    */
    /* TODO: Compressed texture images can be obtained from the GL in uncompressed form
    by calling GetTexImage and in compressed form by calling
    GetCompressedTexImageARB.  Queried compressed images can be saved and
    later reused by calling CompressedTexImage[123]DARB.  Pre-compressed
    texture images do not need to be processed by the GL and should
    significantly improve texture loading performance relative to uncompressed
    images. */

/* Setup the width and height to be the internal texture width and height. */
    width  = This->pow2Width;
    height = This->pow2Height;
2714
/* check to see if we're a 'virtual' texture, e.g. we're not a pbuffer of texture, we're a back buffer*/
2715 2716
    IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapChain);

2717 2718 2719 2720 2721
    if (This->Flags & SFLAG_INDRAWABLE && !(This->Flags & SFLAG_INTEXTURE)) {
        /* if were not a real texture then read the back buffer into a real texture */
        /* we don't want to interfere with the back buffer so read the data into a temporary
         * texture and then save the data out of the temporary texture
         */
2722 2723
        GLint prevRead;
        ENTER_GL();
2724
        TRACE("(%p) Reading render target into texture\n", This);
2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739

        glGenTextures(1, &tmpTexture);
        glBindTexture(GL_TEXTURE_2D, tmpTexture);

        glTexImage2D(GL_TEXTURE_2D,
                        0,
                        GL_RGBA,
                        width,
                        height,
                        0/*border*/,
                        GL_RGBA,
                        GL_UNSIGNED_INT_8_8_8_8_REV,
                        NULL);

        glGetIntegerv(GL_READ_BUFFER, &prevRead);
2740
        checkGLcall("glGetIntegerv");
2741
        glReadBuffer(swapChain ? GL_BACK : This->resource.wineD3DDevice->offscreenBuffer);
2742
        checkGLcall("glReadBuffer");
2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
        glCopyTexImage2D(GL_TEXTURE_2D,
                            0,
                            GL_RGBA,
                            0,
                            0,
                            width,
                            height,
                            0);

        checkGLcall("glCopyTexImage2D");
        glReadBuffer(prevRead);
        LEAVE_GL();

2756
    } else { /* bind the real texture, and make sure it up to date */
2757
        surface_internal_preload(iface, SRGB_RGB);
2758
        surface_bind_and_dirtify(This, FALSE);
2759 2760 2761
    }
    allocatedMemory = HeapAlloc(GetProcessHeap(), 0, width  * height * 4);
    ENTER_GL();
2762 2763
    FIXME("Saving texture level %d width %d height %d\n", This->texture_level, width, height);
    glGetTexImage(GL_TEXTURE_2D, This->texture_level, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, allocatedMemory);
2764 2765 2766 2767 2768 2769
    checkGLcall("glTexImage2D");
    if (tmpTexture) {
        glBindTexture(GL_TEXTURE_2D, 0);
        glDeleteTextures(1, &tmpTexture);
    }
    LEAVE_GL();
2770 2771 2772 2773

    f = fopen(filename, "w+");
    if (NULL == f) {
        ERR("opening of %s failed with: %s\n", filename, strerror(errno));
2774
        return WINED3DERR_INVALIDCALL;
2775
    }
2776
/* Save the data out to a TGA file because 1: it's an easy raw format, 2: it supports an alpha channel */
2777
    TRACE("(%p) opened %s with format %s\n", This, filename, debug_d3dformat(This->resource.format_desc->format));
2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
/* TGA header */
    fputc(0,f);
    fputc(0,f);
    fputc(2,f);
    fputc(0,f);
    fputc(0,f);
    fputc(0,f);
    fputc(0,f);
    fputc(0,f);
    fputc(0,f);
    fputc(0,f);
    fputc(0,f);
    fputc(0,f);
/* short width*/
    fwrite(&width,2,1,f);
/* short height */
    fwrite(&height,2,1,f);
/* format rgba */
    fputc(0x20,f);
    fputc(0x28,f);
/* raw data */
2799
    /* if the data is upside down if we've fetched it from a back buffer, so it needs flipping again to make it the correct way up */
2800 2801 2802 2803 2804 2805
    if(swapChain)
        textureRow = allocatedMemory + (width * (height - 1) *4);
    else
        textureRow = allocatedMemory;
    for (y = 0 ; y < height; y++) {
        for (i = 0; i < width;  i++) {
2806
            color = *((const DWORD*)textureRow);
2807 2808 2809 2810 2811
            fputc((color >> 16) & 0xFF, f); /* B */
            fputc((color >>  8) & 0xFF, f); /* G */
            fputc((color >>  0) & 0xFF, f); /* R */
            fputc((color >> 24) & 0xFF, f); /* A */
            textureRow += 4;
2812
        }
2813 2814 2815
        /* take two rows of the pointer to the texture memory */
        if(swapChain)
            (textureRow-= width << 3);
2816 2817

    }
2818
    TRACE("Closing file\n");
2819
    fclose(f);
2820 2821 2822 2823 2824

    if(swapChain) {
        IWineD3DSwapChain_Release(swapChain);
    }
    HeapFree(GetProcessHeap(), 0, allocatedMemory);
2825
    return WINED3D_OK;
2826 2827
}

2828
static HRESULT WINAPI IWineD3DSurfaceImpl_SetFormat(IWineD3DSurface *iface, WINED3DFORMAT format) {
2829
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2830
    HRESULT hr;
2831

2832 2833 2834
    TRACE("(%p) : Calling base function first\n", This);
    hr = IWineD3DBaseSurfaceImpl_SetFormat(iface, format);
    if(SUCCEEDED(hr)) {
2835
        This->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
2836 2837
        TRACE("(%p) : glFormat %d, glFormatInternal %d, glType %d\n", This, This->resource.format_desc->glFormat,
                This->resource.format_desc->glInternal, This->resource.format_desc->glType);
2838
    }
2839
    return hr;
2840 2841
}

2842
static HRESULT WINAPI IWineD3DSurfaceImpl_SetMem(IWineD3DSurface *iface, void *Mem) {
2843 2844 2845 2846 2847 2848 2849 2850
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;

    if(This->Flags & (SFLAG_LOCKED | SFLAG_DCINUSE)) {
        WARN("Surface is locked or the HDC is in use\n");
        return WINED3DERR_INVALIDCALL;
    }

    if(Mem && Mem != This->resource.allocatedMemory) {
2851
        void *release = NULL;
2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867

        /* Do I have to copy the old surface content? */
        if(This->Flags & SFLAG_DIBSECTION) {
                /* Release the DC. No need to hold the critical section for the update
                 * Thread because this thread runs only on front buffers, but this method
                 * fails for render targets in the check above.
                 */
                SelectObject(This->hDC, This->dib.holdbitmap);
                DeleteDC(This->hDC);
                /* Release the DIB section */
                DeleteObject(This->dib.DIBsection);
                This->dib.bitmap_data = NULL;
                This->resource.allocatedMemory = NULL;
                This->hDC = NULL;
                This->Flags &= ~SFLAG_DIBSECTION;
        } else if(!(This->Flags & SFLAG_USERPTR)) {
2868 2869
            release = This->resource.heapMemory;
            This->resource.heapMemory = NULL;
2870 2871
        }
        This->resource.allocatedMemory = Mem;
2872 2873 2874
        This->Flags |= SFLAG_USERPTR | SFLAG_INSYSMEM;

        /* Now the surface memory is most up do date. Invalidate drawable and texture */
2875
        IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2876 2877 2878

        /* For client textures opengl has to be notified */
        if(This->Flags & SFLAG_CLIENT) {
2879
            DWORD oldFlags = This->Flags;
2880
            This->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
2881 2882
            if(oldFlags & SFLAG_ALLOCATED) surface_internal_preload(iface, SRGB_RGB);
            if(oldFlags & SFLAG_SRGBALLOCATED) surface_internal_preload(iface, SRGB_SRGB);
2883 2884 2885 2886 2887
            /* And hope that the app behaves correctly and did not free the old surface memory before setting a new pointer */
        }

        /* Now free the old memory if any */
        HeapFree(GetProcessHeap(), 0, release);
2888
    } else if(This->Flags & SFLAG_USERPTR) {
Austin English's avatar
Austin English committed
2889
        /* LockRect and GetDC will re-create the dib section and allocated memory */
2890
        This->resource.allocatedMemory = NULL;
2891 2892
        /* HeapMemory should be NULL already */
        if(This->resource.heapMemory != NULL) ERR("User pointer surface has heap memory allocated\n");
2893
        This->Flags &= ~SFLAG_USERPTR;
2894 2895

        if(This->Flags & SFLAG_CLIENT) {
2896
            DWORD oldFlags = This->Flags;
2897
            This->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
2898
            /* This respecifies an empty texture and opengl knows that the old memory is gone */
2899 2900
            if(oldFlags & SFLAG_ALLOCATED) surface_internal_preload(iface, SRGB_RGB);
            if(oldFlags & SFLAG_SRGBALLOCATED) surface_internal_preload(iface, SRGB_SRGB);
2901
        }
2902 2903 2904 2905
    }
    return WINED3D_OK;
}

2906 2907 2908 2909 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 2957 2958 2959 2960 2961 2962 2963 2964
void flip_surface(IWineD3DSurfaceImpl *front, IWineD3DSurfaceImpl *back) {

    /* Flip the surface contents */
    /* Flip the DC */
    {
        HDC tmp;
        tmp = front->hDC;
        front->hDC = back->hDC;
        back->hDC = tmp;
    }

    /* Flip the DIBsection */
    {
        HBITMAP tmp;
        BOOL hasDib = front->Flags & SFLAG_DIBSECTION;
        tmp = front->dib.DIBsection;
        front->dib.DIBsection = back->dib.DIBsection;
        back->dib.DIBsection = tmp;

        if(back->Flags & SFLAG_DIBSECTION) front->Flags |= SFLAG_DIBSECTION;
        else front->Flags &= ~SFLAG_DIBSECTION;
        if(hasDib) back->Flags |= SFLAG_DIBSECTION;
        else back->Flags &= ~SFLAG_DIBSECTION;
    }

    /* Flip the surface data */
    {
        void* tmp;

        tmp = front->dib.bitmap_data;
        front->dib.bitmap_data = back->dib.bitmap_data;
        back->dib.bitmap_data = tmp;

        tmp = front->resource.allocatedMemory;
        front->resource.allocatedMemory = back->resource.allocatedMemory;
        back->resource.allocatedMemory = tmp;

        tmp = front->resource.heapMemory;
        front->resource.heapMemory = back->resource.heapMemory;
        back->resource.heapMemory = tmp;
    }

    /* Flip the PBO */
    {
        GLuint tmp_pbo = front->pbo;
        front->pbo = back->pbo;
        back->pbo = tmp_pbo;
    }

    /* client_memory should not be different, but just in case */
    {
        BOOL tmp;
        tmp = front->dib.client_memory;
        front->dib.client_memory = back->dib.client_memory;
        back->dib.client_memory = tmp;
    }

    /* Flip the opengl texture */
    {
2965 2966 2967 2968 2969 2970 2971 2972 2973
        GLuint tmp;

        tmp = back->texture_name;
        back->texture_name = front->texture_name;
        front->texture_name = tmp;

        tmp = back->texture_name_srgb;
        back->texture_name_srgb = front->texture_name_srgb;
        front->texture_name_srgb = tmp;
2974 2975 2976 2977 2978 2979 2980 2981 2982
    }

    {
        DWORD tmp_flags = back->Flags;
        back->Flags = front->Flags;
        front->Flags = tmp_flags;
    }
}

2983
static HRESULT WINAPI IWineD3DSurfaceImpl_Flip(IWineD3DSurface *iface, IWineD3DSurface *override, DWORD Flags) {
2984
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2985 2986
    IWineD3DSwapChainImpl *swapchain = NULL;
    HRESULT hr;
2987
    TRACE("(%p)->(%p,%x)\n", This, override, Flags);
2988

2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004
    /* Flipping is only supported on RenderTargets and overlays*/
    if( !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_OVERLAY)) ) {
        WARN("Tried to flip a non-render target, non-overlay surface\n");
        return WINEDDERR_NOTFLIPPABLE;
    }

    if(This->resource.usage & WINED3DUSAGE_OVERLAY) {
        flip_surface(This, (IWineD3DSurfaceImpl *) override);

        /* Update the overlay if it is visible */
        if(This->overlay_dest) {
            return IWineD3DSurface_DrawOverlay((IWineD3DSurface *) This);
        } else {
            return WINED3D_OK;
        }
    }
3005 3006 3007 3008 3009 3010 3011 3012 3013

    if(override) {
        /* DDraw sets this for the X11 surfaces, so don't confuse the user 
         * FIXME("(%p) Target override is not supported by now\n", This);
         * Additionally, it isn't really possible to support triple-buffering
         * properly on opengl at all
         */
    }

3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035
    IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **) &swapchain);
    if(!swapchain) {
        ERR("Flipped surface is not on a swapchain\n");
        return WINEDDERR_NOTFLIPPABLE;
    }

    /* Just overwrite the swapchain presentation interval. This is ok because only ddraw apps can call Flip,
     * and only d3d8 and d3d9 apps specify the presentation interval
     */
    if((Flags & (WINEDDFLIP_NOVSYNC | WINEDDFLIP_INTERVAL2 | WINEDDFLIP_INTERVAL3 | WINEDDFLIP_INTERVAL4)) == 0) {
        /* Most common case first to avoid wasting time on all the other cases */
        swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_ONE;
    } else if(Flags & WINEDDFLIP_NOVSYNC) {
        swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
    } else if(Flags & WINEDDFLIP_INTERVAL2) {
        swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_TWO;
    } else if(Flags & WINEDDFLIP_INTERVAL3) {
        swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_THREE;
    } else {
        swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_FOUR;
    }

3036
    /* Flipping a OpenGL surface -> Use WineD3DDevice::Present */
3037 3038 3039
    hr = IWineD3DSwapChain_Present((IWineD3DSwapChain *) swapchain, NULL, NULL, 0, NULL, 0);
    IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
    return hr;
3040 3041
}

3042 3043 3044
/* Does a direct frame buffer -> texture copy. Stretching is done
 * with single pixel copy calls
 */
3045 3046 3047 3048
static inline void fb_copy_to_texture_direct(IWineD3DSurfaceImpl *This, IWineD3DSurface *SrcSurface,
        IWineD3DSwapChainImpl *swapchain, const WINED3DRECT *srect, const WINED3DRECT *drect,
        BOOL upsidedown, WINED3DTEXTUREFILTERTYPE Filter)
{
3049 3050 3051 3052 3053 3054 3055
    IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
    float xrel, yrel;
    UINT row;
    IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;


    ActivateContext(myDevice, SrcSurface, CTXUSAGE_BLIT);
3056
    surface_internal_preload((IWineD3DSurface *) This, SRGB_RGB);
3057
    ENTER_GL();
3058 3059

    /* Bind the target texture */
3060
    glBindTexture(This->texture_target, This->texture_name);
3061
    checkGLcall("glBindTexture");
3062
    if(!swapchain) {
3063 3064
        TRACE("Reading from an offscreen target\n");
        upsidedown = !upsidedown;
3065
        glReadBuffer(myDevice->offscreenBuffer);
3066
    } else {
3067 3068
        GLenum buffer = surface_get_gl_buffer(SrcSurface, (IWineD3DSwapChain *)swapchain);
        glReadBuffer(buffer);
3069 3070 3071 3072 3073 3074
    }
    checkGLcall("glReadBuffer");

    xrel = (float) (srect->x2 - srect->x1) / (float) (drect->x2 - drect->x1);
    yrel = (float) (srect->y2 - srect->y1) / (float) (drect->y2 - drect->y1);

3075 3076
    if ((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
    {
3077
        FIXME("Doing a pixel by pixel copy from the framebuffer to a texture, expect major performance issues\n");
3078

3079
        if(Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) {
3080 3081
            ERR("Texture filtering not supported in direct blit\n");
        }
3082 3083 3084 3085
    }
    else if ((Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT)
            && ((yrel - 1.0f < -eps) || (yrel - 1.0f > eps)))
    {
3086
        ERR("Texture filtering not supported in direct blit\n");
3087 3088
    }

3089 3090 3091 3092
    if (upsidedown
            && !((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
            && !((yrel - 1.0f < -eps) || (yrel - 1.0f > eps)))
    {
3093 3094
        /* Upside down copy without stretching is nice, one glCopyTexSubImage call will do */

3095 3096 3097 3098
        glCopyTexSubImage2D(This->texture_target, This->texture_level,
                drect->x1 /*xoffset */, drect->y1 /* y offset */,
                srect->x1, Src->currentDesc.Height - srect->y2,
                drect->x2 - drect->x1, drect->y2 - drect->y1);
3099 3100 3101
    } else {
        UINT yoffset = Src->currentDesc.Height - srect->y1 + drect->y1 - 1;
        /* I have to process this row by row to swap the image,
3102
         * otherwise it would be upside down, so stretching in y direction
3103 3104
         * doesn't cost extra time
         *
3105
         * However, stretching in x direction can be avoided if not necessary
3106 3107
         */
        for(row = drect->y1; row < drect->y2; row++) {
3108 3109
            if ((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
            {
3110 3111 3112 3113 3114 3115
                /* Well, that stuff works, but it's very slow.
                 * find a better way instead
                 */
                UINT col;

                for(col = drect->x1; col < drect->x2; col++) {
3116 3117 3118
                    glCopyTexSubImage2D(This->texture_target, This->texture_level,
                            drect->x1 + col /* x offset */, row /* y offset */,
                            srect->x1 + col * xrel, yoffset - (int) (row * yrel), 1, 1);
3119 3120
                }
            } else {
3121 3122 3123
                glCopyTexSubImage2D(This->texture_target, This->texture_level,
                        drect->x1 /* x offset */, row /* y offset */,
                        srect->x1, yoffset - (int) (row * yrel), drect->x2-drect->x1, 1);
3124 3125 3126
            }
        }
    }
3127
    checkGLcall("glCopyTexSubImage2D");
3128

3129 3130 3131 3132
    LEAVE_GL();
}

/* Uses the hardware to stretch and flip the image */
3133 3134 3135 3136
static inline void fb_copy_to_texture_hwstretch(IWineD3DSurfaceImpl *This, IWineD3DSurface *SrcSurface,
        IWineD3DSwapChainImpl *swapchain, const WINED3DRECT *srect, const WINED3DRECT *drect,
        BOOL upsidedown, WINED3DTEXTUREFILTERTYPE Filter)
{
3137
    GLuint src, backup = 0;
3138 3139 3140 3141 3142
    IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
    IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
    float left, right, top, bottom; /* Texture coordinates */
    UINT fbwidth = Src->currentDesc.Width;
    UINT fbheight = Src->currentDesc.Height;
3143
    GLenum drawBuffer = GL_BACK;
3144
    GLenum texture_target;
3145
    BOOL noBackBufferBackup;
3146 3147 3148 3149

    TRACE("Using hwstretch blit\n");
    /* Activate the Proper context for reading from the source surface, set it up for blitting */
    ActivateContext(myDevice, SrcSurface, CTXUSAGE_BLIT);
3150
    surface_internal_preload((IWineD3DSurface *) This, SRGB_RGB);
3151

3152
    noBackBufferBackup = !swapchain && wined3d_settings.offscreen_rendering_mode == ORM_FBO;
3153 3154
    if (!noBackBufferBackup && !Src->texture_name)
    {
3155
        /* Get it a description */
3156
        surface_internal_preload(SrcSurface, SRGB_RGB);
3157 3158 3159
    }
    ENTER_GL();

3160 3161 3162
    /* Try to use an aux buffer for drawing the rectangle. This way it doesn't need restoring.
     * This way we don't have to wait for the 2nd readback to finish to leave this function.
     */
3163
    if(myDevice->activeContext->aux_buffers >= 2) {
3164 3165
        /* Got more than one aux buffer? Use the 2nd aux buffer */
        drawBuffer = GL_AUX1;
3166
    } else if((swapchain || myDevice->offscreenBuffer == GL_BACK) && myDevice->activeContext->aux_buffers >= 1) {
3167 3168 3169 3170
        /* Only one aux buffer, but it isn't used (Onscreen rendering, or non-aux orm)? Use it! */
        drawBuffer = GL_AUX0;
    }

3171
    if(noBackBufferBackup) {
3172
        glGenTextures(1, &backup);
3173
        checkGLcall("glGenTextures");
3174
        glBindTexture(GL_TEXTURE_2D, backup);
3175
        checkGLcall("glBindTexture(GL_TEXTURE_2D, backup)");
3176
        texture_target = GL_TEXTURE_2D;
3177 3178 3179 3180
    } else {
        /* Backup the back buffer and copy the source buffer into a texture to draw an upside down stretched quad. If
         * we are reading from the back buffer, the backup can be used as source texture
         */
3181 3182 3183
        texture_target = Src->texture_target;
        glBindTexture(texture_target, Src->texture_name);
        checkGLcall("glBindTexture(texture_target, Src->texture_name)");
3184 3185
        glEnable(texture_target);
        checkGLcall("glEnable(texture_target)");
3186 3187 3188

        /* For now invalidate the texture copy of the back buffer. Drawable and sysmem copy are untouched */
        Src->Flags &= ~SFLAG_INTEXTURE;
3189
    }
3190

3191 3192 3193
    if(swapchain) {
        glReadBuffer(surface_get_gl_buffer(SrcSurface, (IWineD3DSwapChain *)swapchain));
    } else {
3194 3195
        TRACE("Reading from an offscreen target\n");
        upsidedown = !upsidedown;
3196 3197
        glReadBuffer(myDevice->offscreenBuffer);
    }
3198 3199

    /* TODO: Only back up the part that will be overwritten */
3200
    glCopyTexSubImage2D(texture_target, 0,
3201 3202 3203 3204 3205 3206 3207
                        0, 0 /* read offsets */,
                        0, 0,
                        fbwidth,
                        fbheight);

    checkGLcall("glCopyTexSubImage2D");

3208
    /* No issue with overriding these - the sampler is dirty due to blit usage */
3209
    glTexParameteri(texture_target, GL_TEXTURE_MAG_FILTER,
3210
                    magLookup[Filter - WINED3DTEXF_NONE]);
3211
    checkGLcall("glTexParameteri");
3212
    glTexParameteri(texture_target, GL_TEXTURE_MIN_FILTER,
3213
                    minMipLookup[Filter].mip[WINED3DTEXF_NONE]);
3214 3215
    checkGLcall("glTexParameteri");

3216
    if(!swapchain || (IWineD3DSurface *) Src == swapchain->backBuffer[0]) {
3217
        src = backup ? backup : Src->texture_name;
3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245
    } else {
        glReadBuffer(GL_FRONT);
        checkGLcall("glReadBuffer(GL_FRONT)");

        glGenTextures(1, &src);
        checkGLcall("glGenTextures(1, &src)");
        glBindTexture(GL_TEXTURE_2D, src);
        checkGLcall("glBindTexture(GL_TEXTURE_2D, src)");

        /* TODO: Only copy the part that will be read. Use srect->x1, srect->y2 as origin, but with the width watch
         * out for power of 2 sizes
         */
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, Src->pow2Width, Src->pow2Height, 0,
                    GL_RGBA, GL_UNSIGNED_BYTE, NULL);
        checkGLcall("glTexImage2D");
        glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
                            0, 0 /* read offsets */,
                            0, 0,
                            fbwidth,
                            fbheight);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        checkGLcall("glTexParameteri");
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        checkGLcall("glTexParameteri");

        glReadBuffer(GL_BACK);
        checkGLcall("glReadBuffer(GL_BACK)");
3246 3247 3248 3249 3250 3251

        if(texture_target != GL_TEXTURE_2D) {
            glDisable(texture_target);
            glEnable(GL_TEXTURE_2D);
            texture_target = GL_TEXTURE_2D;
        }
3252 3253 3254
    }
    checkGLcall("glEnd and previous");

3255 3256
    left = srect->x1;
    right = srect->x2;
3257 3258

    if(upsidedown) {
3259 3260
        top = Src->currentDesc.Height - srect->y1;
        bottom = Src->currentDesc.Height - srect->y2;
3261
    } else {
3262 3263 3264 3265 3266 3267 3268 3269 3270
        top = Src->currentDesc.Height - srect->y2;
        bottom = Src->currentDesc.Height - srect->y1;
    }

    if(Src->Flags & SFLAG_NORMCOORD) {
        left /= Src->pow2Width;
        right /= Src->pow2Width;
        top /= Src->pow2Height;
        bottom /= Src->pow2Height;
3271 3272 3273
    }

    /* draw the source texture stretched and upside down. The correct surface is bound already */
3274 3275
    glTexParameteri(texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP);
3276

3277 3278 3279
    glDrawBuffer(drawBuffer);
    glReadBuffer(drawBuffer);

3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298
    glBegin(GL_QUADS);
        /* bottom left */
        glTexCoord2f(left, bottom);
        glVertex2i(0, fbheight);

        /* top left */
        glTexCoord2f(left, top);
        glVertex2i(0, fbheight - drect->y2 - drect->y1);

        /* top right */
        glTexCoord2f(right, top);
        glVertex2i(drect->x2 - drect->x1, fbheight - drect->y2 - drect->y1);

        /* bottom right */
        glTexCoord2f(right, bottom);
        glVertex2i(drect->x2 - drect->x1, fbheight);
    glEnd();
    checkGLcall("glEnd and previous");

3299 3300
    if (texture_target != This->texture_target)
    {
3301
        glDisable(texture_target);
3302 3303
        glEnable(This->texture_target);
        texture_target = This->texture_target;
3304 3305
    }

3306
    /* Now read the stretched and upside down image into the destination texture */
3307
    glBindTexture(texture_target, This->texture_name);
3308
    checkGLcall("glBindTexture");
3309
    glCopyTexSubImage2D(texture_target,
3310 3311 3312 3313 3314 3315
                        0,
                        drect->x1, drect->y1, /* xoffset, yoffset */
                        0, 0, /* We blitted the image to the origin */
                        drect->x2 - drect->x1, drect->y2 - drect->y1);
    checkGLcall("glCopyTexSubImage2D");

3316
    if(drawBuffer == GL_BACK) {
3317 3318 3319 3320 3321 3322 3323 3324 3325 3326
        /* Write the back buffer backup back */
        if(backup) {
            if(texture_target != GL_TEXTURE_2D) {
                glDisable(texture_target);
                glEnable(GL_TEXTURE_2D);
                texture_target = GL_TEXTURE_2D;
            }
            glBindTexture(GL_TEXTURE_2D, backup);
            checkGLcall("glBindTexture(GL_TEXTURE_2D, backup)");
        } else {
3327 3328
            if (texture_target != Src->texture_target)
            {
3329
                glDisable(texture_target);
3330 3331
                glEnable(Src->texture_target);
                texture_target = Src->texture_target;
3332
            }
3333 3334
            glBindTexture(Src->texture_target, Src->texture_name);
            checkGLcall("glBindTexture(Src->texture_target, Src->texture_name)");
3335 3336
        }

3337 3338
        glBegin(GL_QUADS);
            /* top left */
3339
            glTexCoord2f(0.0f, (float)fbheight / (float)Src->pow2Height);
3340
            glVertex2i(0, 0);
3341

3342
            /* bottom left */
3343
            glTexCoord2f(0.0f, 0.0f);
3344
            glVertex2i(0, fbheight);
3345

3346
            /* bottom right */
3347
            glTexCoord2f((float)fbwidth / (float)Src->pow2Width, 0.0f);
3348
            glVertex2i(fbwidth, Src->currentDesc.Height);
3349

3350 3351 3352 3353 3354 3355 3356 3357
            /* top right */
            glTexCoord2f((float) fbwidth / (float) Src->pow2Width, (float) fbheight / (float) Src->pow2Height);
            glVertex2i(fbwidth, 0);
        glEnd();
    } else {
        /* Restore the old draw buffer */
        glDrawBuffer(GL_BACK);
    }
3358 3359
    glDisable(texture_target);
    checkGLcall("glDisable(texture_target)");
3360 3361

    /* Cleanup */
3362 3363
    if (src != Src->texture_name && src != backup)
    {
3364 3365 3366
        glDeleteTextures(1, &src);
        checkGLcall("glDeleteTextures(1, &src)");
    }
3367 3368 3369 3370
    if(backup) {
        glDeleteTextures(1, &backup);
        checkGLcall("glDeleteTextures(1, &backup)");
    }
3371

3372 3373 3374
    LEAVE_GL();
}

3375
/* Not called from the VTable */
3376 3377 3378 3379
static HRESULT IWineD3DSurfaceImpl_BltOverride(IWineD3DSurfaceImpl *This, const RECT *DestRect,
        IWineD3DSurface *SrcSurface, const RECT *SrcRect, DWORD Flags, const WINEDDBLTFX *DDBltFx,
        WINED3DTEXTUREFILTERTYPE Filter)
{
3380
    WINED3DRECT rect;
3381
    IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3382
    IWineD3DSwapChainImpl *srcSwapchain = NULL, *dstSwapchain = NULL;
3383 3384
    IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;

3385
    TRACE("(%p)->(%p,%p,%p,%08x,%p)\n", This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx);
3386 3387

    /* Get the swapchain. One of the surfaces has to be a primary surface */
3388 3389 3390 3391
    if(This->resource.pool == WINED3DPOOL_SYSTEMMEM) {
        WARN("Destination is in sysmem, rejecting gl blt\n");
        return WINED3DERR_INVALIDCALL;
    }
3392 3393 3394
    IWineD3DSurface_GetContainer( (IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&dstSwapchain);
    if(dstSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) dstSwapchain);
    if(Src) {
3395 3396 3397 3398
        if(Src->resource.pool == WINED3DPOOL_SYSTEMMEM) {
            WARN("Src is in sysmem, rejecting gl blt\n");
            return WINED3DERR_INVALIDCALL;
        }
3399 3400 3401 3402 3403 3404 3405 3406 3407
        IWineD3DSurface_GetContainer( (IWineD3DSurface *) Src, &IID_IWineD3DSwapChain, (void **)&srcSwapchain);
        if(srcSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) srcSwapchain);
    }

    /* Early sort out of cases where no render target is used */
    if(!dstSwapchain && !srcSwapchain &&
        SrcSurface != myDevice->render_targets[0] && This != (IWineD3DSurfaceImpl *) myDevice->render_targets[0]) {
        TRACE("No surface is render target, not using hardware blit. Src = %p, dst = %p\n", Src, This);
        return WINED3DERR_INVALIDCALL;
3408 3409
    }

3410
    /* No destination color keying supported */
3411
    if(Flags & (WINEDDBLT_KEYDEST | WINEDDBLT_KEYDESTOVERRIDE)) {
3412 3413 3414 3415 3416
        /* Can we support that with glBlendFunc if blitting to the frame buffer? */
        TRACE("Destination color key not supported in accelerated Blit, falling back to software\n");
        return WINED3DERR_INVALIDCALL;
    }

3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428
    if (DestRect) {
        rect.x1 = DestRect->left;
        rect.y1 = DestRect->top;
        rect.x2 = DestRect->right;
        rect.y2 = DestRect->bottom;
    } else {
        rect.x1 = 0;
        rect.y1 = 0;
        rect.x2 = This->currentDesc.Width;
        rect.y2 = This->currentDesc.Height;
    }

3429
    /* The only case where both surfaces on a swapchain are supported is a back buffer -> front buffer blit on the same swapchain */
3430 3431
    if(dstSwapchain && dstSwapchain == srcSwapchain && dstSwapchain->backBuffer &&
       ((IWineD3DSurface *) This == dstSwapchain->frontBuffer) && SrcSurface == dstSwapchain->backBuffer[0]) {
3432 3433
        /* Half-life does a Blt from the back buffer to the front buffer,
         * Full surface size, no flags... Use present instead
3434 3435
         *
         * This path will only be entered for d3d7 and ddraw apps, because d3d8/9 offer no way to blit TO the front buffer
3436
         */
3437 3438

        /* Check rects - IWineD3DDevice_Present doesn't handle them */
3439 3440 3441
        while(1)
        {
            RECT mySrcRect;
3442
            TRACE("Looking if a Present can be done...\n");
3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460
            /* Source Rectangle must be full surface */
            if( SrcRect ) {
                if(SrcRect->left != 0 || SrcRect->top != 0 ||
                   SrcRect->right != Src->currentDesc.Width || SrcRect->bottom != Src->currentDesc.Height) {
                    TRACE("No, Source rectangle doesn't match\n");
                    break;
                }
            }
            mySrcRect.left = 0;
            mySrcRect.top = 0;
            mySrcRect.right = Src->currentDesc.Width;
            mySrcRect.bottom = Src->currentDesc.Height;

            /* No stretching may occur */
            if(mySrcRect.right != rect.x2 - rect.x1 ||
               mySrcRect.bottom != rect.y2 - rect.y1) {
                TRACE("No, stretching is done\n");
                break;
3461 3462
            }

3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492
            /* Destination must be full surface or match the clipping rectangle */
            if(This->clipper && ((IWineD3DClipperImpl *) This->clipper)->hWnd)
            {
                RECT cliprect;
                POINT pos[2];
                GetClientRect(((IWineD3DClipperImpl *) This->clipper)->hWnd, &cliprect);
                pos[0].x = rect.x1;
                pos[0].y = rect.y1;
                pos[1].x = rect.x2;
                pos[1].y = rect.y2;
                MapWindowPoints(GetDesktopWindow(), ((IWineD3DClipperImpl *) This->clipper)->hWnd,
                                pos, 2);

                if(pos[0].x != cliprect.left  || pos[0].y != cliprect.top   ||
                   pos[1].x != cliprect.right || pos[1].y != cliprect.bottom)
                {
                    TRACE("No, dest rectangle doesn't match(clipper)\n");
                    TRACE("Clip rect at (%d,%d)-(%d,%d)\n", cliprect.left, cliprect.top, cliprect.right, cliprect.bottom);
                    TRACE("Blt dest: (%d,%d)-(%d,%d)\n", rect.x1, rect.y1, rect.x2, rect.y2);
                    break;
                }
            }
            else
            {
                if(rect.x1 != 0 || rect.y1 != 0 ||
                   rect.x2 != This->currentDesc.Width || rect.y2 != This->currentDesc.Height) {
                    TRACE("No, dest rectangle doesn't match(surface size)\n");
                    break;
                }
            }
3493

3494
            TRACE("Yes\n");
3495

3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510
            /* These flags are unimportant for the flag check, remove them */
            if((Flags & ~(WINEDDBLT_DONOTWAIT | WINEDDBLT_WAIT)) == 0) {
                WINED3DSWAPEFFECT orig_swap = dstSwapchain->presentParms.SwapEffect;

                /* The idea behind this is that a glReadPixels and a glDrawPixels call
                    * take very long, while a flip is fast.
                    * This applies to Half-Life, which does such Blts every time it finished
                    * a frame, and to Prince of Persia 3D, which uses this to draw at least the main
                    * menu. This is also used by all apps when they do windowed rendering
                    *
                    * The problem is that flipping is not really the same as copying. After a
                    * Blt the front buffer is a copy of the back buffer, and the back buffer is
                    * untouched. Therefore it's necessary to override the swap effect
                    * and to set it back after the flip.
                    *
3511
                    * Windowed Direct3D < 7 apps do the same. The D3D7 sdk demos are nice
3512 3513 3514 3515
                    * testcases.
                    */

                dstSwapchain->presentParms.SwapEffect = WINED3DSWAPEFFECT_COPY;
3516
                dstSwapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
3517 3518

                TRACE("Full screen back buffer -> front buffer blt, performing a flip instead\n");
3519
                IWineD3DSwapChain_Present((IWineD3DSwapChain *) dstSwapchain, NULL, NULL, 0, NULL, 0);
3520 3521 3522 3523

                dstSwapchain->presentParms.SwapEffect = orig_swap;

                return WINED3D_OK;
3524
            }
3525
            break;
3526 3527
        }

3528 3529
        TRACE("Unsupported blit between buffers on the same swapchain\n");
        return WINED3DERR_INVALIDCALL;
3530 3531 3532 3533 3534 3535 3536
    } else if(dstSwapchain && dstSwapchain == srcSwapchain) {
        FIXME("Implement hardware blit between two surfaces on the same swapchain\n");
        return WINED3DERR_INVALIDCALL;
    } else if(dstSwapchain && srcSwapchain) {
        FIXME("Implement hardware blit between two different swapchains\n");
        return WINED3DERR_INVALIDCALL;
    } else if(dstSwapchain) {
3537 3538 3539
        if(SrcSurface == myDevice->render_targets[0]) {
            TRACE("Blit from active render target to a swapchain\n");
            /* Handled with regular texture -> swapchain blit */
3540
        }
3541
    } else if(srcSwapchain && This == (IWineD3DSurfaceImpl *) myDevice->render_targets[0]) {
3542
        FIXME("Implement blit from a swapchain to the active render target\n");
3543 3544
        return WINED3DERR_INVALIDCALL;
    }
3545

3546
    if((srcSwapchain || SrcSurface == myDevice->render_targets[0]) && !dstSwapchain) {
3547 3548 3549
        /* Blit from render target to texture */
        WINED3DRECT srect;
        BOOL upsideDown, stretchx;
3550
        BOOL paletteOverride = FALSE;
3551

3552
        if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3553 3554 3555 3556 3557
            TRACE("Color keying not supported by frame buffer to texture blit\n");
            return WINED3DERR_INVALIDCALL;
            /* Destination color key is checked above */
        }

3558
        /* Make sure that the top pixel is always above the bottom pixel, and keep a separate upside down flag
3559 3560
         * glCopyTexSubImage is a bit picky about the parameters we pass to it
         */
3561 3562 3563 3564 3565 3566 3567 3568 3569
        if(SrcRect) {
            if(SrcRect->top < SrcRect->bottom) {
                srect.y1 = SrcRect->top;
                srect.y2 = SrcRect->bottom;
                upsideDown = FALSE;
            } else {
                srect.y1 = SrcRect->bottom;
                srect.y2 = SrcRect->top;
                upsideDown = TRUE;
3570
            }
3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585
            srect.x1 = SrcRect->left;
            srect.x2 = SrcRect->right;
        } else {
            srect.x1 = 0;
            srect.y1 = 0;
            srect.x2 = Src->currentDesc.Width;
            srect.y2 = Src->currentDesc.Height;
            upsideDown = FALSE;
        }
        if(rect.x1 > rect.x2) {
            UINT tmp = rect.x2;
            rect.x2 = rect.x1;
            rect.x1 = tmp;
            upsideDown = !upsideDown;
        }
3586

3587 3588 3589 3590 3591
        if(rect.x2 - rect.x1 != srect.x2 - srect.x1) {
            stretchx = TRUE;
        } else {
            stretchx = FALSE;
        }
3592

3593 3594
        /* When blitting from a render target a texture, the texture isn't required to have a palette.
         * In this case grab the palette from the render target. */
3595 3596
        if ((This->resource.format_desc->format == WINED3DFMT_P8) && (This->palette == NULL))
        {
3597 3598 3599 3600 3601
            paletteOverride = TRUE;
            TRACE("Source surface (%p) lacks palette, overriding palette with palette %p of destination surface (%p)\n", Src, This->palette, This);
            This->palette = Src->palette;
        }

3602
        /* Blt is a pretty powerful call, while glCopyTexSubImage2D is not. glCopyTexSubImage cannot
3603
         * flip the image nor scale it.
3604 3605 3606 3607 3608 3609 3610 3611
         *
         * -> If the app asks for a unscaled, upside down copy, just perform one glCopyTexSubImage2D call
         * -> If the app wants a image width an unscaled width, copy it line per line
         * -> If the app wants a image that is scaled on the x axis, and the destination rectangle is smaller
         *    than the frame buffer, draw an upside down scaled image onto the fb, read it back and restore the
         *    back buffer. This is slower than reading line per line, thus not used for flipping
         * -> If the app wants a scaled image with a dest rect that is bigger than the fb, it has to be copied
         *    pixel by pixel
3612 3613 3614 3615
         *
         * If EXT_framebuffer_blit is supported that can be used instead. Note that EXT_framebuffer_blit implies
         * FBO support, so it doesn't really make sense to try and make it work with different offscreen rendering
         * backends.
3616
         */
3617 3618 3619
        if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && GL_SUPPORT(EXT_FRAMEBUFFER_BLIT)
                && surface_can_stretch_rect(Src, This))
        {
3620 3621
            stretch_rect_fbo((IWineD3DDevice *)myDevice, SrcSurface, &srect,
                    (IWineD3DSurface *)This, &rect, Filter, upsideDown);
3622 3623 3624
        } else if((!stretchx) || rect.x2 - rect.x1 > Src->currentDesc.Width ||
                                    rect.y2 - rect.y1 > Src->currentDesc.Height) {
            TRACE("No stretching in x direction, using direct framebuffer -> texture copy\n");
3625
            fb_copy_to_texture_direct(This, SrcSurface, srcSwapchain, &srect, &rect, upsideDown, Filter);
3626 3627
        } else {
            TRACE("Using hardware stretching to flip / stretch the texture\n");
3628
            fb_copy_to_texture_hwstretch(This, SrcSurface, srcSwapchain, &srect, &rect, upsideDown, Filter);
3629
        }
3630

3631 3632 3633 3634
        /* Clear the palette as the surface didn't have a palette attached, it would confuse GetPalette and other calls */
        if(paletteOverride)
            This->palette = NULL;

3635
        if(!(This->Flags & SFLAG_DONOTFREE)) {
3636
            HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
3637
            This->resource.allocatedMemory = NULL;
3638
            This->resource.heapMemory = NULL;
3639
        } else {
3640
            This->Flags &= ~SFLAG_INSYSMEM;
3641
        }
3642 3643 3644
        /* The texture is now most up to date - If the surface is a render target and has a drawable, this
         * path is never entered
         */
3645
        IWineD3DSurface_ModifyLocation((IWineD3DSurface *) This, SFLAG_INTEXTURE, TRUE);
3646

3647 3648 3649 3650
        return WINED3D_OK;
    } else if(Src) {
        /* Blit from offscreen surface to render target */
        float glTexCoord[4];
3651
        DWORD oldCKeyFlags = Src->CKeyFlags;
3652
        WINEDDCOLORKEY oldBltCKey = Src->SrcBltCKey;
3653
        RECT SourceRectangle;
3654
        BOOL paletteOverride = FALSE;
3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668

        TRACE("Blt from surface %p to rendertarget %p\n", Src, This);

        if(SrcRect) {
            SourceRectangle.left = SrcRect->left;
            SourceRectangle.right = SrcRect->right;
            SourceRectangle.top = SrcRect->top;
            SourceRectangle.bottom = SrcRect->bottom;
        } else {
            SourceRectangle.left = 0;
            SourceRectangle.right = Src->currentDesc.Width;
            SourceRectangle.top = 0;
            SourceRectangle.bottom = Src->currentDesc.Height;
        }
3669 3670 3671 3672 3673

        /* When blitting from an offscreen surface to a rendertarget, the source
         * surface is not required to have a palette. Our rendering / conversion
         * code further down the road retrieves the palette from the surface, so
         * it must have a palette set. */
3674 3675
        if ((Src->resource.format_desc->format == WINED3DFMT_P8) && (Src->palette == NULL))
        {
3676 3677 3678 3679 3680
            paletteOverride = TRUE;
            TRACE("Source surface (%p) lacks palette, overriding palette with palette %p of destination surface (%p)\n", Src, This->palette, This);
            Src->palette = This->palette;
        }

3681 3682 3683 3684
        if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && GL_SUPPORT(EXT_FRAMEBUFFER_BLIT)
                && !(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE))
                && surface_can_stretch_rect(Src, This))
        {
3685 3686 3687 3688 3689 3690
            TRACE("Using stretch_rect_fbo\n");
            /* The source is always a texture, but never the currently active render target, and the texture
             * contents are never upside down
             */
            stretch_rect_fbo((IWineD3DDevice *)myDevice, SrcSurface, (WINED3DRECT *) &SourceRectangle,
                              (IWineD3DSurface *)This, &rect, Filter, FALSE);
3691 3692 3693 3694

            /* Clear the palette as the surface didn't have a palette attached, it would confuse GetPalette and other calls */
            if(paletteOverride)
                Src->palette = NULL;
3695 3696
            return WINED3D_OK;
        }
3697

3698 3699 3700 3701 3702 3703 3704
        if(!CalculateTexRect(Src, &SourceRectangle, glTexCoord)) {
            /* Fall back to software */
            WARN("(%p) Source texture area (%d,%d)-(%d,%d) is too big\n", Src,
                    SourceRectangle.left, SourceRectangle.top,
                    SourceRectangle.right, SourceRectangle.bottom);
            return WINED3DERR_INVALIDCALL;
        }
3705

3706 3707
        /* Color keying: Check if we have to do a color keyed blt,
         * and if not check if a color key is activated.
3708 3709 3710
         *
         * Just modify the color keying parameters in the surface and restore them afterwards
         * The surface keeps track of the color key last used to load the opengl surface.
3711
         * PreLoad will catch the change to the flags and color key and reload if necessary.
3712
         */
3713
        if(Flags & WINEDDBLT_KEYSRC) {
3714
            /* Use color key from surface */
3715
        } else if(Flags & WINEDDBLT_KEYSRCOVERRIDE) {
3716
            /* Use color key from DDBltFx */
3717
            Src->CKeyFlags |= WINEDDSD_CKSRCBLT;
3718
            Src->SrcBltCKey = DDBltFx->ddckSrcColorkey;
3719 3720
        } else {
            /* Do not use color key */
3721
            Src->CKeyFlags &= ~WINEDDSD_CKSRCBLT;
3722
        }
3723

3724
        /* Now load the surface */
3725
        surface_internal_preload((IWineD3DSurface *) Src, SRGB_RGB);
3726

3727 3728
        /* Activate the destination context, set it up for blitting */
        ActivateContext(myDevice, (IWineD3DSurface *) This, CTXUSAGE_BLIT);
3729

3730 3731 3732 3733 3734 3735
        /* The coordinates of the ddraw front buffer are always fullscreen ('screen coordinates',
         * while OpenGL coordinates are window relative.
         * Also beware of the origin difference(top left vs bottom left).
         * Also beware that the front buffer's surface size is screen width x screen height,
         * whereas the real gl drawable size is the size of the window.
         */
3736 3737 3738 3739 3740 3741 3742 3743 3744 3745
        if (dstSwapchain && (IWineD3DSurface *)This == dstSwapchain->frontBuffer) {
            RECT windowsize;
            POINT offset = {0,0};
            UINT h;
            ClientToScreen(dstSwapchain->win_handle, &offset);
            GetClientRect(dstSwapchain->win_handle, &windowsize);
            h = windowsize.bottom - windowsize.top;
            rect.x1 -= offset.x; rect.x2 -=offset.x;
            rect.y1 -= offset.y; rect.y2 -=offset.y;
            rect.y1 += This->currentDesc.Height - h; rect.y2 += This->currentDesc.Height - h;
3746
        }
3747

3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761
        if (!is_identity_fixup(This->resource.format_desc->color_fixup))
        {
            FIXME("Destination format %s has a fixup, this is not supported.\n",
                    debug_d3dformat(This->resource.format_desc->format));
            dump_color_fixup_desc(This->resource.format_desc->color_fixup);
        }

        if (!myDevice->blitter->color_fixup_supported(Src->resource.format_desc->color_fixup))
        {
            FIXME("Source format %s has an unsupported fixup:\n",
                    debug_d3dformat(Src->resource.format_desc->format));
            dump_color_fixup_desc(Src->resource.format_desc->color_fixup);
        }

3762
        myDevice->blitter->set_shader((IWineD3DDevice *) myDevice, Src->resource.format_desc,
3763
                Src->texture_target, Src->pow2Width, Src->pow2Height);
3764

3765 3766
        ENTER_GL();

3767
        /* Bind the texture */
3768
        glBindTexture(Src->texture_target, Src->texture_name);
3769 3770
        checkGLcall("glBindTexture");

3771
        /* Filtering for StretchRect */
3772
        glTexParameteri(Src->texture_target, GL_TEXTURE_MAG_FILTER, magLookup[Filter - WINED3DTEXF_NONE]);
3773
        checkGLcall("glTexParameteri");
3774
        glTexParameteri(Src->texture_target, GL_TEXTURE_MIN_FILTER, minMipLookup[Filter].mip[WINED3DTEXF_NONE]);
3775
        checkGLcall("glTexParameteri");
3776 3777
        glTexParameteri(Src->texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
        glTexParameteri(Src->texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP);
3778 3779 3780 3781
        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
        checkGLcall("glTexEnvi");

        /* This is for color keying */
3782
        if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3783 3784
            glEnable(GL_ALPHA_TEST);
            checkGLcall("glEnable GL_ALPHA_TEST");
3785 3786 3787 3788 3789

            /* When the primary render target uses P8, the alpha component contains the palette index.
             * Which means that the colorkey is one of the palette entries. In other cases pixels that
             * should be masked away have alpha set to 0. */
            if(primary_render_target_is_p8(myDevice))
3790
                glAlphaFunc(GL_NOTEQUAL, (float)Src->SrcBltCKey.dwColorSpaceLowValue / 256.0f);
3791
            else
3792
                glAlphaFunc(GL_NOTEQUAL, 0.0f);
3793
            checkGLcall("glAlphaFunc");
3794 3795 3796
        } else {
            glDisable(GL_ALPHA_TEST);
            checkGLcall("glDisable GL_ALPHA_TEST");
3797 3798
        }

3799
        /* Draw a textured quad
3800
         */
3801 3802
        glBegin(GL_QUADS);

3803
        glColor3f(1.0f, 1.0f, 1.0f);
3804
        glTexCoord2f(glTexCoord[0], glTexCoord[2]);
3805
        glVertex3f(rect.x1, rect.y1, 0.0f);
3806 3807

        glTexCoord2f(glTexCoord[0], glTexCoord[3]);
3808
        glVertex3f(rect.x1, rect.y2, 0.0f);
3809 3810

        glTexCoord2f(glTexCoord[1], glTexCoord[3]);
3811
        glVertex3f(rect.x2, rect.y2, 0.0f);
3812 3813

        glTexCoord2f(glTexCoord[1], glTexCoord[2]);
3814 3815
        glVertex3f(rect.x2, rect.y1, 0.0f);

3816 3817 3818
        glEnd();
        checkGLcall("glEnd");

3819
        if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3820 3821 3822 3823
            glDisable(GL_ALPHA_TEST);
            checkGLcall("glDisable(GL_ALPHA_TEST)");
        }

3824 3825
        glBindTexture(Src->texture_target, 0);
        checkGLcall("glBindTexture(Src->texture_target, 0)");
3826

3827 3828
        /* Restore the color key parameters */
        Src->CKeyFlags = oldCKeyFlags;
3829
        Src->SrcBltCKey = oldBltCKey;
3830

3831 3832 3833 3834
        /* Clear the palette as the surface didn't have a palette attached, it would confuse GetPalette and other calls */
        if(paletteOverride)
            Src->palette = NULL;

3835
        LEAVE_GL();
3836

3837 3838 3839
        /* Leave the opengl state valid for blitting */
        myDevice->blitter->unset_shader((IWineD3DDevice *) myDevice);

3840 3841 3842 3843
        /* Flush in case the drawable is used by multiple GL contexts */
        if(dstSwapchain && (This == (IWineD3DSurfaceImpl *) dstSwapchain->frontBuffer || dstSwapchain->num_contexts >= 2))
            glFlush();

3844
        /* TODO: If the surface is locked often, perform the Blt in software on the memory instead */
3845 3846 3847
        /* The surface is now in the drawable. On onscreen surfaces or without fbos the texture
         * is outdated now
         */
3848
        IWineD3DSurface_ModifyLocation((IWineD3DSurface *) This, SFLAG_INDRAWABLE, TRUE);
3849

3850 3851 3852
        return WINED3D_OK;
    } else {
        /* Source-Less Blit to render target */
3853
        if (Flags & WINEDDBLT_COLORFILL) {
3854 3855 3856 3857 3858
            /* This is easy to handle for the D3D Device... */
            DWORD color;

            TRACE("Colorfill\n");

3859 3860 3861 3862 3863 3864 3865 3866 3867
            /* This == (IWineD3DSurfaceImpl *) myDevice->render_targets[0] || dstSwapchain
                must be true if we are here */
            if (This != (IWineD3DSurfaceImpl *) myDevice->render_targets[0] &&
                    !(This == (IWineD3DSurfaceImpl*) dstSwapchain->frontBuffer ||
                      (dstSwapchain->backBuffer && This == (IWineD3DSurfaceImpl*) dstSwapchain->backBuffer[0]))) {
                TRACE("Surface is higher back buffer, falling back to software\n");
                return WINED3DERR_INVALIDCALL;
            }

3868 3869 3870
            /* The color as given in the Blt function is in the format of the frame-buffer...
             * 'clear' expect it in ARGB format => we need to do some conversion :-)
             */
3871 3872
            if (This->resource.format_desc->format == WINED3DFMT_P8)
            {
3873 3874 3875 3876 3877
                DWORD alpha;

                if (primary_render_target_is_p8(myDevice)) alpha = DDBltFx->u5.dwFillColor << 24;
                else alpha = 0xFF000000;

3878
                if (This->palette) {
3879
                    color = (alpha |
3880 3881 3882
                            (This->palette->palents[DDBltFx->u5.dwFillColor].peRed << 16) |
                            (This->palette->palents[DDBltFx->u5.dwFillColor].peGreen << 8) |
                            (This->palette->palents[DDBltFx->u5.dwFillColor].peBlue));
3883
                } else {
3884
                    color = alpha;
3885
                }
3886
            }
3887 3888
            else if (This->resource.format_desc->format == WINED3DFMT_R5G6B5)
            {
3889 3890
                if (DDBltFx->u5.dwFillColor == 0xFFFF) {
                    color = 0xFFFFFFFF;
3891
                } else {
3892 3893 3894 3895
                    color = ((0xFF000000) |
                            ((DDBltFx->u5.dwFillColor & 0xF800) << 8) |
                            ((DDBltFx->u5.dwFillColor & 0x07E0) << 5) |
                            ((DDBltFx->u5.dwFillColor & 0x001F) << 3));
3896 3897
                }
            }
3898 3899 3900
            else if ((This->resource.format_desc->format == WINED3DFMT_R8G8B8)
                    || (This->resource.format_desc->format == WINED3DFMT_X8R8G8B8))
            {
3901
                color = 0xFF000000 | DDBltFx->u5.dwFillColor;
3902
            }
3903 3904
            else if (This->resource.format_desc->format == WINED3DFMT_A8R8G8B8)
            {
3905 3906 3907 3908 3909 3910 3911 3912
                color = DDBltFx->u5.dwFillColor;
            }
            else {
                ERR("Wrong surface type for BLT override(Format doesn't match) !\n");
                return WINED3DERR_INVALIDCALL;
            }

            TRACE("(%p) executing Render Target override, color = %x\n", This, color);
3913 3914
            IWineD3DDeviceImpl_ClearSurface(myDevice, This, 1 /* Number of rectangles */,
                    &rect, WINED3DCLEAR_TARGET, color, 0.0f /* Z */, 0 /* Stencil */);
3915
            return WINED3D_OK;
3916
        }
3917 3918
    }

3919
    /* Default: Fall back to the generic blt. Not an error, a TRACE is enough */
3920
    TRACE("Didn't find any usable render target setup for hw blit, falling back to software\n");
3921 3922 3923
    return WINED3DERR_INVALIDCALL;
}

3924 3925
static HRESULT IWineD3DSurfaceImpl_BltZ(IWineD3DSurfaceImpl *This, const RECT *DestRect,
        IWineD3DSurface *SrcSurface, const RECT *SrcRect, DWORD Flags, const WINEDDBLTFX *DDBltFx)
3926 3927
{
    IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3928 3929 3930
    float depth;

    if (Flags & WINEDDBLT_DEPTHFILL) {
3931 3932
        switch(This->resource.format_desc->format)
        {
3933
            case WINED3DFMT_D16_UNORM:
3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946
                depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000ffff;
                break;
            case WINED3DFMT_D15S1:
                depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000fffe;
                break;
            case WINED3DFMT_D24S8:
            case WINED3DFMT_D24X8:
                depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x00ffffff;
                break;
            case WINED3DFMT_D32:
                depth = (float) DDBltFx->u5.dwFillDepth / (float) 0xffffffff;
                break;
            default:
3947
                depth = 0.0f;
3948
                ERR("Unexpected format for depth fill: %s\n", debug_d3dformat(This->resource.format_desc->format));
3949
        }
3950 3951 3952

        return IWineD3DDevice_Clear((IWineD3DDevice *) myDevice,
                                    DestRect == NULL ? 0 : 1,
3953
                                    (const WINED3DRECT *)DestRect,
3954 3955
                                    WINED3DCLEAR_ZBUFFER,
                                    0x00000000,
3956
                                    depth,
3957
                                    0x00000000);
3958
    }
3959 3960 3961 3962 3963

    FIXME("(%p): Unsupp depthstencil blit\n", This);
    return WINED3DERR_INVALIDCALL;
}

3964 3965
static HRESULT WINAPI IWineD3DSurfaceImpl_Blt(IWineD3DSurface *iface, const RECT *DestRect, IWineD3DSurface *SrcSurface,
        const RECT *SrcRect, DWORD Flags, const WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter) {
3966 3967
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
    IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
3968
    IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3969
    TRACE("(%p)->(%p,%p,%p,%x,%p)\n", This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx);
3970
    TRACE("(%p): Usage is %s\n", This, debug_d3dusage(This->resource.usage));
3971

3972 3973 3974 3975 3976 3977
    if ( (This->Flags & SFLAG_LOCKED) || ((Src != NULL) && (Src->Flags & SFLAG_LOCKED)))
    {
        WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
        return WINEDDERR_SURFACEBUSY;
    }

3978 3979 3980
    /* Accessing the depth stencil is supposed to fail between a BeginScene and EndScene pair,
     * except depth blits, which seem to work
     */
3981
    if(iface == myDevice->stencilBufferTarget || (SrcSurface && SrcSurface == myDevice->stencilBufferTarget)) {
3982
        if(myDevice->inScene && !(Flags & WINEDDBLT_DEPTHFILL)) {
3983 3984 3985 3986 3987 3988
            TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
            return WINED3DERR_INVALIDCALL;
        } else if(IWineD3DSurfaceImpl_BltZ(This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx) == WINED3D_OK) {
            TRACE("Z Blit override handled the blit\n");
            return WINED3D_OK;
        }
3989 3990
    }

3991 3992 3993
    /* Special cases for RenderTargets */
    if( (This->resource.usage & WINED3DUSAGE_RENDERTARGET) ||
        ( Src && (Src->resource.usage & WINED3DUSAGE_RENDERTARGET) )) {
3994
        if(IWineD3DSurfaceImpl_BltOverride(This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx, Filter) == WINED3D_OK) return WINED3D_OK;
3995 3996 3997 3998 3999 4000
    }

    /* For the rest call the X11 surface implementation.
     * For RenderTargets this should be implemented OpenGL accelerated in BltOverride,
     * other Blts are rather rare
     */
4001
    return IWineD3DBaseSurfaceImpl_Blt(iface, DestRect, SrcSurface, SrcRect, Flags, DDBltFx, Filter);
4002 4003
}

4004 4005 4006
static HRESULT WINAPI IWineD3DSurfaceImpl_BltFast(IWineD3DSurface *iface, DWORD dstx, DWORD dsty,
        IWineD3DSurface *Source, const RECT *rsrc, DWORD trans)
{
4007 4008
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
    IWineD3DSurfaceImpl *srcImpl = (IWineD3DSurfaceImpl *) Source;
4009
    IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
4010
    TRACE("(%p)->(%d, %d, %p, %p, %08x\n", iface, dstx, dsty, Source, rsrc, trans);
4011

4012 4013 4014 4015 4016 4017
    if ( (This->Flags & SFLAG_LOCKED) || ((srcImpl != NULL) && (srcImpl->Flags & SFLAG_LOCKED)))
    {
        WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
        return WINEDDERR_SURFACEBUSY;
    }

4018 4019 4020 4021 4022 4023 4024
    if(myDevice->inScene &&
       (iface == myDevice->stencilBufferTarget ||
       (Source && Source == myDevice->stencilBufferTarget))) {
        TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
        return WINED3DERR_INVALIDCALL;
    }

4025 4026 4027 4028 4029
    /* Special cases for RenderTargets */
    if( (This->resource.usage & WINED3DUSAGE_RENDERTARGET) ||
        ( srcImpl && (srcImpl->resource.usage & WINED3DUSAGE_RENDERTARGET) )) {

        RECT SrcRect, DstRect;
4030
        DWORD Flags=0;
4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048

        if(rsrc) {
            SrcRect.left = rsrc->left;
            SrcRect.top= rsrc->top;
            SrcRect.bottom = rsrc->bottom;
            SrcRect.right = rsrc->right;
        } else {
            SrcRect.left = 0;
            SrcRect.top = 0;
            SrcRect.right = srcImpl->currentDesc.Width;
            SrcRect.bottom = srcImpl->currentDesc.Height;
        }

        DstRect.left = dstx;
        DstRect.top=dsty;
        DstRect.right = dstx + SrcRect.right - SrcRect.left;
        DstRect.bottom = dsty + SrcRect.bottom - SrcRect.top;

4049
        /* Convert BltFast flags into Btl ones because it is called from SurfaceImpl_Blt as well */
4050 4051 4052 4053 4054 4055 4056 4057
        if(trans & WINEDDBLTFAST_SRCCOLORKEY)
            Flags |= WINEDDBLT_KEYSRC;
        if(trans & WINEDDBLTFAST_DESTCOLORKEY)
            Flags |= WINEDDBLT_KEYDEST;
        if(trans & WINEDDBLTFAST_WAIT)
            Flags |= WINEDDBLT_WAIT;
        if(trans & WINEDDBLTFAST_DONOTWAIT)
            Flags |= WINEDDBLT_DONOTWAIT;
4058

4059
        if(IWineD3DSurfaceImpl_BltOverride(This, &DstRect, Source, &SrcRect, Flags, NULL, WINED3DTEXF_POINT) == WINED3D_OK) return WINED3D_OK;
4060 4061 4062
    }


4063
    return IWineD3DBaseSurfaceImpl_BltFast(iface, dstx, dsty, Source, rsrc, trans);
4064 4065
}

4066 4067
static HRESULT WINAPI IWineD3DSurfaceImpl_RealizePalette(IWineD3DSurface *iface)
{
4068 4069 4070 4071 4072 4073
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
    RGBQUAD col[256];
    IWineD3DPaletteImpl *pal = This->palette;
    unsigned int n;
    TRACE("(%p)\n", This);

4074 4075
    if (!pal) return WINED3D_OK;

4076 4077
    if (This->resource.format_desc->format == WINED3DFMT_P8
            || This->resource.format_desc->format == WINED3DFMT_A8P8)
4078
    {
4079 4080 4081 4082 4083 4084 4085 4086
        int bpp;
        GLenum format, internal, type;
        CONVERT_TYPES convert;

        /* Check if we are using a RTL mode which uses texturing for uploads */
        BOOL use_texture = (wined3d_settings.rendertargetlock_mode == RTL_READTEX || wined3d_settings.rendertargetlock_mode == RTL_TEXTEX);

        /* Check if we have hardware palette conversion if we have convert is set to NO_CONVERSION */
4087
        d3dfmt_get_conv(This, TRUE, use_texture, &format, &internal, &type, &convert, &bpp, FALSE);
4088 4089 4090

        if((This->resource.usage & WINED3DUSAGE_RENDERTARGET) && (convert == NO_CONVERSION))
        {
4091 4092
            IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;

4093 4094 4095 4096 4097 4098 4099
            /* Make sure the texture is up to date. This call doesn't do anything if the texture is already up to date. */
            IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL);

            /* We want to force a palette refresh, so mark the drawable as not being up to date */
            IWineD3DSurface_ModifyLocation(iface, SFLAG_INDRAWABLE, FALSE);

            /* Re-upload the palette */
4100
            ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
4101 4102 4103 4104 4105 4106 4107 4108
            d3dfmt_p8_upload_palette(iface, convert);
        } else {
            if(!(This->Flags & SFLAG_INSYSMEM)) {
                TRACE("Palette changed with surface that does not have an up to date system memory copy\n");
                IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
            }
            TRACE("Dirtifying surface\n");
            IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
4109 4110 4111 4112 4113 4114
        }
    }

    if(This->Flags & SFLAG_DIBSECTION) {
        TRACE("(%p): Updating the hdc's palette\n", This);
        for (n=0; n<256; n++) {
4115 4116 4117
            col[n].rgbRed   = pal->palents[n].peRed;
            col[n].rgbGreen = pal->palents[n].peGreen;
            col[n].rgbBlue  = pal->palents[n].peBlue;
4118 4119 4120 4121 4122
            col[n].rgbReserved = 0;
        }
        SetDIBColorTable(This->hDC, 0, 256, col);
    }

4123
    /* Propagate the changes to the drawable when we have a palette. */
4124
    if(This->resource.usage & WINED3DUSAGE_RENDERTARGET)
4125 4126 4127 4128 4129
        IWineD3DSurface_LoadLocation(iface, SFLAG_INDRAWABLE, NULL);

    return WINED3D_OK;
}

4130
static HRESULT WINAPI IWineD3DSurfaceImpl_PrivateSetup(IWineD3DSurface *iface) {
4131 4132
    /** Check against the maximum texture sizes supported by the video card **/
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4133
    unsigned int pow2Width, pow2Height;
4134

4135 4136
    This->texture_name = 0;
    This->texture_target = GL_TEXTURE_2D;
4137 4138

    /* Non-power2 support */
4139
    if (GL_SUPPORT(ARB_TEXTURE_NON_POWER_OF_TWO) || GL_SUPPORT(WINE_NORMALIZED_TEXRECT)) {
4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152
        pow2Width = This->currentDesc.Width;
        pow2Height = This->currentDesc.Height;
    } else {
        /* Find the nearest pow2 match */
        pow2Width = pow2Height = 1;
        while (pow2Width < This->currentDesc.Width) pow2Width <<= 1;
        while (pow2Height < This->currentDesc.Height) pow2Height <<= 1;
    }
    This->pow2Width  = pow2Width;
    This->pow2Height = pow2Height;

    if (pow2Width > This->currentDesc.Width || pow2Height > This->currentDesc.Height) {
        /** TODO: add support for non power two compressed textures **/
4153
        if (This->resource.format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
4154
        {
4155 4156 4157 4158 4159 4160 4161 4162 4163 4164
            FIXME("(%p) Compressed non-power-two textures are not supported w(%d) h(%d)\n",
                  This, This->currentDesc.Width, This->currentDesc.Height);
            return WINED3DERR_NOTAVAILABLE;
        }
    }

    if(pow2Width != This->currentDesc.Width ||
       pow2Height != This->currentDesc.Height) {
        This->Flags |= SFLAG_NONPOW2;
    }
4165 4166 4167 4168 4169

    TRACE("%p\n", This);
    if ((This->pow2Width > GL_LIMITS(texture_size) || This->pow2Height > GL_LIMITS(texture_size)) && !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL))) {
        /* one of three options
        1: Do the same as we do with nonpow 2 and scale the texture, (any texture ops would require the texture to be scaled which is potentially slow)
4170
        2: Set the texture to the maximum size (bad idea)
4171 4172 4173
        3:    WARN and return WINED3DERR_NOTAVAILABLE;
        4: Create the surface, but allow it to be used only for DirectDraw Blts. Some apps(e.g. Swat 3) create textures with a Height of 16 and a Width > 3000 and blt 16x16 letter areas from them to the render target.
        */
4174 4175
        WARN("(%p) Creating an oversized surface: %ux%u (texture is %ux%u)\n",
             This, This->pow2Width, This->pow2Height, This->currentDesc.Width, This->currentDesc.Height);
4176 4177 4178 4179 4180 4181 4182 4183
        This->Flags |= SFLAG_OVERSIZE;

        /* This will be initialized on the first blt */
        This->glRect.left = 0;
        This->glRect.top = 0;
        This->glRect.right = 0;
        This->glRect.bottom = 0;
    } else {
4184 4185 4186 4187 4188
        /* Check this after the oversize check - do not make an oversized surface a texture_rectangle one.
           Second also don't use ARB_TEXTURE_RECTANGLE in case the surface format is P8 and EXT_PALETTED_TEXTURE
           is used in combination with texture uploads (RTL_READTEX/RTL_TEXTEX). The reason is that EXT_PALETTED_TEXTURE
           doesn't work in combination with ARB_TEXTURE_RECTANGLE.
        */
4189 4190 4191 4192
        if(This->Flags & SFLAG_NONPOW2 && GL_SUPPORT(ARB_TEXTURE_RECTANGLE)
                && !((This->resource.format_desc->format == WINED3DFMT_P8) && GL_SUPPORT(EXT_PALETTED_TEXTURE)
                && (wined3d_settings.rendertargetlock_mode == RTL_READTEX
                || wined3d_settings.rendertargetlock_mode == RTL_TEXTEX)))
4193
        {
4194
            This->texture_target = GL_TEXTURE_RECTANGLE_ARB;
4195 4196
            This->pow2Width  = This->currentDesc.Width;
            This->pow2Height = This->currentDesc.Height;
4197
            This->Flags &= ~(SFLAG_NONPOW2 | SFLAG_NORMCOORD);
4198 4199
        }

4200 4201 4202 4203 4204 4205 4206 4207
        /* No oversize, gl rect is the full texture size */
        This->Flags &= ~SFLAG_OVERSIZE;
        This->glRect.left = 0;
        This->glRect.top = 0;
        This->glRect.right = This->pow2Width;
        This->glRect.bottom = This->pow2Height;
    }

4208 4209 4210 4211 4212 4213 4214 4215
    if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
        switch(wined3d_settings.offscreen_rendering_mode) {
            case ORM_FBO:        This->get_drawable_size = get_drawable_size_fbo;        break;
            case ORM_PBUFFER:    This->get_drawable_size = get_drawable_size_pbuffer;    break;
            case ORM_BACKBUFFER: This->get_drawable_size = get_drawable_size_backbuffer; break;
        }
    }

4216 4217
    This->Flags |= SFLAG_INSYSMEM;

4218 4219 4220
    return WINED3D_OK;
}

4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313
struct depth_blt_info
{
    GLenum binding;
    GLenum bind_target;
    enum tex_types tex_type;
    GLfloat coords[4][3];
};

static void surface_get_depth_blt_info(GLenum target, GLsizei w, GLsizei h, struct depth_blt_info *info)
{
    GLfloat (*coords)[3] = info->coords;

    switch (target)
    {
        default:
            FIXME("Unsupported texture target %#x\n", target);
            /* Fall back to GL_TEXTURE_2D */
        case GL_TEXTURE_2D:
            info->binding = GL_TEXTURE_BINDING_2D;
            info->bind_target = GL_TEXTURE_2D;
            info->tex_type = tex_2d;
            coords[0][0] = 0.0f;    coords[0][1] = 1.0f;    coords[0][2] = 0.0f;
            coords[1][0] = 1.0f;    coords[1][1] = 1.0f;    coords[1][2] = 0.0f;
            coords[2][0] = 0.0f;    coords[2][1] = 0.0f;    coords[2][2] = 0.0f;
            coords[3][0] = 1.0f;    coords[3][1] = 0.0f;    coords[3][2] = 0.0f;
            break;

        case GL_TEXTURE_RECTANGLE_ARB:
            info->binding = GL_TEXTURE_BINDING_RECTANGLE_ARB;
            info->bind_target = GL_TEXTURE_RECTANGLE_ARB;
            info->tex_type = tex_rect;
            coords[0][0] = 0.0f;    coords[0][1] = h;       coords[0][2] = 0.0f;
            coords[1][0] = w;       coords[1][1] = h;       coords[1][2] = 0.0f;
            coords[2][0] = 0.0f;    coords[2][1] = 0.0f;    coords[2][2] = 0.0f;
            coords[3][0] = w;       coords[3][1] = 0.0f;    coords[3][2] = 0.0f;
            break;

        case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
            info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
            info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
            info->tex_type = tex_cube;
            coords[0][0] =  1.0f;   coords[0][1] = -1.0f;   coords[0][2] =  1.0f;
            coords[1][0] =  1.0f;   coords[1][1] = -1.0f;   coords[1][2] = -1.0f;
            coords[2][0] =  1.0f;   coords[2][1] =  1.0f;   coords[2][2] =  1.0f;
            coords[3][0] =  1.0f;   coords[3][1] =  1.0f;   coords[3][2] = -1.0f;

        case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
            info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
            info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
            info->tex_type = tex_cube;
            coords[0][0] = -1.0f;   coords[0][1] = -1.0f;   coords[0][2] = -1.0f;
            coords[1][0] = -1.0f;   coords[1][1] = -1.0f;   coords[1][2] =  1.0f;
            coords[2][0] = -1.0f;   coords[2][1] =  1.0f;   coords[2][2] = -1.0f;
            coords[3][0] = -1.0f;   coords[3][1] =  1.0f;   coords[3][2] =  1.0f;

        case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
            info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
            info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
            info->tex_type = tex_cube;
            coords[0][0] = -1.0f;   coords[0][1] =  1.0f;   coords[0][2] =  1.0f;
            coords[1][0] =  1.0f;   coords[1][1] =  1.0f;   coords[1][2] =  1.0f;
            coords[2][0] = -1.0f;   coords[2][1] =  1.0f;   coords[2][2] = -1.0f;
            coords[3][0] =  1.0f;   coords[3][1] =  1.0f;   coords[3][2] = -1.0f;

        case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
            info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
            info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
            info->tex_type = tex_cube;
            coords[0][0] = -1.0f;   coords[0][1] = -1.0f;   coords[0][2] = -1.0f;
            coords[1][0] =  1.0f;   coords[1][1] = -1.0f;   coords[1][2] = -1.0f;
            coords[2][0] = -1.0f;   coords[2][1] = -1.0f;   coords[2][2] =  1.0f;
            coords[3][0] =  1.0f;   coords[3][1] = -1.0f;   coords[3][2] =  1.0f;

        case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
            info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
            info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
            info->tex_type = tex_cube;
            coords[0][0] = -1.0f;   coords[0][1] = -1.0f;   coords[0][2] =  1.0f;
            coords[1][0] =  1.0f;   coords[1][1] = -1.0f;   coords[1][2] =  1.0f;
            coords[2][0] = -1.0f;   coords[2][1] =  1.0f;   coords[2][2] =  1.0f;
            coords[3][0] =  1.0f;   coords[3][1] =  1.0f;   coords[3][2] =  1.0f;

        case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
            info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
            info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
            info->tex_type = tex_cube;
            coords[0][0] =  1.0f;   coords[0][1] = -1.0f;   coords[0][2] = -1.0f;
            coords[1][0] = -1.0f;   coords[1][1] = -1.0f;   coords[1][2] = -1.0f;
            coords[2][0] =  1.0f;   coords[2][1] =  1.0f;   coords[2][2] = -1.0f;
            coords[3][0] = -1.0f;   coords[3][1] =  1.0f;   coords[3][2] = -1.0f;
    }
}

4314
/* GL locking is done by the caller */
4315
static void surface_depth_blt(IWineD3DSurfaceImpl *This, GLuint texture, GLsizei w, GLsizei h, GLenum target)
4316 4317
{
    IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
4318
    struct depth_blt_info info;
4319 4320 4321 4322 4323
    GLint old_binding = 0;

    glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_VIEWPORT_BIT);

    glDisable(GL_CULL_FACE);
4324
    glDisable(GL_BLEND);
4325 4326 4327 4328 4329 4330
    glDisable(GL_ALPHA_TEST);
    glDisable(GL_SCISSOR_TEST);
    glDisable(GL_STENCIL_TEST);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_ALWAYS);
    glDepthMask(GL_TRUE);
4331
    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
4332 4333
    glViewport(0, 0, w, h);

4334
    surface_get_depth_blt_info(target, w, h, &info);
4335
    GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
4336 4337
    glGetIntegerv(info.binding, &old_binding);
    glBindTexture(info.bind_target, texture);
4338

4339
    device->shader_backend->shader_select_depth_blt((IWineD3DDevice *)device, info.tex_type);
4340 4341

    glBegin(GL_TRIANGLE_STRIP);
4342
    glTexCoord3fv(info.coords[0]);
4343
    glVertex2f(-1.0f, -1.0f);
4344
    glTexCoord3fv(info.coords[1]);
4345
    glVertex2f(1.0f, -1.0f);
4346
    glTexCoord3fv(info.coords[2]);
4347
    glVertex2f(-1.0f, 1.0f);
4348
    glTexCoord3fv(info.coords[3]);
4349 4350 4351
    glVertex2f(1.0f, 1.0f);
    glEnd();

4352
    glBindTexture(info.bind_target, old_binding);
4353 4354 4355 4356 4357 4358

    glPopAttrib();

    device->shader_backend->shader_deselect_depth_blt((IWineD3DDevice *)device);
}

4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371
void surface_modify_ds_location(IWineD3DSurface *iface, DWORD location) {
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;

    TRACE("(%p) New location %#x\n", This, location);

    if (location & ~SFLAG_DS_LOCATIONS) {
        FIXME("(%p) Invalid location (%#x) specified\n", This, location);
    }

    This->Flags &= ~SFLAG_DS_LOCATIONS;
    This->Flags |= location;
}

4372
/* Context activation is done by the caller. */
4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394
void surface_load_ds_location(IWineD3DSurface *iface, DWORD location) {
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
    IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;

    TRACE("(%p) New location %#x\n", This, location);

    /* TODO: Make this work for modes other than FBO */
    if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return;

    if (This->Flags & location) {
        TRACE("(%p) Location (%#x) is already up to date\n", This, location);
        return;
    }

    if (This->current_renderbuffer) {
        FIXME("(%p) Not supported with fixed up depth stencil\n", This);
        return;
    }

    if (location == SFLAG_DS_OFFSCREEN) {
        if (This->Flags & SFLAG_DS_ONSCREEN) {
            GLint old_binding = 0;
4395
            GLenum bind_target;
4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407

            TRACE("(%p) Copying onscreen depth buffer to depth texture\n", This);

            ENTER_GL();

            if (!device->depth_blt_texture) {
                glGenTextures(1, &device->depth_blt_texture);
            }

            /* Note that we use depth_blt here as well, rather than glCopyTexImage2D
             * directly on the FBO texture. That's because we need to flip. */
            GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
4408 4409
            if (This->texture_target == GL_TEXTURE_RECTANGLE_ARB)
            {
4410 4411 4412 4413 4414 4415 4416
                glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
                bind_target = GL_TEXTURE_RECTANGLE_ARB;
            } else {
                glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
                bind_target = GL_TEXTURE_2D;
            }
            glBindTexture(bind_target, device->depth_blt_texture);
4417 4418
            glCopyTexImage2D(bind_target, This->texture_level, This->resource.format_desc->glInternal,
                    0, 0, This->currentDesc.Width, This->currentDesc.Height, 0);
4419 4420 4421 4422
            glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
            glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
            glTexParameteri(bind_target, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE);
            glBindTexture(bind_target, old_binding);
4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438

            /* Setup the destination */
            if (!device->depth_blt_rb) {
                GL_EXTCALL(glGenRenderbuffersEXT(1, &device->depth_blt_rb));
                checkGLcall("glGenRenderbuffersEXT");
            }
            if (device->depth_blt_rb_w != This->currentDesc.Width
                    || device->depth_blt_rb_h != This->currentDesc.Height) {
                GL_EXTCALL(glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, device->depth_blt_rb));
                checkGLcall("glBindRenderbufferEXT");
                GL_EXTCALL(glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA8, This->currentDesc.Width, This->currentDesc.Height));
                checkGLcall("glRenderbufferStorageEXT");
                device->depth_blt_rb_w = This->currentDesc.Width;
                device->depth_blt_rb_h = This->currentDesc.Height;
            }

4439
            context_bind_fbo((IWineD3DDevice *)device, GL_FRAMEBUFFER_EXT, &device->activeContext->dst_fbo);
4440 4441
            GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, device->depth_blt_rb));
            checkGLcall("glFramebufferRenderbufferEXT");
4442
            context_attach_depth_stencil_fbo(device, GL_FRAMEBUFFER_EXT, iface, FALSE);
4443 4444

            /* Do the actual blit */
4445
            surface_depth_blt(This, device->depth_blt_texture, This->currentDesc.Width, This->currentDesc.Height, bind_target);
4446 4447
            checkGLcall("depth_blt");

4448 4449
            if (device->activeContext->current_fbo) {
                context_bind_fbo((IWineD3DDevice *)device, GL_FRAMEBUFFER_EXT, &device->activeContext->current_fbo->id);
4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466
            } else {
                GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
                checkGLcall("glBindFramebuffer()");
            }

            LEAVE_GL();
        } else {
            FIXME("No up to date depth stencil location\n");
        }
    } else if (location == SFLAG_DS_ONSCREEN) {
        if (This->Flags & SFLAG_DS_OFFSCREEN) {
            TRACE("(%p) Copying depth texture to onscreen depth buffer\n", This);

            ENTER_GL();

            GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
            checkGLcall("glBindFramebuffer()");
4467 4468
            surface_depth_blt(This, This->texture_name, This->currentDesc.Width,
                    This->currentDesc.Height, This->texture_target);
4469 4470
            checkGLcall("depth_blt");

4471 4472
            if (device->activeContext->current_fbo) {
                GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, device->activeContext->current_fbo->id));
4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486
                checkGLcall("glBindFramebuffer()");
            }

            LEAVE_GL();
        } else {
            FIXME("No up to date depth stencil location\n");
        }
    } else {
        ERR("(%p) Invalid location (%#x) specified\n", This, location);
    }

    This->Flags |= location;
}

4487 4488
static void WINAPI IWineD3DSurfaceImpl_ModifyLocation(IWineD3DSurface *iface, DWORD flag, BOOL persistent) {
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4489
    IWineD3DBaseTexture *texture;
4490
    IWineD3DSurfaceImpl *overlay;
4491

4492
    TRACE("(%p)->(%s, %s)\n", iface, debug_surflocation(flag),
4493 4494
          persistent ? "TRUE" : "FALSE");

4495
    if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
4496 4497
        if (This->Flags & SFLAG_SWAPCHAIN)
        {
4498 4499 4500 4501 4502 4503 4504
            TRACE("Surface %p is an onscreen surface\n", iface);
        } else {
            /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
            if (flag & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE)) flag |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
        }
    }

4505
    if(persistent) {
4506 4507
        if(((This->Flags & SFLAG_INTEXTURE) && !(flag & SFLAG_INTEXTURE)) ||
           ((This->Flags & SFLAG_INSRGBTEX) && !(flag & SFLAG_INSRGBTEX))) {
4508 4509 4510 4511 4512 4513
            if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&texture) == WINED3D_OK) {
                TRACE("Passing to container\n");
                IWineD3DBaseTexture_SetDirty(texture, TRUE);
                IWineD3DBaseTexture_Release(texture);
            }
        }
4514 4515
        This->Flags &= ~SFLAG_LOCATIONS;
        This->Flags |= flag;
4516 4517 4518 4519 4520 4521 4522

        /* Redraw emulated overlays, if any */
        if(flag & SFLAG_INDRAWABLE && !list_empty(&This->overlays)) {
            LIST_FOR_EACH_ENTRY(overlay, &This->overlays, IWineD3DSurfaceImpl, overlay_entry) {
                IWineD3DSurface_DrawOverlay((IWineD3DSurface *) overlay);
            }
        }
4523
    } else {
4524
        if((This->Flags & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)) && (flag & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX))) {
4525 4526 4527 4528 4529 4530
            if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&texture) == WINED3D_OK) {
                TRACE("Passing to container\n");
                IWineD3DBaseTexture_SetDirty(texture, TRUE);
                IWineD3DBaseTexture_Release(texture);
            }
        }
4531 4532
        This->Flags &= ~flag;
    }
4533 4534 4535 4536

    if(!(This->Flags & SFLAG_LOCATIONS)) {
        ERR("%p: Surface does not have any up to date location\n", This);
    }
4537 4538
}

4539
struct coords {
4540
    GLfloat x, y, z;
4541 4542
};

4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558
struct float_rect
{
    float l;
    float t;
    float r;
    float b;
};

static inline void cube_coords_float(const RECT *r, UINT w, UINT h, struct float_rect *f)
{
    f->l = ((r->left * 2.0f) / w) - 1.0f;
    f->t = ((r->top * 2.0f) / h) - 1.0f;
    f->r = ((r->right * 2.0f) / w) - 1.0f;
    f->b = ((r->bottom * 2.0f) / h) - 1.0f;
}

4559
static inline void surface_blt_to_drawable(IWineD3DSurfaceImpl *This, const RECT *rect_in) {
4560
    struct coords coords[4];
4561
    RECT rect;
4562 4563
    IWineD3DSwapChain *swapchain;
    IWineD3DBaseTexture *texture;
4564
    IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
4565
    GLenum bind_target;
4566
    struct float_rect f;
4567

4568 4569 4570 4571 4572 4573 4574 4575 4576
    if(rect_in) {
        rect = *rect_in;
    } else {
        rect.left = 0;
        rect.top = 0;
        rect.right = This->currentDesc.Width;
        rect.bottom = This->currentDesc.Height;
    }

4577
    switch (This->texture_target)
4578 4579 4580
    {
        case GL_TEXTURE_2D:
            bind_target = GL_TEXTURE_2D;
4581

4582 4583 4584
            coords[0].x = (float)rect.left / This->pow2Width;
            coords[0].y = (float)rect.top / This->pow2Height;
            coords[0].z = 0;
4585

4586 4587 4588
            coords[1].x = (float)rect.left / This->pow2Width;
            coords[1].y = (float)rect.bottom / This->pow2Height;
            coords[1].z = 0;
4589

4590 4591 4592
            coords[2].x = (float)rect.right / This->pow2Width;
            coords[2].y = (float)rect.bottom / This->pow2Height;
            coords[2].z = 0;
4593

4594 4595 4596 4597
            coords[3].x = (float)rect.right / This->pow2Width;
            coords[3].y = (float)rect.top / This->pow2Height;
            coords[3].z = 0;
            break;
4598

4599 4600 4601 4602 4603 4604 4605
        case GL_TEXTURE_RECTANGLE_ARB:
            bind_target = GL_TEXTURE_RECTANGLE_ARB;
            coords[0].x = rect.left;    coords[0].y = rect.top;     coords[0].z = 0;
            coords[1].x = rect.left;    coords[1].y = rect.bottom;  coords[1].z = 0;
            coords[2].x = rect.right;   coords[2].y = rect.bottom;  coords[2].z = 0;
            coords[3].x = rect.right;   coords[3].y = rect.top;     coords[3].z = 0;
            break;
4606

4607 4608
        case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
            bind_target = GL_TEXTURE_CUBE_MAP_ARB;
4609 4610 4611 4612 4613
            cube_coords_float(&rect, This->pow2Width, This->pow2Height, &f);
            coords[0].x =    1; coords[0].y = -f.t; coords[0].z = -f.l;
            coords[1].x =    1; coords[1].y = -f.b; coords[1].z = -f.l;
            coords[2].x =    1; coords[2].y = -f.b; coords[2].z = -f.r;
            coords[3].x =    1; coords[3].y = -f.t; coords[3].z = -f.r;
4614
            break;
4615

4616 4617
        case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
            bind_target = GL_TEXTURE_CUBE_MAP_ARB;
4618 4619 4620 4621 4622
            cube_coords_float(&rect, This->pow2Width, This->pow2Height, &f);
            coords[0].x =   -1; coords[0].y = -f.t; coords[0].z =  f.l;
            coords[1].x =   -1; coords[1].y = -f.b; coords[1].z =  f.l;
            coords[2].x =   -1; coords[2].y = -f.b; coords[2].z =  f.r;
            coords[3].x =   -1; coords[3].y = -f.t; coords[3].z =  f.r;
4623
            break;
4624

4625 4626
        case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
            bind_target = GL_TEXTURE_CUBE_MAP_ARB;
4627 4628 4629 4630 4631
            cube_coords_float(&rect, This->pow2Width, This->pow2Height, &f);
            coords[0].x =  f.l; coords[0].y =    1; coords[0].z =  f.t;
            coords[1].x =  f.l; coords[1].y =    1; coords[1].z =  f.b;
            coords[2].x =  f.r; coords[2].y =    1; coords[2].z =  f.b;
            coords[3].x =  f.r; coords[3].y =    1; coords[3].z =  f.t;
4632
            break;
4633

4634 4635
        case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
            bind_target = GL_TEXTURE_CUBE_MAP_ARB;
4636 4637 4638 4639 4640
            cube_coords_float(&rect, This->pow2Width, This->pow2Height, &f);
            coords[0].x =  f.l; coords[0].y =   -1; coords[0].z = -f.t;
            coords[1].x =  f.l; coords[1].y =   -1; coords[1].z = -f.b;
            coords[2].x =  f.r; coords[2].y =   -1; coords[2].z = -f.b;
            coords[3].x =  f.r; coords[3].y =   -1; coords[3].z = -f.t;
4641
            break;
4642

4643 4644
        case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
            bind_target = GL_TEXTURE_CUBE_MAP_ARB;
4645 4646 4647 4648 4649
            cube_coords_float(&rect, This->pow2Width, This->pow2Height, &f);
            coords[0].x =  f.l; coords[0].y = -f.t; coords[0].z =    1;
            coords[1].x =  f.l; coords[1].y = -f.b; coords[1].z =    1;
            coords[2].x =  f.r; coords[2].y = -f.b; coords[2].z =    1;
            coords[3].x =  f.r; coords[3].y = -f.t; coords[3].z =    1;
4650
            break;
4651

4652 4653
        case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
            bind_target = GL_TEXTURE_CUBE_MAP_ARB;
4654 4655 4656 4657 4658
            cube_coords_float(&rect, This->pow2Width, This->pow2Height, &f);
            coords[0].x = -f.l; coords[0].y = -f.t; coords[0].z =   -1;
            coords[1].x = -f.l; coords[1].y = -f.b; coords[1].z =   -1;
            coords[2].x = -f.r; coords[2].y = -f.b; coords[2].z =   -1;
            coords[3].x = -f.r; coords[3].y = -f.t; coords[3].z =   -1;
4659
            break;
4660

4661
        default:
4662
            ERR("Unexpected texture target %#x\n", This->texture_target);
4663 4664
            return;
    }
4665

4666 4667
    ActivateContext(device, (IWineD3DSurface*)This, CTXUSAGE_BLIT);
    ENTER_GL();
4668

4669 4670
    glEnable(bind_target);
    checkGLcall("glEnable(bind_target)");
4671 4672
    glBindTexture(bind_target, This->texture_name);
    checkGLcall("bind_target, This->texture_name)");
4673 4674 4675 4676
    glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    checkGLcall("glTexParameteri");
    glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    checkGLcall("glTexParameteri");
4677

4678 4679 4680 4681 4682 4683 4684
    if (device->render_offscreen)
    {
        LONG tmp = rect.top;
        rect.top = rect.bottom;
        rect.bottom = tmp;
    }

4685
    glBegin(GL_QUADS);
4686
    glTexCoord3fv(&coords[0].x);
4687
    glVertex2i(rect.left, rect.top);
4688

4689
    glTexCoord3fv(&coords[1].x);
4690
    glVertex2i(rect.left, rect.bottom);
4691

4692
    glTexCoord3fv(&coords[2].x);
4693
    glVertex2i(rect.right, rect.bottom);
4694

4695
    glTexCoord3fv(&coords[3].x);
4696
    glVertex2i(rect.right, rect.top);
4697 4698 4699
    glEnd();
    checkGLcall("glEnd");

4700 4701 4702
    glDisable(bind_target);
    checkGLcall("glDisable(bind_target)");

4703
    LEAVE_GL();
4704

4705 4706
    if(SUCCEEDED(IWineD3DSurface_GetContainer((IWineD3DSurface*)This, &IID_IWineD3DSwapChain, (void **) &swapchain)))
    {
4707
        /* Make sure to flush the buffers. This is needed in apps like Red Alert II and Tiberian SUN that use multiple WGL contexts. */
4708 4709
        if(((IWineD3DSwapChainImpl*)swapchain)->frontBuffer == (IWineD3DSurface*)This ||
           ((IWineD3DSwapChainImpl*)swapchain)->num_contexts >= 2)
4710 4711 4712
            glFlush();

        IWineD3DSwapChain_Release(swapchain);
4713 4714 4715 4716
    } else {
        /* We changed the filtering settings on the texture. Inform the container about this to get the filters
         * reset properly next draw
         */
4717 4718
        if(SUCCEEDED(IWineD3DSurface_GetContainer((IWineD3DSurface*)This, &IID_IWineD3DBaseTexture, (void **) &texture)))
        {
4719 4720 4721 4722 4723
            ((IWineD3DBaseTextureImpl *) texture)->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
            ((IWineD3DBaseTextureImpl *) texture)->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
            ((IWineD3DBaseTextureImpl *) texture)->baseTexture.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
            IWineD3DBaseTexture_Release(texture);
        }
4724
    }
4725 4726
}

4727 4728 4729 4730 4731 4732
/*****************************************************************************
 * IWineD3DSurface::LoadLocation
 *
 * Copies the current surface data from wherever it is to the requested
 * location. The location is one of the surface flags, SFLAG_INSYSMEM,
 * SFLAG_INTEXTURE and SFLAG_INDRAWABLE. When the surface is current in
4733 4734 4735
 * multiple locations, the gl texture is preferred over the drawable, which is
 * preferred over system memory. The PBO counts as system memory. If rect is
 * not NULL, only the specified rectangle is copied (only supported for
4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747
 * sysmem<->drawable copies at the moment). If rect is NULL, the destination
 * location is marked up to date after the copy.
 *
 * Parameters:
 *  flag: Surface location flag to be updated
 *  rect: rectangle to be copied
 *
 * Returns:
 *  WINED3D_OK on success
 *  WINED3DERR_DEVICELOST on an internal error
 *
 *****************************************************************************/
4748 4749
static HRESULT WINAPI IWineD3DSurfaceImpl_LoadLocation(IWineD3DSurface *iface, DWORD flag, const RECT *rect) {
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4750 4751 4752 4753 4754 4755
    IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
    GLenum format, internal, type;
    CONVERT_TYPES convert;
    int bpp;
    int width, pitch, outpitch;
    BYTE *mem;
4756
    BOOL drawable_read_ok = TRUE;
4757

4758
    if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
4759 4760
        if (This->Flags & SFLAG_SWAPCHAIN)
        {
4761 4762 4763 4764 4765
            TRACE("Surface %p is an onscreen surface\n", iface);
        } else {
            /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets.
             * Prefer SFLAG_INTEXTURE. */
            if (flag == SFLAG_INDRAWABLE) flag = SFLAG_INTEXTURE;
4766
            drawable_read_ok = FALSE;
4767 4768 4769
        }
    }

4770
    TRACE("(%p)->(%s, %p)\n", iface, debug_surflocation(flag), rect);
4771 4772 4773 4774 4775 4776 4777 4778 4779 4780
    if(rect) {
        TRACE("Rectangle: (%d,%d)-(%d,%d)\n", rect->left, rect->top, rect->right, rect->bottom);
    }

    if(This->Flags & flag) {
        TRACE("Location already up to date\n");
        return WINED3D_OK;
    }

    if(!(This->Flags & SFLAG_LOCATIONS)) {
4781
        ERR("%p: Surface does not have any up to date location\n", This);
4782 4783 4784 4785 4786
        This->Flags |= SFLAG_LOST;
        return WINED3DERR_DEVICELOST;
    }

    if(flag == SFLAG_INSYSMEM) {
4787 4788
        surface_prepare_system_memory(This);

4789
        /* Download the surface to system memory */
4790
        if(This->Flags & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)) {
4791
            if(!device->isInDraw) ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
4792
            surface_bind_and_dirtify(This, !(This->Flags & SFLAG_INTEXTURE));
4793

4794
            surface_download_data(This);
4795
        } else {
4796
            /* Note: It might be faster to download into a texture first. */
4797
            read_from_framebuffer(This, rect,
4798
                                  This->resource.allocatedMemory,
4799
                                  IWineD3DSurface_GetPitch(iface));
4800 4801 4802
        }
    } else if(flag == SFLAG_INDRAWABLE) {
        if(This->Flags & SFLAG_INTEXTURE) {
4803
            surface_blt_to_drawable(This, rect);
4804
        } else {
4805 4806 4807 4808 4809 4810 4811 4812 4813
            if((This->Flags & SFLAG_LOCATIONS) == SFLAG_INSRGBTEX) {
                /* This needs a shader to convert the srgb data sampled from the GL texture into RGB
                 * values, otherwise we get incorrect values in the target. For now go the slow way
                 * via a system memory copy
                 */
                IWineD3DSurfaceImpl_LoadLocation(iface, SFLAG_INSYSMEM, rect);
            }

            d3dfmt_get_conv(This, TRUE /* We need color keying */, FALSE /* We won't use textures */, &format, &internal, &type, &convert, &bpp, FALSE);
4814 4815 4816 4817 4818

            /* The width is in 'length' not in bytes */
            width = This->currentDesc.Width;
            pitch = IWineD3DSurface_GetPitch(iface);

4819 4820 4821 4822
            /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
             * but it isn't set (yet) in all cases it is getting called. */
            if((convert != NO_CONVERSION) && (This->Flags & SFLAG_PBO)) {
                TRACE("Removing the pbo attached to surface %p\n", This);
4823
                if (!device->isInDraw) ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
4824 4825 4826
                surface_remove_pbo(This);
            }

4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851
            if((convert != NO_CONVERSION) && This->resource.allocatedMemory) {
                int height = This->currentDesc.Height;

                /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
                outpitch = width * bpp;
                outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);

                mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
                if(!mem) {
                    ERR("Out of memory %d, %d!\n", outpitch, height);
                    return WINED3DERR_OUTOFVIDEOMEMORY;
                }
                d3dfmt_convert_surface(This->resource.allocatedMemory, mem, pitch, width, height, outpitch, convert, This);

                This->Flags |= SFLAG_CONVERTED;
            } else {
                This->Flags &= ~SFLAG_CONVERTED;
                mem = This->resource.allocatedMemory;
            }

            flush_to_framebuffer_drawpixels(This, format, type, bpp, mem);

            /* Don't delete PBO memory */
            if((mem != This->resource.allocatedMemory) && !(This->Flags & SFLAG_PBO))
                HeapFree(GetProcessHeap(), 0, mem);
4852
        }
4853 4854 4855
    } else /* if(flag & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)) */ {
        if (drawable_read_ok && (This->Flags & SFLAG_INDRAWABLE)) {
            read_from_framebuffer_texture(This, flag == SFLAG_INSRGBTEX);
4856
        } else { /* Upload from system memory */
4857 4858 4859 4860 4861 4862 4863
            BOOL srgb = flag == SFLAG_INSRGBTEX;
            DWORD alloc_flag = srgb ? SFLAG_SRGBALLOCATED : SFLAG_ALLOCATED;
            d3dfmt_get_conv(This, TRUE /* We need color keying */, TRUE /* We will use textures */, &format, &internal, &type, &convert, &bpp, srgb);

            if(srgb) {
                if((This->Flags & (SFLAG_INTEXTURE | SFLAG_INSYSMEM)) == SFLAG_INTEXTURE) {
                    /* Performance warning ... */
4864
                    FIXME("%p: Downloading rgb texture to reload it as srgb\n", This);
4865 4866 4867 4868 4869
                    IWineD3DSurfaceImpl_LoadLocation(iface, SFLAG_INSYSMEM, rect);
                }
            } else {
                if((This->Flags & SFLAG_LOCATIONS) == SFLAG_INSRGBTEX) {
                    /* Performance warning ... */
4870
                    FIXME("%p: Downloading srgb texture to reload it as rgb\n", This);
4871 4872 4873
                    IWineD3DSurfaceImpl_LoadLocation(iface, SFLAG_INSYSMEM, rect);
                }
            }
4874

4875
            if(!device->isInDraw) ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
4876
            surface_bind_and_dirtify(This, srgb);
4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887

            if(This->CKeyFlags & WINEDDSD_CKSRCBLT) {
                This->Flags |= SFLAG_GLCKEY;
                This->glCKey = This->SrcBltCKey;
            }
            else This->Flags &= ~SFLAG_GLCKEY;

            /* The width is in 'length' not in bytes */
            width = This->currentDesc.Width;
            pitch = IWineD3DSurface_GetPitch(iface);

4888 4889 4890 4891 4892 4893 4894
            /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
             * but it isn't set (yet) in all cases it is getting called. */
            if((convert != NO_CONVERSION) && (This->Flags & SFLAG_PBO)) {
                TRACE("Removing the pbo attached to surface %p\n", This);
                surface_remove_pbo(This);
            }

4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909
            if((convert != NO_CONVERSION) && This->resource.allocatedMemory) {
                int height = This->currentDesc.Height;

                /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
                outpitch = width * bpp;
                outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);

                mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
                if(!mem) {
                    ERR("Out of memory %d, %d!\n", outpitch, height);
                    return WINED3DERR_OUTOFVIDEOMEMORY;
                }
                d3dfmt_convert_surface(This->resource.allocatedMemory, mem, pitch, width, height, outpitch, convert, This);

                This->Flags |= SFLAG_CONVERTED;
4910 4911 4912 4913
            }
            else if ((This->resource.format_desc->format == WINED3DFMT_P8)
                    && (GL_SUPPORT(EXT_PALETTED_TEXTURE) || GL_SUPPORT(ARB_FRAGMENT_PROGRAM)))
            {
4914 4915 4916 4917 4918 4919 4920 4921 4922
                d3dfmt_p8_upload_palette(iface, convert);
                This->Flags &= ~SFLAG_CONVERTED;
                mem = This->resource.allocatedMemory;
            } else {
                This->Flags &= ~SFLAG_CONVERTED;
                mem = This->resource.allocatedMemory;
            }

            /* Make sure the correct pitch is used */
4923
            ENTER_GL();
4924
            glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
4925
            LEAVE_GL();
4926 4927 4928

            if ((This->Flags & SFLAG_NONPOW2) && !(This->Flags & SFLAG_OVERSIZE)) {
                TRACE("non power of two support\n");
4929
                if(!(This->Flags & alloc_flag)) {
4930
                    surface_allocate_surface(This, internal, This->pow2Width, This->pow2Height, format, type);
4931
                    This->Flags |= alloc_flag;
4932 4933 4934 4935 4936 4937 4938 4939
                }
                if (mem || (This->Flags & SFLAG_PBO)) {
                    surface_upload_data(This, internal, This->currentDesc.Width, This->currentDesc.Height, format, type, mem);
                }
            } else {
                /* When making the realloc conditional, keep in mind that GL_APPLE_client_storage may be in use, and This->resource.allocatedMemory
                 * changed. So also keep track of memory changes. In this case the texture has to be reallocated
                 */
4940
                if(!(This->Flags & alloc_flag)) {
4941
                    surface_allocate_surface(This, internal, This->glRect.right - This->glRect.left, This->glRect.bottom - This->glRect.top, format, type);
4942
                    This->Flags |= alloc_flag;
4943 4944 4945 4946 4947 4948 4949
                }
                if (mem || (This->Flags & SFLAG_PBO)) {
                    surface_upload_data(This, internal, This->glRect.right - This->glRect.left, This->glRect.bottom - This->glRect.top, format, type, mem);
                }
            }

            /* Restore the default pitch */
4950
            ENTER_GL();
4951
            glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
4952
            LEAVE_GL();
4953 4954 4955 4956

            /* Don't delete PBO memory */
            if((mem != This->resource.allocatedMemory) && !(This->Flags & SFLAG_PBO))
                HeapFree(GetProcessHeap(), 0, mem);
4957 4958 4959
        }
    }

4960 4961
    if(rect == NULL) {
        This->Flags |= flag;
4962 4963
    }

4964
    if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && !(This->Flags & SFLAG_SWAPCHAIN)
4965 4966 4967
            && (This->Flags & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE))) {
        /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
        This->Flags |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4968 4969
    }

4970 4971 4972
    return WINED3D_OK;
}

4973 4974
static HRESULT WINAPI IWineD3DSurfaceImpl_SetContainer(IWineD3DSurface *iface, IWineD3DBase *container)
{
4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
    IWineD3DSwapChain *swapchain = NULL;

    /* Update the drawable size method */
    if(container) {
        IWineD3DBase_QueryInterface(container, &IID_IWineD3DSwapChain, (void **) &swapchain);
    }
    if(swapchain) {
        This->get_drawable_size = get_drawable_size_swapchain;
        IWineD3DSwapChain_Release(swapchain);
    } else if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
        switch(wined3d_settings.offscreen_rendering_mode) {
            case ORM_FBO:        This->get_drawable_size = get_drawable_size_fbo;        break;
            case ORM_PBUFFER:    This->get_drawable_size = get_drawable_size_pbuffer;    break;
            case ORM_BACKBUFFER: This->get_drawable_size = get_drawable_size_backbuffer; break;
        }
    }

    return IWineD3DBaseSurfaceImpl_SetContainer(iface, container);
}

4996 4997 4998 4999
static WINED3DSURFTYPE WINAPI IWineD3DSurfaceImpl_GetImplType(IWineD3DSurface *iface) {
    return SURFACE_OPENGL;
}

5000 5001 5002 5003 5004 5005 5006
static HRESULT WINAPI IWineD3DSurfaceImpl_DrawOverlay(IWineD3DSurface *iface) {
    IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
    HRESULT hr;

    /* If there's no destination surface there is nothing to do */
    if(!This->overlay_dest) return WINED3D_OK;

5007 5008 5009 5010 5011 5012 5013
    /* Blt calls ModifyLocation on the dest surface, which in turn calls DrawOverlay to
     * update the overlay. Prevent an endless recursion
     */
    if(This->overlay_dest->Flags & SFLAG_INOVERLAYDRAW) {
        return WINED3D_OK;
    }
    This->overlay_dest->Flags |= SFLAG_INOVERLAYDRAW;
5014 5015 5016
    hr = IWineD3DSurfaceImpl_Blt((IWineD3DSurface *) This->overlay_dest, &This->overlay_destrect,
                                 iface, &This->overlay_srcrect, WINEDDBLT_WAIT,
                                 NULL, WINED3DTEXF_LINEAR);
5017
    This->overlay_dest->Flags &= ~SFLAG_INOVERLAYDRAW;
5018 5019 5020 5021

    return hr;
}

5022
const IWineD3DSurfaceVtbl IWineD3DSurface_Vtbl =
5023
{
5024
    /* IUnknown */
5025
    IWineD3DBaseSurfaceImpl_QueryInterface,
5026
    IWineD3DBaseSurfaceImpl_AddRef,
5027
    IWineD3DSurfaceImpl_Release,
5028
    /* IWineD3DResource */
5029 5030 5031 5032 5033 5034 5035
    IWineD3DBaseSurfaceImpl_GetParent,
    IWineD3DBaseSurfaceImpl_GetDevice,
    IWineD3DBaseSurfaceImpl_SetPrivateData,
    IWineD3DBaseSurfaceImpl_GetPrivateData,
    IWineD3DBaseSurfaceImpl_FreePrivateData,
    IWineD3DBaseSurfaceImpl_SetPriority,
    IWineD3DBaseSurfaceImpl_GetPriority,
5036
    IWineD3DSurfaceImpl_PreLoad,
5037
    IWineD3DSurfaceImpl_UnLoad,
5038
    IWineD3DBaseSurfaceImpl_GetType,
5039
    /* IWineD3DSurface */
5040 5041
    IWineD3DBaseSurfaceImpl_GetContainer,
    IWineD3DBaseSurfaceImpl_GetDesc,
5042 5043 5044 5045
    IWineD3DSurfaceImpl_LockRect,
    IWineD3DSurfaceImpl_UnlockRect,
    IWineD3DSurfaceImpl_GetDC,
    IWineD3DSurfaceImpl_ReleaseDC,
5046
    IWineD3DSurfaceImpl_Flip,
5047
    IWineD3DSurfaceImpl_Blt,
5048 5049 5050 5051
    IWineD3DBaseSurfaceImpl_GetBltStatus,
    IWineD3DBaseSurfaceImpl_GetFlipStatus,
    IWineD3DBaseSurfaceImpl_IsLost,
    IWineD3DBaseSurfaceImpl_Restore,
5052
    IWineD3DSurfaceImpl_BltFast,
5053 5054
    IWineD3DBaseSurfaceImpl_GetPalette,
    IWineD3DBaseSurfaceImpl_SetPalette,
5055
    IWineD3DSurfaceImpl_RealizePalette,
5056 5057
    IWineD3DBaseSurfaceImpl_SetColorKey,
    IWineD3DBaseSurfaceImpl_GetPitch,
5058
    IWineD3DSurfaceImpl_SetMem,
5059 5060 5061 5062 5063 5064
    IWineD3DBaseSurfaceImpl_SetOverlayPosition,
    IWineD3DBaseSurfaceImpl_GetOverlayPosition,
    IWineD3DBaseSurfaceImpl_UpdateOverlayZOrder,
    IWineD3DBaseSurfaceImpl_UpdateOverlay,
    IWineD3DBaseSurfaceImpl_SetClipper,
    IWineD3DBaseSurfaceImpl_GetClipper,
5065 5066
    /* Internal use: */
    IWineD3DSurfaceImpl_LoadTexture,
5067
    IWineD3DSurfaceImpl_BindTexture,
5068
    IWineD3DSurfaceImpl_SaveSnapshot,
5069
    IWineD3DSurfaceImpl_SetContainer,
5070
    IWineD3DBaseSurfaceImpl_GetData,
5071
    IWineD3DSurfaceImpl_SetFormat,
5072
    IWineD3DSurfaceImpl_PrivateSetup,
5073
    IWineD3DSurfaceImpl_ModifyLocation,
5074
    IWineD3DSurfaceImpl_LoadLocation,
5075 5076
    IWineD3DSurfaceImpl_GetImplType,
    IWineD3DSurfaceImpl_DrawOverlay
5077
};
5078 5079 5080 5081
#undef GLINFO_LOCATION

#define GLINFO_LOCATION device->adapter->gl_info
static HRESULT ffp_blit_alloc(IWineD3DDevice *iface) { return WINED3D_OK; }
5082
/* Context activation is done by the caller. */
5083 5084
static void ffp_blit_free(IWineD3DDevice *iface) { }

5085
/* Context activation is done by the caller. */
5086 5087 5088
static HRESULT ffp_blit_set(IWineD3DDevice *iface, const struct GlPixelFormatDesc *format_desc,
        GLenum textype, UINT width, UINT height)
{
5089
    ENTER_GL();
5090 5091
    glEnable(textype);
    checkGLcall("glEnable(textype)");
5092
    LEAVE_GL();
5093 5094 5095
    return WINED3D_OK;
}

5096
/* Context activation is done by the caller. */
5097 5098
static void ffp_blit_unset(IWineD3DDevice *iface) {
    IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
5099
    ENTER_GL();
5100 5101 5102 5103 5104 5105 5106 5107 5108 5109
    glDisable(GL_TEXTURE_2D);
    checkGLcall("glDisable(GL_TEXTURE_2D)");
    if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
        glDisable(GL_TEXTURE_CUBE_MAP_ARB);
        checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
    }
    if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
        glDisable(GL_TEXTURE_RECTANGLE_ARB);
        checkGLcall("glDisable(GL_TEXTURE_RECTANGLE_ARB)");
    }
5110
    LEAVE_GL();
5111 5112
}

5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128
static BOOL ffp_blit_color_fixup_supported(struct color_fixup_desc fixup)
{
    if (TRACE_ON(d3d_surface) && TRACE_ON(d3d))
    {
        TRACE("Checking support for fixup:\n");
        dump_color_fixup_desc(fixup);
    }

    /* We only support identity conversions. */
    if (is_identity_fixup(fixup))
    {
        TRACE("[OK]\n");
        return TRUE;
    }

    TRACE("[FAILED]\n");
5129 5130 5131
    return FALSE;
}

5132 5133 5134 5135
const struct blit_shader ffp_blit =  {
    ffp_blit_alloc,
    ffp_blit_free,
    ffp_blit_set,
5136
    ffp_blit_unset,
5137
    ffp_blit_color_fixup_supported
5138
};