wined3d: Do not release a reference we do not have in IWineD3DSurfaceImpl_Flip().
[wine] / dlls / wined3d / surface.c
1 /*
2  * IWineD3DSurface Implementation
3  *
4  * Copyright 1998 Lionel Ulmer
5  * Copyright 2000-2001 TransGaming Technologies Inc.
6  * Copyright 2002-2005 Jason Edmeades
7  * Copyright 2002-2003 Raphael Junqueira
8  * 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  * Copyright 2009 Henri Verbeet for CodeWeavers
14  *
15  * This library is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU Lesser General Public
17  * License as published by the Free Software Foundation; either
18  * version 2.1 of the License, or (at your option) any later version.
19  *
20  * This library is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23  * Lesser General Public License for more details.
24  *
25  * You should have received a copy of the GNU Lesser General Public
26  * License along with this library; if not, write to the Free Software
27  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
28  */
29
30 #include "config.h"
31 #include "wine/port.h"
32 #include "wined3d_private.h"
33
34 WINE_DEFAULT_DEBUG_CHANNEL(d3d_surface);
35 WINE_DECLARE_DEBUG_CHANNEL(d3d);
36
37 static void surface_cleanup(IWineD3DSurfaceImpl *This)
38 {
39     TRACE("(%p) : Cleaning up.\n", This);
40
41     if (This->texture_name || (This->Flags & SFLAG_PBO) || !list_empty(&This->renderbuffers))
42     {
43         const struct wined3d_gl_info *gl_info;
44         renderbuffer_entry_t *entry, *entry2;
45         struct wined3d_context *context;
46
47         context = context_acquire(This->resource.device, NULL);
48         gl_info = context->gl_info;
49
50         ENTER_GL();
51
52         if (This->texture_name)
53         {
54             TRACE("Deleting texture %u.\n", This->texture_name);
55             glDeleteTextures(1, &This->texture_name);
56         }
57
58         if (This->Flags & SFLAG_PBO)
59         {
60             TRACE("Deleting PBO %u.\n", This->pbo);
61             GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
62         }
63
64         LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry)
65         {
66             TRACE("Deleting renderbuffer %u.\n", entry->id);
67             gl_info->fbo_ops.glDeleteRenderbuffers(1, &entry->id);
68             HeapFree(GetProcessHeap(), 0, entry);
69         }
70
71         LEAVE_GL();
72
73         context_release(context);
74     }
75
76     if (This->Flags & SFLAG_DIBSECTION)
77     {
78         /* Release the DC. */
79         SelectObject(This->hDC, This->dib.holdbitmap);
80         DeleteDC(This->hDC);
81         /* Release the DIB section. */
82         DeleteObject(This->dib.DIBsection);
83         This->dib.bitmap_data = NULL;
84         This->resource.allocatedMemory = NULL;
85     }
86
87     if (This->Flags & SFLAG_USERPTR) IWineD3DSurface_SetMem((IWineD3DSurface *)This, NULL);
88     if (This->overlay_dest) list_remove(&This->overlay_entry);
89
90     HeapFree(GetProcessHeap(), 0, This->palette9);
91
92     resource_cleanup((IWineD3DResource *)This);
93 }
94
95 void surface_set_container(IWineD3DSurfaceImpl *surface, enum wined3d_container_type type, IWineD3DBase *container)
96 {
97     TRACE("surface %p, container %p.\n", surface, container);
98
99     if (type == WINED3D_CONTAINER_SWAPCHAIN)
100     {
101         surface->get_drawable_size = get_drawable_size_swapchain;
102     }
103     else
104     {
105         switch (wined3d_settings.offscreen_rendering_mode)
106         {
107             case ORM_FBO:
108                 surface->get_drawable_size = get_drawable_size_fbo;
109                 break;
110
111             case ORM_BACKBUFFER:
112                 surface->get_drawable_size = get_drawable_size_backbuffer;
113                 break;
114
115             default:
116                 ERR("Unhandled offscreen rendering mode %#x.\n", wined3d_settings.offscreen_rendering_mode);
117                 return;
118         }
119     }
120
121     surface->container.type = type;
122     surface->container.u.base = container;
123 }
124
125 struct blt_info
126 {
127     GLenum binding;
128     GLenum bind_target;
129     enum tex_types tex_type;
130     GLfloat coords[4][3];
131 };
132
133 struct float_rect
134 {
135     float l;
136     float t;
137     float r;
138     float b;
139 };
140
141 static inline void cube_coords_float(const RECT *r, UINT w, UINT h, struct float_rect *f)
142 {
143     f->l = ((r->left * 2.0f) / w) - 1.0f;
144     f->t = ((r->top * 2.0f) / h) - 1.0f;
145     f->r = ((r->right * 2.0f) / w) - 1.0f;
146     f->b = ((r->bottom * 2.0f) / h) - 1.0f;
147 }
148
149 static void surface_get_blt_info(GLenum target, const RECT *rect_in, GLsizei w, GLsizei h, struct blt_info *info)
150 {
151     GLfloat (*coords)[3] = info->coords;
152     RECT rect;
153     struct float_rect f;
154
155     if (rect_in)
156         rect = *rect_in;
157     else
158     {
159         rect.left = 0;
160         rect.top = h;
161         rect.right = w;
162         rect.bottom = 0;
163     }
164
165     switch (target)
166     {
167         default:
168             FIXME("Unsupported texture target %#x\n", target);
169             /* Fall back to GL_TEXTURE_2D */
170         case GL_TEXTURE_2D:
171             info->binding = GL_TEXTURE_BINDING_2D;
172             info->bind_target = GL_TEXTURE_2D;
173             info->tex_type = tex_2d;
174             coords[0][0] = (float)rect.left / w;
175             coords[0][1] = (float)rect.top / h;
176             coords[0][2] = 0.0f;
177
178             coords[1][0] = (float)rect.right / w;
179             coords[1][1] = (float)rect.top / h;
180             coords[1][2] = 0.0f;
181
182             coords[2][0] = (float)rect.left / w;
183             coords[2][1] = (float)rect.bottom / h;
184             coords[2][2] = 0.0f;
185
186             coords[3][0] = (float)rect.right / w;
187             coords[3][1] = (float)rect.bottom / h;
188             coords[3][2] = 0.0f;
189             break;
190
191         case GL_TEXTURE_RECTANGLE_ARB:
192             info->binding = GL_TEXTURE_BINDING_RECTANGLE_ARB;
193             info->bind_target = GL_TEXTURE_RECTANGLE_ARB;
194             info->tex_type = tex_rect;
195             coords[0][0] = rect.left;   coords[0][1] = rect.top;     coords[0][2] = 0.0f;
196             coords[1][0] = rect.right;  coords[1][1] = rect.top;     coords[1][2] = 0.0f;
197             coords[2][0] = rect.left;   coords[2][1] = rect.bottom;  coords[2][2] = 0.0f;
198             coords[3][0] = rect.right;  coords[3][1] = rect.bottom;  coords[3][2] = 0.0f;
199             break;
200
201         case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
202             info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
203             info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
204             info->tex_type = tex_cube;
205             cube_coords_float(&rect, w, h, &f);
206
207             coords[0][0] =  1.0f;   coords[0][1] = -f.t;   coords[0][2] = -f.l;
208             coords[1][0] =  1.0f;   coords[1][1] = -f.t;   coords[1][2] = -f.r;
209             coords[2][0] =  1.0f;   coords[2][1] = -f.b;   coords[2][2] = -f.l;
210             coords[3][0] =  1.0f;   coords[3][1] = -f.b;   coords[3][2] = -f.r;
211             break;
212
213         case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
214             info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
215             info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
216             info->tex_type = tex_cube;
217             cube_coords_float(&rect, w, h, &f);
218
219             coords[0][0] = -1.0f;   coords[0][1] = -f.t;   coords[0][2] = f.l;
220             coords[1][0] = -1.0f;   coords[1][1] = -f.t;   coords[1][2] = f.r;
221             coords[2][0] = -1.0f;   coords[2][1] = -f.b;   coords[2][2] = f.l;
222             coords[3][0] = -1.0f;   coords[3][1] = -f.b;   coords[3][2] = f.r;
223             break;
224
225         case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
226             info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
227             info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
228             info->tex_type = tex_cube;
229             cube_coords_float(&rect, w, h, &f);
230
231             coords[0][0] = f.l;   coords[0][1] =  1.0f;   coords[0][2] = f.t;
232             coords[1][0] = f.r;   coords[1][1] =  1.0f;   coords[1][2] = f.t;
233             coords[2][0] = f.l;   coords[2][1] =  1.0f;   coords[2][2] = f.b;
234             coords[3][0] = f.r;   coords[3][1] =  1.0f;   coords[3][2] = f.b;
235             break;
236
237         case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
238             info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
239             info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
240             info->tex_type = tex_cube;
241             cube_coords_float(&rect, w, h, &f);
242
243             coords[0][0] = f.l;   coords[0][1] = -1.0f;   coords[0][2] = -f.t;
244             coords[1][0] = f.r;   coords[1][1] = -1.0f;   coords[1][2] = -f.t;
245             coords[2][0] = f.l;   coords[2][1] = -1.0f;   coords[2][2] = -f.b;
246             coords[3][0] = f.r;   coords[3][1] = -1.0f;   coords[3][2] = -f.b;
247             break;
248
249         case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
250             info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
251             info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
252             info->tex_type = tex_cube;
253             cube_coords_float(&rect, w, h, &f);
254
255             coords[0][0] = f.l;   coords[0][1] = -f.t;   coords[0][2] =  1.0f;
256             coords[1][0] = f.r;   coords[1][1] = -f.t;   coords[1][2] =  1.0f;
257             coords[2][0] = f.l;   coords[2][1] = -f.b;   coords[2][2] =  1.0f;
258             coords[3][0] = f.r;   coords[3][1] = -f.b;   coords[3][2] =  1.0f;
259             break;
260
261         case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
262             info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
263             info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
264             info->tex_type = tex_cube;
265             cube_coords_float(&rect, w, h, &f);
266
267             coords[0][0] = -f.l;   coords[0][1] = -f.t;   coords[0][2] = -1.0f;
268             coords[1][0] = -f.r;   coords[1][1] = -f.t;   coords[1][2] = -1.0f;
269             coords[2][0] = -f.l;   coords[2][1] = -f.b;   coords[2][2] = -1.0f;
270             coords[3][0] = -f.r;   coords[3][1] = -f.b;   coords[3][2] = -1.0f;
271             break;
272     }
273 }
274
275 static inline void surface_get_rect(IWineD3DSurfaceImpl *This, const RECT *rect_in, RECT *rect_out)
276 {
277     if (rect_in)
278         *rect_out = *rect_in;
279     else
280     {
281         rect_out->left = 0;
282         rect_out->top = 0;
283         rect_out->right = This->currentDesc.Width;
284         rect_out->bottom = This->currentDesc.Height;
285     }
286 }
287
288 /* GL locking and context activation is done by the caller */
289 void draw_textured_quad(IWineD3DSurfaceImpl *src_surface, const RECT *src_rect, const RECT *dst_rect, WINED3DTEXTUREFILTERTYPE Filter)
290 {
291     struct blt_info info;
292
293     surface_get_blt_info(src_surface->texture_target, src_rect, src_surface->pow2Width, src_surface->pow2Height, &info);
294
295     glEnable(info.bind_target);
296     checkGLcall("glEnable(bind_target)");
297
298     /* Bind the texture */
299     glBindTexture(info.bind_target, src_surface->texture_name);
300     checkGLcall("glBindTexture");
301
302     /* Filtering for StretchRect */
303     glTexParameteri(info.bind_target, GL_TEXTURE_MAG_FILTER,
304             wined3d_gl_mag_filter(magLookup, Filter));
305     checkGLcall("glTexParameteri");
306     glTexParameteri(info.bind_target, GL_TEXTURE_MIN_FILTER,
307             wined3d_gl_min_mip_filter(minMipLookup, Filter, WINED3DTEXF_NONE));
308     checkGLcall("glTexParameteri");
309     glTexParameteri(info.bind_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
310     glTexParameteri(info.bind_target, GL_TEXTURE_WRAP_T, GL_CLAMP);
311     glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
312     checkGLcall("glTexEnvi");
313
314     /* Draw a quad */
315     glBegin(GL_TRIANGLE_STRIP);
316     glTexCoord3fv(info.coords[0]);
317     glVertex2i(dst_rect->left, dst_rect->top);
318
319     glTexCoord3fv(info.coords[1]);
320     glVertex2i(dst_rect->right, dst_rect->top);
321
322     glTexCoord3fv(info.coords[2]);
323     glVertex2i(dst_rect->left, dst_rect->bottom);
324
325     glTexCoord3fv(info.coords[3]);
326     glVertex2i(dst_rect->right, dst_rect->bottom);
327     glEnd();
328
329     /* Unbind the texture */
330     glBindTexture(info.bind_target, 0);
331     checkGLcall("glBindTexture(info->bind_target, 0)");
332
333     /* We changed the filtering settings on the texture. Inform the
334      * container about this to get the filters reset properly next draw. */
335     if (src_surface->container.type == WINED3D_CONTAINER_TEXTURE)
336     {
337         IWineD3DBaseTextureImpl *texture = src_surface->container.u.texture;
338         texture->baseTexture.texture_rgb.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
339         texture->baseTexture.texture_rgb.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
340         texture->baseTexture.texture_rgb.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
341     }
342 }
343
344 HRESULT surface_init(IWineD3DSurfaceImpl *surface, WINED3DSURFTYPE surface_type, UINT alignment,
345         UINT width, UINT height, UINT level, BOOL lockable, BOOL discard, WINED3DMULTISAMPLE_TYPE multisample_type,
346         UINT multisample_quality, IWineD3DDeviceImpl *device, DWORD usage, WINED3DFORMAT format,
347         WINED3DPOOL pool, IUnknown *parent, const struct wined3d_parent_ops *parent_ops)
348 {
349     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
350     const struct wined3d_format_desc *format_desc = getFormatDescEntry(format, gl_info);
351     void (*cleanup)(IWineD3DSurfaceImpl *This);
352     unsigned int resource_size;
353     HRESULT hr;
354
355     if (multisample_quality > 0)
356     {
357         FIXME("multisample_quality set to %u, substituting 0\n", multisample_quality);
358         multisample_quality = 0;
359     }
360
361     /* FIXME: Check that the format is supported by the device. */
362
363     resource_size = wined3d_format_calculate_size(format_desc, alignment, width, height);
364
365     /* Look at the implementation and set the correct Vtable. */
366     switch (surface_type)
367     {
368         case SURFACE_OPENGL:
369             surface->lpVtbl = &IWineD3DSurface_Vtbl;
370             cleanup = surface_cleanup;
371             break;
372
373         case SURFACE_GDI:
374             surface->lpVtbl = &IWineGDISurface_Vtbl;
375             cleanup = surface_gdi_cleanup;
376             break;
377
378         default:
379             ERR("Requested unknown surface implementation %#x.\n", surface_type);
380             return WINED3DERR_INVALIDCALL;
381     }
382
383     hr = resource_init((IWineD3DResource *)surface, WINED3DRTYPE_SURFACE,
384             device, resource_size, usage, format_desc, pool, parent, parent_ops);
385     if (FAILED(hr))
386     {
387         WARN("Failed to initialize resource, returning %#x.\n", hr);
388         return hr;
389     }
390
391     /* "Standalone" surface. */
392     surface_set_container(surface, WINED3D_CONTAINER_NONE, NULL);
393
394     surface->currentDesc.Width = width;
395     surface->currentDesc.Height = height;
396     surface->currentDesc.MultiSampleType = multisample_type;
397     surface->currentDesc.MultiSampleQuality = multisample_quality;
398     surface->texture_level = level;
399     list_init(&surface->overlays);
400
401     /* Flags */
402     surface->Flags = SFLAG_NORMCOORD; /* Default to normalized coords. */
403     if (discard) surface->Flags |= SFLAG_DISCARD;
404     if (lockable || format == WINED3DFMT_D16_LOCKABLE) surface->Flags |= SFLAG_LOCKABLE;
405
406     /* Quick lockable sanity check.
407      * TODO: remove this after surfaces, usage and lockability have been debugged properly
408      * this function is too deep to need to care about things like this.
409      * Levels need to be checked too, since they all affect what can be done. */
410     switch (pool)
411     {
412         case WINED3DPOOL_SCRATCH:
413             if(!lockable)
414             {
415                 FIXME("Called with a pool of SCRATCH and a lockable of FALSE "
416                         "which are mutually exclusive, setting lockable to TRUE.\n");
417                 lockable = TRUE;
418             }
419             break;
420
421         case WINED3DPOOL_SYSTEMMEM:
422             if (!lockable)
423                 FIXME("Called with a pool of SYSTEMMEM and a lockable of FALSE, this is acceptable but unexpected.\n");
424             break;
425
426         case WINED3DPOOL_MANAGED:
427             if (usage & WINED3DUSAGE_DYNAMIC)
428                 FIXME("Called with a pool of MANAGED and a usage of DYNAMIC which are mutually exclusive.\n");
429             break;
430
431         case WINED3DPOOL_DEFAULT:
432             if (lockable && !(usage & (WINED3DUSAGE_DYNAMIC | WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL)))
433                 WARN("Creating a lockable surface with a POOL of DEFAULT, that doesn't specify DYNAMIC usage.\n");
434             break;
435
436         default:
437             FIXME("Unknown pool %#x.\n", pool);
438             break;
439     };
440
441     if (usage & WINED3DUSAGE_RENDERTARGET && pool != WINED3DPOOL_DEFAULT)
442     {
443         FIXME("Trying to create a render target that isn't in the default pool.\n");
444     }
445
446     /* Mark the texture as dirty so that it gets loaded first time around. */
447     surface_add_dirty_rect(surface, NULL);
448     list_init(&surface->renderbuffers);
449
450     TRACE("surface %p, memory %p, size %u\n", surface, surface->resource.allocatedMemory, surface->resource.size);
451
452     /* Call the private setup routine */
453     hr = IWineD3DSurface_PrivateSetup((IWineD3DSurface *)surface);
454     if (FAILED(hr))
455     {
456         ERR("Private setup failed, returning %#x\n", hr);
457         cleanup(surface);
458         return hr;
459     }
460
461     return hr;
462 }
463
464 static void surface_force_reload(IWineD3DSurfaceImpl *surface)
465 {
466     surface->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
467 }
468
469 void surface_set_texture_name(IWineD3DSurfaceImpl *surface, GLuint new_name, BOOL srgb)
470 {
471     GLuint *name;
472     DWORD flag;
473
474     TRACE("surface %p, new_name %u, srgb %#x.\n", surface, new_name, srgb);
475
476     if(srgb)
477     {
478         name = &surface->texture_name_srgb;
479         flag = SFLAG_INSRGBTEX;
480     }
481     else
482     {
483         name = &surface->texture_name;
484         flag = SFLAG_INTEXTURE;
485     }
486
487     if (!*name && new_name)
488     {
489         /* FIXME: We shouldn't need to remove SFLAG_INTEXTURE if the
490          * surface has no texture name yet. See if we can get rid of this. */
491         if (surface->Flags & flag)
492             ERR("Surface has %s set, but no texture name.\n", debug_surflocation(flag));
493         surface_modify_location(surface, flag, FALSE);
494     }
495
496     *name = new_name;
497     surface_force_reload(surface);
498 }
499
500 void surface_set_texture_target(IWineD3DSurfaceImpl *surface, GLenum target)
501 {
502     TRACE("surface %p, target %#x.\n", surface, target);
503
504     if (surface->texture_target != target)
505     {
506         if (target == GL_TEXTURE_RECTANGLE_ARB)
507         {
508             surface->Flags &= ~SFLAG_NORMCOORD;
509         }
510         else if (surface->texture_target == GL_TEXTURE_RECTANGLE_ARB)
511         {
512             surface->Flags |= SFLAG_NORMCOORD;
513         }
514     }
515     surface->texture_target = target;
516     surface_force_reload(surface);
517 }
518
519 /* Context activation is done by the caller. */
520 static void surface_bind_and_dirtify(IWineD3DSurfaceImpl *This, BOOL srgb) {
521     DWORD active_sampler;
522
523     /* We don't need a specific texture unit, but after binding the texture the current unit is dirty.
524      * Read the unit back instead of switching to 0, this avoids messing around with the state manager's
525      * gl states. The current texture unit should always be a valid one.
526      *
527      * To be more specific, this is tricky because we can implicitly be called
528      * from sampler() in state.c. This means we can't touch anything other than
529      * whatever happens to be the currently active texture, or we would risk
530      * marking already applied sampler states dirty again.
531      *
532      * TODO: Track the current active texture per GL context instead of using glGet
533      */
534     GLint active_texture;
535     ENTER_GL();
536     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
537     LEAVE_GL();
538     active_sampler = This->resource.device->rev_tex_unit_map[active_texture - GL_TEXTURE0_ARB];
539
540     if (active_sampler != WINED3D_UNMAPPED_STAGE)
541     {
542         IWineD3DDeviceImpl_MarkStateDirty(This->resource.device, STATE_SAMPLER(active_sampler));
543     }
544     IWineD3DSurface_BindTexture((IWineD3DSurface *)This, srgb);
545 }
546
547 /* This function checks if the primary render target uses the 8bit paletted format. */
548 static BOOL primary_render_target_is_p8(IWineD3DDeviceImpl *device)
549 {
550     if (device->render_targets && device->render_targets[0])
551     {
552         IWineD3DSurfaceImpl *render_target = device->render_targets[0];
553         if ((render_target->resource.usage & WINED3DUSAGE_RENDERTARGET)
554                 && (render_target->resource.format_desc->format == WINED3DFMT_P8_UINT))
555             return TRUE;
556     }
557     return FALSE;
558 }
559
560 /* This call just downloads data, the caller is responsible for binding the
561  * correct texture. */
562 /* Context activation is done by the caller. */
563 static void surface_download_data(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info)
564 {
565     const struct wined3d_format_desc *format_desc = This->resource.format_desc;
566
567     /* Only support read back of converted P8 surfaces */
568     if (This->Flags & SFLAG_CONVERTED && format_desc->format != WINED3DFMT_P8_UINT)
569     {
570         FIXME("Read back converted textures unsupported, format=%s\n", debug_d3dformat(format_desc->format));
571         return;
572     }
573
574     ENTER_GL();
575
576     if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
577     {
578         TRACE("(%p) : Calling glGetCompressedTexImageARB level %d, format %#x, type %#x, data %p.\n",
579                 This, This->texture_level, format_desc->glFormat, format_desc->glType,
580                 This->resource.allocatedMemory);
581
582         if (This->Flags & SFLAG_PBO)
583         {
584             GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
585             checkGLcall("glBindBufferARB");
586             GL_EXTCALL(glGetCompressedTexImageARB(This->texture_target, This->texture_level, NULL));
587             checkGLcall("glGetCompressedTexImageARB");
588             GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
589             checkGLcall("glBindBufferARB");
590         }
591         else
592         {
593             GL_EXTCALL(glGetCompressedTexImageARB(This->texture_target,
594                     This->texture_level, This->resource.allocatedMemory));
595             checkGLcall("glGetCompressedTexImageARB");
596         }
597
598         LEAVE_GL();
599     } else {
600         void *mem;
601         GLenum format = format_desc->glFormat;
602         GLenum type = format_desc->glType;
603         int src_pitch = 0;
604         int dst_pitch = 0;
605
606         /* In case of P8 the index is stored in the alpha component if the primary render target uses P8 */
607         if (format_desc->format == WINED3DFMT_P8_UINT && primary_render_target_is_p8(This->resource.device))
608         {
609             format = GL_ALPHA;
610             type = GL_UNSIGNED_BYTE;
611         }
612
613         if (This->Flags & SFLAG_NONPOW2) {
614             unsigned char alignment = This->resource.device->surface_alignment;
615             src_pitch = format_desc->byte_count * This->pow2Width;
616             dst_pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This);
617             src_pitch = (src_pitch + alignment - 1) & ~(alignment - 1);
618             mem = HeapAlloc(GetProcessHeap(), 0, src_pitch * This->pow2Height);
619         } else {
620             mem = This->resource.allocatedMemory;
621         }
622
623         TRACE("(%p) : Calling glGetTexImage level %d, format %#x, type %#x, data %p\n",
624                 This, This->texture_level, format, type, mem);
625
626         if(This->Flags & SFLAG_PBO) {
627             GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
628             checkGLcall("glBindBufferARB");
629
630             glGetTexImage(This->texture_target, This->texture_level, format, type, NULL);
631             checkGLcall("glGetTexImage");
632
633             GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
634             checkGLcall("glBindBufferARB");
635         } else {
636             glGetTexImage(This->texture_target, This->texture_level, format, type, mem);
637             checkGLcall("glGetTexImage");
638         }
639         LEAVE_GL();
640
641         if (This->Flags & SFLAG_NONPOW2) {
642             const BYTE *src_data;
643             BYTE *dst_data;
644             UINT y;
645             /*
646              * Some games (e.g. warhammer 40k) don't work properly with the odd pitches, preventing
647              * the surface pitch from being used to box non-power2 textures. Instead we have to use a hack to
648              * repack the texture so that the bpp * width pitch can be used instead of bpp * pow2width.
649              *
650              * We're doing this...
651              *
652              * instead of boxing the texture :
653              * |<-texture width ->|  -->pow2width|   /\
654              * |111111111111111111|              |   |
655              * |222 Texture 222222| boxed empty  | texture height
656              * |3333 Data 33333333|              |   |
657              * |444444444444444444|              |   \/
658              * -----------------------------------   |
659              * |     boxed  empty | boxed empty  | pow2height
660              * |                  |              |   \/
661              * -----------------------------------
662              *
663              *
664              * we're repacking the data to the expected texture width
665              *
666              * |<-texture width ->|  -->pow2width|   /\
667              * |111111111111111111222222222222222|   |
668              * |222333333333333333333444444444444| texture height
669              * |444444                           |   |
670              * |                                 |   \/
671              * |                                 |   |
672              * |            empty                | pow2height
673              * |                                 |   \/
674              * -----------------------------------
675              *
676              * == is the same as
677              *
678              * |<-texture width ->|    /\
679              * |111111111111111111|
680              * |222222222222222222|texture height
681              * |333333333333333333|
682              * |444444444444444444|    \/
683              * --------------------
684              *
685              * this also means that any references to allocatedMemory should work with the data as if were a
686              * standard texture with a non-power2 width instead of texture boxed up to be a power2 texture.
687              *
688              * internally the texture is still stored in a boxed format so any references to textureName will
689              * get a boxed texture with width pow2width and not a texture of width currentDesc.Width.
690              *
691              * Performance should not be an issue, because applications normally do not lock the surfaces when
692              * rendering. If an app does, the SFLAG_DYNLOCK flag will kick in and the memory copy won't be released,
693              * and doesn't have to be re-read.
694              */
695             src_data = mem;
696             dst_data = This->resource.allocatedMemory;
697             TRACE("(%p) : Repacking the surface data from pitch %d to pitch %d\n", This, src_pitch, dst_pitch);
698             for (y = 1 ; y < This->currentDesc.Height; y++) {
699                 /* skip the first row */
700                 src_data += src_pitch;
701                 dst_data += dst_pitch;
702                 memcpy(dst_data, src_data, dst_pitch);
703             }
704
705             HeapFree(GetProcessHeap(), 0, mem);
706         }
707     }
708
709     /* Surface has now been downloaded */
710     This->Flags |= SFLAG_INSYSMEM;
711 }
712
713 /* This call just uploads data, the caller is responsible for binding the
714  * correct texture. */
715 /* Context activation is done by the caller. */
716 static void surface_upload_data(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info,
717         const struct wined3d_format_desc *format_desc, BOOL srgb, const GLvoid *data)
718 {
719     GLsizei width = This->currentDesc.Width;
720     GLsizei height = This->currentDesc.Height;
721     GLenum internal;
722
723     if (srgb)
724     {
725         internal = format_desc->glGammaInternal;
726     }
727     else if (This->resource.usage & WINED3DUSAGE_RENDERTARGET && surface_is_offscreen(This))
728     {
729         internal = format_desc->rtInternal;
730     }
731     else
732     {
733         internal = format_desc->glInternal;
734     }
735
736     TRACE("This %p, internal %#x, width %d, height %d, format %#x, type %#x, data %p.\n",
737             This, internal, width, height, format_desc->glFormat, format_desc->glType, data);
738     TRACE("target %#x, level %u, resource size %u.\n",
739             This->texture_target, This->texture_level, This->resource.size);
740
741     if (format_desc->heightscale != 1.0f && format_desc->heightscale != 0.0f) height *= format_desc->heightscale;
742
743     ENTER_GL();
744
745     if (This->Flags & SFLAG_PBO)
746     {
747         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
748         checkGLcall("glBindBufferARB");
749
750         TRACE("(%p) pbo: %#x, data: %p.\n", This, This->pbo, data);
751         data = NULL;
752     }
753
754     if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
755     {
756         TRACE("Calling glCompressedTexSubImage2DARB.\n");
757
758         GL_EXTCALL(glCompressedTexSubImage2DARB(This->texture_target, This->texture_level,
759                 0, 0, width, height, internal, This->resource.size, data));
760         checkGLcall("glCompressedTexSubImage2DARB");
761     }
762     else
763     {
764         TRACE("Calling glTexSubImage2D.\n");
765
766         glTexSubImage2D(This->texture_target, This->texture_level,
767                 0, 0, width, height, format_desc->glFormat, format_desc->glType, data);
768         checkGLcall("glTexSubImage2D");
769     }
770
771     if (This->Flags & SFLAG_PBO)
772     {
773         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
774         checkGLcall("glBindBufferARB");
775     }
776
777     LEAVE_GL();
778
779     if (gl_info->quirks & WINED3D_QUIRK_FBO_TEX_UPDATE)
780     {
781         IWineD3DDeviceImpl *device = This->resource.device;
782         unsigned int i;
783
784         for (i = 0; i < device->numContexts; ++i)
785         {
786             context_surface_update(device->contexts[i], This);
787         }
788     }
789 }
790
791 /* This call just allocates the texture, the caller is responsible for binding
792  * the correct texture. */
793 /* Context activation is done by the caller. */
794 static void surface_allocate_surface(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info,
795         const struct wined3d_format_desc *format_desc, BOOL srgb)
796 {
797     BOOL enable_client_storage = FALSE;
798     GLsizei width = This->pow2Width;
799     GLsizei height = This->pow2Height;
800     const BYTE *mem = NULL;
801     GLenum internal;
802
803     if (srgb)
804     {
805         internal = format_desc->glGammaInternal;
806     }
807     else if (This->resource.usage & WINED3DUSAGE_RENDERTARGET && surface_is_offscreen(This))
808     {
809         internal = format_desc->rtInternal;
810     }
811     else
812     {
813         internal = format_desc->glInternal;
814     }
815
816     if (format_desc->heightscale != 1.0f && format_desc->heightscale != 0.0f) height *= format_desc->heightscale;
817
818     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",
819             This, This->texture_target, This->texture_level, debug_d3dformat(format_desc->format),
820             internal, width, height, format_desc->glFormat, format_desc->glType);
821
822     ENTER_GL();
823
824     if (gl_info->supported[APPLE_CLIENT_STORAGE])
825     {
826         if(This->Flags & (SFLAG_NONPOW2 | SFLAG_DIBSECTION | SFLAG_CONVERTED) || This->resource.allocatedMemory == NULL) {
827             /* In some cases we want to disable client storage.
828              * SFLAG_NONPOW2 has a bigger opengl texture than the client memory, and different pitches
829              * SFLAG_DIBSECTION: Dibsections may have read / write protections on the memory. Avoid issues...
830              * SFLAG_CONVERTED: The conversion destination memory is freed after loading the surface
831              * allocatedMemory == NULL: Not defined in the extension. Seems to disable client storage effectively
832              */
833             glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
834             checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
835             This->Flags &= ~SFLAG_CLIENT;
836             enable_client_storage = TRUE;
837         } else {
838             This->Flags |= SFLAG_CLIENT;
839
840             /* Point opengl to our allocated texture memory. Do not use resource.allocatedMemory here because
841              * it might point into a pbo. Instead use heapMemory, but get the alignment right.
842              */
843             mem = (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
844         }
845     }
846
847     if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED && mem)
848     {
849         GL_EXTCALL(glCompressedTexImage2DARB(This->texture_target, This->texture_level,
850                 internal, width, height, 0, This->resource.size, mem));
851         checkGLcall("glCompressedTexImage2DARB");
852     }
853     else
854     {
855         glTexImage2D(This->texture_target, This->texture_level,
856                 internal, width, height, 0, format_desc->glFormat, format_desc->glType, mem);
857         checkGLcall("glTexImage2D");
858     }
859
860     if(enable_client_storage) {
861         glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
862         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
863     }
864     LEAVE_GL();
865 }
866
867 /* In D3D the depth stencil dimensions have to be greater than or equal to the
868  * render target dimensions. With FBOs, the dimensions have to be an exact match. */
869 /* TODO: We should synchronize the renderbuffer's content with the texture's content. */
870 /* GL locking is done by the caller */
871 void surface_set_compatible_renderbuffer(IWineD3DSurfaceImpl *surface, unsigned int width, unsigned int height)
872 {
873     const struct wined3d_gl_info *gl_info = &surface->resource.device->adapter->gl_info;
874     renderbuffer_entry_t *entry;
875     GLuint renderbuffer = 0;
876     unsigned int src_width, src_height;
877
878     src_width = surface->pow2Width;
879     src_height = surface->pow2Height;
880
881     /* A depth stencil smaller than the render target is not valid */
882     if (width > src_width || height > src_height) return;
883
884     /* Remove any renderbuffer set if the sizes match */
885     if (gl_info->supported[ARB_FRAMEBUFFER_OBJECT]
886             || (width == src_width && height == src_height))
887     {
888         surface->current_renderbuffer = NULL;
889         return;
890     }
891
892     /* Look if we've already got a renderbuffer of the correct dimensions */
893     LIST_FOR_EACH_ENTRY(entry, &surface->renderbuffers, renderbuffer_entry_t, entry)
894     {
895         if (entry->width == width && entry->height == height)
896         {
897             renderbuffer = entry->id;
898             surface->current_renderbuffer = entry;
899             break;
900         }
901     }
902
903     if (!renderbuffer)
904     {
905         gl_info->fbo_ops.glGenRenderbuffers(1, &renderbuffer);
906         gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
907         gl_info->fbo_ops.glRenderbufferStorage(GL_RENDERBUFFER,
908                 surface->resource.format_desc->glInternal, width, height);
909
910         entry = HeapAlloc(GetProcessHeap(), 0, sizeof(renderbuffer_entry_t));
911         entry->width = width;
912         entry->height = height;
913         entry->id = renderbuffer;
914         list_add_head(&surface->renderbuffers, &entry->entry);
915
916         surface->current_renderbuffer = entry;
917     }
918
919     checkGLcall("set_compatible_renderbuffer");
920 }
921
922 GLenum surface_get_gl_buffer(IWineD3DSurfaceImpl *surface)
923 {
924     IWineD3DSwapChainImpl *swapchain = surface->container.u.swapchain;
925
926     TRACE("surface %p.\n", surface);
927
928     if (surface->container.type != WINED3D_CONTAINER_SWAPCHAIN)
929     {
930         ERR("Surface %p is not on a swapchain.\n", surface);
931         return GL_NONE;
932     }
933
934     if (swapchain->back_buffers && swapchain->back_buffers[0] == surface)
935     {
936         if (swapchain->render_to_fbo)
937         {
938             TRACE("Returning GL_COLOR_ATTACHMENT0\n");
939             return GL_COLOR_ATTACHMENT0;
940         }
941         TRACE("Returning GL_BACK\n");
942         return GL_BACK;
943     }
944     else if (surface == swapchain->front_buffer)
945     {
946         TRACE("Returning GL_FRONT\n");
947         return GL_FRONT;
948     }
949
950     FIXME("Higher back buffer, returning GL_BACK\n");
951     return GL_BACK;
952 }
953
954 /* Slightly inefficient way to handle multiple dirty rects but it works :) */
955 void surface_add_dirty_rect(IWineD3DSurfaceImpl *surface, const RECT *dirty_rect)
956 {
957     TRACE("surface %p, dirty_rect %s.\n", surface, wine_dbgstr_rect(dirty_rect));
958
959     if (!(surface->Flags & SFLAG_INSYSMEM) && (surface->Flags & SFLAG_INTEXTURE))
960         /* No partial locking for textures yet. */
961         surface_load_location(surface, SFLAG_INSYSMEM, NULL);
962
963     surface_modify_location(surface, SFLAG_INSYSMEM, TRUE);
964     if (dirty_rect)
965     {
966         surface->dirtyRect.left = min(surface->dirtyRect.left, dirty_rect->left);
967         surface->dirtyRect.top = min(surface->dirtyRect.top, dirty_rect->top);
968         surface->dirtyRect.right = max(surface->dirtyRect.right, dirty_rect->right);
969         surface->dirtyRect.bottom = max(surface->dirtyRect.bottom, dirty_rect->bottom);
970     }
971     else
972     {
973         surface->dirtyRect.left = 0;
974         surface->dirtyRect.top = 0;
975         surface->dirtyRect.right = surface->currentDesc.Width;
976         surface->dirtyRect.bottom = surface->currentDesc.Height;
977     }
978
979     /* if the container is a basetexture then mark it dirty. */
980     if (surface->container.type == WINED3D_CONTAINER_TEXTURE)
981     {
982         TRACE("Passing to container.\n");
983         IWineD3DBaseTexture_SetDirty((IWineD3DBaseTexture *)surface->container.u.texture, TRUE);
984     }
985 }
986
987 static BOOL surface_convert_color_to_argb(IWineD3DSurfaceImpl *This, DWORD color, DWORD *argb_color)
988 {
989     IWineD3DDeviceImpl *device = This->resource.device;
990
991     switch(This->resource.format_desc->format)
992     {
993         case WINED3DFMT_P8_UINT:
994             {
995                 DWORD alpha;
996
997                 if (primary_render_target_is_p8(device))
998                     alpha = color << 24;
999                 else
1000                     alpha = 0xFF000000;
1001
1002                 if (This->palette) {
1003                     *argb_color = (alpha |
1004                             (This->palette->palents[color].peRed << 16) |
1005                             (This->palette->palents[color].peGreen << 8) |
1006                             (This->palette->palents[color].peBlue));
1007                 } else {
1008                     *argb_color = alpha;
1009                 }
1010             }
1011             break;
1012
1013         case WINED3DFMT_B5G6R5_UNORM:
1014             {
1015                 if (color == 0xFFFF) {
1016                     *argb_color = 0xFFFFFFFF;
1017                 } else {
1018                     *argb_color = ((0xFF000000) |
1019                             ((color & 0xF800) << 8) |
1020                             ((color & 0x07E0) << 5) |
1021                             ((color & 0x001F) << 3));
1022                 }
1023             }
1024             break;
1025
1026         case WINED3DFMT_B8G8R8_UNORM:
1027         case WINED3DFMT_B8G8R8X8_UNORM:
1028             *argb_color = 0xFF000000 | color;
1029             break;
1030
1031         case WINED3DFMT_B8G8R8A8_UNORM:
1032             *argb_color = color;
1033             break;
1034
1035         default:
1036             ERR("Unhandled conversion from %s to ARGB!\n", debug_d3dformat(This->resource.format_desc->format));
1037             return FALSE;
1038     }
1039     return TRUE;
1040 }
1041
1042 static ULONG WINAPI IWineD3DSurfaceImpl_Release(IWineD3DSurface *iface)
1043 {
1044     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1045     ULONG ref = InterlockedDecrement(&This->resource.ref);
1046     TRACE("(%p) : Releasing from %d\n", This, ref + 1);
1047
1048     if (!ref)
1049     {
1050         surface_cleanup(This);
1051         This->resource.parent_ops->wined3d_object_destroyed(This->resource.parent);
1052
1053         TRACE("(%p) Released.\n", This);
1054         HeapFree(GetProcessHeap(), 0, This);
1055     }
1056
1057     return ref;
1058 }
1059
1060 /* ****************************************************
1061    IWineD3DSurface IWineD3DResource parts follow
1062    **************************************************** */
1063
1064 void surface_internal_preload(IWineD3DSurfaceImpl *surface, enum WINED3DSRGB srgb)
1065 {
1066     IWineD3DDeviceImpl *device = surface->resource.device;
1067
1068     TRACE("iface %p, srgb %#x.\n", surface, srgb);
1069
1070     if (surface->container.type == WINED3D_CONTAINER_TEXTURE)
1071     {
1072         IWineD3DBaseTextureImpl *texture = surface->container.u.texture;
1073
1074         TRACE("Passing to container.\n");
1075         texture->baseTexture.internal_preload((IWineD3DBaseTexture *)texture, srgb);
1076     }
1077     else
1078     {
1079         struct wined3d_context *context = NULL;
1080
1081         TRACE("(%p) : About to load surface\n", surface);
1082
1083         if (!device->isInDraw) context = context_acquire(device, NULL);
1084
1085         if (surface->resource.format_desc->format == WINED3DFMT_P8_UINT
1086                 || surface->resource.format_desc->format == WINED3DFMT_P8_UINT_A8_UNORM)
1087         {
1088             if (palette9_changed(surface))
1089             {
1090                 TRACE("Reloading surface because the d3d8/9 palette was changed\n");
1091                 /* TODO: This is not necessarily needed with hw palettized texture support */
1092                 surface_load_location(surface, SFLAG_INSYSMEM, NULL);
1093                 /* Make sure the texture is reloaded because of the palette change, this kills performance though :( */
1094                 surface_modify_location(surface, SFLAG_INTEXTURE, FALSE);
1095             }
1096         }
1097
1098         IWineD3DSurface_LoadTexture((IWineD3DSurface *)surface, srgb == SRGB_SRGB ? TRUE : FALSE);
1099
1100         if (surface->resource.pool == WINED3DPOOL_DEFAULT)
1101         {
1102             /* Tell opengl to try and keep this texture in video ram (well mostly) */
1103             GLclampf tmp;
1104             tmp = 0.9f;
1105             ENTER_GL();
1106             glPrioritizeTextures(1, &surface->texture_name, &tmp);
1107             LEAVE_GL();
1108         }
1109
1110         if (context) context_release(context);
1111     }
1112 }
1113
1114 static void WINAPI IWineD3DSurfaceImpl_PreLoad(IWineD3DSurface *iface)
1115 {
1116     surface_internal_preload((IWineD3DSurfaceImpl *)iface, SRGB_ANY);
1117 }
1118
1119 /* Context activation is done by the caller. */
1120 static void surface_remove_pbo(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info)
1121 {
1122     This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
1123     This->resource.allocatedMemory =
1124             (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1125
1126     ENTER_GL();
1127     GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1128     checkGLcall("glBindBufferARB(GL_PIXEL_UNPACK_BUFFER, This->pbo)");
1129     GL_EXTCALL(glGetBufferSubDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0, This->resource.size, This->resource.allocatedMemory));
1130     checkGLcall("glGetBufferSubDataARB");
1131     GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
1132     checkGLcall("glDeleteBuffersARB");
1133     LEAVE_GL();
1134
1135     This->pbo = 0;
1136     This->Flags &= ~SFLAG_PBO;
1137 }
1138
1139 BOOL surface_init_sysmem(IWineD3DSurfaceImpl *surface)
1140 {
1141     if (!surface->resource.allocatedMemory)
1142     {
1143         surface->resource.heapMemory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1144                 surface->resource.size + RESOURCE_ALIGNMENT);
1145         if (!surface->resource.heapMemory)
1146         {
1147             ERR("Out of memory\n");
1148             return FALSE;
1149         }
1150         surface->resource.allocatedMemory =
1151             (BYTE *)(((ULONG_PTR)surface->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1152     }
1153     else
1154     {
1155         memset(surface->resource.allocatedMemory, 0, surface->resource.size);
1156     }
1157
1158     surface_modify_location(surface, SFLAG_INSYSMEM, TRUE);
1159
1160     return TRUE;
1161 }
1162
1163 static void WINAPI IWineD3DSurfaceImpl_UnLoad(IWineD3DSurface *iface)
1164 {
1165     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
1166     IWineD3DDeviceImpl *device = This->resource.device;
1167     const struct wined3d_gl_info *gl_info;
1168     renderbuffer_entry_t *entry, *entry2;
1169     struct wined3d_context *context;
1170
1171     TRACE("(%p)\n", iface);
1172
1173     if(This->resource.pool == WINED3DPOOL_DEFAULT) {
1174         /* Default pool resources are supposed to be destroyed before Reset is called.
1175          * Implicit resources stay however. So this means we have an implicit render target
1176          * or depth stencil. The content may be destroyed, but we still have to tear down
1177          * opengl resources, so we cannot leave early.
1178          *
1179          * Put the surfaces into sysmem, and reset the content. The D3D content is undefined,
1180          * but we can't set the sysmem INDRAWABLE because when we're rendering the swapchain
1181          * or the depth stencil into an FBO the texture or render buffer will be removed
1182          * and all flags get lost
1183          */
1184         surface_init_sysmem(This);
1185     }
1186     else
1187     {
1188         /* Load the surface into system memory */
1189         surface_load_location(This, SFLAG_INSYSMEM, NULL);
1190         surface_modify_location(This, SFLAG_INDRAWABLE, FALSE);
1191     }
1192     surface_modify_location(This, SFLAG_INTEXTURE, FALSE);
1193     surface_modify_location(This, SFLAG_INSRGBTEX, FALSE);
1194     This->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
1195
1196     context = context_acquire(device, NULL);
1197     gl_info = context->gl_info;
1198
1199     /* Destroy PBOs, but load them into real sysmem before */
1200     if (This->Flags & SFLAG_PBO)
1201         surface_remove_pbo(This, gl_info);
1202
1203     /* Destroy fbo render buffers. This is needed for implicit render targets, for
1204      * all application-created targets the application has to release the surface
1205      * before calling _Reset
1206      */
1207     LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry) {
1208         ENTER_GL();
1209         gl_info->fbo_ops.glDeleteRenderbuffers(1, &entry->id);
1210         LEAVE_GL();
1211         list_remove(&entry->entry);
1212         HeapFree(GetProcessHeap(), 0, entry);
1213     }
1214     list_init(&This->renderbuffers);
1215     This->current_renderbuffer = NULL;
1216
1217     /* If we're in a texture, the texture name belongs to the texture.
1218      * Otherwise, destroy it. */
1219     if (This->container.type != WINED3D_CONTAINER_TEXTURE)
1220     {
1221         ENTER_GL();
1222         glDeleteTextures(1, &This->texture_name);
1223         This->texture_name = 0;
1224         glDeleteTextures(1, &This->texture_name_srgb);
1225         This->texture_name_srgb = 0;
1226         LEAVE_GL();
1227     }
1228
1229     context_release(context);
1230
1231     resource_unload((IWineD3DResourceImpl *)This);
1232 }
1233
1234 /* ******************************************************
1235    IWineD3DSurface IWineD3DSurface parts follow
1236    ****************************************************** */
1237
1238 /* Read the framebuffer back into the surface */
1239 static void read_from_framebuffer(IWineD3DSurfaceImpl *This, const RECT *rect, void *dest, UINT pitch)
1240 {
1241     IWineD3DDeviceImpl *device = This->resource.device;
1242     const struct wined3d_gl_info *gl_info;
1243     struct wined3d_context *context;
1244     BYTE *mem;
1245     GLint fmt;
1246     GLint type;
1247     BYTE *row, *top, *bottom;
1248     int i;
1249     BOOL bpp;
1250     RECT local_rect;
1251     BOOL srcIsUpsideDown;
1252     GLint rowLen = 0;
1253     GLint skipPix = 0;
1254     GLint skipRow = 0;
1255
1256     if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
1257         static BOOL warned = FALSE;
1258         if(!warned) {
1259             ERR("The application tries to lock the render target, but render target locking is disabled\n");
1260             warned = TRUE;
1261         }
1262         return;
1263     }
1264
1265     /* Activate the surface. Set it up for blitting now, although not necessarily needed for LockRect.
1266      * Certain graphics drivers seem to dislike some enabled states when reading from opengl, the blitting usage
1267      * should help here. Furthermore unlockrect will need the context set up for blitting. The context manager will find
1268      * context->last_was_blit set on the unlock.
1269      */
1270     context = context_acquire(device, This);
1271     context_apply_blit_state(context, device);
1272     gl_info = context->gl_info;
1273
1274     ENTER_GL();
1275
1276     /* Select the correct read buffer, and give some debug output.
1277      * There is no need to keep track of the current read buffer or reset it, every part of the code
1278      * that reads sets the read buffer as desired.
1279      */
1280     if (surface_is_offscreen(This))
1281     {
1282         /* Locking the primary render target which is not on a swapchain(=offscreen render target).
1283          * Read from the back buffer
1284          */
1285         TRACE("Locking offscreen render target\n");
1286         glReadBuffer(device->offscreenBuffer);
1287         srcIsUpsideDown = TRUE;
1288     }
1289     else
1290     {
1291         /* Onscreen surfaces are always part of a swapchain */
1292         GLenum buffer = surface_get_gl_buffer(This);
1293         TRACE("Locking %#x buffer\n", buffer);
1294         glReadBuffer(buffer);
1295         checkGLcall("glReadBuffer");
1296         srcIsUpsideDown = FALSE;
1297     }
1298
1299     /* TODO: Get rid of the extra rectangle comparison and construction of a full surface rectangle */
1300     if(!rect) {
1301         local_rect.left = 0;
1302         local_rect.top = 0;
1303         local_rect.right = This->currentDesc.Width;
1304         local_rect.bottom = This->currentDesc.Height;
1305     } else {
1306         local_rect = *rect;
1307     }
1308     /* TODO: Get rid of the extra GetPitch call, LockRect does that too. Cache the pitch */
1309
1310     switch(This->resource.format_desc->format)
1311     {
1312         case WINED3DFMT_P8_UINT:
1313         {
1314             if (primary_render_target_is_p8(device))
1315             {
1316                 /* In case of P8 render targets the index is stored in the alpha component */
1317                 fmt = GL_ALPHA;
1318                 type = GL_UNSIGNED_BYTE;
1319                 mem = dest;
1320                 bpp = This->resource.format_desc->byte_count;
1321             } else {
1322                 /* GL can't return palettized data, so read ARGB pixels into a
1323                  * separate block of memory and convert them into palettized format
1324                  * in software. Slow, but if the app means to use palettized render
1325                  * targets and locks it...
1326                  *
1327                  * Use GL_RGB, GL_UNSIGNED_BYTE to read the surface for performance reasons
1328                  * Don't use GL_BGR as in the WINED3DFMT_R8G8B8 case, instead watch out
1329                  * for the color channels when palettizing the colors.
1330                  */
1331                 fmt = GL_RGB;
1332                 type = GL_UNSIGNED_BYTE;
1333                 pitch *= 3;
1334                 mem = HeapAlloc(GetProcessHeap(), 0, This->resource.size * 3);
1335                 if(!mem) {
1336                     ERR("Out of memory\n");
1337                     LEAVE_GL();
1338                     return;
1339                 }
1340                 bpp = This->resource.format_desc->byte_count * 3;
1341             }
1342         }
1343         break;
1344
1345         default:
1346             mem = dest;
1347             fmt = This->resource.format_desc->glFormat;
1348             type = This->resource.format_desc->glType;
1349             bpp = This->resource.format_desc->byte_count;
1350     }
1351
1352     if(This->Flags & SFLAG_PBO) {
1353         GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
1354         checkGLcall("glBindBufferARB");
1355         if(mem != NULL) {
1356             ERR("mem not null for pbo -- unexpected\n");
1357             mem = NULL;
1358         }
1359     }
1360
1361     /* Save old pixel store pack state */
1362     glGetIntegerv(GL_PACK_ROW_LENGTH, &rowLen);
1363     checkGLcall("glGetIntegerv");
1364     glGetIntegerv(GL_PACK_SKIP_PIXELS, &skipPix);
1365     checkGLcall("glGetIntegerv");
1366     glGetIntegerv(GL_PACK_SKIP_ROWS, &skipRow);
1367     checkGLcall("glGetIntegerv");
1368
1369     /* Setup pixel store pack state -- to glReadPixels into the correct place */
1370     glPixelStorei(GL_PACK_ROW_LENGTH, This->currentDesc.Width);
1371     checkGLcall("glPixelStorei");
1372     glPixelStorei(GL_PACK_SKIP_PIXELS, local_rect.left);
1373     checkGLcall("glPixelStorei");
1374     glPixelStorei(GL_PACK_SKIP_ROWS, local_rect.top);
1375     checkGLcall("glPixelStorei");
1376
1377     glReadPixels(local_rect.left, (!srcIsUpsideDown) ? (This->currentDesc.Height - local_rect.bottom) : local_rect.top ,
1378                  local_rect.right - local_rect.left,
1379                  local_rect.bottom - local_rect.top,
1380                  fmt, type, mem);
1381     checkGLcall("glReadPixels");
1382
1383     /* Reset previous pixel store pack state */
1384     glPixelStorei(GL_PACK_ROW_LENGTH, rowLen);
1385     checkGLcall("glPixelStorei");
1386     glPixelStorei(GL_PACK_SKIP_PIXELS, skipPix);
1387     checkGLcall("glPixelStorei");
1388     glPixelStorei(GL_PACK_SKIP_ROWS, skipRow);
1389     checkGLcall("glPixelStorei");
1390
1391     if(This->Flags & SFLAG_PBO) {
1392         GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
1393         checkGLcall("glBindBufferARB");
1394
1395         /* Check if we need to flip the image. If we need to flip use glMapBufferARB
1396          * to get a pointer to it and perform the flipping in software. This is a lot
1397          * faster than calling glReadPixels for each line. In case we want more speed
1398          * we should rerender it flipped in a FBO and read the data back from the FBO. */
1399         if(!srcIsUpsideDown) {
1400             GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1401             checkGLcall("glBindBufferARB");
1402
1403             mem = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
1404             checkGLcall("glMapBufferARB");
1405         }
1406     }
1407
1408     /* TODO: Merge this with the palettization loop below for P8 targets */
1409     if(!srcIsUpsideDown) {
1410         UINT len, off;
1411         /* glReadPixels returns the image upside down, and there is no way to prevent this.
1412             Flip the lines in software */
1413         len = (local_rect.right - local_rect.left) * bpp;
1414         off = local_rect.left * bpp;
1415
1416         row = HeapAlloc(GetProcessHeap(), 0, len);
1417         if(!row) {
1418             ERR("Out of memory\n");
1419             if (This->resource.format_desc->format == WINED3DFMT_P8_UINT) HeapFree(GetProcessHeap(), 0, mem);
1420             LEAVE_GL();
1421             return;
1422         }
1423
1424         top = mem + pitch * local_rect.top;
1425         bottom = mem + pitch * (local_rect.bottom - 1);
1426         for(i = 0; i < (local_rect.bottom - local_rect.top) / 2; i++) {
1427             memcpy(row, top + off, len);
1428             memcpy(top + off, bottom + off, len);
1429             memcpy(bottom + off, row, len);
1430             top += pitch;
1431             bottom -= pitch;
1432         }
1433         HeapFree(GetProcessHeap(), 0, row);
1434
1435         /* Unmap the temp PBO buffer */
1436         if(This->Flags & SFLAG_PBO) {
1437             GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
1438             GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1439         }
1440     }
1441
1442     LEAVE_GL();
1443     context_release(context);
1444
1445     /* For P8 textures we need to perform an inverse palette lookup. This is done by searching for a palette
1446      * index which matches the RGB value. Note this isn't guaranteed to work when there are multiple entries for
1447      * the same color but we have no choice.
1448      * In case of P8 render targets, the index is stored in the alpha component so no conversion is needed.
1449      */
1450     if (This->resource.format_desc->format == WINED3DFMT_P8_UINT && !primary_render_target_is_p8(device))
1451     {
1452         const PALETTEENTRY *pal = NULL;
1453         DWORD width = pitch / 3;
1454         int x, y, c;
1455
1456         if(This->palette) {
1457             pal = This->palette->palents;
1458         } else {
1459             ERR("Palette is missing, cannot perform inverse palette lookup\n");
1460             HeapFree(GetProcessHeap(), 0, mem);
1461             return ;
1462         }
1463
1464         for(y = local_rect.top; y < local_rect.bottom; y++) {
1465             for(x = local_rect.left; x < local_rect.right; x++) {
1466                 /*                      start              lines            pixels      */
1467                 const BYTE *blue = mem + y * pitch + x * (sizeof(BYTE) * 3);
1468                 const BYTE *green = blue  + 1;
1469                 const BYTE *red = green + 1;
1470
1471                 for(c = 0; c < 256; c++) {
1472                     if(*red   == pal[c].peRed   &&
1473                        *green == pal[c].peGreen &&
1474                        *blue  == pal[c].peBlue)
1475                     {
1476                         *((BYTE *) dest + y * width + x) = c;
1477                         break;
1478                     }
1479                 }
1480             }
1481         }
1482         HeapFree(GetProcessHeap(), 0, mem);
1483     }
1484 }
1485
1486 /* Read the framebuffer contents into a texture */
1487 static void read_from_framebuffer_texture(IWineD3DSurfaceImpl *This, BOOL srgb)
1488 {
1489     IWineD3DDeviceImpl *device = This->resource.device;
1490     const struct wined3d_gl_info *gl_info;
1491     struct wined3d_context *context;
1492
1493     if (!surface_is_offscreen(This))
1494     {
1495         /* We would need to flip onscreen surfaces, but there's no efficient
1496          * way to do that here. It makes more sense for the caller to
1497          * explicitly go through sysmem. */
1498         ERR("Not supported for onscreen targets.\n");
1499         return;
1500     }
1501
1502     /* Activate the surface to read from. In some situations it isn't the currently active target(e.g. backbuffer
1503      * locking during offscreen rendering). RESOURCELOAD is ok because glCopyTexSubImage2D isn't affected by any
1504      * states in the stateblock, and no driver was found yet that had bugs in that regard.
1505      */
1506     context = context_acquire(device, This);
1507     gl_info = context->gl_info;
1508
1509     surface_prepare_texture(This, gl_info, srgb);
1510     surface_bind_and_dirtify(This, srgb);
1511
1512     TRACE("Reading back offscreen render target %p.\n", This);
1513
1514     ENTER_GL();
1515
1516     glReadBuffer(device->offscreenBuffer);
1517     checkGLcall("glReadBuffer");
1518
1519     glCopyTexSubImage2D(This->texture_target, This->texture_level,
1520             0, 0, 0, 0, This->currentDesc.Width, This->currentDesc.Height);
1521     checkGLcall("glCopyTexSubImage2D");
1522
1523     LEAVE_GL();
1524
1525     context_release(context);
1526 }
1527
1528 /* Context activation is done by the caller. */
1529 static void surface_prepare_texture_internal(IWineD3DSurfaceImpl *surface,
1530         const struct wined3d_gl_info *gl_info, BOOL srgb)
1531 {
1532     DWORD alloc_flag = srgb ? SFLAG_SRGBALLOCATED : SFLAG_ALLOCATED;
1533     CONVERT_TYPES convert;
1534     struct wined3d_format_desc desc;
1535
1536     if (surface->Flags & alloc_flag) return;
1537
1538     d3dfmt_get_conv(surface, TRUE, TRUE, &desc, &convert);
1539     if(convert != NO_CONVERSION || desc.convert) surface->Flags |= SFLAG_CONVERTED;
1540     else surface->Flags &= ~SFLAG_CONVERTED;
1541
1542     surface_bind_and_dirtify(surface, srgb);
1543     surface_allocate_surface(surface, gl_info, &desc, srgb);
1544     surface->Flags |= alloc_flag;
1545 }
1546
1547 /* Context activation is done by the caller. */
1548 void surface_prepare_texture(IWineD3DSurfaceImpl *surface, const struct wined3d_gl_info *gl_info, BOOL srgb)
1549 {
1550     if (surface->container.type == WINED3D_CONTAINER_TEXTURE)
1551     {
1552         IWineD3DBaseTextureImpl *texture = surface->container.u.texture;
1553         UINT sub_count = texture->baseTexture.level_count * texture->baseTexture.layer_count;
1554         UINT i;
1555
1556         TRACE("surface %p is a subresource of texture %p.\n", surface, texture);
1557
1558         for (i = 0; i < sub_count; ++i)
1559         {
1560             IWineD3DSurfaceImpl *s = (IWineD3DSurfaceImpl *)texture->baseTexture.sub_resources[i];
1561             surface_prepare_texture_internal(s, gl_info, srgb);
1562         }
1563
1564         return;
1565     }
1566
1567     surface_prepare_texture_internal(surface, gl_info, srgb);
1568 }
1569
1570 static void surface_prepare_system_memory(IWineD3DSurfaceImpl *This)
1571 {
1572     IWineD3DDeviceImpl *device = This->resource.device;
1573     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1574
1575     /* Performance optimization: Count how often a surface is locked, if it is locked regularly do not throw away the system memory copy.
1576      * This avoids the need to download the surface from opengl all the time. The surface is still downloaded if the opengl texture is
1577      * changed
1578      */
1579     if(!(This->Flags & SFLAG_DYNLOCK)) {
1580         This->lockCount++;
1581         /* MAXLOCKCOUNT is defined in wined3d_private.h */
1582         if(This->lockCount > MAXLOCKCOUNT) {
1583             TRACE("Surface is locked regularly, not freeing the system memory copy any more\n");
1584             This->Flags |= SFLAG_DYNLOCK;
1585         }
1586     }
1587
1588     /* Create a PBO for dynamically locked surfaces but don't do it for converted or non-pow2 surfaces.
1589      * Also don't create a PBO for systemmem surfaces.
1590      */
1591     if (gl_info->supported[ARB_PIXEL_BUFFER_OBJECT] && (This->Flags & SFLAG_DYNLOCK)
1592             && !(This->Flags & (SFLAG_PBO | SFLAG_CONVERTED | SFLAG_NONPOW2))
1593             && (This->resource.pool != WINED3DPOOL_SYSTEMMEM))
1594     {
1595         GLenum error;
1596         struct wined3d_context *context;
1597
1598         context = context_acquire(device, NULL);
1599         ENTER_GL();
1600
1601         GL_EXTCALL(glGenBuffersARB(1, &This->pbo));
1602         error = glGetError();
1603         if(This->pbo == 0 || error != GL_NO_ERROR) {
1604             ERR("Failed to bind the PBO with error %s (%#x)\n", debug_glerror(error), error);
1605         }
1606
1607         TRACE("Attaching pbo=%#x to (%p)\n", This->pbo, This);
1608
1609         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1610         checkGLcall("glBindBufferARB");
1611
1612         GL_EXTCALL(glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->resource.size + 4, This->resource.allocatedMemory, GL_STREAM_DRAW_ARB));
1613         checkGLcall("glBufferDataARB");
1614
1615         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1616         checkGLcall("glBindBufferARB");
1617
1618         /* We don't need the system memory anymore and we can't even use it for PBOs */
1619         if(!(This->Flags & SFLAG_CLIENT)) {
1620             HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
1621             This->resource.heapMemory = NULL;
1622         }
1623         This->resource.allocatedMemory = NULL;
1624         This->Flags |= SFLAG_PBO;
1625         LEAVE_GL();
1626         context_release(context);
1627     }
1628     else if (!(This->resource.allocatedMemory || This->Flags & SFLAG_PBO))
1629     {
1630         /* Whatever surface we have, make sure that there is memory allocated for the downloaded copy,
1631          * or a pbo to map
1632          */
1633         if(!This->resource.heapMemory) {
1634             This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
1635         }
1636         This->resource.allocatedMemory =
1637                 (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1638         if(This->Flags & SFLAG_INSYSMEM) {
1639             ERR("Surface without memory or pbo has SFLAG_INSYSMEM set!\n");
1640         }
1641     }
1642 }
1643
1644 static HRESULT WINAPI IWineD3DSurfaceImpl_LockRect(IWineD3DSurface *iface, WINED3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags) {
1645     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1646     IWineD3DDeviceImpl *device = This->resource.device;
1647     const RECT *pass_rect = pRect;
1648
1649     TRACE("iface %p, locked_rect %p, rect %s, flags %#x.\n",
1650             iface, pLockedRect, wine_dbgstr_rect(pRect), Flags);
1651
1652     /* This is also done in the base class, but we have to verify this before loading any data from
1653      * gl into the sysmem copy. The PBO may be mapped, a different rectangle locked, the discard flag
1654      * may interfere, and all other bad things may happen
1655      */
1656     if (This->Flags & SFLAG_LOCKED) {
1657         WARN("Surface is already locked, returning D3DERR_INVALIDCALL\n");
1658         return WINED3DERR_INVALIDCALL;
1659     }
1660     This->Flags |= SFLAG_LOCKED;
1661
1662     if (!(This->Flags & SFLAG_LOCKABLE))
1663     {
1664         TRACE("Warning: trying to lock unlockable surf@%p\n", This);
1665     }
1666
1667     if (Flags & WINED3DLOCK_DISCARD) {
1668         /* Set SFLAG_INSYSMEM, so we'll never try to download the data from the texture. */
1669         TRACE("WINED3DLOCK_DISCARD flag passed, marking local copy as up to date\n");
1670         surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1671         This->Flags |= SFLAG_INSYSMEM;
1672         goto lock_end;
1673     }
1674
1675     if (This->Flags & SFLAG_INSYSMEM) {
1676         TRACE("Local copy is up to date, not downloading data\n");
1677         surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1678         goto lock_end;
1679     }
1680
1681     /* surface_load_location() does not check if the rectangle specifies
1682      * the full surface. Most callers don't need that, so do it here. */
1683     if (pRect && pRect->top == 0 && pRect->left == 0
1684             && pRect->right == This->currentDesc.Width
1685             && pRect->bottom == This->currentDesc.Height)
1686     {
1687         pass_rect = NULL;
1688     }
1689
1690     if (!(wined3d_settings.rendertargetlock_mode == RTL_DISABLE
1691             && ((This->container.type == WINED3D_CONTAINER_SWAPCHAIN) || This == device->render_targets[0])))
1692     {
1693         surface_load_location(This, SFLAG_INSYSMEM, pass_rect);
1694     }
1695
1696 lock_end:
1697     if (This->Flags & SFLAG_PBO)
1698     {
1699         const struct wined3d_gl_info *gl_info;
1700         struct wined3d_context *context;
1701
1702         context = context_acquire(device, NULL);
1703         gl_info = context->gl_info;
1704
1705         ENTER_GL();
1706         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1707         checkGLcall("glBindBufferARB");
1708
1709         /* This shouldn't happen but could occur if some other function didn't handle the PBO properly */
1710         if(This->resource.allocatedMemory) {
1711             ERR("The surface already has PBO memory allocated!\n");
1712         }
1713
1714         This->resource.allocatedMemory = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
1715         checkGLcall("glMapBufferARB");
1716
1717         /* Make sure the pbo isn't set anymore in order not to break non-pbo calls */
1718         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1719         checkGLcall("glBindBufferARB");
1720
1721         LEAVE_GL();
1722         context_release(context);
1723     }
1724
1725     if (Flags & (WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY)) {
1726         /* Don't dirtify */
1727     }
1728     else
1729     {
1730         surface_add_dirty_rect(This, pRect);
1731
1732         if (This->container.type == WINED3D_CONTAINER_TEXTURE)
1733         {
1734             TRACE("Making container dirty.\n");
1735             IWineD3DBaseTexture_SetDirty((IWineD3DBaseTexture *)This->container.u.texture, TRUE);
1736         }
1737         else
1738         {
1739             TRACE("Surface is standalone, no need to dirty the container\n");
1740         }
1741     }
1742
1743     return IWineD3DBaseSurfaceImpl_LockRect(iface, pLockedRect, pRect, Flags);
1744 }
1745
1746 static void flush_to_framebuffer_drawpixels(IWineD3DSurfaceImpl *This, GLenum fmt, GLenum type, UINT bpp, const BYTE *mem) {
1747     GLint  prev_store;
1748     GLint  prev_rasterpos[4];
1749     GLint skipBytes = 0;
1750     UINT pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This);    /* target is argb, 4 byte */
1751     IWineD3DDeviceImpl *device = This->resource.device;
1752     const struct wined3d_gl_info *gl_info;
1753     struct wined3d_context *context;
1754
1755     /* Activate the correct context for the render target */
1756     context = context_acquire(device, This);
1757     context_apply_blit_state(context, device);
1758     gl_info = context->gl_info;
1759
1760     ENTER_GL();
1761
1762     if (!surface_is_offscreen(This))
1763     {
1764         GLenum buffer = surface_get_gl_buffer(This);
1765         TRACE("Unlocking %#x buffer.\n", buffer);
1766         context_set_draw_buffer(context, buffer);
1767     }
1768     else
1769     {
1770         /* Primary offscreen render target */
1771         TRACE("Offscreen render target.\n");
1772         context_set_draw_buffer(context, device->offscreenBuffer);
1773     }
1774
1775     glGetIntegerv(GL_PACK_SWAP_BYTES, &prev_store);
1776     checkGLcall("glGetIntegerv");
1777     glGetIntegerv(GL_CURRENT_RASTER_POSITION, &prev_rasterpos[0]);
1778     checkGLcall("glGetIntegerv");
1779     glPixelZoom(1.0f, -1.0f);
1780     checkGLcall("glPixelZoom");
1781
1782     /* If not fullscreen, we need to skip a number of bytes to find the next row of data */
1783     glGetIntegerv(GL_UNPACK_ROW_LENGTH, &skipBytes);
1784     glPixelStorei(GL_UNPACK_ROW_LENGTH, This->currentDesc.Width);
1785
1786     glRasterPos3i(This->lockedRect.left, This->lockedRect.top, 1);
1787     checkGLcall("glRasterPos3i");
1788
1789     /* Some drivers(radeon dri, others?) don't like exceptions during
1790      * glDrawPixels. If the surface is a DIB section, it might be in GDIMode
1791      * after ReleaseDC. Reading it will cause an exception, which x11drv will
1792      * catch to put the dib section in InSync mode, which leads to a crash
1793      * and a blocked x server on my radeon card.
1794      *
1795      * The following lines read the dib section so it is put in InSync mode
1796      * before glDrawPixels is called and the crash is prevented. There won't
1797      * be any interfering gdi accesses, because UnlockRect is called from
1798      * ReleaseDC, and the app won't use the dc any more afterwards.
1799      */
1800     if((This->Flags & SFLAG_DIBSECTION) && !(This->Flags & SFLAG_PBO)) {
1801         volatile BYTE read;
1802         read = This->resource.allocatedMemory[0];
1803     }
1804
1805     if(This->Flags & SFLAG_PBO) {
1806         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1807         checkGLcall("glBindBufferARB");
1808     }
1809
1810     /* When the surface is locked we only have to refresh the locked part else we need to update the whole image */
1811     if(This->Flags & SFLAG_LOCKED) {
1812         glDrawPixels(This->lockedRect.right - This->lockedRect.left,
1813                      (This->lockedRect.bottom - This->lockedRect.top)-1,
1814                      fmt, type,
1815                      mem + bpp * This->lockedRect.left + pitch * This->lockedRect.top);
1816         checkGLcall("glDrawPixels");
1817     } else {
1818         glDrawPixels(This->currentDesc.Width,
1819                      This->currentDesc.Height,
1820                      fmt, type, mem);
1821         checkGLcall("glDrawPixels");
1822     }
1823
1824     if(This->Flags & SFLAG_PBO) {
1825         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1826         checkGLcall("glBindBufferARB");
1827     }
1828
1829     glPixelZoom(1.0f, 1.0f);
1830     checkGLcall("glPixelZoom");
1831
1832     glRasterPos3iv(&prev_rasterpos[0]);
1833     checkGLcall("glRasterPos3iv");
1834
1835     /* Reset to previous pack row length */
1836     glPixelStorei(GL_UNPACK_ROW_LENGTH, skipBytes);
1837     checkGLcall("glPixelStorei(GL_UNPACK_ROW_LENGTH)");
1838
1839     LEAVE_GL();
1840     context_release(context);
1841 }
1842
1843 static HRESULT WINAPI IWineD3DSurfaceImpl_UnlockRect(IWineD3DSurface *iface) {
1844     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1845     IWineD3DDeviceImpl *device = This->resource.device;
1846     BOOL fullsurface;
1847
1848     if (!(This->Flags & SFLAG_LOCKED)) {
1849         WARN("trying to Unlock an unlocked surf@%p\n", This);
1850         return WINEDDERR_NOTLOCKED;
1851     }
1852
1853     if (This->Flags & SFLAG_PBO)
1854     {
1855         const struct wined3d_gl_info *gl_info;
1856         struct wined3d_context *context;
1857
1858         TRACE("Freeing PBO memory\n");
1859
1860         context = context_acquire(device, NULL);
1861         gl_info = context->gl_info;
1862
1863         ENTER_GL();
1864         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1865         GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
1866         GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1867         checkGLcall("glUnmapBufferARB");
1868         LEAVE_GL();
1869         context_release(context);
1870
1871         This->resource.allocatedMemory = NULL;
1872     }
1873
1874     TRACE("(%p) : dirtyfied(%d)\n", This, This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE) ? 0 : 1);
1875
1876     if (This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE)) {
1877         TRACE("(%p) : Not Dirtified so nothing to do, return now\n", This);
1878         goto unlock_end;
1879     }
1880
1881     if (This->container.type == WINED3D_CONTAINER_SWAPCHAIN
1882             || (device->render_targets && This == device->render_targets[0]))
1883     {
1884         if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
1885             static BOOL warned = FALSE;
1886             if(!warned) {
1887                 ERR("The application tries to write to the render target, but render target locking is disabled\n");
1888                 warned = TRUE;
1889             }
1890             goto unlock_end;
1891         }
1892
1893         if(This->dirtyRect.left   == 0 &&
1894            This->dirtyRect.top    == 0 &&
1895            This->dirtyRect.right  == This->currentDesc.Width &&
1896            This->dirtyRect.bottom == This->currentDesc.Height) {
1897             fullsurface = TRUE;
1898         } else {
1899             /* TODO: Proper partial rectangle tracking */
1900             fullsurface = FALSE;
1901             This->Flags |= SFLAG_INSYSMEM;
1902         }
1903
1904         switch(wined3d_settings.rendertargetlock_mode) {
1905             case RTL_READTEX:
1906                 surface_load_location(This, SFLAG_INTEXTURE, NULL /* partial texture loading not supported yet */);
1907                 /* drop through */
1908
1909             case RTL_READDRAW:
1910                 surface_load_location(This, SFLAG_INDRAWABLE, fullsurface ? NULL : &This->dirtyRect);
1911                 break;
1912         }
1913
1914         if(!fullsurface) {
1915             /* Partial rectangle tracking is not commonly implemented, it is only done for render targets. Overwrite
1916              * the flags to bring them back into a sane state. INSYSMEM was set before to tell LoadLocation where
1917              * to read the rectangle from. Indrawable is set because all modifications from the partial sysmem copy
1918              * are written back to the drawable, thus the surface is merged again in the drawable. The sysmem copy is
1919              * not fully up to date because only a subrectangle was read in LockRect.
1920              */
1921             This->Flags &= ~SFLAG_INSYSMEM;
1922             This->Flags |= SFLAG_INDRAWABLE;
1923         }
1924
1925         This->dirtyRect.left   = This->currentDesc.Width;
1926         This->dirtyRect.top    = This->currentDesc.Height;
1927         This->dirtyRect.right  = 0;
1928         This->dirtyRect.bottom = 0;
1929     }
1930     else if (This == device->depth_stencil)
1931     {
1932         FIXME("Depth Stencil buffer locking is not implemented\n");
1933     } else {
1934         /* The rest should be a normal texture */
1935         /* Check if the texture is bound, if yes dirtify the sampler to force a re-upload of the texture
1936          * Can't load the texture here because PreLoad may destroy and recreate the gl texture, so sampler
1937          * states need resetting
1938          */
1939         if (This->container.type == WINED3D_CONTAINER_TEXTURE)
1940         {
1941             IWineD3DBaseTextureImpl *texture = This->container.u.texture;
1942             if (texture->baseTexture.bindCount)
1943                 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_SAMPLER(texture->baseTexture.sampler));
1944         }
1945     }
1946
1947     unlock_end:
1948     This->Flags &= ~SFLAG_LOCKED;
1949     memset(&This->lockedRect, 0, sizeof(RECT));
1950
1951     /* Overlays have to be redrawn manually after changes with the GL implementation */
1952     if(This->overlay_dest) {
1953         IWineD3DSurface_DrawOverlay(iface);
1954     }
1955     return WINED3D_OK;
1956 }
1957
1958 static void surface_release_client_storage(IWineD3DSurfaceImpl *surface)
1959 {
1960     struct wined3d_context *context;
1961
1962     context = context_acquire(surface->resource.device, NULL);
1963
1964     ENTER_GL();
1965     glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
1966     if (surface->texture_name)
1967     {
1968         surface_bind_and_dirtify(surface, FALSE);
1969         glTexImage2D(surface->texture_target, surface->texture_level,
1970                 GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
1971     }
1972     if (surface->texture_name_srgb)
1973     {
1974         surface_bind_and_dirtify(surface, TRUE);
1975         glTexImage2D(surface->texture_target, surface->texture_level,
1976                 GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
1977     }
1978     glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1979
1980     LEAVE_GL();
1981     context_release(context);
1982
1983     surface_modify_location(surface, SFLAG_INSRGBTEX, FALSE);
1984     surface_modify_location(surface, SFLAG_INTEXTURE, FALSE);
1985     surface_force_reload(surface);
1986 }
1987
1988 static HRESULT WINAPI IWineD3DSurfaceImpl_GetDC(IWineD3DSurface *iface, HDC *pHDC)
1989 {
1990     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1991     WINED3DLOCKED_RECT lock;
1992     HRESULT hr;
1993     RGBQUAD col[256];
1994
1995     TRACE("(%p)->(%p)\n",This,pHDC);
1996
1997     if(This->Flags & SFLAG_USERPTR) {
1998         ERR("Not supported on surfaces with an application-provided surfaces\n");
1999         return WINEDDERR_NODC;
2000     }
2001
2002     /* Give more detailed info for ddraw */
2003     if (This->Flags & SFLAG_DCINUSE)
2004         return WINEDDERR_DCALREADYCREATED;
2005
2006     /* Can't GetDC if the surface is locked */
2007     if (This->Flags & SFLAG_LOCKED)
2008         return WINED3DERR_INVALIDCALL;
2009
2010     memset(&lock, 0, sizeof(lock)); /* To be sure */
2011
2012     /* Create a DIB section if there isn't a hdc yet */
2013     if (!This->hDC)
2014     {
2015         if (This->Flags & SFLAG_CLIENT)
2016         {
2017             surface_load_location(This, SFLAG_INSYSMEM, NULL);
2018             surface_release_client_storage(This);
2019         }
2020         hr = IWineD3DBaseSurfaceImpl_CreateDIBSection(iface);
2021         if(FAILED(hr)) return WINED3DERR_INVALIDCALL;
2022
2023         /* Use the dib section from now on if we are not using a PBO */
2024         if(!(This->Flags & SFLAG_PBO))
2025             This->resource.allocatedMemory = This->dib.bitmap_data;
2026     }
2027
2028     /* Lock the surface */
2029     hr = IWineD3DSurface_LockRect(iface,
2030                                   &lock,
2031                                   NULL,
2032                                   0);
2033
2034     if(This->Flags & SFLAG_PBO) {
2035         /* Sync the DIB with the PBO. This can't be done earlier because LockRect activates the allocatedMemory */
2036         memcpy(This->dib.bitmap_data, This->resource.allocatedMemory, This->dib.bitmap_size);
2037     }
2038
2039     if(FAILED(hr)) {
2040         ERR("IWineD3DSurface_LockRect failed with hr = %08x\n", hr);
2041         /* keep the dib section */
2042         return hr;
2043     }
2044
2045     if (This->resource.format_desc->format == WINED3DFMT_P8_UINT
2046             || This->resource.format_desc->format == WINED3DFMT_P8_UINT_A8_UNORM)
2047     {
2048         /* GetDC on palettized formats is unsupported in D3D9, and the method is missing in
2049             D3D8, so this should only be used for DX <=7 surfaces (with non-device palettes) */
2050         unsigned int n;
2051         const PALETTEENTRY *pal = NULL;
2052
2053         if(This->palette) {
2054             pal = This->palette->palents;
2055         } else {
2056             IWineD3DSurfaceImpl *dds_primary;
2057             IWineD3DSwapChainImpl *swapchain;
2058             swapchain = (IWineD3DSwapChainImpl *)This->resource.device->swapchains[0];
2059             dds_primary = swapchain->front_buffer;
2060             if (dds_primary && dds_primary->palette)
2061                 pal = dds_primary->palette->palents;
2062         }
2063
2064         if (pal) {
2065             for (n=0; n<256; n++) {
2066                 col[n].rgbRed   = pal[n].peRed;
2067                 col[n].rgbGreen = pal[n].peGreen;
2068                 col[n].rgbBlue  = pal[n].peBlue;
2069                 col[n].rgbReserved = 0;
2070             }
2071             SetDIBColorTable(This->hDC, 0, 256, col);
2072         }
2073     }
2074
2075     *pHDC = This->hDC;
2076     TRACE("returning %p\n",*pHDC);
2077     This->Flags |= SFLAG_DCINUSE;
2078
2079     return WINED3D_OK;
2080 }
2081
2082 static HRESULT WINAPI IWineD3DSurfaceImpl_ReleaseDC(IWineD3DSurface *iface, HDC hDC)
2083 {
2084     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2085
2086     TRACE("(%p)->(%p)\n",This,hDC);
2087
2088     if (!(This->Flags & SFLAG_DCINUSE))
2089         return WINEDDERR_NODC;
2090
2091     if (This->hDC !=hDC) {
2092         WARN("Application tries to release an invalid DC(%p), surface dc is %p\n", hDC, This->hDC);
2093         return WINEDDERR_NODC;
2094     }
2095
2096     if((This->Flags & SFLAG_PBO) && This->resource.allocatedMemory) {
2097         /* Copy the contents of the DIB over to the PBO */
2098         memcpy(This->resource.allocatedMemory, This->dib.bitmap_data, This->dib.bitmap_size);
2099     }
2100
2101     /* we locked first, so unlock now */
2102     IWineD3DSurface_UnlockRect(iface);
2103
2104     This->Flags &= ~SFLAG_DCINUSE;
2105
2106     return WINED3D_OK;
2107 }
2108
2109 /* ******************************************************
2110    IWineD3DSurface Internal (No mapping to directx api) parts follow
2111    ****************************************************** */
2112
2113 HRESULT d3dfmt_get_conv(IWineD3DSurfaceImpl *This, BOOL need_alpha_ck, BOOL use_texturing, struct wined3d_format_desc *desc, CONVERT_TYPES *convert)
2114 {
2115     BOOL colorkey_active = need_alpha_ck && (This->CKeyFlags & WINEDDSD_CKSRCBLT);
2116     IWineD3DDeviceImpl *device = This->resource.device;
2117     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2118     BOOL blit_supported = FALSE;
2119
2120     /* Copy the default values from the surface. Below we might perform fixups */
2121     /* TODO: get rid of color keying desc fixups by using e.g. a table. */
2122     *desc = *This->resource.format_desc;
2123     *convert = NO_CONVERSION;
2124
2125     /* Ok, now look if we have to do any conversion */
2126     switch(This->resource.format_desc->format)
2127     {
2128         case WINED3DFMT_P8_UINT:
2129             /* ****************
2130                 Paletted Texture
2131                 **************** */
2132
2133             /* Below the call to blit_supported is disabled for Wine 1.2 because the function isn't operating correctly yet.
2134              * At the moment 8-bit blits are handled in software and if certain GL extensions are around, surface conversion
2135              * is performed at upload time. The blit_supported call recognizes it as a destination fixup. This type of upload 'fixup'
2136              * and 8-bit to 8-bit blits need to be handled by the blit_shader.
2137              * TODO: get rid of this #if 0
2138              */
2139 #if 0
2140             blit_supported = device->blitter->blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
2141                                                              &rect, This->resource.usage, This->resource.pool,
2142                                                              This->resource.format_desc, &rect, This->resource.usage,
2143                                                              This->resource.pool, This->resource.format_desc);
2144 #endif
2145             blit_supported = gl_info->supported[EXT_PALETTED_TEXTURE] || gl_info->supported[ARB_FRAGMENT_PROGRAM];
2146
2147             /* Use conversion when the blit_shader backend supports it. It only supports this in case of
2148              * texturing. Further also use conversion in case of color keying.
2149              * Paletted textures can be emulated using shaders but only do that for 2D purposes e.g. situations
2150              * in which the main render target uses p8. Some games like GTA Vice City use P8 for texturing which
2151              * conflicts with this.
2152              */
2153             if (!((blit_supported && device->render_targets && This == device->render_targets[0]))
2154                     || colorkey_active || !use_texturing)
2155             {
2156                 desc->glFormat = GL_RGBA;
2157                 desc->glInternal = GL_RGBA;
2158                 desc->glType = GL_UNSIGNED_BYTE;
2159                 desc->conv_byte_count = 4;
2160                 if(colorkey_active) {
2161                     *convert = CONVERT_PALETTED_CK;
2162                 } else {
2163                     *convert = CONVERT_PALETTED;
2164                 }
2165             }
2166             break;
2167
2168         case WINED3DFMT_B2G3R3_UNORM:
2169             /* **********************
2170                 GL_UNSIGNED_BYTE_3_3_2
2171                 ********************** */
2172             if (colorkey_active) {
2173                 /* This texture format will never be used.. So do not care about color keying
2174                     up until the point in time it will be needed :-) */
2175                 FIXME(" ColorKeying not supported in the RGB 332 format !\n");
2176             }
2177             break;
2178
2179         case WINED3DFMT_B5G6R5_UNORM:
2180             if (colorkey_active) {
2181                 *convert = CONVERT_CK_565;
2182                 desc->glFormat = GL_RGBA;
2183                 desc->glInternal = GL_RGB5_A1;
2184                 desc->glType = GL_UNSIGNED_SHORT_5_5_5_1;
2185                 desc->conv_byte_count = 2;
2186             }
2187             break;
2188
2189         case WINED3DFMT_B5G5R5X1_UNORM:
2190             if (colorkey_active) {
2191                 *convert = CONVERT_CK_5551;
2192                 desc->glFormat = GL_BGRA;
2193                 desc->glInternal = GL_RGB5_A1;
2194                 desc->glType = GL_UNSIGNED_SHORT_1_5_5_5_REV;
2195                 desc->conv_byte_count = 2;
2196             }
2197             break;
2198
2199         case WINED3DFMT_B8G8R8_UNORM:
2200             if (colorkey_active) {
2201                 *convert = CONVERT_CK_RGB24;
2202                 desc->glFormat = GL_RGBA;
2203                 desc->glInternal = GL_RGBA8;
2204                 desc->glType = GL_UNSIGNED_INT_8_8_8_8;
2205                 desc->conv_byte_count = 4;
2206             }
2207             break;
2208
2209         case WINED3DFMT_B8G8R8X8_UNORM:
2210             if (colorkey_active) {
2211                 *convert = CONVERT_RGB32_888;
2212                 desc->glFormat = GL_RGBA;
2213                 desc->glInternal = GL_RGBA8;
2214                 desc->glType = GL_UNSIGNED_INT_8_8_8_8;
2215                 desc->conv_byte_count = 4;
2216             }
2217             break;
2218
2219         default:
2220             break;
2221     }
2222
2223     return WINED3D_OK;
2224 }
2225
2226 void d3dfmt_p8_init_palette(IWineD3DSurfaceImpl *This, BYTE table[256][4], BOOL colorkey)
2227 {
2228     IWineD3DDeviceImpl *device = This->resource.device;
2229     IWineD3DPaletteImpl *pal = This->palette;
2230     BOOL index_in_alpha = FALSE;
2231     unsigned int i;
2232
2233     /* Old games like StarCraft, C&C, Red Alert and others use P8 render targets.
2234      * Reading back the RGB output each lockrect (each frame as they lock the whole screen)
2235      * is slow. Further RGB->P8 conversion is not possible because palettes can have
2236      * duplicate entries. Store the color key in the unused alpha component to speed the
2237      * download up and to make conversion unneeded. */
2238     index_in_alpha = primary_render_target_is_p8(device);
2239
2240     if (!pal)
2241     {
2242         UINT dxVersion = ((IWineD3DImpl *)device->wined3d)->dxVersion;
2243
2244         /* In DirectDraw the palette is a property of the surface, there are no such things as device palettes. */
2245         if (dxVersion <= 7)
2246         {
2247             ERR("This code should never get entered for DirectDraw!, expect problems\n");
2248             if (index_in_alpha)
2249             {
2250                 /* Guarantees that memory representation remains correct after sysmem<->texture transfers even if
2251                  * there's no palette at this time. */
2252                 for (i = 0; i < 256; i++) table[i][3] = i;
2253             }
2254         }
2255         else
2256         {
2257             /* Direct3D >= 8 palette usage style: P8 textures use device palettes, palette entry format is A8R8G8B8,
2258              * alpha is stored in peFlags and may be used by the app if D3DPTEXTURECAPS_ALPHAPALETTE device
2259              * capability flag is present (wine does advertise this capability) */
2260             for (i = 0; i < 256; ++i)
2261             {
2262                 table[i][0] = device->palettes[device->currentPalette][i].peRed;
2263                 table[i][1] = device->palettes[device->currentPalette][i].peGreen;
2264                 table[i][2] = device->palettes[device->currentPalette][i].peBlue;
2265                 table[i][3] = device->palettes[device->currentPalette][i].peFlags;
2266             }
2267         }
2268     }
2269     else
2270     {
2271         TRACE("Using surface palette %p\n", pal);
2272         /* Get the surface's palette */
2273         for (i = 0; i < 256; ++i)
2274         {
2275             table[i][0] = pal->palents[i].peRed;
2276             table[i][1] = pal->palents[i].peGreen;
2277             table[i][2] = pal->palents[i].peBlue;
2278
2279             /* When index_in_alpha is set the palette index is stored in the
2280              * alpha component. In case of a readback we can then read
2281              * GL_ALPHA. Color keying is handled in BltOverride using a
2282              * GL_ALPHA_TEST using GL_NOT_EQUAL. In case of index_in_alpha the
2283              * color key itself is passed to glAlphaFunc in other cases the
2284              * alpha component of pixels that should be masked away is set to 0. */
2285             if (index_in_alpha)
2286             {
2287                 table[i][3] = i;
2288             }
2289             else if (colorkey && (i >= This->SrcBltCKey.dwColorSpaceLowValue)
2290                     && (i <= This->SrcBltCKey.dwColorSpaceHighValue))
2291             {
2292                 table[i][3] = 0x00;
2293             }
2294             else if(pal->Flags & WINEDDPCAPS_ALPHA)
2295             {
2296                 table[i][3] = pal->palents[i].peFlags;
2297             }
2298             else
2299             {
2300                 table[i][3] = 0xFF;
2301             }
2302         }
2303     }
2304 }
2305
2306 static HRESULT d3dfmt_convert_surface(const BYTE *src, BYTE *dst, UINT pitch, UINT width,
2307         UINT height, UINT outpitch, CONVERT_TYPES convert, IWineD3DSurfaceImpl *This)
2308 {
2309     const BYTE *source;
2310     BYTE *dest;
2311     TRACE("(%p)->(%p),(%d,%d,%d,%d,%p)\n", src, dst, pitch, height, outpitch, convert,This);
2312
2313     switch (convert) {
2314         case NO_CONVERSION:
2315         {
2316             memcpy(dst, src, pitch * height);
2317             break;
2318         }
2319         case CONVERT_PALETTED:
2320         case CONVERT_PALETTED_CK:
2321         {
2322             IWineD3DPaletteImpl* pal = This->palette;
2323             BYTE table[256][4];
2324             unsigned int x, y;
2325
2326             if( pal == NULL) {
2327                 /* TODO: If we are a sublevel, try to get the palette from level 0 */
2328             }
2329
2330             d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
2331
2332             for (y = 0; y < height; y++)
2333             {
2334                 source = src + pitch * y;
2335                 dest = dst + outpitch * y;
2336                 /* This is an 1 bpp format, using the width here is fine */
2337                 for (x = 0; x < width; x++) {
2338                     BYTE color = *source++;
2339                     *dest++ = table[color][0];
2340                     *dest++ = table[color][1];
2341                     *dest++ = table[color][2];
2342                     *dest++ = table[color][3];
2343                 }
2344             }
2345         }
2346         break;
2347
2348         case CONVERT_CK_565:
2349         {
2350             /* Converting the 565 format in 5551 packed to emulate color-keying.
2351
2352               Note : in all these conversion, it would be best to average the averaging
2353                       pixels to get the color of the pixel that will be color-keyed to
2354                       prevent 'color bleeding'. This will be done later on if ever it is
2355                       too visible.
2356
2357               Note2: Nvidia documents say that their driver does not support alpha + color keying
2358                      on the same surface and disables color keying in such a case
2359             */
2360             unsigned int x, y;
2361             const WORD *Source;
2362             WORD *Dest;
2363
2364             TRACE("Color keyed 565\n");
2365
2366             for (y = 0; y < height; y++) {
2367                 Source = (const WORD *)(src + y * pitch);
2368                 Dest = (WORD *) (dst + y * outpitch);
2369                 for (x = 0; x < width; x++ ) {
2370                     WORD color = *Source++;
2371                     *Dest = ((color & 0xFFC0) | ((color & 0x1F) << 1));
2372                     if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2373                         (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2374                         *Dest |= 0x0001;
2375                     }
2376                     Dest++;
2377                 }
2378             }
2379         }
2380         break;
2381
2382         case CONVERT_CK_5551:
2383         {
2384             /* Converting X1R5G5B5 format to R5G5B5A1 to emulate color-keying. */
2385             unsigned int x, y;
2386             const WORD *Source;
2387             WORD *Dest;
2388             TRACE("Color keyed 5551\n");
2389             for (y = 0; y < height; y++) {
2390                 Source = (const WORD *)(src + y * pitch);
2391                 Dest = (WORD *) (dst + y * outpitch);
2392                 for (x = 0; x < width; x++ ) {
2393                     WORD color = *Source++;
2394                     *Dest = color;
2395                     if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2396                         (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2397                         *Dest |= (1 << 15);
2398                     }
2399                     else {
2400                         *Dest &= ~(1 << 15);
2401                     }
2402                     Dest++;
2403                 }
2404             }
2405         }
2406         break;
2407
2408         case CONVERT_CK_RGB24:
2409         {
2410             /* Converting R8G8B8 format to R8G8B8A8 with color-keying. */
2411             unsigned int x, y;
2412             for (y = 0; y < height; y++)
2413             {
2414                 source = src + pitch * y;
2415                 dest = dst + outpitch * y;
2416                 for (x = 0; x < width; x++) {
2417                     DWORD color = ((DWORD)source[0] << 16) + ((DWORD)source[1] << 8) + (DWORD)source[2] ;
2418                     DWORD dstcolor = color << 8;
2419                     if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2420                         (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2421                         dstcolor |= 0xff;
2422                     }
2423                     *(DWORD*)dest = dstcolor;
2424                     source += 3;
2425                     dest += 4;
2426                 }
2427             }
2428         }
2429         break;
2430
2431         case CONVERT_RGB32_888:
2432         {
2433             /* Converting X8R8G8B8 format to R8G8B8A8 with color-keying. */
2434             unsigned int x, y;
2435             for (y = 0; y < height; y++)
2436             {
2437                 source = src + pitch * y;
2438                 dest = dst + outpitch * y;
2439                 for (x = 0; x < width; x++) {
2440                     DWORD color = 0xffffff & *(const DWORD*)source;
2441                     DWORD dstcolor = color << 8;
2442                     if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2443                         (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2444                         dstcolor |= 0xff;
2445                     }
2446                     *(DWORD*)dest = dstcolor;
2447                     source += 4;
2448                     dest += 4;
2449                 }
2450             }
2451         }
2452         break;
2453
2454         default:
2455             ERR("Unsupported conversion type %#x.\n", convert);
2456     }
2457     return WINED3D_OK;
2458 }
2459
2460 BOOL palette9_changed(IWineD3DSurfaceImpl *This)
2461 {
2462     IWineD3DDeviceImpl *device = This->resource.device;
2463
2464     if (This->palette || (This->resource.format_desc->format != WINED3DFMT_P8_UINT
2465             && This->resource.format_desc->format != WINED3DFMT_P8_UINT_A8_UNORM))
2466     {
2467         /* If a ddraw-style palette is attached assume no d3d9 palette change.
2468          * Also the palette isn't interesting if the surface format isn't P8 or A8P8
2469          */
2470         return FALSE;
2471     }
2472
2473     if (This->palette9)
2474     {
2475         if (!memcmp(This->palette9, device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256))
2476         {
2477             return FALSE;
2478         }
2479     } else {
2480         This->palette9 = HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY) * 256);
2481     }
2482     memcpy(This->palette9, device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256);
2483     return TRUE;
2484 }
2485
2486 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadTexture(IWineD3DSurface *iface, BOOL srgb_mode) {
2487     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2488     DWORD flag = srgb_mode ? SFLAG_INSRGBTEX : SFLAG_INTEXTURE;
2489
2490     TRACE("iface %p, srgb %#x.\n", iface, srgb_mode);
2491
2492     if (!(This->Flags & flag)) {
2493         TRACE("Reloading because surface is dirty\n");
2494     } else if(/* Reload: gl texture has ck, now no ckey is set OR */
2495               ((This->Flags & SFLAG_GLCKEY) && (!(This->CKeyFlags & WINEDDSD_CKSRCBLT))) ||
2496               /* Reload: vice versa  OR */
2497               ((!(This->Flags & SFLAG_GLCKEY)) && (This->CKeyFlags & WINEDDSD_CKSRCBLT)) ||
2498               /* Also reload: Color key is active AND the color key has changed */
2499               ((This->CKeyFlags & WINEDDSD_CKSRCBLT) && (
2500                 (This->glCKey.dwColorSpaceLowValue != This->SrcBltCKey.dwColorSpaceLowValue) ||
2501                 (This->glCKey.dwColorSpaceHighValue != This->SrcBltCKey.dwColorSpaceHighValue)))) {
2502         TRACE("Reloading because of color keying\n");
2503         /* To perform the color key conversion we need a sysmem copy of
2504          * the surface. Make sure we have it
2505          */
2506
2507         surface_load_location(This, SFLAG_INSYSMEM, NULL);
2508         /* Make sure the texture is reloaded because of the color key change, this kills performance though :( */
2509         /* TODO: This is not necessarily needed with hw palettized texture support */
2510         surface_modify_location(This, SFLAG_INSYSMEM, TRUE);
2511     } else {
2512         TRACE("surface is already in texture\n");
2513         return WINED3D_OK;
2514     }
2515
2516     /* Resources are placed in system RAM and do not need to be recreated when a device is lost.
2517      *  These resources are not bound by device size or format restrictions. Because of this,
2518      *  these resources cannot be accessed by the Direct3D device nor set as textures or render targets.
2519      *  However, these resources can always be created, locked, and copied.
2520      */
2521     if (This->resource.pool == WINED3DPOOL_SCRATCH )
2522     {
2523         FIXME("(%p) Operation not supported for scratch textures\n",This);
2524         return WINED3DERR_INVALIDCALL;
2525     }
2526
2527     surface_load_location(This, flag, NULL /* no partial locking for textures yet */);
2528
2529     if (!(This->Flags & SFLAG_DONOTFREE)) {
2530         HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
2531         This->resource.allocatedMemory = NULL;
2532         This->resource.heapMemory = NULL;
2533         surface_modify_location(This, SFLAG_INSYSMEM, FALSE);
2534     }
2535
2536     return WINED3D_OK;
2537 }
2538
2539 /* Context activation is done by the caller. */
2540 static void WINAPI IWineD3DSurfaceImpl_BindTexture(IWineD3DSurface *iface, BOOL srgb)
2541 {
2542     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2543
2544     TRACE("iface %p, srgb %#x.\n", iface, srgb);
2545
2546     if (This->container.type == WINED3D_CONTAINER_TEXTURE)
2547     {
2548         TRACE("Passing to container.\n");
2549         IWineD3DBaseTexture_BindTexture((IWineD3DBaseTexture *)This->container.u.texture, srgb);
2550     }
2551     else
2552     {
2553         GLuint *name;
2554
2555         TRACE("(%p) : Binding surface\n", This);
2556
2557         name = srgb ? &This->texture_name_srgb : &This->texture_name;
2558
2559         ENTER_GL();
2560
2561         if (!This->texture_level)
2562         {
2563             if (!*name) {
2564                 glGenTextures(1, name);
2565                 checkGLcall("glGenTextures");
2566                 TRACE("Surface %p given name %d\n", This, *name);
2567
2568                 glBindTexture(This->texture_target, *name);
2569                 checkGLcall("glBindTexture");
2570                 glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2571                 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)");
2572                 glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2573                 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)");
2574                 glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
2575                 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE)");
2576                 glTexParameteri(This->texture_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2577                 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_MIN_FILTER, GL_NEAREST)");
2578                 glTexParameteri(This->texture_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2579                 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_MAG_FILTER, GL_NEAREST)");
2580             }
2581             /* This is where we should be reducing the amount of GLMemoryUsed */
2582         } else if (*name) {
2583             /* Mipmap surfaces should have a base texture container */
2584             ERR("Mipmap surface has a glTexture bound to it!\n");
2585         }
2586
2587         glBindTexture(This->texture_target, *name);
2588         checkGLcall("glBindTexture");
2589
2590         LEAVE_GL();
2591     }
2592 }
2593
2594 static HRESULT WINAPI IWineD3DSurfaceImpl_SetFormat(IWineD3DSurface *iface, WINED3DFORMAT format) {
2595     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2596     HRESULT hr;
2597
2598     TRACE("(%p) : Calling base function first\n", This);
2599     hr = IWineD3DBaseSurfaceImpl_SetFormat(iface, format);
2600     if(SUCCEEDED(hr)) {
2601         This->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
2602         TRACE("(%p) : glFormat %d, glFormatInternal %d, glType %d\n", This, This->resource.format_desc->glFormat,
2603                 This->resource.format_desc->glInternal, This->resource.format_desc->glType);
2604     }
2605     return hr;
2606 }
2607
2608 static HRESULT WINAPI IWineD3DSurfaceImpl_SetMem(IWineD3DSurface *iface, void *Mem) {
2609     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
2610
2611     if(This->Flags & (SFLAG_LOCKED | SFLAG_DCINUSE)) {
2612         WARN("Surface is locked or the HDC is in use\n");
2613         return WINED3DERR_INVALIDCALL;
2614     }
2615
2616     if(Mem && Mem != This->resource.allocatedMemory) {
2617         void *release = NULL;
2618
2619         /* Do I have to copy the old surface content? */
2620         if(This->Flags & SFLAG_DIBSECTION) {
2621                 /* Release the DC. No need to hold the critical section for the update
2622                  * Thread because this thread runs only on front buffers, but this method
2623                  * fails for render targets in the check above.
2624                  */
2625                 SelectObject(This->hDC, This->dib.holdbitmap);
2626                 DeleteDC(This->hDC);
2627                 /* Release the DIB section */
2628                 DeleteObject(This->dib.DIBsection);
2629                 This->dib.bitmap_data = NULL;
2630                 This->resource.allocatedMemory = NULL;
2631                 This->hDC = NULL;
2632                 This->Flags &= ~SFLAG_DIBSECTION;
2633         } else if(!(This->Flags & SFLAG_USERPTR)) {
2634             release = This->resource.heapMemory;
2635             This->resource.heapMemory = NULL;
2636         }
2637         This->resource.allocatedMemory = Mem;
2638         This->Flags |= SFLAG_USERPTR | SFLAG_INSYSMEM;
2639
2640         /* Now the surface memory is most up do date. Invalidate drawable and texture */
2641         surface_modify_location(This, SFLAG_INSYSMEM, TRUE);
2642
2643         /* For client textures opengl has to be notified */
2644         if (This->Flags & SFLAG_CLIENT)
2645             surface_release_client_storage(This);
2646
2647         /* Now free the old memory if any */
2648         HeapFree(GetProcessHeap(), 0, release);
2649     } else if(This->Flags & SFLAG_USERPTR) {
2650         /* LockRect and GetDC will re-create the dib section and allocated memory */
2651         This->resource.allocatedMemory = NULL;
2652         /* HeapMemory should be NULL already */
2653         if(This->resource.heapMemory != NULL) ERR("User pointer surface has heap memory allocated\n");
2654         This->Flags &= ~SFLAG_USERPTR;
2655
2656         if (This->Flags & SFLAG_CLIENT)
2657             surface_release_client_storage(This);
2658     }
2659     return WINED3D_OK;
2660 }
2661
2662 void flip_surface(IWineD3DSurfaceImpl *front, IWineD3DSurfaceImpl *back) {
2663
2664     /* Flip the surface contents */
2665     /* Flip the DC */
2666     {
2667         HDC tmp;
2668         tmp = front->hDC;
2669         front->hDC = back->hDC;
2670         back->hDC = tmp;
2671     }
2672
2673     /* Flip the DIBsection */
2674     {
2675         HBITMAP tmp;
2676         BOOL hasDib = front->Flags & SFLAG_DIBSECTION;
2677         tmp = front->dib.DIBsection;
2678         front->dib.DIBsection = back->dib.DIBsection;
2679         back->dib.DIBsection = tmp;
2680
2681         if(back->Flags & SFLAG_DIBSECTION) front->Flags |= SFLAG_DIBSECTION;
2682         else front->Flags &= ~SFLAG_DIBSECTION;
2683         if(hasDib) back->Flags |= SFLAG_DIBSECTION;
2684         else back->Flags &= ~SFLAG_DIBSECTION;
2685     }
2686
2687     /* Flip the surface data */
2688     {
2689         void* tmp;
2690
2691         tmp = front->dib.bitmap_data;
2692         front->dib.bitmap_data = back->dib.bitmap_data;
2693         back->dib.bitmap_data = tmp;
2694
2695         tmp = front->resource.allocatedMemory;
2696         front->resource.allocatedMemory = back->resource.allocatedMemory;
2697         back->resource.allocatedMemory = tmp;
2698
2699         tmp = front->resource.heapMemory;
2700         front->resource.heapMemory = back->resource.heapMemory;
2701         back->resource.heapMemory = tmp;
2702     }
2703
2704     /* Flip the PBO */
2705     {
2706         GLuint tmp_pbo = front->pbo;
2707         front->pbo = back->pbo;
2708         back->pbo = tmp_pbo;
2709     }
2710
2711     /* client_memory should not be different, but just in case */
2712     {
2713         BOOL tmp;
2714         tmp = front->dib.client_memory;
2715         front->dib.client_memory = back->dib.client_memory;
2716         back->dib.client_memory = tmp;
2717     }
2718
2719     /* Flip the opengl texture */
2720     {
2721         GLuint tmp;
2722
2723         tmp = back->texture_name;
2724         back->texture_name = front->texture_name;
2725         front->texture_name = tmp;
2726
2727         tmp = back->texture_name_srgb;
2728         back->texture_name_srgb = front->texture_name_srgb;
2729         front->texture_name_srgb = tmp;
2730     }
2731
2732     {
2733         DWORD tmp_flags = back->Flags;
2734         back->Flags = front->Flags;
2735         front->Flags = tmp_flags;
2736     }
2737 }
2738
2739 static HRESULT WINAPI IWineD3DSurfaceImpl_Flip(IWineD3DSurface *iface, IWineD3DSurface *override, DWORD Flags) {
2740     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2741     IWineD3DSwapChainImpl *swapchain = NULL;
2742
2743     TRACE("(%p)->(%p,%x)\n", This, override, Flags);
2744
2745     /* Flipping is only supported on RenderTargets and overlays*/
2746     if( !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_OVERLAY)) ) {
2747         WARN("Tried to flip a non-render target, non-overlay surface\n");
2748         return WINEDDERR_NOTFLIPPABLE;
2749     }
2750
2751     if(This->resource.usage & WINED3DUSAGE_OVERLAY) {
2752         flip_surface(This, (IWineD3DSurfaceImpl *) override);
2753
2754         /* Update the overlay if it is visible */
2755         if(This->overlay_dest) {
2756             return IWineD3DSurface_DrawOverlay((IWineD3DSurface *) This);
2757         } else {
2758             return WINED3D_OK;
2759         }
2760     }
2761
2762     if(override) {
2763         /* DDraw sets this for the X11 surfaces, so don't confuse the user
2764          * FIXME("(%p) Target override is not supported by now\n", This);
2765          * Additionally, it isn't really possible to support triple-buffering
2766          * properly on opengl at all
2767          */
2768     }
2769
2770     if (This->container.type != WINED3D_CONTAINER_SWAPCHAIN)
2771     {
2772         ERR("Flipped surface is not on a swapchain\n");
2773         return WINEDDERR_NOTFLIPPABLE;
2774     }
2775     swapchain = This->container.u.swapchain;
2776
2777     /* Just overwrite the swapchain presentation interval. This is ok because only ddraw apps can call Flip,
2778      * and only d3d8 and d3d9 apps specify the presentation interval
2779      */
2780     if((Flags & (WINEDDFLIP_NOVSYNC | WINEDDFLIP_INTERVAL2 | WINEDDFLIP_INTERVAL3 | WINEDDFLIP_INTERVAL4)) == 0) {
2781         /* Most common case first to avoid wasting time on all the other cases */
2782         swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_ONE;
2783     } else if(Flags & WINEDDFLIP_NOVSYNC) {
2784         swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
2785     } else if(Flags & WINEDDFLIP_INTERVAL2) {
2786         swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_TWO;
2787     } else if(Flags & WINEDDFLIP_INTERVAL3) {
2788         swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_THREE;
2789     } else {
2790         swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_FOUR;
2791     }
2792
2793     /* Flipping a OpenGL surface -> Use WineD3DDevice::Present */
2794     return IWineD3DSwapChain_Present((IWineD3DSwapChain *)swapchain,
2795             NULL, NULL, swapchain->win_handle, NULL, 0);
2796 }
2797
2798 /* Does a direct frame buffer -> texture copy. Stretching is done
2799  * with single pixel copy calls
2800  */
2801 static void fb_copy_to_texture_direct(IWineD3DSurfaceImpl *dst_surface, IWineD3DSurfaceImpl *src_surface,
2802         const RECT *src_rect, const RECT *dst_rect_in, WINED3DTEXTUREFILTERTYPE Filter)
2803 {
2804     IWineD3DDeviceImpl *device = dst_surface->resource.device;
2805     float xrel, yrel;
2806     UINT row;
2807     struct wined3d_context *context;
2808     BOOL upsidedown = FALSE;
2809     RECT dst_rect = *dst_rect_in;
2810
2811     /* Make sure that the top pixel is always above the bottom pixel, and keep a separate upside down flag
2812      * glCopyTexSubImage is a bit picky about the parameters we pass to it
2813      */
2814     if(dst_rect.top > dst_rect.bottom) {
2815         UINT tmp = dst_rect.bottom;
2816         dst_rect.bottom = dst_rect.top;
2817         dst_rect.top = tmp;
2818         upsidedown = TRUE;
2819     }
2820
2821     context = context_acquire(device, src_surface);
2822     context_apply_blit_state(context, device);
2823     surface_internal_preload(dst_surface, SRGB_RGB);
2824     ENTER_GL();
2825
2826     /* Bind the target texture */
2827     glBindTexture(dst_surface->texture_target, dst_surface->texture_name);
2828     checkGLcall("glBindTexture");
2829     if (surface_is_offscreen(src_surface))
2830     {
2831         TRACE("Reading from an offscreen target\n");
2832         upsidedown = !upsidedown;
2833         glReadBuffer(device->offscreenBuffer);
2834     }
2835     else
2836     {
2837         glReadBuffer(surface_get_gl_buffer(src_surface));
2838     }
2839     checkGLcall("glReadBuffer");
2840
2841     xrel = (float) (src_rect->right - src_rect->left) / (float) (dst_rect.right - dst_rect.left);
2842     yrel = (float) (src_rect->bottom - src_rect->top) / (float) (dst_rect.bottom - dst_rect.top);
2843
2844     if ((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
2845     {
2846         FIXME("Doing a pixel by pixel copy from the framebuffer to a texture, expect major performance issues\n");
2847
2848         if(Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) {
2849             ERR("Texture filtering not supported in direct blit\n");
2850         }
2851     }
2852     else if ((Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT)
2853             && ((yrel - 1.0f < -eps) || (yrel - 1.0f > eps)))
2854     {
2855         ERR("Texture filtering not supported in direct blit\n");
2856     }
2857
2858     if (upsidedown
2859             && !((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
2860             && !((yrel - 1.0f < -eps) || (yrel - 1.0f > eps)))
2861     {
2862         /* Upside down copy without stretching is nice, one glCopyTexSubImage call will do */
2863
2864         glCopyTexSubImage2D(dst_surface->texture_target, dst_surface->texture_level,
2865                 dst_rect.left /*xoffset */, dst_rect.top /* y offset */,
2866                 src_rect->left, src_surface->currentDesc.Height - src_rect->bottom,
2867                 dst_rect.right - dst_rect.left, dst_rect.bottom - dst_rect.top);
2868     } else {
2869         UINT yoffset = src_surface->currentDesc.Height - src_rect->top + dst_rect.top - 1;
2870         /* I have to process this row by row to swap the image,
2871          * otherwise it would be upside down, so stretching in y direction
2872          * doesn't cost extra time
2873          *
2874          * However, stretching in x direction can be avoided if not necessary
2875          */
2876         for(row = dst_rect.top; row < dst_rect.bottom; row++) {
2877             if ((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
2878             {
2879                 /* Well, that stuff works, but it's very slow.
2880                  * find a better way instead
2881                  */
2882                 UINT col;
2883
2884                 for (col = dst_rect.left; col < dst_rect.right; ++col)
2885                 {
2886                     glCopyTexSubImage2D(dst_surface->texture_target, dst_surface->texture_level,
2887                             dst_rect.left + col /* x offset */, row /* y offset */,
2888                             src_rect->left + col * xrel, yoffset - (int) (row * yrel), 1, 1);
2889                 }
2890             }
2891             else
2892             {
2893                 glCopyTexSubImage2D(dst_surface->texture_target, dst_surface->texture_level,
2894                         dst_rect.left /* x offset */, row /* y offset */,
2895                         src_rect->left, yoffset - (int) (row * yrel), dst_rect.right - dst_rect.left, 1);
2896             }
2897         }
2898     }
2899     checkGLcall("glCopyTexSubImage2D");
2900
2901     LEAVE_GL();
2902     context_release(context);
2903
2904     /* The texture is now most up to date - If the surface is a render target and has a drawable, this
2905      * path is never entered
2906      */
2907     surface_modify_location(dst_surface, SFLAG_INTEXTURE, TRUE);
2908 }
2909
2910 /* Uses the hardware to stretch and flip the image */
2911 static void fb_copy_to_texture_hwstretch(IWineD3DSurfaceImpl *dst_surface, IWineD3DSurfaceImpl *src_surface,
2912         const RECT *src_rect, const RECT *dst_rect_in, WINED3DTEXTUREFILTERTYPE Filter)
2913 {
2914     IWineD3DDeviceImpl *device = dst_surface->resource.device;
2915     GLuint src, backup = 0;
2916     IWineD3DSwapChainImpl *src_swapchain = NULL;
2917     float left, right, top, bottom; /* Texture coordinates */
2918     UINT fbwidth = src_surface->currentDesc.Width;
2919     UINT fbheight = src_surface->currentDesc.Height;
2920     struct wined3d_context *context;
2921     GLenum drawBuffer = GL_BACK;
2922     GLenum texture_target;
2923     BOOL noBackBufferBackup;
2924     BOOL src_offscreen;
2925     BOOL upsidedown = FALSE;
2926     RECT dst_rect = *dst_rect_in;
2927
2928     TRACE("Using hwstretch blit\n");
2929     /* Activate the Proper context for reading from the source surface, set it up for blitting */
2930     context = context_acquire(device, src_surface);
2931     context_apply_blit_state(context, device);
2932     surface_internal_preload(dst_surface, SRGB_RGB);
2933
2934     src_offscreen = surface_is_offscreen(src_surface);
2935     noBackBufferBackup = src_offscreen && wined3d_settings.offscreen_rendering_mode == ORM_FBO;
2936     if (!noBackBufferBackup && !src_surface->texture_name)
2937     {
2938         /* Get it a description */
2939         surface_internal_preload(src_surface, SRGB_RGB);
2940     }
2941     ENTER_GL();
2942
2943     /* Try to use an aux buffer for drawing the rectangle. This way it doesn't need restoring.
2944      * This way we don't have to wait for the 2nd readback to finish to leave this function.
2945      */
2946     if (context->aux_buffers >= 2)
2947     {
2948         /* Got more than one aux buffer? Use the 2nd aux buffer */
2949         drawBuffer = GL_AUX1;
2950     }
2951     else if ((!src_offscreen || device->offscreenBuffer == GL_BACK) && context->aux_buffers >= 1)
2952     {
2953         /* Only one aux buffer, but it isn't used (Onscreen rendering, or non-aux orm)? Use it! */
2954         drawBuffer = GL_AUX0;
2955     }
2956
2957     if(noBackBufferBackup) {
2958         glGenTextures(1, &backup);
2959         checkGLcall("glGenTextures");
2960         glBindTexture(GL_TEXTURE_2D, backup);
2961         checkGLcall("glBindTexture(GL_TEXTURE_2D, backup)");
2962         texture_target = GL_TEXTURE_2D;
2963     } else {
2964         /* Backup the back buffer and copy the source buffer into a texture to draw an upside down stretched quad. If
2965          * we are reading from the back buffer, the backup can be used as source texture
2966          */
2967         texture_target = src_surface->texture_target;
2968         glBindTexture(texture_target, src_surface->texture_name);
2969         checkGLcall("glBindTexture(texture_target, src_surface->texture_name)");
2970         glEnable(texture_target);
2971         checkGLcall("glEnable(texture_target)");
2972
2973         /* For now invalidate the texture copy of the back buffer. Drawable and sysmem copy are untouched */
2974         src_surface->Flags &= ~SFLAG_INTEXTURE;
2975     }
2976
2977     /* Make sure that the top pixel is always above the bottom pixel, and keep a separate upside down flag
2978      * glCopyTexSubImage is a bit picky about the parameters we pass to it
2979      */
2980     if(dst_rect.top > dst_rect.bottom) {
2981         UINT tmp = dst_rect.bottom;
2982         dst_rect.bottom = dst_rect.top;
2983         dst_rect.top = tmp;
2984         upsidedown = TRUE;
2985     }
2986
2987     if (src_offscreen)
2988     {
2989         TRACE("Reading from an offscreen target\n");
2990         upsidedown = !upsidedown;
2991         glReadBuffer(device->offscreenBuffer);
2992     }
2993     else
2994     {
2995         glReadBuffer(surface_get_gl_buffer(src_surface));
2996     }
2997
2998     /* TODO: Only back up the part that will be overwritten */
2999     glCopyTexSubImage2D(texture_target, 0,
3000                         0, 0 /* read offsets */,
3001                         0, 0,
3002                         fbwidth,
3003                         fbheight);
3004
3005     checkGLcall("glCopyTexSubImage2D");
3006
3007     /* No issue with overriding these - the sampler is dirty due to blit usage */
3008     glTexParameteri(texture_target, GL_TEXTURE_MAG_FILTER,
3009             wined3d_gl_mag_filter(magLookup, Filter));
3010     checkGLcall("glTexParameteri");
3011     glTexParameteri(texture_target, GL_TEXTURE_MIN_FILTER,
3012             wined3d_gl_min_mip_filter(minMipLookup, Filter, WINED3DTEXF_NONE));
3013     checkGLcall("glTexParameteri");
3014
3015     if (src_surface->container.type == WINED3D_CONTAINER_SWAPCHAIN)
3016         src_swapchain = src_surface->container.u.swapchain;
3017     if (!src_swapchain || src_surface == src_swapchain->back_buffers[0])
3018     {
3019         src = backup ? backup : src_surface->texture_name;
3020     }
3021     else
3022     {
3023         glReadBuffer(GL_FRONT);
3024         checkGLcall("glReadBuffer(GL_FRONT)");
3025
3026         glGenTextures(1, &src);
3027         checkGLcall("glGenTextures(1, &src)");
3028         glBindTexture(GL_TEXTURE_2D, src);
3029         checkGLcall("glBindTexture(GL_TEXTURE_2D, src)");
3030
3031         /* TODO: Only copy the part that will be read. Use src_rect->left, src_rect->bottom as origin, but with the width watch
3032          * out for power of 2 sizes
3033          */
3034         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, src_surface->pow2Width,
3035                 src_surface->pow2Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
3036         checkGLcall("glTexImage2D");
3037         glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
3038                             0, 0 /* read offsets */,
3039                             0, 0,
3040                             fbwidth,
3041                             fbheight);
3042
3043         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
3044         checkGLcall("glTexParameteri");
3045         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
3046         checkGLcall("glTexParameteri");
3047
3048         glReadBuffer(GL_BACK);
3049         checkGLcall("glReadBuffer(GL_BACK)");
3050
3051         if(texture_target != GL_TEXTURE_2D) {
3052             glDisable(texture_target);
3053             glEnable(GL_TEXTURE_2D);
3054             texture_target = GL_TEXTURE_2D;
3055         }
3056     }
3057     checkGLcall("glEnd and previous");
3058
3059     left = src_rect->left;
3060     right = src_rect->right;
3061
3062     if (upsidedown)
3063     {
3064         top = src_surface->currentDesc.Height - src_rect->top;
3065         bottom = src_surface->currentDesc.Height - src_rect->bottom;
3066     }
3067     else
3068     {
3069         top = src_surface->currentDesc.Height - src_rect->bottom;
3070         bottom = src_surface->currentDesc.Height - src_rect->top;
3071     }
3072
3073     if (src_surface->Flags & SFLAG_NORMCOORD)
3074     {
3075         left /= src_surface->pow2Width;
3076         right /= src_surface->pow2Width;
3077         top /= src_surface->pow2Height;
3078         bottom /= src_surface->pow2Height;
3079     }
3080
3081     /* draw the source texture stretched and upside down. The correct surface is bound already */
3082     glTexParameteri(texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
3083     glTexParameteri(texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP);
3084
3085     context_set_draw_buffer(context, drawBuffer);
3086     glReadBuffer(drawBuffer);
3087
3088     glBegin(GL_QUADS);
3089         /* bottom left */
3090         glTexCoord2f(left, bottom);
3091         glVertex2i(0, fbheight);
3092
3093         /* top left */
3094         glTexCoord2f(left, top);
3095         glVertex2i(0, fbheight - dst_rect.bottom - dst_rect.top);
3096
3097         /* top right */
3098         glTexCoord2f(right, top);
3099         glVertex2i(dst_rect.right - dst_rect.left, fbheight - dst_rect.bottom - dst_rect.top);
3100
3101         /* bottom right */
3102         glTexCoord2f(right, bottom);
3103         glVertex2i(dst_rect.right - dst_rect.left, fbheight);
3104     glEnd();
3105     checkGLcall("glEnd and previous");
3106
3107     if (texture_target != dst_surface->texture_target)
3108     {
3109         glDisable(texture_target);
3110         glEnable(dst_surface->texture_target);
3111         texture_target = dst_surface->texture_target;
3112     }
3113
3114     /* Now read the stretched and upside down image into the destination texture */
3115     glBindTexture(texture_target, dst_surface->texture_name);
3116     checkGLcall("glBindTexture");
3117     glCopyTexSubImage2D(texture_target,
3118                         0,
3119                         dst_rect.left, dst_rect.top, /* xoffset, yoffset */
3120                         0, 0, /* We blitted the image to the origin */
3121                         dst_rect.right - dst_rect.left, dst_rect.bottom - dst_rect.top);
3122     checkGLcall("glCopyTexSubImage2D");
3123
3124     if(drawBuffer == GL_BACK) {
3125         /* Write the back buffer backup back */
3126         if(backup) {
3127             if(texture_target != GL_TEXTURE_2D) {
3128                 glDisable(texture_target);
3129                 glEnable(GL_TEXTURE_2D);
3130                 texture_target = GL_TEXTURE_2D;
3131             }
3132             glBindTexture(GL_TEXTURE_2D, backup);
3133             checkGLcall("glBindTexture(GL_TEXTURE_2D, backup)");
3134         }
3135         else
3136         {
3137             if (texture_target != src_surface->texture_target)
3138             {
3139                 glDisable(texture_target);
3140                 glEnable(src_surface->texture_target);
3141                 texture_target = src_surface->texture_target;
3142             }
3143             glBindTexture(src_surface->texture_target, src_surface->texture_name);
3144             checkGLcall("glBindTexture(src_surface->texture_target, src_surface->texture_name)");
3145         }
3146
3147         glBegin(GL_QUADS);
3148             /* top left */
3149             glTexCoord2f(0.0f, (float)fbheight / (float)src_surface->pow2Height);
3150             glVertex2i(0, 0);
3151
3152             /* bottom left */
3153             glTexCoord2f(0.0f, 0.0f);
3154             glVertex2i(0, fbheight);
3155
3156             /* bottom right */
3157             glTexCoord2f((float)fbwidth / (float)src_surface->pow2Width, 0.0f);
3158             glVertex2i(fbwidth, src_surface->currentDesc.Height);
3159
3160             /* top right */
3161             glTexCoord2f((float)fbwidth / (float)src_surface->pow2Width,
3162                     (float)fbheight / (float)src_surface->pow2Height);
3163             glVertex2i(fbwidth, 0);
3164         glEnd();
3165     }
3166     glDisable(texture_target);
3167     checkGLcall("glDisable(texture_target)");
3168
3169     /* Cleanup */
3170     if (src != src_surface->texture_name && src != backup)
3171     {
3172         glDeleteTextures(1, &src);
3173         checkGLcall("glDeleteTextures(1, &src)");
3174     }
3175     if(backup) {
3176         glDeleteTextures(1, &backup);
3177         checkGLcall("glDeleteTextures(1, &backup)");
3178     }
3179
3180     LEAVE_GL();
3181
3182     if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
3183
3184     context_release(context);
3185
3186     /* The texture is now most up to date - If the surface is a render target and has a drawable, this
3187      * path is never entered
3188      */
3189     surface_modify_location(dst_surface, SFLAG_INTEXTURE, TRUE);
3190 }
3191
3192 /* Until the blit_shader is ready, define some prototypes here. */
3193 static BOOL fbo_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
3194                                const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool,
3195                                const struct wined3d_format_desc *src_format_desc,
3196                                const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool,
3197                                const struct wined3d_format_desc *dst_format_desc);
3198
3199 /* Front buffer coordinates are always full screen coordinates, but our GL
3200  * drawable is limited to the window's client area. The sysmem and texture
3201  * copies do have the full screen size. Note that GL has a bottom-left
3202  * origin, while D3D has a top-left origin. */
3203 void surface_translate_frontbuffer_coords(IWineD3DSurfaceImpl *surface, HWND window, RECT *rect)
3204 {
3205     POINT offset = {0, surface->currentDesc.Height};
3206     RECT windowsize;
3207
3208     GetClientRect(window, &windowsize);
3209     offset.y -= windowsize.bottom - windowsize.top;
3210     ScreenToClient(window, &offset);
3211     OffsetRect(rect, offset.x, offset.y);
3212 }
3213
3214 static BOOL surface_is_full_rect(IWineD3DSurfaceImpl *surface, const RECT *r)
3215 {
3216     if ((r->left && r->right) || abs(r->right - r->left) != surface->currentDesc.Width)
3217         return FALSE;
3218     if ((r->top && r->bottom) || abs(r->bottom - r->top) != surface->currentDesc.Height)
3219         return FALSE;
3220     return TRUE;
3221 }
3222
3223 /* blit between surface locations. onscreen on different swapchains is not supported.
3224  * depth / stencil is not supported. */
3225 static void surface_blt_fbo(IWineD3DDeviceImpl *device, const WINED3DTEXTUREFILTERTYPE filter,
3226         IWineD3DSurfaceImpl *src_surface, DWORD src_location, const RECT *src_rect_in,
3227         IWineD3DSurfaceImpl *dst_surface, DWORD dst_location, const RECT *dst_rect_in)
3228 {
3229     const struct wined3d_gl_info *gl_info;
3230     struct wined3d_context *context;
3231     RECT src_rect, dst_rect;
3232     GLenum gl_filter;
3233
3234     TRACE("device %p, filter %s,\n", device, debug_d3dtexturefiltertype(filter));
3235     TRACE("src_surface %p, src_location %s, src_rect %s,\n",
3236             src_surface, debug_surflocation(src_location), wine_dbgstr_rect(src_rect_in));
3237     TRACE("dst_surface %p, dst_location %s, dst_rect %s.\n",
3238             dst_surface, debug_surflocation(dst_location), wine_dbgstr_rect(dst_rect_in));
3239
3240     src_rect = *src_rect_in;
3241     dst_rect = *dst_rect_in;
3242
3243     switch (filter)
3244     {
3245         case WINED3DTEXF_LINEAR:
3246             gl_filter = GL_LINEAR;
3247             break;
3248
3249         default:
3250             FIXME("Unsupported filter mode %s (%#x).\n", debug_d3dtexturefiltertype(filter), filter);
3251         case WINED3DTEXF_NONE:
3252         case WINED3DTEXF_POINT:
3253             gl_filter = GL_NEAREST;
3254             break;
3255     }
3256
3257     if (src_location == SFLAG_INDRAWABLE && surface_is_offscreen(src_surface))
3258         src_location = SFLAG_INTEXTURE;
3259     if (dst_location == SFLAG_INDRAWABLE && surface_is_offscreen(dst_surface))
3260         dst_location = SFLAG_INTEXTURE;
3261
3262     /* Make sure the locations are up-to-date. Loading the destination
3263      * surface isn't required if the entire surface is overwritten. (And is
3264      * in fact harmful if we're being called by surface_load_location() with
3265      * the purpose of loading the destination surface.) */
3266     surface_load_location(src_surface, src_location, NULL);
3267     if (!surface_is_full_rect(dst_surface, &dst_rect))
3268         surface_load_location(dst_surface, dst_location, NULL);
3269
3270     if (src_location == SFLAG_INDRAWABLE) context = context_acquire(device, src_surface);
3271     else if (dst_location == SFLAG_INDRAWABLE) context = context_acquire(device, dst_surface);
3272     else context = context_acquire(device, NULL);
3273
3274     if (!context->valid)
3275     {
3276         context_release(context);
3277         WARN("Invalid context, skipping blit.\n");
3278         return;
3279     }
3280
3281     gl_info = context->gl_info;
3282
3283     if (src_location == SFLAG_INDRAWABLE)
3284     {
3285         GLenum buffer = surface_get_gl_buffer(src_surface);
3286
3287         TRACE("Source surface %p is onscreen.\n", src_surface);
3288
3289         if (buffer == GL_FRONT)
3290             surface_translate_frontbuffer_coords(src_surface, context->win_handle, &src_rect);
3291
3292         src_rect.top = src_surface->currentDesc.Height - src_rect.top;
3293         src_rect.bottom = src_surface->currentDesc.Height - src_rect.bottom;
3294
3295         ENTER_GL();
3296         context_bind_fbo(context, GL_READ_FRAMEBUFFER, NULL);
3297         glReadBuffer(buffer);
3298         checkGLcall("glReadBuffer()");
3299     }
3300     else
3301     {
3302         TRACE("Source surface %p is offscreen.\n", src_surface);
3303         ENTER_GL();
3304         context_apply_fbo_state_blit(context, GL_READ_FRAMEBUFFER, src_surface, NULL, src_location);
3305         glReadBuffer(GL_COLOR_ATTACHMENT0);
3306         checkGLcall("glReadBuffer()");
3307     }
3308     LEAVE_GL();
3309
3310     if (dst_location == SFLAG_INDRAWABLE)
3311     {
3312         GLenum buffer = surface_get_gl_buffer(dst_surface);
3313
3314         TRACE("Destination surface %p is onscreen.\n", dst_surface);
3315
3316         if (buffer == GL_FRONT)
3317             surface_translate_frontbuffer_coords(dst_surface, context->win_handle, &dst_rect);
3318
3319         dst_rect.top = dst_surface->currentDesc.Height - dst_rect.top;
3320         dst_rect.bottom = dst_surface->currentDesc.Height - dst_rect.bottom;
3321
3322         ENTER_GL();
3323         context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, NULL);
3324         context_set_draw_buffer(context, buffer);
3325     }
3326     else
3327     {
3328         TRACE("Destination surface %p is offscreen.\n", dst_surface);
3329
3330         ENTER_GL();
3331         context_apply_fbo_state_blit(context, GL_DRAW_FRAMEBUFFER, dst_surface, NULL, dst_location);
3332         context_set_draw_buffer(context, GL_COLOR_ATTACHMENT0);
3333     }
3334
3335     glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
3336     IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE));
3337     IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1));
3338     IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2));
3339     IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3));
3340
3341     glDisable(GL_SCISSOR_TEST);
3342     IWineD3DDeviceImpl_MarkStateDirty(device, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
3343
3344     gl_info->fbo_ops.glBlitFramebuffer(src_rect.left, src_rect.top, src_rect.right, src_rect.bottom,
3345             dst_rect.left, dst_rect.top, dst_rect.right, dst_rect.bottom, GL_COLOR_BUFFER_BIT, gl_filter);
3346     checkGLcall("glBlitFramebuffer()");
3347
3348     LEAVE_GL();
3349
3350     if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
3351
3352     context_release(context);
3353 }
3354
3355 /* Not called from the VTable */
3356 static HRESULT IWineD3DSurfaceImpl_BltOverride(IWineD3DSurfaceImpl *dst_surface, const RECT *DestRect,
3357         IWineD3DSurfaceImpl *src_surface, const RECT *SrcRect, DWORD Flags, const WINEDDBLTFX *DDBltFx,
3358         WINED3DTEXTUREFILTERTYPE Filter)
3359 {
3360     IWineD3DDeviceImpl *device = dst_surface->resource.device;
3361     IWineD3DSwapChainImpl *srcSwapchain = NULL, *dstSwapchain = NULL;
3362     RECT dst_rect, src_rect;
3363
3364     TRACE("dst_surface %p, dst_rect %s, src_surface %p, src_rect %s, flags %#x, blt_fx %p, filter %s.\n",
3365             dst_surface, wine_dbgstr_rect(DestRect), src_surface, wine_dbgstr_rect(SrcRect),
3366             Flags, DDBltFx, debug_d3dtexturefiltertype(Filter));
3367
3368     /* Get the swapchain. One of the surfaces has to be a primary surface */
3369     if (dst_surface->resource.pool == WINED3DPOOL_SYSTEMMEM)
3370     {
3371         WARN("Destination is in sysmem, rejecting gl blt\n");
3372         return WINED3DERR_INVALIDCALL;
3373     }
3374
3375     if (dst_surface->container.type == WINED3D_CONTAINER_SWAPCHAIN)
3376         dstSwapchain = dst_surface->container.u.swapchain;
3377
3378     if (src_surface)
3379     {
3380         if (src_surface->resource.pool == WINED3DPOOL_SYSTEMMEM)
3381         {
3382             WARN("Src is in sysmem, rejecting gl blt\n");
3383             return WINED3DERR_INVALIDCALL;
3384         }
3385
3386         if (src_surface->container.type == WINED3D_CONTAINER_SWAPCHAIN)
3387             srcSwapchain = src_surface->container.u.swapchain;
3388     }
3389
3390     /* Early sort out of cases where no render target is used */
3391     if (!dstSwapchain && !srcSwapchain
3392             && src_surface != device->render_targets[0]
3393             && dst_surface != device->render_targets[0])
3394     {
3395         TRACE("No surface is render target, not using hardware blit.\n");
3396         return WINED3DERR_INVALIDCALL;
3397     }
3398
3399     /* No destination color keying supported */
3400     if(Flags & (WINEDDBLT_KEYDEST | WINEDDBLT_KEYDESTOVERRIDE)) {
3401         /* Can we support that with glBlendFunc if blitting to the frame buffer? */
3402         TRACE("Destination color key not supported in accelerated Blit, falling back to software\n");
3403         return WINED3DERR_INVALIDCALL;
3404     }
3405
3406     surface_get_rect(dst_surface, DestRect, &dst_rect);
3407     if (src_surface) surface_get_rect(src_surface, SrcRect, &src_rect);
3408
3409     /* The only case where both surfaces on a swapchain are supported is a back buffer -> front buffer blit on the same swapchain */
3410     if (dstSwapchain && dstSwapchain == srcSwapchain && dstSwapchain->back_buffers
3411             && dst_surface == dstSwapchain->front_buffer
3412             && src_surface == dstSwapchain->back_buffers[0])
3413     {
3414         /* Half-Life does a Blt from the back buffer to the front buffer,
3415          * Full surface size, no flags... Use present instead
3416          *
3417          * This path will only be entered for d3d7 and ddraw apps, because d3d8/9 offer no way to blit TO the front buffer
3418          */
3419
3420         /* Check rects - IWineD3DDevice_Present doesn't handle them */
3421         while(1)
3422         {
3423             TRACE("Looking if a Present can be done...\n");
3424             /* Source Rectangle must be full surface */
3425             if (src_rect.left || src_rect.top
3426                     || src_rect.right != src_surface->currentDesc.Width
3427                     || src_rect.bottom != src_surface->currentDesc.Height)
3428             {
3429                 TRACE("No, Source rectangle doesn't match\n");
3430                 break;
3431             }
3432
3433             /* No stretching may occur */
3434             if(src_rect.right != dst_rect.right - dst_rect.left ||
3435                src_rect.bottom != dst_rect.bottom - dst_rect.top) {
3436                 TRACE("No, stretching is done\n");
3437                 break;
3438             }
3439
3440             /* Destination must be full surface or match the clipping rectangle */
3441             if (dst_surface->clipper && ((IWineD3DClipperImpl *)dst_surface->clipper)->hWnd)
3442             {
3443                 RECT cliprect;
3444                 POINT pos[2];
3445                 GetClientRect(((IWineD3DClipperImpl *)dst_surface->clipper)->hWnd, &cliprect);
3446                 pos[0].x = dst_rect.left;
3447                 pos[0].y = dst_rect.top;
3448                 pos[1].x = dst_rect.right;
3449                 pos[1].y = dst_rect.bottom;
3450                 MapWindowPoints(GetDesktopWindow(), ((IWineD3DClipperImpl *)dst_surface->clipper)->hWnd, pos, 2);
3451
3452                 if(pos[0].x != cliprect.left  || pos[0].y != cliprect.top   ||
3453                    pos[1].x != cliprect.right || pos[1].y != cliprect.bottom)
3454                 {
3455                     TRACE("No, dest rectangle doesn't match(clipper)\n");
3456                     TRACE("Clip rect at %s\n", wine_dbgstr_rect(&cliprect));
3457                     TRACE("Blt dest: %s\n", wine_dbgstr_rect(&dst_rect));
3458                     break;
3459                 }
3460             }
3461             else if (dst_rect.left || dst_rect.top
3462                     || dst_rect.right != dst_surface->currentDesc.Width
3463                     || dst_rect.bottom != dst_surface->currentDesc.Height)
3464             {
3465                 TRACE("No, dest rectangle doesn't match(surface size)\n");
3466                 break;
3467             }
3468
3469             TRACE("Yes\n");
3470
3471             /* These flags are unimportant for the flag check, remove them */
3472             if((Flags & ~(WINEDDBLT_DONOTWAIT | WINEDDBLT_WAIT)) == 0) {
3473                 WINED3DSWAPEFFECT orig_swap = dstSwapchain->presentParms.SwapEffect;
3474
3475                 /* The idea behind this is that a glReadPixels and a glDrawPixels call
3476                     * take very long, while a flip is fast.
3477                     * This applies to Half-Life, which does such Blts every time it finished
3478                     * a frame, and to Prince of Persia 3D, which uses this to draw at least the main
3479                     * menu. This is also used by all apps when they do windowed rendering
3480                     *
3481                     * The problem is that flipping is not really the same as copying. After a
3482                     * Blt the front buffer is a copy of the back buffer, and the back buffer is
3483                     * untouched. Therefore it's necessary to override the swap effect
3484                     * and to set it back after the flip.
3485                     *
3486                     * Windowed Direct3D < 7 apps do the same. The D3D7 sdk demos are nice
3487                     * testcases.
3488                     */
3489
3490                 dstSwapchain->presentParms.SwapEffect = WINED3DSWAPEFFECT_COPY;
3491                 dstSwapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
3492
3493                 TRACE("Full screen back buffer -> front buffer blt, performing a flip instead\n");
3494                 IWineD3DSwapChain_Present((IWineD3DSwapChain *)dstSwapchain,
3495                         NULL, NULL, dstSwapchain->win_handle, NULL, 0);
3496
3497                 dstSwapchain->presentParms.SwapEffect = orig_swap;
3498
3499                 return WINED3D_OK;
3500             }
3501             break;
3502         }
3503
3504         TRACE("Unsupported blit between buffers on the same swapchain\n");
3505         return WINED3DERR_INVALIDCALL;
3506     } else if(dstSwapchain && dstSwapchain == srcSwapchain) {
3507         FIXME("Implement hardware blit between two surfaces on the same swapchain\n");
3508         return WINED3DERR_INVALIDCALL;
3509     } else if(dstSwapchain && srcSwapchain) {
3510         FIXME("Implement hardware blit between two different swapchains\n");
3511         return WINED3DERR_INVALIDCALL;
3512     }
3513     else if (dstSwapchain)
3514     {
3515         /* Handled with regular texture -> swapchain blit */
3516         if (src_surface == device->render_targets[0])
3517             TRACE("Blit from active render target to a swapchain\n");
3518     }
3519     else if (srcSwapchain && dst_surface == device->render_targets[0])
3520     {
3521         FIXME("Implement blit from a swapchain to the active render target\n");
3522         return WINED3DERR_INVALIDCALL;
3523     }
3524
3525     if ((srcSwapchain || src_surface == device->render_targets[0]) && !dstSwapchain)
3526     {
3527         /* Blit from render target to texture */
3528         BOOL stretchx;
3529
3530         /* P8 read back is not implemented */
3531         if (src_surface->resource.format_desc->format == WINED3DFMT_P8_UINT
3532                 || dst_surface->resource.format_desc->format == WINED3DFMT_P8_UINT)
3533         {
3534             TRACE("P8 read back not supported by frame buffer to texture blit\n");
3535             return WINED3DERR_INVALIDCALL;
3536         }
3537
3538         if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3539             TRACE("Color keying not supported by frame buffer to texture blit\n");
3540             return WINED3DERR_INVALIDCALL;
3541             /* Destination color key is checked above */
3542         }
3543
3544         if(dst_rect.right - dst_rect.left != src_rect.right - src_rect.left) {
3545             stretchx = TRUE;
3546         } else {
3547             stretchx = FALSE;
3548         }
3549
3550         /* Blt is a pretty powerful call, while glCopyTexSubImage2D is not. glCopyTexSubImage cannot
3551          * flip the image nor scale it.
3552          *
3553          * -> If the app asks for a unscaled, upside down copy, just perform one glCopyTexSubImage2D call
3554          * -> If the app wants a image width an unscaled width, copy it line per line
3555          * -> If the app wants a image that is scaled on the x axis, and the destination rectangle is smaller
3556          *    than the frame buffer, draw an upside down scaled image onto the fb, read it back and restore the
3557          *    back buffer. This is slower than reading line per line, thus not used for flipping
3558          * -> If the app wants a scaled image with a dest rect that is bigger than the fb, it has to be copied
3559          *    pixel by pixel
3560          *
3561          * If EXT_framebuffer_blit is supported that can be used instead. Note that EXT_framebuffer_blit implies
3562          * FBO support, so it doesn't really make sense to try and make it work with different offscreen rendering
3563          * backends.
3564          */
3565         if (fbo_blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
3566                 &src_rect, src_surface->resource.usage, src_surface->resource.pool, src_surface->resource.format_desc,
3567                 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool, dst_surface->resource.format_desc))
3568         {
3569             surface_blt_fbo(device, Filter,
3570                     src_surface, SFLAG_INDRAWABLE, &src_rect,
3571                     dst_surface, SFLAG_INDRAWABLE, &dst_rect);
3572             surface_modify_location(dst_surface, SFLAG_INDRAWABLE, TRUE);
3573         }
3574         else if (!stretchx || dst_rect.right - dst_rect.left > src_surface->currentDesc.Width
3575                 || dst_rect.bottom - dst_rect.top > src_surface->currentDesc.Height)
3576         {
3577             TRACE("No stretching in x direction, using direct framebuffer -> texture copy\n");
3578             fb_copy_to_texture_direct(dst_surface, src_surface, &src_rect, &dst_rect, Filter);
3579         } else {
3580             TRACE("Using hardware stretching to flip / stretch the texture\n");
3581             fb_copy_to_texture_hwstretch(dst_surface, src_surface, &src_rect, &dst_rect, Filter);
3582         }
3583
3584         if (!(dst_surface->Flags & SFLAG_DONOTFREE))
3585         {
3586             HeapFree(GetProcessHeap(), 0, dst_surface->resource.heapMemory);
3587             dst_surface->resource.allocatedMemory = NULL;
3588             dst_surface->resource.heapMemory = NULL;
3589         }
3590         else
3591         {
3592             dst_surface->Flags &= ~SFLAG_INSYSMEM;
3593         }
3594
3595         return WINED3D_OK;
3596     }
3597     else if (src_surface)
3598     {
3599         /* Blit from offscreen surface to render target */
3600         DWORD oldCKeyFlags = src_surface->CKeyFlags;
3601         WINEDDCOLORKEY oldBltCKey = src_surface->SrcBltCKey;
3602         struct wined3d_context *context;
3603
3604         TRACE("Blt from surface %p to rendertarget %p\n", src_surface, dst_surface);
3605
3606         if (!(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE))
3607                 && fbo_blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
3608                         &src_rect, src_surface->resource.usage, src_surface->resource.pool,
3609                         src_surface->resource.format_desc,
3610                         &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool,
3611                         dst_surface->resource.format_desc))
3612         {
3613             TRACE("Using surface_blt_fbo.\n");
3614             /* The source is always a texture, but never the currently active render target, and the texture
3615              * contents are never upside down. */
3616             surface_blt_fbo(device, Filter,
3617                     src_surface, SFLAG_INDRAWABLE, &src_rect,
3618                     dst_surface, SFLAG_INDRAWABLE, &dst_rect);
3619             surface_modify_location(dst_surface, SFLAG_INDRAWABLE, TRUE);
3620             return WINED3D_OK;
3621         }
3622
3623         if (!(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE))
3624                 && arbfp_blit.blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
3625                         &src_rect, src_surface->resource.usage, src_surface->resource.pool,
3626                         src_surface->resource.format_desc,
3627                         &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool,
3628                         dst_surface->resource.format_desc))
3629         {
3630             return arbfp_blit_surface(device, src_surface, &src_rect, dst_surface, &dst_rect, BLIT_OP_BLIT, Filter);
3631         }
3632
3633         /* Color keying: Check if we have to do a color keyed blt,
3634          * and if not check if a color key is activated.
3635          *
3636          * Just modify the color keying parameters in the surface and restore them afterwards
3637          * The surface keeps track of the color key last used to load the opengl surface.
3638          * PreLoad will catch the change to the flags and color key and reload if necessary.
3639          */
3640         if(Flags & WINEDDBLT_KEYSRC) {
3641             /* Use color key from surface */
3642         } else if(Flags & WINEDDBLT_KEYSRCOVERRIDE) {
3643             /* Use color key from DDBltFx */
3644             src_surface->CKeyFlags |= WINEDDSD_CKSRCBLT;
3645             src_surface->SrcBltCKey = DDBltFx->ddckSrcColorkey;
3646         } else {
3647             /* Do not use color key */
3648             src_surface->CKeyFlags &= ~WINEDDSD_CKSRCBLT;
3649         }
3650
3651         /* Now load the surface */
3652         surface_internal_preload(src_surface, SRGB_RGB);
3653
3654         /* Activate the destination context, set it up for blitting */
3655         context = context_acquire(device, dst_surface);
3656         context_apply_blit_state(context, device);
3657
3658         if (dstSwapchain && dst_surface == dstSwapchain->front_buffer)
3659             surface_translate_frontbuffer_coords(dst_surface, context->win_handle, &dst_rect);
3660
3661         if (!device->blitter->blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
3662                 &src_rect, src_surface->resource.usage, src_surface->resource.pool, src_surface->resource.format_desc,
3663                 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool, dst_surface->resource.format_desc))
3664         {
3665             FIXME("Unsupported blit operation falling back to software\n");
3666             return WINED3DERR_INVALIDCALL;
3667         }
3668
3669         device->blitter->set_shader((IWineD3DDevice *)device, src_surface);
3670
3671         ENTER_GL();
3672
3673         /* This is for color keying */
3674         if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3675             glEnable(GL_ALPHA_TEST);
3676             checkGLcall("glEnable(GL_ALPHA_TEST)");
3677
3678             /* When the primary render target uses P8, the alpha component contains the palette index.
3679              * Which means that the colorkey is one of the palette entries. In other cases pixels that
3680              * should be masked away have alpha set to 0. */
3681             if (primary_render_target_is_p8(device))
3682                 glAlphaFunc(GL_NOTEQUAL, (float)src_surface->SrcBltCKey.dwColorSpaceLowValue / 256.0f);
3683             else
3684                 glAlphaFunc(GL_NOTEQUAL, 0.0f);
3685             checkGLcall("glAlphaFunc");
3686         } else {
3687             glDisable(GL_ALPHA_TEST);
3688             checkGLcall("glDisable(GL_ALPHA_TEST)");
3689         }
3690
3691         /* Draw a textured quad
3692          */
3693         draw_textured_quad(src_surface, &src_rect, &dst_rect, Filter);
3694
3695         if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3696             glDisable(GL_ALPHA_TEST);
3697             checkGLcall("glDisable(GL_ALPHA_TEST)");
3698         }
3699
3700         /* Restore the color key parameters */
3701         src_surface->CKeyFlags = oldCKeyFlags;
3702         src_surface->SrcBltCKey = oldBltCKey;
3703
3704         LEAVE_GL();
3705
3706         /* Leave the opengl state valid for blitting */
3707         device->blitter->unset_shader((IWineD3DDevice *)device);
3708
3709         if (wined3d_settings.strict_draw_ordering || (dstSwapchain
3710                 && (dst_surface == dstSwapchain->front_buffer
3711                 || dstSwapchain->num_contexts > 1)))
3712             wglFlush(); /* Flush to ensure ordering across contexts. */
3713
3714         context_release(context);
3715
3716         /* TODO: If the surface is locked often, perform the Blt in software on the memory instead */
3717         /* The surface is now in the drawable. On onscreen surfaces or without fbos the texture
3718          * is outdated now
3719          */
3720         surface_modify_location(dst_surface, SFLAG_INDRAWABLE, TRUE);
3721
3722         return WINED3D_OK;
3723     } else {
3724         /* Source-Less Blit to render target */
3725         if (Flags & WINEDDBLT_COLORFILL) {
3726             DWORD color;
3727
3728             TRACE("Colorfill\n");
3729
3730             /* The color as given in the Blt function is in the format of the frame-buffer...
3731              * 'clear' expect it in ARGB format => we need to do some conversion :-)
3732              */
3733             if (!surface_convert_color_to_argb(dst_surface, DDBltFx->u5.dwFillColor, &color))
3734             {
3735                 /* The color conversion function already prints an error, so need to do it here */
3736                 return WINED3DERR_INVALIDCALL;
3737             }
3738
3739             if (ffp_blit.blit_supported(&device->adapter->gl_info, BLIT_OP_COLOR_FILL,
3740                     NULL, 0, 0, NULL,
3741                     &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool,
3742                     dst_surface->resource.format_desc))
3743             {
3744                 return ffp_blit.color_fill(device, dst_surface, &dst_rect, color);
3745             }
3746             else if (cpu_blit.blit_supported(&device->adapter->gl_info, BLIT_OP_COLOR_FILL,
3747                     NULL, 0, 0, NULL,
3748                     &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool,
3749                     dst_surface->resource.format_desc))
3750             {
3751                 return cpu_blit.color_fill(device, dst_surface, &dst_rect, color);
3752             }
3753             return WINED3DERR_INVALIDCALL;
3754         }
3755     }
3756
3757     /* Default: Fall back to the generic blt. Not an error, a TRACE is enough */
3758     TRACE("Didn't find any usable render target setup for hw blit, falling back to software\n");
3759     return WINED3DERR_INVALIDCALL;
3760 }
3761
3762 static HRESULT IWineD3DSurfaceImpl_BltZ(IWineD3DSurfaceImpl *This, const RECT *DestRect,
3763         IWineD3DSurface *src_surface, const RECT *src_rect, DWORD Flags, const WINEDDBLTFX *DDBltFx)
3764 {
3765     IWineD3DDeviceImpl *device = This->resource.device;
3766     float depth;
3767
3768     if (Flags & WINEDDBLT_DEPTHFILL) {
3769         switch(This->resource.format_desc->format)
3770         {
3771             case WINED3DFMT_D16_UNORM:
3772                 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000ffff;
3773                 break;
3774             case WINED3DFMT_S1_UINT_D15_UNORM:
3775                 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x00007fff;
3776                 break;
3777             case WINED3DFMT_D24_UNORM_S8_UINT:
3778             case WINED3DFMT_X8D24_UNORM:
3779                 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x00ffffff;
3780                 break;
3781             case WINED3DFMT_D32_UNORM:
3782                 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0xffffffff;
3783                 break;
3784             default:
3785                 depth = 0.0f;
3786                 ERR("Unexpected format for depth fill: %s\n", debug_d3dformat(This->resource.format_desc->format));
3787         }
3788
3789         return IWineD3DDevice_Clear((IWineD3DDevice *)device, DestRect ? 1 : 0, (const WINED3DRECT *)DestRect,
3790                 WINED3DCLEAR_ZBUFFER, 0x00000000, depth, 0x00000000);
3791     }
3792
3793     FIXME("(%p): Unsupp depthstencil blit\n", This);
3794     return WINED3DERR_INVALIDCALL;
3795 }
3796
3797 static HRESULT WINAPI IWineD3DSurfaceImpl_Blt(IWineD3DSurface *iface, const RECT *DestRect,
3798         IWineD3DSurface *src_surface, const RECT *SrcRect, DWORD Flags,
3799         const WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter)
3800 {
3801     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3802     IWineD3DSurfaceImpl *src = (IWineD3DSurfaceImpl *)src_surface;
3803     IWineD3DDeviceImpl *device = This->resource.device;
3804
3805     TRACE("iface %p, dst_rect %s, src_surface %p, src_rect %s, flags %#x, fx %p, filter %s.\n",
3806             iface, wine_dbgstr_rect(DestRect), src_surface, wine_dbgstr_rect(SrcRect),
3807             Flags, DDBltFx, debug_d3dtexturefiltertype(Filter));
3808     TRACE("Usage is %s.\n", debug_d3dusage(This->resource.usage));
3809
3810     if ((This->Flags & SFLAG_LOCKED) || (src && (src->Flags & SFLAG_LOCKED)))
3811     {
3812         WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
3813         return WINEDDERR_SURFACEBUSY;
3814     }
3815
3816     /* Accessing the depth stencil is supposed to fail between a BeginScene and EndScene pair,
3817      * except depth blits, which seem to work
3818      */
3819     if (This == device->depth_stencil || (src && src == device->depth_stencil))
3820     {
3821         if (device->inScene && !(Flags & WINEDDBLT_DEPTHFILL))
3822         {
3823             TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3824             return WINED3DERR_INVALIDCALL;
3825         }
3826         else if (SUCCEEDED(IWineD3DSurfaceImpl_BltZ(This, DestRect, src_surface, SrcRect, Flags, DDBltFx)))
3827         {
3828             TRACE("Z Blit override handled the blit\n");
3829             return WINED3D_OK;
3830         }
3831     }
3832
3833     /* Special cases for RenderTargets */
3834     if ((This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3835             || (src && (src->resource.usage & WINED3DUSAGE_RENDERTARGET)))
3836     {
3837         if (SUCCEEDED(IWineD3DSurfaceImpl_BltOverride(This, DestRect, src, SrcRect, Flags, DDBltFx, Filter)))
3838             return WINED3D_OK;
3839     }
3840
3841     /* For the rest call the X11 surface implementation.
3842      * For RenderTargets this should be implemented OpenGL accelerated in BltOverride,
3843      * other Blts are rather rare. */
3844     return IWineD3DBaseSurfaceImpl_Blt(iface, DestRect, src_surface, SrcRect, Flags, DDBltFx, Filter);
3845 }
3846
3847 static HRESULT WINAPI IWineD3DSurfaceImpl_BltFast(IWineD3DSurface *iface, DWORD dstx, DWORD dsty,
3848         IWineD3DSurface *src_surface, const RECT *rsrc, DWORD trans)
3849 {
3850     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3851     IWineD3DSurfaceImpl *src = (IWineD3DSurfaceImpl *)src_surface;
3852     IWineD3DDeviceImpl *device = This->resource.device;
3853
3854     TRACE("iface %p, dst_x %u, dst_y %u, src_surface %p, src_rect %s, flags %#x.\n",
3855             iface, dstx, dsty, src_surface, wine_dbgstr_rect(rsrc), trans);
3856
3857     if ((This->Flags & SFLAG_LOCKED) || (src->Flags & SFLAG_LOCKED))
3858     {
3859         WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
3860         return WINEDDERR_SURFACEBUSY;
3861     }
3862
3863     if (device->inScene && (This == device->depth_stencil || src == device->depth_stencil))
3864     {
3865         TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3866         return WINED3DERR_INVALIDCALL;
3867     }
3868
3869     /* Special cases for RenderTargets */
3870     if ((This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3871             || (src->resource.usage & WINED3DUSAGE_RENDERTARGET))
3872     {
3873
3874         RECT SrcRect, DstRect;
3875         DWORD Flags=0;
3876
3877         surface_get_rect(src, rsrc, &SrcRect);
3878
3879         DstRect.left = dstx;
3880         DstRect.top=dsty;
3881         DstRect.right = dstx + SrcRect.right - SrcRect.left;
3882         DstRect.bottom = dsty + SrcRect.bottom - SrcRect.top;
3883
3884         /* Convert BltFast flags into Btl ones because it is called from SurfaceImpl_Blt as well */
3885         if(trans & WINEDDBLTFAST_SRCCOLORKEY)
3886             Flags |= WINEDDBLT_KEYSRC;
3887         if(trans & WINEDDBLTFAST_DESTCOLORKEY)
3888             Flags |= WINEDDBLT_KEYDEST;
3889         if(trans & WINEDDBLTFAST_WAIT)
3890             Flags |= WINEDDBLT_WAIT;
3891         if(trans & WINEDDBLTFAST_DONOTWAIT)
3892             Flags |= WINEDDBLT_DONOTWAIT;
3893
3894         if (SUCCEEDED(IWineD3DSurfaceImpl_BltOverride(This,
3895                 &DstRect, src, &SrcRect, Flags, NULL, WINED3DTEXF_POINT)))
3896             return WINED3D_OK;
3897     }
3898
3899     return IWineD3DBaseSurfaceImpl_BltFast(iface, dstx, dsty, src_surface, rsrc, trans);
3900 }
3901
3902 static HRESULT WINAPI IWineD3DSurfaceImpl_RealizePalette(IWineD3DSurface *iface)
3903 {
3904     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3905     RGBQUAD col[256];
3906     IWineD3DPaletteImpl *pal = This->palette;
3907     unsigned int n;
3908     TRACE("(%p)\n", This);
3909
3910     if (!pal) return WINED3D_OK;
3911
3912     if (This->resource.format_desc->format == WINED3DFMT_P8_UINT
3913             || This->resource.format_desc->format == WINED3DFMT_P8_UINT_A8_UNORM)
3914     {
3915         if (This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3916         {
3917             /* Make sure the texture is up to date. This call doesn't do
3918              * anything if the texture is already up to date. */
3919             surface_load_location(This, SFLAG_INTEXTURE, NULL);
3920
3921             /* We want to force a palette refresh, so mark the drawable as not being up to date */
3922             surface_modify_location(This, SFLAG_INDRAWABLE, FALSE);
3923         }
3924         else
3925         {
3926             if (!(This->Flags & SFLAG_INSYSMEM))
3927             {
3928                 TRACE("Palette changed with surface that does not have an up to date system memory copy.\n");
3929                 surface_load_location(This, SFLAG_INSYSMEM, NULL);
3930             }
3931             TRACE("Dirtifying surface\n");
3932             surface_modify_location(This, SFLAG_INSYSMEM, TRUE);
3933         }
3934     }
3935
3936     if(This->Flags & SFLAG_DIBSECTION) {
3937         TRACE("(%p): Updating the hdc's palette\n", This);
3938         for (n=0; n<256; n++) {
3939             col[n].rgbRed   = pal->palents[n].peRed;
3940             col[n].rgbGreen = pal->palents[n].peGreen;
3941             col[n].rgbBlue  = pal->palents[n].peBlue;
3942             col[n].rgbReserved = 0;
3943         }
3944         SetDIBColorTable(This->hDC, 0, 256, col);
3945     }
3946
3947     /* Propagate the changes to the drawable when we have a palette. */
3948     if (This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3949         surface_load_location(This, SFLAG_INDRAWABLE, NULL);
3950
3951     return WINED3D_OK;
3952 }
3953
3954 static HRESULT WINAPI IWineD3DSurfaceImpl_PrivateSetup(IWineD3DSurface *iface) {
3955     /** Check against the maximum texture sizes supported by the video card **/
3956     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3957     const struct wined3d_gl_info *gl_info = &This->resource.device->adapter->gl_info;
3958     unsigned int pow2Width, pow2Height;
3959
3960     This->texture_name = 0;
3961     This->texture_target = GL_TEXTURE_2D;
3962
3963     /* Non-power2 support */
3964     if (gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] || gl_info->supported[WINED3D_GL_NORMALIZED_TEXRECT])
3965     {
3966         pow2Width = This->currentDesc.Width;
3967         pow2Height = This->currentDesc.Height;
3968     }
3969     else
3970     {
3971         /* Find the nearest pow2 match */
3972         pow2Width = pow2Height = 1;
3973         while (pow2Width < This->currentDesc.Width) pow2Width <<= 1;
3974         while (pow2Height < This->currentDesc.Height) pow2Height <<= 1;
3975     }
3976     This->pow2Width  = pow2Width;
3977     This->pow2Height = pow2Height;
3978
3979     if (pow2Width > This->currentDesc.Width || pow2Height > This->currentDesc.Height) {
3980         /** TODO: add support for non power two compressed textures **/
3981         if (This->resource.format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
3982         {
3983             FIXME("(%p) Compressed non-power-two textures are not supported w(%d) h(%d)\n",
3984                   This, This->currentDesc.Width, This->currentDesc.Height);
3985             return WINED3DERR_NOTAVAILABLE;
3986         }
3987     }
3988
3989     if(pow2Width != This->currentDesc.Width ||
3990        pow2Height != This->currentDesc.Height) {
3991         This->Flags |= SFLAG_NONPOW2;
3992     }
3993
3994     TRACE("%p\n", This);
3995     if ((This->pow2Width > gl_info->limits.texture_size || This->pow2Height > gl_info->limits.texture_size)
3996             && !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL)))
3997     {
3998         /* one of three options
3999         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)
4000         2: Set the texture to the maximum size (bad idea)
4001         3:    WARN and return WINED3DERR_NOTAVAILABLE;
4002         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.
4003         */
4004         if(This->resource.pool == WINED3DPOOL_DEFAULT || This->resource.pool == WINED3DPOOL_MANAGED)
4005         {
4006             WARN("(%p) Unable to allocate a surface which exceeds the maximum OpenGL texture size\n", This);
4007             return WINED3DERR_NOTAVAILABLE;
4008         }
4009
4010         /* We should never use this surface in combination with OpenGL! */
4011         TRACE("(%p) Creating an oversized surface: %ux%u\n", This, This->pow2Width, This->pow2Height);
4012     }
4013     else
4014     {
4015         /* Don't use ARB_TEXTURE_RECTANGLE in case the surface format is P8 and EXT_PALETTED_TEXTURE
4016            is used in combination with texture uploads (RTL_READTEX/RTL_TEXTEX). The reason is that EXT_PALETTED_TEXTURE
4017            doesn't work in combination with ARB_TEXTURE_RECTANGLE.
4018         */
4019         if (This->Flags & SFLAG_NONPOW2 && gl_info->supported[ARB_TEXTURE_RECTANGLE]
4020                 && !(This->resource.format_desc->format == WINED3DFMT_P8_UINT
4021                 && gl_info->supported[EXT_PALETTED_TEXTURE]
4022                 && wined3d_settings.rendertargetlock_mode == RTL_READTEX))
4023         {
4024             This->texture_target = GL_TEXTURE_RECTANGLE_ARB;
4025             This->pow2Width  = This->currentDesc.Width;
4026             This->pow2Height = This->currentDesc.Height;
4027             This->Flags &= ~(SFLAG_NONPOW2 | SFLAG_NORMCOORD);
4028         }
4029     }
4030
4031     switch (wined3d_settings.offscreen_rendering_mode)
4032     {
4033         case ORM_FBO:
4034             This->get_drawable_size = get_drawable_size_fbo;
4035             break;
4036
4037         case ORM_BACKBUFFER:
4038             This->get_drawable_size = get_drawable_size_backbuffer;
4039             break;
4040
4041         default:
4042             ERR("Unhandled offscreen rendering mode %#x.\n", wined3d_settings.offscreen_rendering_mode);
4043             return WINED3DERR_INVALIDCALL;
4044     }
4045
4046     This->Flags |= SFLAG_INSYSMEM;
4047
4048     return WINED3D_OK;
4049 }
4050
4051 /* GL locking is done by the caller */
4052 static void surface_depth_blt(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info,
4053         GLuint texture, GLsizei w, GLsizei h, GLenum target)
4054 {
4055     IWineD3DDeviceImpl *device = This->resource.device;
4056     GLint compare_mode = GL_NONE;
4057     struct blt_info info;
4058     GLint old_binding = 0;
4059
4060     glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_VIEWPORT_BIT);
4061
4062     glDisable(GL_CULL_FACE);
4063     glDisable(GL_BLEND);
4064     glDisable(GL_ALPHA_TEST);
4065     glDisable(GL_SCISSOR_TEST);
4066     glDisable(GL_STENCIL_TEST);
4067     glEnable(GL_DEPTH_TEST);
4068     glDepthFunc(GL_ALWAYS);
4069     glDepthMask(GL_TRUE);
4070     glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
4071     glViewport(0, 0, w, h);
4072
4073     surface_get_blt_info(target, NULL, w, h, &info);
4074     GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
4075     glGetIntegerv(info.binding, &old_binding);
4076     glBindTexture(info.bind_target, texture);
4077     if (gl_info->supported[ARB_SHADOW])
4078     {
4079         glGetTexParameteriv(info.bind_target, GL_TEXTURE_COMPARE_MODE_ARB, &compare_mode);
4080         if (compare_mode != GL_NONE) glTexParameteri(info.bind_target, GL_TEXTURE_COMPARE_MODE_ARB, GL_NONE);
4081     }
4082
4083     device->shader_backend->shader_select_depth_blt((IWineD3DDevice *)device,
4084             info.tex_type, &This->ds_current_size);
4085
4086     glBegin(GL_TRIANGLE_STRIP);
4087     glTexCoord3fv(info.coords[0]);
4088     glVertex2f(-1.0f, -1.0f);
4089     glTexCoord3fv(info.coords[1]);
4090     glVertex2f(1.0f, -1.0f);
4091     glTexCoord3fv(info.coords[2]);
4092     glVertex2f(-1.0f, 1.0f);
4093     glTexCoord3fv(info.coords[3]);
4094     glVertex2f(1.0f, 1.0f);
4095     glEnd();
4096
4097     if (compare_mode != GL_NONE) glTexParameteri(info.bind_target, GL_TEXTURE_COMPARE_MODE_ARB, compare_mode);
4098     glBindTexture(info.bind_target, old_binding);
4099
4100     glPopAttrib();
4101
4102     device->shader_backend->shader_deselect_depth_blt((IWineD3DDevice *)device);
4103 }
4104
4105 void surface_modify_ds_location(IWineD3DSurfaceImpl *surface,
4106         DWORD location, UINT w, UINT h)
4107 {
4108     TRACE("surface %p, new location %#x, w %u, h %u.\n", surface, location, w, h);
4109
4110     if (location & ~SFLAG_DS_LOCATIONS)
4111         FIXME("Invalid location (%#x) specified.\n", location);
4112
4113     surface->ds_current_size.cx = w;
4114     surface->ds_current_size.cy = h;
4115     surface->Flags &= ~SFLAG_DS_LOCATIONS;
4116     surface->Flags |= location;
4117 }
4118
4119 /* Context activation is done by the caller. */
4120 void surface_load_ds_location(IWineD3DSurfaceImpl *surface, struct wined3d_context *context, DWORD location)
4121 {
4122     IWineD3DDeviceImpl *device = surface->resource.device;
4123     const struct wined3d_gl_info *gl_info = context->gl_info;
4124
4125     TRACE("surface %p, new location %#x.\n", surface, location);
4126
4127     /* TODO: Make this work for modes other than FBO */
4128     if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return;
4129
4130     if (!(surface->Flags & location))
4131     {
4132         surface->ds_current_size.cx = 0;
4133         surface->ds_current_size.cy = 0;
4134     }
4135
4136     if (surface->ds_current_size.cx == surface->currentDesc.Width
4137             && surface->ds_current_size.cy == surface->currentDesc.Height)
4138     {
4139         TRACE("Location (%#x) is already up to date.\n", location);
4140         return;
4141     }
4142
4143     if (surface->current_renderbuffer)
4144     {
4145         FIXME("Not supported with fixed up depth stencil.\n");
4146         return;
4147     }
4148
4149     if (!(surface->Flags & SFLAG_LOCATIONS))
4150     {
4151         FIXME("No up to date depth stencil location.\n");
4152         surface->Flags |= location;
4153         return;
4154     }
4155
4156     if (location == SFLAG_DS_OFFSCREEN)
4157     {
4158         GLint old_binding = 0;
4159         GLenum bind_target;
4160
4161         TRACE("Copying onscreen depth buffer to depth texture.\n");
4162
4163         ENTER_GL();
4164
4165         if (!device->depth_blt_texture)
4166         {
4167             glGenTextures(1, &device->depth_blt_texture);
4168         }
4169
4170         /* Note that we use depth_blt here as well, rather than glCopyTexImage2D
4171          * directly on the FBO texture. That's because we need to flip. */
4172         context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
4173         if (surface->texture_target == GL_TEXTURE_RECTANGLE_ARB)
4174         {
4175             glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
4176             bind_target = GL_TEXTURE_RECTANGLE_ARB;
4177         }
4178         else
4179         {
4180             glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
4181             bind_target = GL_TEXTURE_2D;
4182         }
4183         glBindTexture(bind_target, device->depth_blt_texture);
4184         glCopyTexImage2D(bind_target, surface->texture_level, surface->resource.format_desc->glInternal,
4185                 0, 0, surface->currentDesc.Width, surface->currentDesc.Height, 0);
4186         glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
4187         glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
4188         glTexParameteri(bind_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
4189         glTexParameteri(bind_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
4190         glTexParameteri(bind_target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
4191         glTexParameteri(bind_target, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE);
4192         glBindTexture(bind_target, old_binding);
4193
4194         /* Setup the destination */
4195         if (!device->depth_blt_rb)
4196         {
4197             gl_info->fbo_ops.glGenRenderbuffers(1, &device->depth_blt_rb);
4198             checkGLcall("glGenRenderbuffersEXT");
4199         }
4200         if (device->depth_blt_rb_w != surface->currentDesc.Width
4201                 || device->depth_blt_rb_h != surface->currentDesc.Height)
4202         {
4203             gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, device->depth_blt_rb);
4204             checkGLcall("glBindRenderbufferEXT");
4205             gl_info->fbo_ops.glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8,
4206                     surface->currentDesc.Width, surface->currentDesc.Height);
4207             checkGLcall("glRenderbufferStorageEXT");
4208             device->depth_blt_rb_w = surface->currentDesc.Width;
4209             device->depth_blt_rb_h = surface->currentDesc.Height;
4210         }
4211
4212         context_bind_fbo(context, GL_FRAMEBUFFER, &context->dst_fbo);
4213         gl_info->fbo_ops.glFramebufferRenderbuffer(GL_FRAMEBUFFER,
4214                 GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, device->depth_blt_rb);
4215         checkGLcall("glFramebufferRenderbufferEXT");
4216         context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER, surface, FALSE);
4217
4218         /* Do the actual blit */
4219         surface_depth_blt(surface, gl_info, device->depth_blt_texture,
4220                 surface->currentDesc.Width, surface->currentDesc.Height, bind_target);
4221         checkGLcall("depth_blt");
4222
4223         if (context->current_fbo) context_bind_fbo(context, GL_FRAMEBUFFER, &context->current_fbo->id);
4224         else context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
4225
4226         LEAVE_GL();
4227
4228         if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
4229     }
4230     else if (location == SFLAG_DS_ONSCREEN)
4231     {
4232         TRACE("Copying depth texture to onscreen depth buffer.\n");
4233
4234         ENTER_GL();
4235
4236         context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
4237         surface_depth_blt(surface, gl_info, surface->texture_name,
4238                 surface->currentDesc.Width, surface->currentDesc.Height, surface->texture_target);
4239         checkGLcall("depth_blt");
4240
4241         if (context->current_fbo) context_bind_fbo(context, GL_FRAMEBUFFER, &context->current_fbo->id);
4242
4243         LEAVE_GL();
4244
4245         if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
4246     }
4247     else
4248     {
4249         ERR("Invalid location (%#x) specified.\n", location);
4250     }
4251
4252     surface->Flags |= location;
4253     surface->ds_current_size.cx = surface->currentDesc.Width;
4254     surface->ds_current_size.cy = surface->currentDesc.Height;
4255 }
4256
4257 void surface_modify_location(IWineD3DSurfaceImpl *surface, DWORD flag, BOOL persistent)
4258 {
4259     IWineD3DSurfaceImpl *overlay;
4260
4261     TRACE("surface %p, location %s, persistent %#x.\n",
4262             surface, debug_surflocation(flag), persistent);
4263
4264     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
4265     {
4266         if (surface_is_offscreen(surface))
4267         {
4268             /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
4269             if (flag & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE)) flag |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4270         }
4271         else
4272         {
4273             TRACE("Surface %p is an onscreen surface.\n", surface);
4274         }
4275     }
4276
4277     if (persistent)
4278     {
4279         if (((surface->Flags & SFLAG_INTEXTURE) && !(flag & SFLAG_INTEXTURE))
4280                 || ((surface->Flags & SFLAG_INSRGBTEX) && !(flag & SFLAG_INSRGBTEX)))
4281         {
4282             if (surface->container.type == WINED3D_CONTAINER_TEXTURE)
4283             {
4284                 TRACE("Passing to container.\n");
4285                 IWineD3DBaseTexture_SetDirty((IWineD3DBaseTexture *)surface->container.u.texture, TRUE);
4286             }
4287         }
4288         surface->Flags &= ~SFLAG_LOCATIONS;
4289         surface->Flags |= flag;
4290
4291         /* Redraw emulated overlays, if any */
4292         if (flag & SFLAG_INDRAWABLE && !list_empty(&surface->overlays))
4293         {
4294             LIST_FOR_EACH_ENTRY(overlay, &surface->overlays, IWineD3DSurfaceImpl, overlay_entry)
4295             {
4296                 IWineD3DSurface_DrawOverlay((IWineD3DSurface *)overlay);
4297             }
4298         }
4299     }
4300     else
4301     {
4302         if ((surface->Flags & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)) && (flag & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)))
4303         {
4304             if (surface->container.type == WINED3D_CONTAINER_TEXTURE)
4305             {
4306                 TRACE("Passing to container\n");
4307                 IWineD3DBaseTexture_SetDirty((IWineD3DBaseTexture *)surface->container.u.texture, TRUE);
4308             }
4309         }
4310         surface->Flags &= ~flag;
4311     }
4312
4313     if (!(surface->Flags & SFLAG_LOCATIONS))
4314     {
4315         ERR("Surface %p does not have any up to date location.\n", surface);
4316     }
4317 }
4318
4319 static inline void surface_blt_to_drawable(IWineD3DSurfaceImpl *This, const RECT *rect_in)
4320 {
4321     IWineD3DDeviceImpl *device = This->resource.device;
4322     IWineD3DSwapChainImpl *swapchain;
4323     struct wined3d_context *context;
4324     RECT src_rect, dst_rect;
4325
4326     surface_get_rect(This, rect_in, &src_rect);
4327
4328     context = context_acquire(device, This);
4329     context_apply_blit_state(context, device);
4330     if (context->render_offscreen)
4331     {
4332         dst_rect.left = src_rect.left;
4333         dst_rect.right = src_rect.right;
4334         dst_rect.top = src_rect.bottom;
4335         dst_rect.bottom = src_rect.top;
4336     }
4337     else
4338     {
4339         dst_rect = src_rect;
4340     }
4341
4342     swapchain = This->container.type == WINED3D_CONTAINER_SWAPCHAIN ? This->container.u.swapchain : NULL;
4343     if (swapchain && This == swapchain->front_buffer)
4344         surface_translate_frontbuffer_coords(This, context->win_handle, &dst_rect);
4345
4346     device->blitter->set_shader((IWineD3DDevice *) device, This);
4347
4348     ENTER_GL();
4349     draw_textured_quad(This, &src_rect, &dst_rect, WINED3DTEXF_POINT);
4350     LEAVE_GL();
4351
4352     device->blitter->unset_shader((IWineD3DDevice *) device);
4353
4354     if (wined3d_settings.strict_draw_ordering || (swapchain
4355             && (This == swapchain->front_buffer || swapchain->num_contexts > 1)))
4356         wglFlush(); /* Flush to ensure ordering across contexts. */
4357
4358     context_release(context);
4359 }
4360
4361 HRESULT surface_load_location(IWineD3DSurfaceImpl *surface, DWORD flag, const RECT *rect)
4362 {
4363     IWineD3DDeviceImpl *device = surface->resource.device;
4364     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4365     BOOL drawable_read_ok = surface_is_offscreen(surface);
4366     struct wined3d_format_desc desc;
4367     CONVERT_TYPES convert;
4368     int width, pitch, outpitch;
4369     BYTE *mem;
4370     BOOL in_fbo = FALSE;
4371
4372     TRACE("surface %p, location %s, rect %s.\n", surface, debug_surflocation(flag), wine_dbgstr_rect(rect));
4373
4374     if (surface->resource.usage & WINED3DUSAGE_DEPTHSTENCIL)
4375     {
4376         if (flag == SFLAG_INTEXTURE)
4377         {
4378             struct wined3d_context *context = context_acquire(device, NULL);
4379             surface_load_ds_location(surface, context, SFLAG_DS_OFFSCREEN);
4380             context_release(context);
4381             return WINED3D_OK;
4382         }
4383         else
4384         {
4385             FIXME("Unimplemented location %#x for depth/stencil buffers.\n", flag);
4386             return WINED3DERR_INVALIDCALL;
4387         }
4388     }
4389
4390     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
4391     {
4392         if (surface_is_offscreen(surface))
4393         {
4394             /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets.
4395              * Prefer SFLAG_INTEXTURE. */
4396             if (flag == SFLAG_INDRAWABLE) flag = SFLAG_INTEXTURE;
4397             drawable_read_ok = FALSE;
4398             in_fbo = TRUE;
4399         }
4400         else
4401         {
4402             TRACE("Surface %p is an onscreen surface.\n", surface);
4403         }
4404     }
4405
4406     if (surface->Flags & flag)
4407     {
4408         TRACE("Location already up to date\n");
4409         return WINED3D_OK;
4410     }
4411
4412     if (!(surface->Flags & SFLAG_LOCATIONS))
4413     {
4414         ERR("Surface %p does not have any up to date location.\n", surface);
4415         surface->Flags |= SFLAG_LOST;
4416         return WINED3DERR_DEVICELOST;
4417     }
4418
4419     if (flag == SFLAG_INSYSMEM)
4420     {
4421         surface_prepare_system_memory(surface);
4422
4423         /* Download the surface to system memory */
4424         if (surface->Flags & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX))
4425         {
4426             struct wined3d_context *context = NULL;
4427
4428             if (!device->isInDraw) context = context_acquire(device, NULL);
4429
4430             surface_bind_and_dirtify(surface, !(surface->Flags & SFLAG_INTEXTURE));
4431             surface_download_data(surface, gl_info);
4432
4433             if (context) context_release(context);
4434         }
4435         else
4436         {
4437             /* Note: It might be faster to download into a texture first. */
4438             read_from_framebuffer(surface, rect, surface->resource.allocatedMemory,
4439                     IWineD3DSurface_GetPitch((IWineD3DSurface *)surface));
4440         }
4441     }
4442     else if (flag == SFLAG_INDRAWABLE)
4443     {
4444         if (surface->Flags & SFLAG_INTEXTURE)
4445         {
4446             surface_blt_to_drawable(surface, rect);
4447         }
4448         else
4449         {
4450             int byte_count;
4451             if ((surface->Flags & SFLAG_LOCATIONS) == SFLAG_INSRGBTEX)
4452             {
4453                 /* This needs a shader to convert the srgb data sampled from the GL texture into RGB
4454                  * values, otherwise we get incorrect values in the target. For now go the slow way
4455                  * via a system memory copy
4456                  */
4457                 surface_load_location(surface, SFLAG_INSYSMEM, rect);
4458             }
4459
4460             d3dfmt_get_conv(surface, FALSE /* We need color keying */,
4461                     FALSE /* We won't use textures */, &desc, &convert);
4462
4463             /* The width is in 'length' not in bytes */
4464             width = surface->currentDesc.Width;
4465             pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *)surface);
4466
4467             /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
4468              * but it isn't set (yet) in all cases it is getting called. */
4469             if ((convert != NO_CONVERSION) && (surface->Flags & SFLAG_PBO))
4470             {
4471                 struct wined3d_context *context = NULL;
4472
4473                 TRACE("Removing the pbo attached to surface %p.\n", surface);
4474
4475                 if (!device->isInDraw) context = context_acquire(device, NULL);
4476                 surface_remove_pbo(surface, gl_info);
4477                 if (context) context_release(context);
4478             }
4479
4480             if ((convert != NO_CONVERSION) && surface->resource.allocatedMemory)
4481             {
4482                 int height = surface->currentDesc.Height;
4483                 byte_count = desc.conv_byte_count;
4484
4485                 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4486                 outpitch = width * byte_count;
4487                 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4488
4489                 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4490                 if(!mem) {
4491                     ERR("Out of memory %d, %d!\n", outpitch, height);
4492                     return WINED3DERR_OUTOFVIDEOMEMORY;
4493                 }
4494                 d3dfmt_convert_surface(surface->resource.allocatedMemory, mem, pitch,
4495                         width, height, outpitch, convert, surface);
4496
4497                 surface->Flags |= SFLAG_CONVERTED;
4498             }
4499             else
4500             {
4501                 surface->Flags &= ~SFLAG_CONVERTED;
4502                 mem = surface->resource.allocatedMemory;
4503                 byte_count = desc.byte_count;
4504             }
4505
4506             flush_to_framebuffer_drawpixels(surface, desc.glFormat, desc.glType, byte_count, mem);
4507
4508             /* Don't delete PBO memory */
4509             if ((mem != surface->resource.allocatedMemory) && !(surface->Flags & SFLAG_PBO))
4510                 HeapFree(GetProcessHeap(), 0, mem);
4511         }
4512     }
4513     else /* if(flag & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)) */
4514     {
4515         const DWORD attach_flags = WINED3DFMT_FLAG_FBO_ATTACHABLE | WINED3DFMT_FLAG_FBO_ATTACHABLE_SRGB;
4516
4517         if (drawable_read_ok && (surface->Flags & SFLAG_INDRAWABLE))
4518         {
4519             read_from_framebuffer_texture(surface, flag == SFLAG_INSRGBTEX);
4520         }
4521         else if (surface->Flags & (SFLAG_INSRGBTEX | SFLAG_INTEXTURE)
4522                 && (surface->resource.format_desc->Flags & attach_flags) == attach_flags
4523                 && fbo_blit_supported(gl_info, BLIT_OP_BLIT,
4524                         NULL, surface->resource.usage, surface->resource.pool, surface->resource.format_desc,
4525                         NULL, surface->resource.usage, surface->resource.pool, surface->resource.format_desc))
4526         {
4527             DWORD src_location = flag == SFLAG_INSRGBTEX ? SFLAG_INTEXTURE : SFLAG_INSRGBTEX;
4528             RECT rect = {0, 0, surface->currentDesc.Width, surface->currentDesc.Height};
4529
4530             surface_blt_fbo(surface->resource.device, WINED3DTEXF_POINT,
4531                     surface, src_location, &rect, surface, flag, &rect);
4532         }
4533         else
4534         {
4535             /* Upload from system memory */
4536             BOOL srgb = flag == SFLAG_INSRGBTEX;
4537             struct wined3d_context *context = NULL;
4538
4539             d3dfmt_get_conv(surface, TRUE /* We need color keying */,
4540                     TRUE /* We will use textures */, &desc, &convert);
4541
4542             if (srgb)
4543             {
4544                 if ((surface->Flags & (SFLAG_INTEXTURE | SFLAG_INSYSMEM)) == SFLAG_INTEXTURE)
4545                 {
4546                     /* Performance warning... */
4547                     FIXME("Downloading RGB surface %p to reload it as sRGB.\n", surface);
4548                     surface_load_location(surface, SFLAG_INSYSMEM, rect);
4549                 }
4550             }
4551             else
4552             {
4553                 if ((surface->Flags & (SFLAG_INSRGBTEX | SFLAG_INSYSMEM)) == SFLAG_INSRGBTEX)
4554                 {
4555                     /* Performance warning... */
4556                     FIXME("Downloading sRGB surface %p to reload it as RGB.\n", surface);
4557                     surface_load_location(surface, SFLAG_INSYSMEM, rect);
4558                 }
4559             }
4560             if (!(surface->Flags & SFLAG_INSYSMEM))
4561             {
4562                 WARN("Trying to load a texture from sysmem, but SFLAG_INSYSMEM is not set.\n");
4563                 /* Lets hope we get it from somewhere... */
4564                 surface_load_location(surface, SFLAG_INSYSMEM, rect);
4565             }
4566
4567             if (!device->isInDraw) context = context_acquire(device, NULL);
4568
4569             surface_prepare_texture(surface, gl_info, srgb);
4570             surface_bind_and_dirtify(surface, srgb);
4571
4572             if (surface->CKeyFlags & WINEDDSD_CKSRCBLT)
4573             {
4574                 surface->Flags |= SFLAG_GLCKEY;
4575                 surface->glCKey = surface->SrcBltCKey;
4576             }
4577             else surface->Flags &= ~SFLAG_GLCKEY;
4578
4579             /* The width is in 'length' not in bytes */
4580             width = surface->currentDesc.Width;
4581             pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *)surface);
4582
4583             /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
4584              * but it isn't set (yet) in all cases it is getting called. */
4585             if ((convert != NO_CONVERSION || desc.convert) && (surface->Flags & SFLAG_PBO))
4586             {
4587                 TRACE("Removing the pbo attached to surface %p.\n", surface);
4588                 surface_remove_pbo(surface, gl_info);
4589             }
4590
4591             if (desc.convert)
4592             {
4593                 /* This code is entered for texture formats which need a fixup. */
4594                 int height = surface->currentDesc.Height;
4595
4596                 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4597                 outpitch = width * desc.conv_byte_count;
4598                 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4599
4600                 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4601                 if(!mem) {
4602                     ERR("Out of memory %d, %d!\n", outpitch, height);
4603                     if (context) context_release(context);
4604                     return WINED3DERR_OUTOFVIDEOMEMORY;
4605                 }
4606                 desc.convert(surface->resource.allocatedMemory, mem, pitch, width, height);
4607             }
4608             else if (convert != NO_CONVERSION && surface->resource.allocatedMemory)
4609             {
4610                 /* This code is only entered for color keying fixups */
4611                 int height = surface->currentDesc.Height;
4612
4613                 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4614                 outpitch = width * desc.conv_byte_count;
4615                 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4616
4617                 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4618                 if(!mem) {
4619                     ERR("Out of memory %d, %d!\n", outpitch, height);
4620                     if (context) context_release(context);
4621                     return WINED3DERR_OUTOFVIDEOMEMORY;
4622                 }
4623                 d3dfmt_convert_surface(surface->resource.allocatedMemory, mem, pitch,
4624                         width, height, outpitch, convert, surface);
4625             }
4626             else
4627             {
4628                 mem = surface->resource.allocatedMemory;
4629             }
4630
4631             /* Make sure the correct pitch is used */
4632             ENTER_GL();
4633             glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
4634             LEAVE_GL();
4635
4636             if (mem || (surface->Flags & SFLAG_PBO))
4637                 surface_upload_data(surface, gl_info, &desc, srgb, mem);
4638
4639             /* Restore the default pitch */
4640             ENTER_GL();
4641             glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
4642             LEAVE_GL();
4643
4644             if (context) context_release(context);
4645
4646             /* Don't delete PBO memory */
4647             if ((mem != surface->resource.allocatedMemory) && !(surface->Flags & SFLAG_PBO))
4648                 HeapFree(GetProcessHeap(), 0, mem);
4649         }
4650     }
4651
4652     if (!rect) surface->Flags |= flag;
4653
4654     if (in_fbo && (surface->Flags & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE)))
4655     {
4656         /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
4657         surface->Flags |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4658     }
4659
4660     return WINED3D_OK;
4661 }
4662
4663 static WINED3DSURFTYPE WINAPI IWineD3DSurfaceImpl_GetImplType(IWineD3DSurface *iface) {
4664     return SURFACE_OPENGL;
4665 }
4666
4667 static HRESULT WINAPI IWineD3DSurfaceImpl_DrawOverlay(IWineD3DSurface *iface) {
4668     IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4669     HRESULT hr;
4670
4671     /* If there's no destination surface there is nothing to do */
4672     if(!This->overlay_dest) return WINED3D_OK;
4673
4674     /* Blt calls ModifyLocation on the dest surface, which in turn calls DrawOverlay to
4675      * update the overlay. Prevent an endless recursion
4676      */
4677     if(This->overlay_dest->Flags & SFLAG_INOVERLAYDRAW) {
4678         return WINED3D_OK;
4679     }
4680     This->overlay_dest->Flags |= SFLAG_INOVERLAYDRAW;
4681     hr = IWineD3DSurfaceImpl_Blt((IWineD3DSurface *) This->overlay_dest, &This->overlay_destrect,
4682                                  iface, &This->overlay_srcrect, WINEDDBLT_WAIT,
4683                                  NULL, WINED3DTEXF_LINEAR);
4684     This->overlay_dest->Flags &= ~SFLAG_INOVERLAYDRAW;
4685
4686     return hr;
4687 }
4688
4689 BOOL surface_is_offscreen(IWineD3DSurfaceImpl *surface)
4690 {
4691     IWineD3DSwapChainImpl *swapchain = surface->container.u.swapchain;
4692
4693     /* Not on a swapchain - must be offscreen */
4694     if (surface->container.type != WINED3D_CONTAINER_SWAPCHAIN) return TRUE;
4695
4696     /* The front buffer is always onscreen */
4697     if (surface == swapchain->front_buffer) return FALSE;
4698
4699     /* If the swapchain is rendered to an FBO, the backbuffer is
4700      * offscreen, otherwise onscreen */
4701     return swapchain->render_to_fbo;
4702 }
4703
4704 const IWineD3DSurfaceVtbl IWineD3DSurface_Vtbl =
4705 {
4706     /* IUnknown */
4707     IWineD3DBaseSurfaceImpl_QueryInterface,
4708     IWineD3DBaseSurfaceImpl_AddRef,
4709     IWineD3DSurfaceImpl_Release,
4710     /* IWineD3DResource */
4711     IWineD3DBaseSurfaceImpl_GetParent,
4712     IWineD3DBaseSurfaceImpl_SetPrivateData,
4713     IWineD3DBaseSurfaceImpl_GetPrivateData,
4714     IWineD3DBaseSurfaceImpl_FreePrivateData,
4715     IWineD3DBaseSurfaceImpl_SetPriority,
4716     IWineD3DBaseSurfaceImpl_GetPriority,
4717     IWineD3DSurfaceImpl_PreLoad,
4718     IWineD3DSurfaceImpl_UnLoad,
4719     IWineD3DBaseSurfaceImpl_GetType,
4720     /* IWineD3DSurface */
4721     IWineD3DBaseSurfaceImpl_GetContainer,
4722     IWineD3DBaseSurfaceImpl_GetDesc,
4723     IWineD3DSurfaceImpl_LockRect,
4724     IWineD3DSurfaceImpl_UnlockRect,
4725     IWineD3DSurfaceImpl_GetDC,
4726     IWineD3DSurfaceImpl_ReleaseDC,
4727     IWineD3DSurfaceImpl_Flip,
4728     IWineD3DSurfaceImpl_Blt,
4729     IWineD3DBaseSurfaceImpl_GetBltStatus,
4730     IWineD3DBaseSurfaceImpl_GetFlipStatus,
4731     IWineD3DBaseSurfaceImpl_IsLost,
4732     IWineD3DBaseSurfaceImpl_Restore,
4733     IWineD3DSurfaceImpl_BltFast,
4734     IWineD3DBaseSurfaceImpl_GetPalette,
4735     IWineD3DBaseSurfaceImpl_SetPalette,
4736     IWineD3DSurfaceImpl_RealizePalette,
4737     IWineD3DBaseSurfaceImpl_SetColorKey,
4738     IWineD3DBaseSurfaceImpl_GetPitch,
4739     IWineD3DSurfaceImpl_SetMem,
4740     IWineD3DBaseSurfaceImpl_SetOverlayPosition,
4741     IWineD3DBaseSurfaceImpl_GetOverlayPosition,
4742     IWineD3DBaseSurfaceImpl_UpdateOverlayZOrder,
4743     IWineD3DBaseSurfaceImpl_UpdateOverlay,
4744     IWineD3DBaseSurfaceImpl_SetClipper,
4745     IWineD3DBaseSurfaceImpl_GetClipper,
4746     /* Internal use: */
4747     IWineD3DSurfaceImpl_LoadTexture,
4748     IWineD3DSurfaceImpl_BindTexture,
4749     IWineD3DBaseSurfaceImpl_GetData,
4750     IWineD3DSurfaceImpl_SetFormat,
4751     IWineD3DSurfaceImpl_PrivateSetup,
4752     IWineD3DSurfaceImpl_GetImplType,
4753     IWineD3DSurfaceImpl_DrawOverlay
4754 };
4755
4756 static HRESULT ffp_blit_alloc(IWineD3DDevice *iface) { return WINED3D_OK; }
4757 /* Context activation is done by the caller. */
4758 static void ffp_blit_free(IWineD3DDevice *iface) { }
4759
4760 /* This function is used in case of 8bit paletted textures using GL_EXT_paletted_texture */
4761 /* Context activation is done by the caller. */
4762 static void ffp_blit_p8_upload_palette(IWineD3DSurfaceImpl *surface, const struct wined3d_gl_info *gl_info)
4763 {
4764     BYTE table[256][4];
4765     BOOL colorkey_active = (surface->CKeyFlags & WINEDDSD_CKSRCBLT) ? TRUE : FALSE;
4766
4767     d3dfmt_p8_init_palette(surface, table, colorkey_active);
4768
4769     TRACE("Using GL_EXT_PALETTED_TEXTURE for 8-bit paletted texture support\n");
4770     ENTER_GL();
4771     GL_EXTCALL(glColorTableEXT(surface->texture_target, GL_RGBA, 256, GL_RGBA, GL_UNSIGNED_BYTE, table));
4772     LEAVE_GL();
4773 }
4774
4775 /* Context activation is done by the caller. */
4776 static HRESULT ffp_blit_set(IWineD3DDevice *iface, IWineD3DSurfaceImpl *surface)
4777 {
4778     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
4779     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4780     enum complex_fixup fixup = get_complex_fixup(surface->resource.format_desc->color_fixup);
4781
4782     /* When EXT_PALETTED_TEXTURE is around, palette conversion is done by the GPU
4783      * else the surface is converted in software at upload time in LoadLocation.
4784      */
4785     if(fixup == COMPLEX_FIXUP_P8 && gl_info->supported[EXT_PALETTED_TEXTURE])
4786         ffp_blit_p8_upload_palette(surface, gl_info);
4787
4788     ENTER_GL();
4789     glEnable(surface->texture_target);
4790     checkGLcall("glEnable(surface->texture_target)");
4791     LEAVE_GL();
4792     return WINED3D_OK;
4793 }
4794
4795 /* Context activation is done by the caller. */
4796 static void ffp_blit_unset(IWineD3DDevice *iface)
4797 {
4798     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
4799     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4800
4801     ENTER_GL();
4802     glDisable(GL_TEXTURE_2D);
4803     checkGLcall("glDisable(GL_TEXTURE_2D)");
4804     if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
4805     {
4806         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
4807         checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
4808     }
4809     if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
4810     {
4811         glDisable(GL_TEXTURE_RECTANGLE_ARB);
4812         checkGLcall("glDisable(GL_TEXTURE_RECTANGLE_ARB)");
4813     }
4814     LEAVE_GL();
4815 }
4816
4817 static BOOL ffp_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
4818                                const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool,
4819                                const struct wined3d_format_desc *src_format_desc,
4820                                const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool,
4821                                const struct wined3d_format_desc *dst_format_desc)
4822 {
4823     enum complex_fixup src_fixup;
4824
4825     if (blit_op == BLIT_OP_COLOR_FILL)
4826     {
4827         if (!(dst_usage & WINED3DUSAGE_RENDERTARGET))
4828         {
4829             TRACE("Color fill not supported\n");
4830             return FALSE;
4831         }
4832
4833         return TRUE;
4834     }
4835
4836     src_fixup = get_complex_fixup(src_format_desc->color_fixup);
4837     if (TRACE_ON(d3d_surface) && TRACE_ON(d3d))
4838     {
4839         TRACE("Checking support for fixup:\n");
4840         dump_color_fixup_desc(src_format_desc->color_fixup);
4841     }
4842
4843     if (blit_op != BLIT_OP_BLIT)
4844     {
4845         TRACE("Unsupported blit_op=%d\n", blit_op);
4846         return FALSE;
4847      }
4848
4849     if (!is_identity_fixup(dst_format_desc->color_fixup))
4850     {
4851         TRACE("Destination fixups are not supported\n");
4852         return FALSE;
4853     }
4854
4855     if (src_fixup == COMPLEX_FIXUP_P8 && gl_info->supported[EXT_PALETTED_TEXTURE])
4856     {
4857         TRACE("P8 fixup supported\n");
4858         return TRUE;
4859     }
4860
4861     /* We only support identity conversions. */
4862     if (is_identity_fixup(src_format_desc->color_fixup))
4863     {
4864         TRACE("[OK]\n");
4865         return TRUE;
4866     }
4867
4868     TRACE("[FAILED]\n");
4869     return FALSE;
4870 }
4871
4872 static HRESULT ffp_blit_color_fill(IWineD3DDeviceImpl *device,
4873         IWineD3DSurfaceImpl *dst_surface, const RECT *dst_rect, DWORD color)
4874 {
4875     const float c[] = {D3DCOLOR_R(color), D3DCOLOR_G(color), D3DCOLOR_B(color), D3DCOLOR_A(color)};
4876
4877     return device_clear_render_targets(device, 1 /* rt_count */, &dst_surface, 1 /* rect_count */,
4878             (const WINED3DRECT *)dst_rect, WINED3DCLEAR_TARGET, c, 0.0f /* depth */, 0 /* stencil */);
4879 }
4880
4881 const struct blit_shader ffp_blit =  {
4882     ffp_blit_alloc,
4883     ffp_blit_free,
4884     ffp_blit_set,
4885     ffp_blit_unset,
4886     ffp_blit_supported,
4887     ffp_blit_color_fill
4888 };
4889
4890 static HRESULT cpu_blit_alloc(IWineD3DDevice *iface)
4891 {
4892     return WINED3D_OK;
4893 }
4894
4895 /* Context activation is done by the caller. */
4896 static void cpu_blit_free(IWineD3DDevice *iface)
4897 {
4898 }
4899
4900 /* Context activation is done by the caller. */
4901 static HRESULT cpu_blit_set(IWineD3DDevice *iface, IWineD3DSurfaceImpl *surface)
4902 {
4903     return WINED3D_OK;
4904 }
4905
4906 /* Context activation is done by the caller. */
4907 static void cpu_blit_unset(IWineD3DDevice *iface)
4908 {
4909 }
4910
4911 static BOOL cpu_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
4912                                const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool,
4913                                const struct wined3d_format_desc *src_format_desc,
4914                                const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool,
4915                                const struct wined3d_format_desc *dst_format_desc)
4916 {
4917     if (blit_op == BLIT_OP_COLOR_FILL)
4918     {
4919         return TRUE;
4920     }
4921
4922     return FALSE;
4923 }
4924
4925 static HRESULT cpu_blit_color_fill(IWineD3DDeviceImpl *device, IWineD3DSurfaceImpl *dst_surface, const RECT *dst_rect, DWORD fill_color)
4926 {
4927     WINEDDBLTFX BltFx;
4928     memset(&BltFx, 0, sizeof(BltFx));
4929     BltFx.dwSize = sizeof(BltFx);
4930     BltFx.u5.dwFillColor = color_convert_argb_to_fmt(fill_color, dst_surface->resource.format_desc->format);
4931     return IWineD3DBaseSurfaceImpl_Blt((IWineD3DSurface*)dst_surface, dst_rect, NULL, NULL, WINEDDBLT_COLORFILL, &BltFx, WINED3DTEXF_POINT);
4932 }
4933
4934 const struct blit_shader cpu_blit =  {
4935     cpu_blit_alloc,
4936     cpu_blit_free,
4937     cpu_blit_set,
4938     cpu_blit_unset,
4939     cpu_blit_supported,
4940     cpu_blit_color_fill
4941 };
4942
4943 static BOOL fbo_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
4944                                const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool,
4945                                const struct wined3d_format_desc *src_format_desc,
4946                                const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool,
4947                                const struct wined3d_format_desc *dst_format_desc)
4948 {
4949     if ((wined3d_settings.offscreen_rendering_mode != ORM_FBO) || !gl_info->fbo_ops.glBlitFramebuffer)
4950         return FALSE;
4951
4952     /* We only support blitting. Things like color keying / color fill should
4953      * be handled by other blitters.
4954      */
4955     if (blit_op != BLIT_OP_BLIT)
4956         return FALSE;
4957
4958     /* Source and/or destination need to be on the GL side */
4959     if (src_pool == WINED3DPOOL_SYSTEMMEM || dst_pool == WINED3DPOOL_SYSTEMMEM)
4960         return FALSE;
4961
4962     if(!((src_format_desc->Flags & WINED3DFMT_FLAG_FBO_ATTACHABLE) || (src_usage & WINED3DUSAGE_RENDERTARGET))
4963         && ((dst_format_desc->Flags & WINED3DFMT_FLAG_FBO_ATTACHABLE) || (dst_usage & WINED3DUSAGE_RENDERTARGET)))
4964         return FALSE;
4965
4966     if (!is_identity_fixup(src_format_desc->color_fixup) ||
4967         !is_identity_fixup(dst_format_desc->color_fixup))
4968         return FALSE;
4969
4970     if (!(src_format_desc->format == dst_format_desc->format
4971         || (is_identity_fixup(src_format_desc->color_fixup)
4972         && is_identity_fixup(dst_format_desc->color_fixup))))
4973         return FALSE;
4974
4975     return TRUE;
4976 }