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