comdlg32: Fix some alignment issues in the Dutch translation.
[wine/hramrach.git] / dlls / wined3d / surface.c
blobbb18b952de004a932a17ea30d0856ae977cecfbe
1 /*
2 * IWineD3DSurface Implementation
4 * Copyright 1998 Lionel Ulmer
5 * Copyright 2000-2001 TransGaming Technologies Inc.
6 * Copyright 2002-2005 Jason Edmeades
7 * Copyright 2002-2003 Raphael Junqueira
8 * Copyright 2004 Christian Costa
9 * Copyright 2005 Oliver Stieber
10 * Copyright 2006-2008 Stefan Dösinger for CodeWeavers
11 * Copyright 2007-2008 Henri Verbeet
12 * Copyright 2006-2008 Roderick Colenbrander
13 * Copyright 2009 Henri Verbeet for CodeWeavers
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.
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.
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
30 #include "config.h"
31 #include "wine/port.h"
32 #include "wined3d_private.h"
34 WINE_DEFAULT_DEBUG_CHANNEL(d3d_surface);
35 WINE_DECLARE_DEBUG_CHANNEL(d3d);
37 #define GLINFO_LOCATION (*gl_info)
39 static void surface_cleanup(IWineD3DSurfaceImpl *This)
41 IWineD3DDeviceImpl *device = This->resource.device;
42 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
43 struct wined3d_context *context = NULL;
44 renderbuffer_entry_t *entry, *entry2;
46 TRACE("(%p) : Cleaning up.\n", This);
48 /* Need a context to destroy the texture. Use the currently active render
49 * target, but only if the primary render target exists. Otherwise
50 * lastActiveRenderTarget is garbage. When destroying the primary render
51 * target, Uninit3D() will activate a context before doing anything. */
52 if (device->render_targets && device->render_targets[0])
54 context = context_acquire(device, NULL);
57 ENTER_GL();
59 if (This->texture_name)
61 /* Release the OpenGL texture. */
62 TRACE("Deleting texture %u.\n", This->texture_name);
63 glDeleteTextures(1, &This->texture_name);
66 if (This->Flags & SFLAG_PBO)
68 /* Delete the PBO. */
69 GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
72 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry)
74 gl_info->fbo_ops.glDeleteRenderbuffers(1, &entry->id);
75 HeapFree(GetProcessHeap(), 0, entry);
78 LEAVE_GL();
80 if (This->Flags & SFLAG_DIBSECTION)
82 /* Release the DC. */
83 SelectObject(This->hDC, This->dib.holdbitmap);
84 DeleteDC(This->hDC);
85 /* Release the DIB section. */
86 DeleteObject(This->dib.DIBsection);
87 This->dib.bitmap_data = NULL;
88 This->resource.allocatedMemory = NULL;
91 if (This->Flags & SFLAG_USERPTR) IWineD3DSurface_SetMem((IWineD3DSurface *)This, NULL);
92 if (This->overlay_dest) list_remove(&This->overlay_entry);
94 HeapFree(GetProcessHeap(), 0, This->palette9);
96 resource_cleanup((IWineD3DResource *)This);
98 if (context) context_release(context);
101 UINT surface_calculate_size(const struct wined3d_format_desc *format_desc, UINT alignment, UINT width, UINT height)
103 UINT size;
105 if (format_desc->format == WINED3DFMT_UNKNOWN)
107 size = 0;
109 else if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
111 UINT row_block_count = (width + format_desc->block_width - 1) / format_desc->block_width;
112 UINT row_count = (height + format_desc->block_height - 1) / format_desc->block_height;
113 size = row_count * row_block_count * format_desc->block_byte_count;
115 else
117 /* The pitch is a multiple of 4 bytes. */
118 size = height * (((width * format_desc->byte_count) + alignment - 1) & ~(alignment - 1));
121 if (format_desc->heightscale != 0.0f) size *= format_desc->heightscale;
123 return size;
126 struct blt_info
128 GLenum binding;
129 GLenum bind_target;
130 enum tex_types tex_type;
131 GLfloat coords[4][3];
134 struct float_rect
136 float l;
137 float t;
138 float r;
139 float b;
142 static inline void cube_coords_float(const RECT *r, UINT w, UINT h, struct float_rect *f)
144 f->l = ((r->left * 2.0f) / w) - 1.0f;
145 f->t = ((r->top * 2.0f) / h) - 1.0f;
146 f->r = ((r->right * 2.0f) / w) - 1.0f;
147 f->b = ((r->bottom * 2.0f) / h) - 1.0f;
150 static void surface_get_blt_info(GLenum target, const RECT *rect_in, GLsizei w, GLsizei h, struct blt_info *info)
152 GLfloat (*coords)[3] = info->coords;
153 RECT rect;
154 struct float_rect f;
156 if (rect_in)
157 rect = *rect_in;
158 else
160 rect.left = 0;
161 rect.top = h;
162 rect.right = w;
163 rect.bottom = 0;
166 switch (target)
168 default:
169 FIXME("Unsupported texture target %#x\n", target);
170 /* Fall back to GL_TEXTURE_2D */
171 case GL_TEXTURE_2D:
172 info->binding = GL_TEXTURE_BINDING_2D;
173 info->bind_target = GL_TEXTURE_2D;
174 info->tex_type = tex_2d;
175 coords[0][0] = (float)rect.left / w;
176 coords[0][1] = (float)rect.top / h;
177 coords[0][2] = 0.0f;
179 coords[1][0] = (float)rect.right / w;
180 coords[1][1] = (float)rect.top / h;
181 coords[1][2] = 0.0f;
183 coords[2][0] = (float)rect.left / w;
184 coords[2][1] = (float)rect.bottom / h;
185 coords[2][2] = 0.0f;
187 coords[3][0] = (float)rect.right / w;
188 coords[3][1] = (float)rect.bottom / h;
189 coords[3][2] = 0.0f;
190 break;
192 case GL_TEXTURE_RECTANGLE_ARB:
193 info->binding = GL_TEXTURE_BINDING_RECTANGLE_ARB;
194 info->bind_target = GL_TEXTURE_RECTANGLE_ARB;
195 info->tex_type = tex_rect;
196 coords[0][0] = rect.left; coords[0][1] = rect.top; coords[0][2] = 0.0f;
197 coords[1][0] = rect.right; coords[1][1] = rect.top; coords[1][2] = 0.0f;
198 coords[2][0] = rect.left; coords[2][1] = rect.bottom; coords[2][2] = 0.0f;
199 coords[3][0] = rect.right; coords[3][1] = rect.bottom; coords[3][2] = 0.0f;
200 break;
202 case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
203 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
204 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
205 info->tex_type = tex_cube;
206 cube_coords_float(&rect, w, h, &f);
208 coords[0][0] = 1.0f; coords[0][1] = -f.t; coords[0][2] = -f.l;
209 coords[1][0] = 1.0f; coords[1][1] = -f.t; coords[1][2] = -f.r;
210 coords[2][0] = 1.0f; coords[2][1] = -f.b; coords[2][2] = -f.l;
211 coords[3][0] = 1.0f; coords[3][1] = -f.b; coords[3][2] = -f.r;
212 break;
214 case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
215 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
216 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
217 info->tex_type = tex_cube;
218 cube_coords_float(&rect, w, h, &f);
220 coords[0][0] = -1.0f; coords[0][1] = -f.t; coords[0][2] = f.l;
221 coords[1][0] = -1.0f; coords[1][1] = -f.t; coords[1][2] = f.r;
222 coords[2][0] = -1.0f; coords[2][1] = -f.b; coords[2][2] = f.l;
223 coords[3][0] = -1.0f; coords[3][1] = -f.b; coords[3][2] = f.r;
224 break;
226 case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
227 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
228 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
229 info->tex_type = tex_cube;
230 cube_coords_float(&rect, w, h, &f);
232 coords[0][0] = f.l; coords[0][1] = 1.0f; coords[0][2] = f.t;
233 coords[1][0] = f.r; coords[1][1] = 1.0f; coords[1][2] = f.t;
234 coords[2][0] = f.l; coords[2][1] = 1.0f; coords[2][2] = f.b;
235 coords[3][0] = f.r; coords[3][1] = 1.0f; coords[3][2] = f.b;
236 break;
238 case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
239 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
240 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
241 info->tex_type = tex_cube;
242 cube_coords_float(&rect, w, h, &f);
244 coords[0][0] = f.l; coords[0][1] = -1.0f; coords[0][2] = -f.t;
245 coords[1][0] = f.r; coords[1][1] = -1.0f; coords[1][2] = -f.t;
246 coords[2][0] = f.l; coords[2][1] = -1.0f; coords[2][2] = -f.b;
247 coords[3][0] = f.r; coords[3][1] = -1.0f; coords[3][2] = -f.b;
248 break;
250 case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
251 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
252 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
253 info->tex_type = tex_cube;
254 cube_coords_float(&rect, w, h, &f);
256 coords[0][0] = f.l; coords[0][1] = -f.t; coords[0][2] = 1.0f;
257 coords[1][0] = f.r; coords[1][1] = -f.t; coords[1][2] = 1.0f;
258 coords[2][0] = f.l; coords[2][1] = -f.b; coords[2][2] = 1.0f;
259 coords[3][0] = f.r; coords[3][1] = -f.b; coords[3][2] = 1.0f;
260 break;
262 case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
263 info->binding = GL_TEXTURE_BINDING_CUBE_MAP_ARB;
264 info->bind_target = GL_TEXTURE_CUBE_MAP_ARB;
265 info->tex_type = tex_cube;
266 cube_coords_float(&rect, w, h, &f);
268 coords[0][0] = -f.l; coords[0][1] = -f.t; coords[0][2] = -1.0f;
269 coords[1][0] = -f.r; coords[1][1] = -f.t; coords[1][2] = -1.0f;
270 coords[2][0] = -f.l; coords[2][1] = -f.b; coords[2][2] = -1.0f;
271 coords[3][0] = -f.r; coords[3][1] = -f.b; coords[3][2] = -1.0f;
272 break;
276 static inline void surface_get_rect(IWineD3DSurfaceImpl *This, const RECT *rect_in, RECT *rect_out)
278 if (rect_in)
279 *rect_out = *rect_in;
280 else
282 rect_out->left = 0;
283 rect_out->top = 0;
284 rect_out->right = This->currentDesc.Width;
285 rect_out->bottom = This->currentDesc.Height;
289 /* GL locking and context activation is done by the caller */
290 void draw_textured_quad(IWineD3DSurfaceImpl *src_surface, const RECT *src_rect, const RECT *dst_rect, WINED3DTEXTUREFILTERTYPE Filter)
292 IWineD3DBaseTextureImpl *texture;
293 struct blt_info info;
295 surface_get_blt_info(src_surface->texture_target, src_rect, src_surface->pow2Width, src_surface->pow2Height, &info);
297 glEnable(info.bind_target);
298 checkGLcall("glEnable(bind_target)");
300 /* Bind the texture */
301 glBindTexture(info.bind_target, src_surface->texture_name);
302 checkGLcall("glBindTexture");
304 /* Filtering for StretchRect */
305 glTexParameteri(info.bind_target, GL_TEXTURE_MAG_FILTER,
306 wined3d_gl_mag_filter(magLookup, Filter));
307 checkGLcall("glTexParameteri");
308 glTexParameteri(info.bind_target, GL_TEXTURE_MIN_FILTER,
309 wined3d_gl_min_mip_filter(minMipLookup, Filter, WINED3DTEXF_NONE));
310 checkGLcall("glTexParameteri");
311 glTexParameteri(info.bind_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
312 glTexParameteri(info.bind_target, GL_TEXTURE_WRAP_T, GL_CLAMP);
313 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
314 checkGLcall("glTexEnvi");
316 /* Draw a quad */
317 glBegin(GL_TRIANGLE_STRIP);
318 glTexCoord3fv(info.coords[0]);
319 glVertex2i(dst_rect->left, dst_rect->top);
321 glTexCoord3fv(info.coords[1]);
322 glVertex2i(dst_rect->right, dst_rect->top);
324 glTexCoord3fv(info.coords[2]);
325 glVertex2i(dst_rect->left, dst_rect->bottom);
327 glTexCoord3fv(info.coords[3]);
328 glVertex2i(dst_rect->right, dst_rect->bottom);
329 glEnd();
331 /* Unbind the texture */
332 glBindTexture(info.bind_target, 0);
333 checkGLcall("glBindTexture(info->bind_target, 0)");
335 /* We changed the filtering settings on the texture. Inform the
336 * container about this to get the filters reset properly next draw. */
337 if (SUCCEEDED(IWineD3DSurface_GetContainer((IWineD3DSurface *)src_surface, &IID_IWineD3DBaseTexture, (void **)&texture)))
339 texture->baseTexture.texture_rgb.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
340 texture->baseTexture.texture_rgb.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
341 texture->baseTexture.texture_rgb.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
342 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture);
346 HRESULT surface_init(IWineD3DSurfaceImpl *surface, WINED3DSURFTYPE surface_type, UINT alignment,
347 UINT width, UINT height, UINT level, BOOL lockable, BOOL discard, WINED3DMULTISAMPLE_TYPE multisample_type,
348 UINT multisample_quality, IWineD3DDeviceImpl *device, DWORD usage, WINED3DFORMAT format,
349 WINED3DPOOL pool, IUnknown *parent, const struct wined3d_parent_ops *parent_ops)
351 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
352 const struct wined3d_format_desc *format_desc = getFormatDescEntry(format, gl_info);
353 void (*cleanup)(IWineD3DSurfaceImpl *This);
354 unsigned int resource_size;
355 HRESULT hr;
357 if (multisample_quality > 0)
359 FIXME("multisample_quality set to %u, substituting 0\n", multisample_quality);
360 multisample_quality = 0;
363 /* FIXME: Check that the format is supported by the device. */
365 resource_size = surface_calculate_size(format_desc, alignment, width, height);
367 /* Look at the implementation and set the correct Vtable. */
368 switch (surface_type)
370 case SURFACE_OPENGL:
371 surface->lpVtbl = &IWineD3DSurface_Vtbl;
372 cleanup = surface_cleanup;
373 break;
375 case SURFACE_GDI:
376 surface->lpVtbl = &IWineGDISurface_Vtbl;
377 cleanup = surface_gdi_cleanup;
378 break;
380 default:
381 ERR("Requested unknown surface implementation %#x.\n", surface_type);
382 return WINED3DERR_INVALIDCALL;
385 hr = resource_init((IWineD3DResource *)surface, WINED3DRTYPE_SURFACE,
386 device, resource_size, usage, format_desc, pool, parent, parent_ops);
387 if (FAILED(hr))
389 WARN("Failed to initialize resource, returning %#x.\n", hr);
390 return hr;
393 /* "Standalone" surface. */
394 IWineD3DSurface_SetContainer((IWineD3DSurface *)surface, NULL);
396 surface->currentDesc.Width = width;
397 surface->currentDesc.Height = height;
398 surface->currentDesc.MultiSampleType = multisample_type;
399 surface->currentDesc.MultiSampleQuality = multisample_quality;
400 surface->texture_level = level;
401 list_init(&surface->overlays);
403 /* Flags */
404 surface->Flags = SFLAG_NORMCOORD; /* Default to normalized coords. */
405 if (discard) surface->Flags |= SFLAG_DISCARD;
406 if (lockable || format == WINED3DFMT_D16_LOCKABLE) surface->Flags |= SFLAG_LOCKABLE;
408 /* Quick lockable sanity check.
409 * TODO: remove this after surfaces, usage and lockability have been debugged properly
410 * this function is too deep to need to care about things like this.
411 * Levels need to be checked too, since they all affect what can be done. */
412 switch (pool)
414 case WINED3DPOOL_SCRATCH:
415 if(!lockable)
417 FIXME("Called with a pool of SCRATCH and a lockable of FALSE "
418 "which are mutually exclusive, setting lockable to TRUE.\n");
419 lockable = TRUE;
421 break;
423 case WINED3DPOOL_SYSTEMMEM:
424 if (!lockable)
425 FIXME("Called with a pool of SYSTEMMEM and a lockable of FALSE, this is acceptable but unexpected.\n");
426 break;
428 case WINED3DPOOL_MANAGED:
429 if (usage & WINED3DUSAGE_DYNAMIC)
430 FIXME("Called with a pool of MANAGED and a usage of DYNAMIC which are mutually exclusive.\n");
431 break;
433 case WINED3DPOOL_DEFAULT:
434 if (lockable && !(usage & (WINED3DUSAGE_DYNAMIC | WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL)))
435 WARN("Creating a lockable surface with a POOL of DEFAULT, that doesn't specify DYNAMIC usage.\n");
436 break;
438 default:
439 FIXME("Unknown pool %#x.\n", pool);
440 break;
443 if (usage & WINED3DUSAGE_RENDERTARGET && pool != WINED3DPOOL_DEFAULT)
445 FIXME("Trying to create a render target that isn't in the default pool.\n");
448 /* Mark the texture as dirty so that it gets loaded first time around. */
449 surface_add_dirty_rect(surface, NULL);
450 list_init(&surface->renderbuffers);
452 TRACE("surface %p, memory %p, size %u\n", surface, surface->resource.allocatedMemory, surface->resource.size);
454 /* Call the private setup routine */
455 hr = IWineD3DSurface_PrivateSetup((IWineD3DSurface *)surface);
456 if (FAILED(hr))
458 ERR("Private setup failed, returning %#x\n", hr);
459 cleanup(surface);
460 return hr;
463 return hr;
466 static void surface_force_reload(IWineD3DSurfaceImpl *surface)
468 surface->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
471 void surface_set_texture_name(IWineD3DSurfaceImpl *surface, GLuint new_name, BOOL srgb)
473 GLuint *name;
474 DWORD flag;
476 TRACE("surface %p, new_name %u, srgb %#x.\n", surface, new_name, srgb);
478 if(srgb)
480 name = &surface->texture_name_srgb;
481 flag = SFLAG_INSRGBTEX;
483 else
485 name = &surface->texture_name;
486 flag = SFLAG_INTEXTURE;
489 if (!*name && new_name)
491 /* FIXME: We shouldn't need to remove SFLAG_INTEXTURE if the
492 * surface has no texture name yet. See if we can get rid of this. */
493 if (surface->Flags & flag)
494 ERR("Surface has SFLAG_INTEXTURE set, but no texture name\n");
495 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)surface, flag, FALSE);
498 *name = new_name;
499 surface_force_reload(surface);
502 void surface_set_texture_target(IWineD3DSurfaceImpl *surface, GLenum target)
504 TRACE("surface %p, target %#x.\n", surface, target);
506 if (surface->texture_target != target)
508 if (target == GL_TEXTURE_RECTANGLE_ARB)
510 surface->Flags &= ~SFLAG_NORMCOORD;
512 else if (surface->texture_target == GL_TEXTURE_RECTANGLE_ARB)
514 surface->Flags |= SFLAG_NORMCOORD;
517 surface->texture_target = target;
518 surface_force_reload(surface);
521 /* Context activation is done by the caller. */
522 static void surface_bind_and_dirtify(IWineD3DSurfaceImpl *This, BOOL srgb) {
523 DWORD active_sampler;
525 /* We don't need a specific texture unit, but after binding the texture the current unit is dirty.
526 * Read the unit back instead of switching to 0, this avoids messing around with the state manager's
527 * gl states. The current texture unit should always be a valid one.
529 * To be more specific, this is tricky because we can implicitly be called
530 * from sampler() in state.c. This means we can't touch anything other than
531 * whatever happens to be the currently active texture, or we would risk
532 * marking already applied sampler states dirty again.
534 * TODO: Track the current active texture per GL context instead of using glGet
536 GLint active_texture;
537 ENTER_GL();
538 glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
539 LEAVE_GL();
540 active_sampler = This->resource.device->rev_tex_unit_map[active_texture - GL_TEXTURE0_ARB];
542 if (active_sampler != WINED3D_UNMAPPED_STAGE)
544 IWineD3DDeviceImpl_MarkStateDirty(This->resource.device, STATE_SAMPLER(active_sampler));
546 IWineD3DSurface_BindTexture((IWineD3DSurface *)This, srgb);
549 /* This function checks if the primary render target uses the 8bit paletted format. */
550 static BOOL primary_render_target_is_p8(IWineD3DDeviceImpl *device)
552 if (device->render_targets && device->render_targets[0])
554 IWineD3DSurfaceImpl *render_target = device->render_targets[0];
555 if ((render_target->resource.usage & WINED3DUSAGE_RENDERTARGET)
556 && (render_target->resource.format_desc->format == WINED3DFMT_P8_UINT))
557 return TRUE;
559 return FALSE;
562 /* This call just downloads data, the caller is responsible for binding the
563 * correct texture. */
564 /* Context activation is done by the caller. */
565 static void surface_download_data(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info)
567 const struct wined3d_format_desc *format_desc = This->resource.format_desc;
569 /* Only support read back of converted P8 surfaces */
570 if (This->Flags & SFLAG_CONVERTED && format_desc->format != WINED3DFMT_P8_UINT)
572 FIXME("Read back converted textures unsupported, format=%s\n", debug_d3dformat(format_desc->format));
573 return;
576 ENTER_GL();
578 if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
580 TRACE("(%p) : Calling glGetCompressedTexImageARB level %d, format %#x, type %#x, data %p.\n",
581 This, This->texture_level, format_desc->glFormat, format_desc->glType,
582 This->resource.allocatedMemory);
584 if (This->Flags & SFLAG_PBO)
586 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
587 checkGLcall("glBindBufferARB");
588 GL_EXTCALL(glGetCompressedTexImageARB(This->texture_target, This->texture_level, NULL));
589 checkGLcall("glGetCompressedTexImageARB");
590 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
591 checkGLcall("glBindBufferARB");
593 else
595 GL_EXTCALL(glGetCompressedTexImageARB(This->texture_target,
596 This->texture_level, This->resource.allocatedMemory));
597 checkGLcall("glGetCompressedTexImageARB");
600 LEAVE_GL();
601 } else {
602 void *mem;
603 GLenum format = format_desc->glFormat;
604 GLenum type = format_desc->glType;
605 int src_pitch = 0;
606 int dst_pitch = 0;
608 /* In case of P8 the index is stored in the alpha component if the primary render target uses P8 */
609 if (format_desc->format == WINED3DFMT_P8_UINT && primary_render_target_is_p8(This->resource.device))
611 format = GL_ALPHA;
612 type = GL_UNSIGNED_BYTE;
615 if (This->Flags & SFLAG_NONPOW2) {
616 unsigned char alignment = This->resource.device->surface_alignment;
617 src_pitch = format_desc->byte_count * This->pow2Width;
618 dst_pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This);
619 src_pitch = (src_pitch + alignment - 1) & ~(alignment - 1);
620 mem = HeapAlloc(GetProcessHeap(), 0, src_pitch * This->pow2Height);
621 } else {
622 mem = This->resource.allocatedMemory;
625 TRACE("(%p) : Calling glGetTexImage level %d, format %#x, type %#x, data %p\n",
626 This, This->texture_level, format, type, mem);
628 if(This->Flags & SFLAG_PBO) {
629 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
630 checkGLcall("glBindBufferARB");
632 glGetTexImage(This->texture_target, This->texture_level, format, type, NULL);
633 checkGLcall("glGetTexImage");
635 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
636 checkGLcall("glBindBufferARB");
637 } else {
638 glGetTexImage(This->texture_target, This->texture_level, format, type, mem);
639 checkGLcall("glGetTexImage");
641 LEAVE_GL();
643 if (This->Flags & SFLAG_NONPOW2) {
644 const BYTE *src_data;
645 BYTE *dst_data;
646 UINT y;
648 * Some games (e.g. warhammer 40k) don't work properly with the odd pitches, preventing
649 * the surface pitch from being used to box non-power2 textures. Instead we have to use a hack to
650 * repack the texture so that the bpp * width pitch can be used instead of bpp * pow2width.
652 * We're doing this...
654 * instead of boxing the texture :
655 * |<-texture width ->| -->pow2width| /\
656 * |111111111111111111| | |
657 * |222 Texture 222222| boxed empty | texture height
658 * |3333 Data 33333333| | |
659 * |444444444444444444| | \/
660 * ----------------------------------- |
661 * | boxed empty | boxed empty | pow2height
662 * | | | \/
663 * -----------------------------------
666 * we're repacking the data to the expected texture width
668 * |<-texture width ->| -->pow2width| /\
669 * |111111111111111111222222222222222| |
670 * |222333333333333333333444444444444| texture height
671 * |444444 | |
672 * | | \/
673 * | | |
674 * | empty | pow2height
675 * | | \/
676 * -----------------------------------
678 * == is the same as
680 * |<-texture width ->| /\
681 * |111111111111111111|
682 * |222222222222222222|texture height
683 * |333333333333333333|
684 * |444444444444444444| \/
685 * --------------------
687 * this also means that any references to allocatedMemory should work with the data as if were a
688 * standard texture with a non-power2 width instead of texture boxed up to be a power2 texture.
690 * internally the texture is still stored in a boxed format so any references to textureName will
691 * get a boxed texture with width pow2width and not a texture of width currentDesc.Width.
693 * Performance should not be an issue, because applications normally do not lock the surfaces when
694 * rendering. If an app does, the SFLAG_DYNLOCK flag will kick in and the memory copy won't be released,
695 * and doesn't have to be re-read.
697 src_data = mem;
698 dst_data = This->resource.allocatedMemory;
699 TRACE("(%p) : Repacking the surface data from pitch %d to pitch %d\n", This, src_pitch, dst_pitch);
700 for (y = 1 ; y < This->currentDesc.Height; y++) {
701 /* skip the first row */
702 src_data += src_pitch;
703 dst_data += dst_pitch;
704 memcpy(dst_data, src_data, dst_pitch);
707 HeapFree(GetProcessHeap(), 0, mem);
711 /* Surface has now been downloaded */
712 This->Flags |= SFLAG_INSYSMEM;
715 /* This call just uploads data, the caller is responsible for binding the
716 * correct texture. */
717 /* Context activation is done by the caller. */
718 static void surface_upload_data(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info,
719 const struct wined3d_format_desc *format_desc, BOOL srgb, const GLvoid *data)
721 GLsizei width = This->currentDesc.Width;
722 GLsizei height = This->currentDesc.Height;
723 GLenum internal;
725 if (srgb)
727 internal = format_desc->glGammaInternal;
729 else if (This->resource.usage & WINED3DUSAGE_RENDERTARGET && surface_is_offscreen(This))
731 internal = format_desc->rtInternal;
733 else
735 internal = format_desc->glInternal;
738 TRACE("This %p, internal %#x, width %d, height %d, format %#x, type %#x, data %p.\n",
739 This, internal, width, height, format_desc->glFormat, format_desc->glType, data);
740 TRACE("target %#x, level %u, resource size %u.\n",
741 This->texture_target, This->texture_level, This->resource.size);
743 if (format_desc->heightscale != 1.0f && format_desc->heightscale != 0.0f) height *= format_desc->heightscale;
745 ENTER_GL();
747 if (This->Flags & SFLAG_PBO)
749 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
750 checkGLcall("glBindBufferARB");
752 TRACE("(%p) pbo: %#x, data: %p.\n", This, This->pbo, data);
753 data = NULL;
756 if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
758 TRACE("Calling glCompressedTexSubImage2DARB.\n");
760 GL_EXTCALL(glCompressedTexSubImage2DARB(This->texture_target, This->texture_level,
761 0, 0, width, height, internal, This->resource.size, data));
762 checkGLcall("glCompressedTexSubImage2DARB");
764 else
766 TRACE("Calling glTexSubImage2D.\n");
768 glTexSubImage2D(This->texture_target, This->texture_level,
769 0, 0, width, height, format_desc->glFormat, format_desc->glType, data);
770 checkGLcall("glTexSubImage2D");
773 if (This->Flags & SFLAG_PBO)
775 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
776 checkGLcall("glBindBufferARB");
779 LEAVE_GL();
781 if (gl_info->quirks & WINED3D_QUIRK_FBO_TEX_UPDATE)
783 IWineD3DDeviceImpl *device = This->resource.device;
784 unsigned int i;
786 for (i = 0; i < device->numContexts; ++i)
788 context_surface_update(device->contexts[i], This);
793 /* This call just allocates the texture, the caller is responsible for binding
794 * the correct texture. */
795 /* Context activation is done by the caller. */
796 static void surface_allocate_surface(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info,
797 const struct wined3d_format_desc *format_desc, BOOL srgb)
799 BOOL enable_client_storage = FALSE;
800 GLsizei width = This->pow2Width;
801 GLsizei height = This->pow2Height;
802 const BYTE *mem = NULL;
803 GLenum internal;
805 if (srgb)
807 internal = format_desc->glGammaInternal;
809 else if (This->resource.usage & WINED3DUSAGE_RENDERTARGET && surface_is_offscreen(This))
811 internal = format_desc->rtInternal;
813 else
815 internal = format_desc->glInternal;
818 if (format_desc->heightscale != 1.0f && format_desc->heightscale != 0.0f) height *= format_desc->heightscale;
820 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",
821 This, This->texture_target, This->texture_level, debug_d3dformat(format_desc->format),
822 internal, width, height, format_desc->glFormat, format_desc->glType);
824 ENTER_GL();
826 if (gl_info->supported[APPLE_CLIENT_STORAGE])
828 if(This->Flags & (SFLAG_NONPOW2 | SFLAG_DIBSECTION | SFLAG_CONVERTED) || This->resource.allocatedMemory == NULL) {
829 /* In some cases we want to disable client storage.
830 * SFLAG_NONPOW2 has a bigger opengl texture than the client memory, and different pitches
831 * SFLAG_DIBSECTION: Dibsections may have read / write protections on the memory. Avoid issues...
832 * SFLAG_CONVERTED: The conversion destination memory is freed after loading the surface
833 * allocatedMemory == NULL: Not defined in the extension. Seems to disable client storage effectively
835 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
836 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
837 This->Flags &= ~SFLAG_CLIENT;
838 enable_client_storage = TRUE;
839 } else {
840 This->Flags |= SFLAG_CLIENT;
842 /* Point opengl to our allocated texture memory. Do not use resource.allocatedMemory here because
843 * it might point into a pbo. Instead use heapMemory, but get the alignment right.
845 mem = (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
849 if (format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED && mem)
851 GL_EXTCALL(glCompressedTexImage2DARB(This->texture_target, This->texture_level,
852 internal, width, height, 0, This->resource.size, mem));
854 else
856 glTexImage2D(This->texture_target, This->texture_level,
857 internal, width, height, 0, format_desc->glFormat, format_desc->glType, mem);
858 checkGLcall("glTexImage2D");
861 if(enable_client_storage) {
862 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
863 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
865 LEAVE_GL();
868 /* In D3D the depth stencil dimensions have to be greater than or equal to the
869 * render target dimensions. With FBOs, the dimensions have to be an exact match. */
870 /* TODO: We should synchronize the renderbuffer's content with the texture's content. */
871 /* GL locking is done by the caller */
872 void surface_set_compatible_renderbuffer(IWineD3DSurfaceImpl *surface, unsigned int width, unsigned int height)
874 const struct wined3d_gl_info *gl_info = &surface->resource.device->adapter->gl_info;
875 renderbuffer_entry_t *entry;
876 GLuint renderbuffer = 0;
877 unsigned int src_width, src_height;
879 src_width = surface->pow2Width;
880 src_height = surface->pow2Height;
882 /* A depth stencil smaller than the render target is not valid */
883 if (width > src_width || height > src_height) return;
885 /* Remove any renderbuffer set if the sizes match */
886 if (gl_info->supported[ARB_FRAMEBUFFER_OBJECT]
887 || (width == src_width && height == src_height))
889 surface->current_renderbuffer = NULL;
890 return;
893 /* Look if we've already got a renderbuffer of the correct dimensions */
894 LIST_FOR_EACH_ENTRY(entry, &surface->renderbuffers, renderbuffer_entry_t, entry)
896 if (entry->width == width && entry->height == height)
898 renderbuffer = entry->id;
899 surface->current_renderbuffer = entry;
900 break;
904 if (!renderbuffer)
906 gl_info->fbo_ops.glGenRenderbuffers(1, &renderbuffer);
907 gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
908 gl_info->fbo_ops.glRenderbufferStorage(GL_RENDERBUFFER,
909 surface->resource.format_desc->glInternal, width, height);
911 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(renderbuffer_entry_t));
912 entry->width = width;
913 entry->height = height;
914 entry->id = renderbuffer;
915 list_add_head(&surface->renderbuffers, &entry->entry);
917 surface->current_renderbuffer = entry;
920 checkGLcall("set_compatible_renderbuffer");
923 GLenum surface_get_gl_buffer(IWineD3DSurfaceImpl *surface)
925 IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)surface->container;
927 TRACE("surface %p.\n", surface);
929 if (!(surface->Flags & SFLAG_SWAPCHAIN))
931 ERR("Surface %p is not on a swapchain.\n", surface);
932 return GL_NONE;
935 if (swapchain->back_buffers && swapchain->back_buffers[0] == surface)
937 if (swapchain->render_to_fbo)
939 TRACE("Returning GL_COLOR_ATTACHMENT0\n");
940 return GL_COLOR_ATTACHMENT0;
942 TRACE("Returning GL_BACK\n");
943 return GL_BACK;
945 else if (surface == swapchain->front_buffer)
947 TRACE("Returning GL_FRONT\n");
948 return GL_FRONT;
951 FIXME("Higher back buffer, returning GL_BACK\n");
952 return GL_BACK;
955 /* Slightly inefficient way to handle multiple dirty rects but it works :) */
956 void surface_add_dirty_rect(IWineD3DSurfaceImpl *surface, const RECT *dirty_rect)
958 IWineD3DBaseTexture *baseTexture = NULL;
960 TRACE("surface %p, dirty_rect %s.\n", surface, wine_dbgstr_rect(dirty_rect));
962 if (!(surface->Flags & SFLAG_INSYSMEM) && (surface->Flags & SFLAG_INTEXTURE))
963 /* No partial locking for textures yet. */
964 IWineD3DSurface_LoadLocation((IWineD3DSurface *)surface, SFLAG_INSYSMEM, NULL);
966 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)surface, SFLAG_INSYSMEM, TRUE);
967 if (dirty_rect)
969 surface->dirtyRect.left = min(surface->dirtyRect.left, dirty_rect->left);
970 surface->dirtyRect.top = min(surface->dirtyRect.top, dirty_rect->top);
971 surface->dirtyRect.right = max(surface->dirtyRect.right, dirty_rect->right);
972 surface->dirtyRect.bottom = max(surface->dirtyRect.bottom, dirty_rect->bottom);
974 else
976 surface->dirtyRect.left = 0;
977 surface->dirtyRect.top = 0;
978 surface->dirtyRect.right = surface->currentDesc.Width;
979 surface->dirtyRect.bottom = surface->currentDesc.Height;
982 /* if the container is a basetexture then mark it dirty. */
983 if (SUCCEEDED(IWineD3DSurface_GetContainer((IWineD3DSurface *)surface,
984 &IID_IWineD3DBaseTexture, (void **)&baseTexture)))
986 TRACE("Passing to container\n");
987 IWineD3DBaseTexture_SetDirty(baseTexture, TRUE);
988 IWineD3DBaseTexture_Release(baseTexture);
992 static BOOL surface_convert_color_to_argb(IWineD3DSurfaceImpl *This, DWORD color, DWORD *argb_color)
994 IWineD3DDeviceImpl *device = This->resource.device;
996 switch(This->resource.format_desc->format)
998 case WINED3DFMT_P8_UINT:
1000 DWORD alpha;
1002 if (primary_render_target_is_p8(device))
1003 alpha = color << 24;
1004 else
1005 alpha = 0xFF000000;
1007 if (This->palette) {
1008 *argb_color = (alpha |
1009 (This->palette->palents[color].peRed << 16) |
1010 (This->palette->palents[color].peGreen << 8) |
1011 (This->palette->palents[color].peBlue));
1012 } else {
1013 *argb_color = alpha;
1016 break;
1018 case WINED3DFMT_B5G6R5_UNORM:
1020 if (color == 0xFFFF) {
1021 *argb_color = 0xFFFFFFFF;
1022 } else {
1023 *argb_color = ((0xFF000000) |
1024 ((color & 0xF800) << 8) |
1025 ((color & 0x07E0) << 5) |
1026 ((color & 0x001F) << 3));
1029 break;
1031 case WINED3DFMT_B8G8R8_UNORM:
1032 case WINED3DFMT_B8G8R8X8_UNORM:
1033 *argb_color = 0xFF000000 | color;
1034 break;
1036 case WINED3DFMT_B8G8R8A8_UNORM:
1037 *argb_color = color;
1038 break;
1040 default:
1041 ERR("Unhandled conversion from %s to ARGB!\n", debug_d3dformat(This->resource.format_desc->format));
1042 return FALSE;
1044 return TRUE;
1047 static ULONG WINAPI IWineD3DSurfaceImpl_Release(IWineD3DSurface *iface)
1049 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1050 ULONG ref = InterlockedDecrement(&This->resource.ref);
1051 TRACE("(%p) : Releasing from %d\n", This, ref + 1);
1053 if (!ref)
1055 surface_cleanup(This);
1056 This->resource.parent_ops->wined3d_object_destroyed(This->resource.parent);
1058 TRACE("(%p) Released.\n", This);
1059 HeapFree(GetProcessHeap(), 0, This);
1062 return ref;
1065 /* ****************************************************
1066 IWineD3DSurface IWineD3DResource parts follow
1067 **************************************************** */
1069 void surface_internal_preload(IWineD3DSurfaceImpl *surface, enum WINED3DSRGB srgb)
1071 /* TODO: check for locks */
1072 IWineD3DDeviceImpl *device = surface->resource.device;
1073 IWineD3DBaseTexture *baseTexture = NULL;
1075 TRACE("(%p)Checking to see if the container is a base texture\n", surface);
1076 if (SUCCEEDED(IWineD3DSurface_GetContainer((IWineD3DSurface *)surface,
1077 &IID_IWineD3DBaseTexture, (void **)&baseTexture)))
1079 IWineD3DBaseTextureImpl *tex_impl = (IWineD3DBaseTextureImpl *)baseTexture;
1080 TRACE("Passing to container\n");
1081 tex_impl->baseTexture.internal_preload(baseTexture, srgb);
1082 IWineD3DBaseTexture_Release(baseTexture);
1083 } else {
1084 struct wined3d_context *context = NULL;
1086 TRACE("(%p) : About to load surface\n", surface);
1088 if (!device->isInDraw) context = context_acquire(device, NULL);
1090 if (surface->resource.format_desc->format == WINED3DFMT_P8_UINT
1091 || surface->resource.format_desc->format == WINED3DFMT_P8_UINT_A8_UNORM)
1093 if (palette9_changed(surface))
1095 TRACE("Reloading surface because the d3d8/9 palette was changed\n");
1096 /* TODO: This is not necessarily needed with hw palettized texture support */
1097 IWineD3DSurface_LoadLocation((IWineD3DSurface *)surface, SFLAG_INSYSMEM, NULL);
1098 /* Make sure the texture is reloaded because of the palette change, this kills performance though :( */
1099 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)surface, SFLAG_INTEXTURE, FALSE);
1103 IWineD3DSurface_LoadTexture((IWineD3DSurface *)surface, srgb == SRGB_SRGB ? TRUE : FALSE);
1105 if (surface->resource.pool == WINED3DPOOL_DEFAULT)
1107 /* Tell opengl to try and keep this texture in video ram (well mostly) */
1108 GLclampf tmp;
1109 tmp = 0.9f;
1110 ENTER_GL();
1111 glPrioritizeTextures(1, &surface->texture_name, &tmp);
1112 LEAVE_GL();
1115 if (context) context_release(context);
1119 static void WINAPI IWineD3DSurfaceImpl_PreLoad(IWineD3DSurface *iface)
1121 surface_internal_preload((IWineD3DSurfaceImpl *)iface, SRGB_ANY);
1124 /* Context activation is done by the caller. */
1125 static void surface_remove_pbo(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info)
1127 This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
1128 This->resource.allocatedMemory =
1129 (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1131 ENTER_GL();
1132 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1133 checkGLcall("glBindBufferARB(GL_PIXEL_UNPACK_BUFFER, This->pbo)");
1134 GL_EXTCALL(glGetBufferSubDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0, This->resource.size, This->resource.allocatedMemory));
1135 checkGLcall("glGetBufferSubDataARB");
1136 GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
1137 checkGLcall("glDeleteBuffersARB");
1138 LEAVE_GL();
1140 This->pbo = 0;
1141 This->Flags &= ~SFLAG_PBO;
1144 BOOL surface_init_sysmem(IWineD3DSurfaceImpl *surface)
1146 if (!surface->resource.allocatedMemory)
1148 surface->resource.heapMemory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1149 surface->resource.size + RESOURCE_ALIGNMENT);
1150 if (!surface->resource.heapMemory)
1152 ERR("Out of memory\n");
1153 return FALSE;
1155 surface->resource.allocatedMemory =
1156 (BYTE *)(((ULONG_PTR)surface->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1158 else
1160 memset(surface->resource.allocatedMemory, 0, surface->resource.size);
1163 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)surface, SFLAG_INSYSMEM, TRUE);
1164 return TRUE;
1167 static void WINAPI IWineD3DSurfaceImpl_UnLoad(IWineD3DSurface *iface) {
1168 IWineD3DBaseTexture *texture = NULL;
1169 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
1170 IWineD3DDeviceImpl *device = This->resource.device;
1171 const struct wined3d_gl_info *gl_info;
1172 renderbuffer_entry_t *entry, *entry2;
1173 struct wined3d_context *context;
1175 TRACE("(%p)\n", iface);
1177 if(This->resource.pool == WINED3DPOOL_DEFAULT) {
1178 /* Default pool resources are supposed to be destroyed before Reset is called.
1179 * Implicit resources stay however. So this means we have an implicit render target
1180 * or depth stencil. The content may be destroyed, but we still have to tear down
1181 * opengl resources, so we cannot leave early.
1183 * Put the surfaces into sysmem, and reset the content. The D3D content is undefined,
1184 * but we can't set the sysmem INDRAWABLE because when we're rendering the swapchain
1185 * or the depth stencil into an FBO the texture or render buffer will be removed
1186 * and all flags get lost
1188 surface_init_sysmem(This);
1190 else
1192 /* Load the surface into system memory */
1193 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
1194 IWineD3DSurface_ModifyLocation(iface, SFLAG_INDRAWABLE, FALSE);
1196 IWineD3DSurface_ModifyLocation(iface, SFLAG_INTEXTURE, FALSE);
1197 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSRGBTEX, FALSE);
1198 This->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
1200 context = context_acquire(device, NULL);
1201 gl_info = context->gl_info;
1203 /* Destroy PBOs, but load them into real sysmem before */
1204 if (This->Flags & SFLAG_PBO)
1205 surface_remove_pbo(This, gl_info);
1207 /* Destroy fbo render buffers. This is needed for implicit render targets, for
1208 * all application-created targets the application has to release the surface
1209 * before calling _Reset
1211 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry) {
1212 ENTER_GL();
1213 gl_info->fbo_ops.glDeleteRenderbuffers(1, &entry->id);
1214 LEAVE_GL();
1215 list_remove(&entry->entry);
1216 HeapFree(GetProcessHeap(), 0, entry);
1218 list_init(&This->renderbuffers);
1219 This->current_renderbuffer = NULL;
1221 /* If we're in a texture, the texture name belongs to the texture. Otherwise,
1222 * destroy it
1224 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **) &texture);
1225 if(!texture) {
1226 ENTER_GL();
1227 glDeleteTextures(1, &This->texture_name);
1228 This->texture_name = 0;
1229 glDeleteTextures(1, &This->texture_name_srgb);
1230 This->texture_name_srgb = 0;
1231 LEAVE_GL();
1232 } else {
1233 IWineD3DBaseTexture_Release(texture);
1236 context_release(context);
1239 /* ******************************************************
1240 IWineD3DSurface IWineD3DSurface parts follow
1241 ****************************************************** */
1243 /* Read the framebuffer back into the surface */
1244 static void read_from_framebuffer(IWineD3DSurfaceImpl *This, const RECT *rect, void *dest, UINT pitch)
1246 IWineD3DDeviceImpl *device = This->resource.device;
1247 const struct wined3d_gl_info *gl_info;
1248 struct wined3d_context *context;
1249 BYTE *mem;
1250 GLint fmt;
1251 GLint type;
1252 BYTE *row, *top, *bottom;
1253 int i;
1254 BOOL bpp;
1255 RECT local_rect;
1256 BOOL srcIsUpsideDown;
1257 GLint rowLen = 0;
1258 GLint skipPix = 0;
1259 GLint skipRow = 0;
1261 if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
1262 static BOOL warned = FALSE;
1263 if(!warned) {
1264 ERR("The application tries to lock the render target, but render target locking is disabled\n");
1265 warned = TRUE;
1267 return;
1270 /* Activate the surface. Set it up for blitting now, although not necessarily needed for LockRect.
1271 * Certain graphics drivers seem to dislike some enabled states when reading from opengl, the blitting usage
1272 * should help here. Furthermore unlockrect will need the context set up for blitting. The context manager will find
1273 * context->last_was_blit set on the unlock.
1275 context = context_acquire(device, This);
1276 context_apply_blit_state(context, device);
1277 gl_info = context->gl_info;
1279 ENTER_GL();
1281 /* Select the correct read buffer, and give some debug output.
1282 * There is no need to keep track of the current read buffer or reset it, every part of the code
1283 * that reads sets the read buffer as desired.
1285 if (surface_is_offscreen(This))
1287 /* Locking the primary render target which is not on a swapchain(=offscreen render target).
1288 * Read from the back buffer
1290 TRACE("Locking offscreen render target\n");
1291 glReadBuffer(device->offscreenBuffer);
1292 srcIsUpsideDown = TRUE;
1294 else
1296 /* Onscreen surfaces are always part of a swapchain */
1297 GLenum buffer = surface_get_gl_buffer(This);
1298 TRACE("Locking %#x buffer\n", buffer);
1299 glReadBuffer(buffer);
1300 checkGLcall("glReadBuffer");
1301 srcIsUpsideDown = FALSE;
1304 /* TODO: Get rid of the extra rectangle comparison and construction of a full surface rectangle */
1305 if(!rect) {
1306 local_rect.left = 0;
1307 local_rect.top = 0;
1308 local_rect.right = This->currentDesc.Width;
1309 local_rect.bottom = This->currentDesc.Height;
1310 } else {
1311 local_rect = *rect;
1313 /* TODO: Get rid of the extra GetPitch call, LockRect does that too. Cache the pitch */
1315 switch(This->resource.format_desc->format)
1317 case WINED3DFMT_P8_UINT:
1319 if (primary_render_target_is_p8(device))
1321 /* In case of P8 render targets the index is stored in the alpha component */
1322 fmt = GL_ALPHA;
1323 type = GL_UNSIGNED_BYTE;
1324 mem = dest;
1325 bpp = This->resource.format_desc->byte_count;
1326 } else {
1327 /* GL can't return palettized data, so read ARGB pixels into a
1328 * separate block of memory and convert them into palettized format
1329 * in software. Slow, but if the app means to use palettized render
1330 * targets and locks it...
1332 * Use GL_RGB, GL_UNSIGNED_BYTE to read the surface for performance reasons
1333 * Don't use GL_BGR as in the WINED3DFMT_R8G8B8 case, instead watch out
1334 * for the color channels when palettizing the colors.
1336 fmt = GL_RGB;
1337 type = GL_UNSIGNED_BYTE;
1338 pitch *= 3;
1339 mem = HeapAlloc(GetProcessHeap(), 0, This->resource.size * 3);
1340 if(!mem) {
1341 ERR("Out of memory\n");
1342 LEAVE_GL();
1343 return;
1345 bpp = This->resource.format_desc->byte_count * 3;
1348 break;
1350 default:
1351 mem = dest;
1352 fmt = This->resource.format_desc->glFormat;
1353 type = This->resource.format_desc->glType;
1354 bpp = This->resource.format_desc->byte_count;
1357 if(This->Flags & SFLAG_PBO) {
1358 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
1359 checkGLcall("glBindBufferARB");
1360 if(mem != NULL) {
1361 ERR("mem not null for pbo -- unexpected\n");
1362 mem = NULL;
1366 /* Save old pixel store pack state */
1367 glGetIntegerv(GL_PACK_ROW_LENGTH, &rowLen);
1368 checkGLcall("glGetIntegerv");
1369 glGetIntegerv(GL_PACK_SKIP_PIXELS, &skipPix);
1370 checkGLcall("glGetIntegerv");
1371 glGetIntegerv(GL_PACK_SKIP_ROWS, &skipRow);
1372 checkGLcall("glGetIntegerv");
1374 /* Setup pixel store pack state -- to glReadPixels into the correct place */
1375 glPixelStorei(GL_PACK_ROW_LENGTH, This->currentDesc.Width);
1376 checkGLcall("glPixelStorei");
1377 glPixelStorei(GL_PACK_SKIP_PIXELS, local_rect.left);
1378 checkGLcall("glPixelStorei");
1379 glPixelStorei(GL_PACK_SKIP_ROWS, local_rect.top);
1380 checkGLcall("glPixelStorei");
1382 glReadPixels(local_rect.left, (!srcIsUpsideDown) ? (This->currentDesc.Height - local_rect.bottom) : local_rect.top ,
1383 local_rect.right - local_rect.left,
1384 local_rect.bottom - local_rect.top,
1385 fmt, type, mem);
1386 checkGLcall("glReadPixels");
1388 /* Reset previous pixel store pack state */
1389 glPixelStorei(GL_PACK_ROW_LENGTH, rowLen);
1390 checkGLcall("glPixelStorei");
1391 glPixelStorei(GL_PACK_SKIP_PIXELS, skipPix);
1392 checkGLcall("glPixelStorei");
1393 glPixelStorei(GL_PACK_SKIP_ROWS, skipRow);
1394 checkGLcall("glPixelStorei");
1396 if(This->Flags & SFLAG_PBO) {
1397 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
1398 checkGLcall("glBindBufferARB");
1400 /* Check if we need to flip the image. If we need to flip use glMapBufferARB
1401 * to get a pointer to it and perform the flipping in software. This is a lot
1402 * faster than calling glReadPixels for each line. In case we want more speed
1403 * we should rerender it flipped in a FBO and read the data back from the FBO. */
1404 if(!srcIsUpsideDown) {
1405 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1406 checkGLcall("glBindBufferARB");
1408 mem = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
1409 checkGLcall("glMapBufferARB");
1413 /* TODO: Merge this with the palettization loop below for P8 targets */
1414 if(!srcIsUpsideDown) {
1415 UINT len, off;
1416 /* glReadPixels returns the image upside down, and there is no way to prevent this.
1417 Flip the lines in software */
1418 len = (local_rect.right - local_rect.left) * bpp;
1419 off = local_rect.left * bpp;
1421 row = HeapAlloc(GetProcessHeap(), 0, len);
1422 if(!row) {
1423 ERR("Out of memory\n");
1424 if (This->resource.format_desc->format == WINED3DFMT_P8_UINT) HeapFree(GetProcessHeap(), 0, mem);
1425 LEAVE_GL();
1426 return;
1429 top = mem + pitch * local_rect.top;
1430 bottom = mem + pitch * (local_rect.bottom - 1);
1431 for(i = 0; i < (local_rect.bottom - local_rect.top) / 2; i++) {
1432 memcpy(row, top + off, len);
1433 memcpy(top + off, bottom + off, len);
1434 memcpy(bottom + off, row, len);
1435 top += pitch;
1436 bottom -= pitch;
1438 HeapFree(GetProcessHeap(), 0, row);
1440 /* Unmap the temp PBO buffer */
1441 if(This->Flags & SFLAG_PBO) {
1442 GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
1443 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1447 LEAVE_GL();
1448 context_release(context);
1450 /* For P8 textures we need to perform an inverse palette lookup. This is done by searching for a palette
1451 * index which matches the RGB value. Note this isn't guaranteed to work when there are multiple entries for
1452 * the same color but we have no choice.
1453 * In case of P8 render targets, the index is stored in the alpha component so no conversion is needed.
1455 if (This->resource.format_desc->format == WINED3DFMT_P8_UINT && !primary_render_target_is_p8(device))
1457 const PALETTEENTRY *pal = NULL;
1458 DWORD width = pitch / 3;
1459 int x, y, c;
1461 if(This->palette) {
1462 pal = This->palette->palents;
1463 } else {
1464 ERR("Palette is missing, cannot perform inverse palette lookup\n");
1465 HeapFree(GetProcessHeap(), 0, mem);
1466 return ;
1469 for(y = local_rect.top; y < local_rect.bottom; y++) {
1470 for(x = local_rect.left; x < local_rect.right; x++) {
1471 /* start lines pixels */
1472 const BYTE *blue = mem + y * pitch + x * (sizeof(BYTE) * 3);
1473 const BYTE *green = blue + 1;
1474 const BYTE *red = green + 1;
1476 for(c = 0; c < 256; c++) {
1477 if(*red == pal[c].peRed &&
1478 *green == pal[c].peGreen &&
1479 *blue == pal[c].peBlue)
1481 *((BYTE *) dest + y * width + x) = c;
1482 break;
1487 HeapFree(GetProcessHeap(), 0, mem);
1491 /* Read the framebuffer contents into a texture */
1492 static void read_from_framebuffer_texture(IWineD3DSurfaceImpl *This, BOOL srgb)
1494 IWineD3DDeviceImpl *device = This->resource.device;
1495 const struct wined3d_gl_info *gl_info;
1496 struct wined3d_context *context;
1497 GLint prevRead;
1498 BOOL alloc_flag = srgb ? SFLAG_SRGBALLOCATED : SFLAG_ALLOCATED;
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.
1504 context = context_acquire(device, This);
1505 gl_info = context->gl_info;
1507 surface_bind_and_dirtify(This, srgb);
1509 ENTER_GL();
1510 glGetIntegerv(GL_READ_BUFFER, &prevRead);
1511 LEAVE_GL();
1513 /* Select the correct read buffer, and give some debug output.
1514 * There is no need to keep track of the current read buffer or reset it, every part of the code
1515 * that reads sets the read buffer as desired.
1517 if (!surface_is_offscreen(This))
1519 GLenum buffer = surface_get_gl_buffer(This);
1520 TRACE("Locking %#x buffer\n", buffer);
1522 ENTER_GL();
1523 glReadBuffer(buffer);
1524 checkGLcall("glReadBuffer");
1525 LEAVE_GL();
1527 else
1529 /* Locking the primary render target which is not on a swapchain(=offscreen render target).
1530 * Read from the back buffer
1532 TRACE("Locking offscreen render target\n");
1533 ENTER_GL();
1534 glReadBuffer(device->offscreenBuffer);
1535 checkGLcall("glReadBuffer");
1536 LEAVE_GL();
1539 if (!(This->Flags & alloc_flag))
1541 surface_allocate_surface(This, gl_info, This->resource.format_desc, srgb);
1542 This->Flags |= alloc_flag;
1545 ENTER_GL();
1546 /* If !SrcIsUpsideDown we should flip the surface.
1547 * This can be done using glCopyTexSubImage2D but this
1548 * is VERY slow, so don't do that. We should prevent
1549 * this code from getting called in such cases or perhaps
1550 * we can use FBOs */
1552 glCopyTexSubImage2D(This->texture_target, This->texture_level,
1553 0, 0, 0, 0, This->currentDesc.Width, This->currentDesc.Height);
1554 checkGLcall("glCopyTexSubImage2D");
1556 glReadBuffer(prevRead);
1557 checkGLcall("glReadBuffer");
1559 LEAVE_GL();
1561 context_release(context);
1563 TRACE("Updated target %d\n", This->texture_target);
1566 /* Context activation is done by the caller. */
1567 static void surface_prepare_texture_internal(IWineD3DSurfaceImpl *surface,
1568 const struct wined3d_gl_info *gl_info, BOOL srgb)
1570 DWORD alloc_flag = srgb ? SFLAG_SRGBALLOCATED : SFLAG_ALLOCATED;
1571 CONVERT_TYPES convert;
1572 struct wined3d_format_desc desc;
1574 if (surface->Flags & alloc_flag) return;
1576 d3dfmt_get_conv(surface, TRUE, TRUE, &desc, &convert);
1577 if(convert != NO_CONVERSION) surface->Flags |= SFLAG_CONVERTED;
1578 else surface->Flags &= ~SFLAG_CONVERTED;
1580 surface_bind_and_dirtify(surface, srgb);
1581 surface_allocate_surface(surface, gl_info, &desc, srgb);
1582 surface->Flags |= alloc_flag;
1585 /* Context activation is done by the caller. */
1586 void surface_prepare_texture(IWineD3DSurfaceImpl *surface, const struct wined3d_gl_info *gl_info, BOOL srgb)
1588 IWineD3DBaseTextureImpl *texture;
1590 if (SUCCEEDED(IWineD3DSurface_GetContainer((IWineD3DSurface *)surface,
1591 &IID_IWineD3DBaseTexture, (void **)&texture)))
1593 UINT sub_count = texture->baseTexture.level_count * texture->baseTexture.layer_count;
1594 UINT i;
1596 TRACE("surface %p is a subresource of texture %p.\n", surface, texture);
1598 for (i = 0; i < sub_count; ++i)
1600 IWineD3DSurfaceImpl *s = (IWineD3DSurfaceImpl *)texture->baseTexture.sub_resources[i];
1601 surface_prepare_texture_internal(s, gl_info, srgb);
1604 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture);
1607 surface_prepare_texture_internal(surface, gl_info, srgb);
1610 static void surface_prepare_system_memory(IWineD3DSurfaceImpl *This)
1612 IWineD3DDeviceImpl *device = This->resource.device;
1613 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1615 /* Performance optimization: Count how often a surface is locked, if it is locked regularly do not throw away the system memory copy.
1616 * This avoids the need to download the surface from opengl all the time. The surface is still downloaded if the opengl texture is
1617 * changed
1619 if(!(This->Flags & SFLAG_DYNLOCK)) {
1620 This->lockCount++;
1621 /* MAXLOCKCOUNT is defined in wined3d_private.h */
1622 if(This->lockCount > MAXLOCKCOUNT) {
1623 TRACE("Surface is locked regularly, not freeing the system memory copy any more\n");
1624 This->Flags |= SFLAG_DYNLOCK;
1628 /* Create a PBO for dynamically locked surfaces but don't do it for converted or non-pow2 surfaces.
1629 * Also don't create a PBO for systemmem surfaces.
1631 if (gl_info->supported[ARB_PIXEL_BUFFER_OBJECT] && (This->Flags & SFLAG_DYNLOCK)
1632 && !(This->Flags & (SFLAG_PBO | SFLAG_CONVERTED | SFLAG_NONPOW2))
1633 && (This->resource.pool != WINED3DPOOL_SYSTEMMEM))
1635 GLenum error;
1636 struct wined3d_context *context;
1638 context = context_acquire(device, NULL);
1639 ENTER_GL();
1641 GL_EXTCALL(glGenBuffersARB(1, &This->pbo));
1642 error = glGetError();
1643 if(This->pbo == 0 || error != GL_NO_ERROR) {
1644 ERR("Failed to bind the PBO with error %s (%#x)\n", debug_glerror(error), error);
1647 TRACE("Attaching pbo=%#x to (%p)\n", This->pbo, This);
1649 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1650 checkGLcall("glBindBufferARB");
1652 GL_EXTCALL(glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->resource.size + 4, This->resource.allocatedMemory, GL_STREAM_DRAW_ARB));
1653 checkGLcall("glBufferDataARB");
1655 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1656 checkGLcall("glBindBufferARB");
1658 /* We don't need the system memory anymore and we can't even use it for PBOs */
1659 if(!(This->Flags & SFLAG_CLIENT)) {
1660 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
1661 This->resource.heapMemory = NULL;
1663 This->resource.allocatedMemory = NULL;
1664 This->Flags |= SFLAG_PBO;
1665 LEAVE_GL();
1666 context_release(context);
1668 else if (!(This->resource.allocatedMemory || This->Flags & SFLAG_PBO))
1670 /* Whatever surface we have, make sure that there is memory allocated for the downloaded copy,
1671 * or a pbo to map
1673 if(!This->resource.heapMemory) {
1674 This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
1676 This->resource.allocatedMemory =
1677 (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1678 if(This->Flags & SFLAG_INSYSMEM) {
1679 ERR("Surface without memory or pbo has SFLAG_INSYSMEM set!\n");
1684 static HRESULT WINAPI IWineD3DSurfaceImpl_LockRect(IWineD3DSurface *iface, WINED3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags) {
1685 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1686 IWineD3DDeviceImpl *device = This->resource.device;
1687 const RECT *pass_rect = pRect;
1689 TRACE("(%p) : rect@%p flags(%08x), output lockedRect@%p, memory@%p\n", This, pRect, Flags, pLockedRect, This->resource.allocatedMemory);
1691 /* This is also done in the base class, but we have to verify this before loading any data from
1692 * gl into the sysmem copy. The PBO may be mapped, a different rectangle locked, the discard flag
1693 * may interfere, and all other bad things may happen
1695 if (This->Flags & SFLAG_LOCKED) {
1696 WARN("Surface is already locked, returning D3DERR_INVALIDCALL\n");
1697 return WINED3DERR_INVALIDCALL;
1699 This->Flags |= SFLAG_LOCKED;
1701 if (!(This->Flags & SFLAG_LOCKABLE))
1703 TRACE("Warning: trying to lock unlockable surf@%p\n", This);
1706 if (Flags & WINED3DLOCK_DISCARD) {
1707 /* Set SFLAG_INSYSMEM, so we'll never try to download the data from the texture. */
1708 TRACE("WINED3DLOCK_DISCARD flag passed, marking local copy as up to date\n");
1709 surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1710 This->Flags |= SFLAG_INSYSMEM;
1711 goto lock_end;
1714 if (This->Flags & SFLAG_INSYSMEM) {
1715 TRACE("Local copy is up to date, not downloading data\n");
1716 surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1717 goto lock_end;
1720 /* IWineD3DSurface_LoadLocation() does not check if the rectangle specifies
1721 * the full surface. Most callers don't need that, so do it here. */
1722 if (pRect && pRect->top == 0 && pRect->left == 0
1723 && pRect->right == This->currentDesc.Width
1724 && pRect->bottom == This->currentDesc.Height)
1726 pass_rect = NULL;
1729 if (!(wined3d_settings.rendertargetlock_mode == RTL_DISABLE
1730 && ((This->Flags & SFLAG_SWAPCHAIN) || This == device->render_targets[0])))
1732 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, pass_rect);
1735 lock_end:
1736 if (This->Flags & SFLAG_PBO)
1738 const struct wined3d_gl_info *gl_info;
1739 struct wined3d_context *context;
1741 context = context_acquire(device, NULL);
1742 gl_info = context->gl_info;
1744 ENTER_GL();
1745 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1746 checkGLcall("glBindBufferARB");
1748 /* This shouldn't happen but could occur if some other function didn't handle the PBO properly */
1749 if(This->resource.allocatedMemory) {
1750 ERR("The surface already has PBO memory allocated!\n");
1753 This->resource.allocatedMemory = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
1754 checkGLcall("glMapBufferARB");
1756 /* Make sure the pbo isn't set anymore in order not to break non-pbo calls */
1757 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1758 checkGLcall("glBindBufferARB");
1760 LEAVE_GL();
1761 context_release(context);
1764 if (Flags & (WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY)) {
1765 /* Don't dirtify */
1766 } else {
1767 IWineD3DBaseTexture *pBaseTexture;
1769 * Dirtify on lock
1770 * as seen in msdn docs
1772 surface_add_dirty_rect(This, pRect);
1774 /** Dirtify Container if needed */
1775 if (SUCCEEDED(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&pBaseTexture))) {
1776 TRACE("Making container dirty\n");
1777 IWineD3DBaseTexture_SetDirty(pBaseTexture, TRUE);
1778 IWineD3DBaseTexture_Release(pBaseTexture);
1779 } else {
1780 TRACE("Surface is standalone, no need to dirty the container\n");
1784 return IWineD3DBaseSurfaceImpl_LockRect(iface, pLockedRect, pRect, Flags);
1787 static void flush_to_framebuffer_drawpixels(IWineD3DSurfaceImpl *This, GLenum fmt, GLenum type, UINT bpp, const BYTE *mem) {
1788 GLint prev_store;
1789 GLint prev_rasterpos[4];
1790 GLint skipBytes = 0;
1791 UINT pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This); /* target is argb, 4 byte */
1792 IWineD3DDeviceImpl *device = This->resource.device;
1793 const struct wined3d_gl_info *gl_info;
1794 struct wined3d_context *context;
1796 /* Activate the correct context for the render target */
1797 context = context_acquire(device, This);
1798 context_apply_blit_state(context, device);
1799 gl_info = context->gl_info;
1801 ENTER_GL();
1803 if (!surface_is_offscreen(This))
1805 GLenum buffer = surface_get_gl_buffer(This);
1806 TRACE("Unlocking %#x buffer.\n", buffer);
1807 context_set_draw_buffer(context, buffer);
1809 else
1811 /* Primary offscreen render target */
1812 TRACE("Offscreen render target.\n");
1813 context_set_draw_buffer(context, device->offscreenBuffer);
1816 glGetIntegerv(GL_PACK_SWAP_BYTES, &prev_store);
1817 checkGLcall("glGetIntegerv");
1818 glGetIntegerv(GL_CURRENT_RASTER_POSITION, &prev_rasterpos[0]);
1819 checkGLcall("glGetIntegerv");
1820 glPixelZoom(1.0f, -1.0f);
1821 checkGLcall("glPixelZoom");
1823 /* If not fullscreen, we need to skip a number of bytes to find the next row of data */
1824 glGetIntegerv(GL_UNPACK_ROW_LENGTH, &skipBytes);
1825 glPixelStorei(GL_UNPACK_ROW_LENGTH, This->currentDesc.Width);
1827 glRasterPos3i(This->lockedRect.left, This->lockedRect.top, 1);
1828 checkGLcall("glRasterPos3i");
1830 /* Some drivers(radeon dri, others?) don't like exceptions during
1831 * glDrawPixels. If the surface is a DIB section, it might be in GDIMode
1832 * after ReleaseDC. Reading it will cause an exception, which x11drv will
1833 * catch to put the dib section in InSync mode, which leads to a crash
1834 * and a blocked x server on my radeon card.
1836 * The following lines read the dib section so it is put in InSync mode
1837 * before glDrawPixels is called and the crash is prevented. There won't
1838 * be any interfering gdi accesses, because UnlockRect is called from
1839 * ReleaseDC, and the app won't use the dc any more afterwards.
1841 if((This->Flags & SFLAG_DIBSECTION) && !(This->Flags & SFLAG_PBO)) {
1842 volatile BYTE read;
1843 read = This->resource.allocatedMemory[0];
1846 if(This->Flags & SFLAG_PBO) {
1847 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1848 checkGLcall("glBindBufferARB");
1851 /* When the surface is locked we only have to refresh the locked part else we need to update the whole image */
1852 if(This->Flags & SFLAG_LOCKED) {
1853 glDrawPixels(This->lockedRect.right - This->lockedRect.left,
1854 (This->lockedRect.bottom - This->lockedRect.top)-1,
1855 fmt, type,
1856 mem + bpp * This->lockedRect.left + pitch * This->lockedRect.top);
1857 checkGLcall("glDrawPixels");
1858 } else {
1859 glDrawPixels(This->currentDesc.Width,
1860 This->currentDesc.Height,
1861 fmt, type, mem);
1862 checkGLcall("glDrawPixels");
1865 if(This->Flags & SFLAG_PBO) {
1866 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1867 checkGLcall("glBindBufferARB");
1870 glPixelZoom(1.0f, 1.0f);
1871 checkGLcall("glPixelZoom");
1873 glRasterPos3iv(&prev_rasterpos[0]);
1874 checkGLcall("glRasterPos3iv");
1876 /* Reset to previous pack row length */
1877 glPixelStorei(GL_UNPACK_ROW_LENGTH, skipBytes);
1878 checkGLcall("glPixelStorei(GL_UNPACK_ROW_LENGTH)");
1880 LEAVE_GL();
1881 context_release(context);
1884 static HRESULT WINAPI IWineD3DSurfaceImpl_UnlockRect(IWineD3DSurface *iface) {
1885 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1886 IWineD3DDeviceImpl *device = This->resource.device;
1887 BOOL fullsurface;
1889 if (!(This->Flags & SFLAG_LOCKED)) {
1890 WARN("trying to Unlock an unlocked surf@%p\n", This);
1891 return WINEDDERR_NOTLOCKED;
1894 if (This->Flags & SFLAG_PBO)
1896 const struct wined3d_gl_info *gl_info;
1897 struct wined3d_context *context;
1899 TRACE("Freeing PBO memory\n");
1901 context = context_acquire(device, NULL);
1902 gl_info = context->gl_info;
1904 ENTER_GL();
1905 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1906 GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
1907 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1908 checkGLcall("glUnmapBufferARB");
1909 LEAVE_GL();
1910 context_release(context);
1912 This->resource.allocatedMemory = NULL;
1915 TRACE("(%p) : dirtyfied(%d)\n", This, This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE) ? 0 : 1);
1917 if (This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE)) {
1918 TRACE("(%p) : Not Dirtified so nothing to do, return now\n", This);
1919 goto unlock_end;
1922 if ((This->Flags & SFLAG_SWAPCHAIN) || (device->render_targets && This == device->render_targets[0]))
1924 if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
1925 static BOOL warned = FALSE;
1926 if(!warned) {
1927 ERR("The application tries to write to the render target, but render target locking is disabled\n");
1928 warned = TRUE;
1930 goto unlock_end;
1933 if(This->dirtyRect.left == 0 &&
1934 This->dirtyRect.top == 0 &&
1935 This->dirtyRect.right == This->currentDesc.Width &&
1936 This->dirtyRect.bottom == This->currentDesc.Height) {
1937 fullsurface = TRUE;
1938 } else {
1939 /* TODO: Proper partial rectangle tracking */
1940 fullsurface = FALSE;
1941 This->Flags |= SFLAG_INSYSMEM;
1944 switch(wined3d_settings.rendertargetlock_mode) {
1945 case RTL_READTEX:
1946 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL /* partial texture loading not supported yet */);
1947 /* drop through */
1949 case RTL_READDRAW:
1950 IWineD3DSurface_LoadLocation(iface, SFLAG_INDRAWABLE, fullsurface ? NULL : &This->dirtyRect);
1951 break;
1954 if(!fullsurface) {
1955 /* Partial rectangle tracking is not commonly implemented, it is only done for render targets. Overwrite
1956 * the flags to bring them back into a sane state. INSYSMEM was set before to tell LoadLocation where
1957 * to read the rectangle from. Indrawable is set because all modifications from the partial sysmem copy
1958 * are written back to the drawable, thus the surface is merged again in the drawable. The sysmem copy is
1959 * not fully up to date because only a subrectangle was read in LockRect.
1961 This->Flags &= ~SFLAG_INSYSMEM;
1962 This->Flags |= SFLAG_INDRAWABLE;
1965 This->dirtyRect.left = This->currentDesc.Width;
1966 This->dirtyRect.top = This->currentDesc.Height;
1967 This->dirtyRect.right = 0;
1968 This->dirtyRect.bottom = 0;
1970 else if (This == device->depth_stencil)
1972 FIXME("Depth Stencil buffer locking is not implemented\n");
1973 } else {
1974 /* The rest should be a normal texture */
1975 IWineD3DBaseTextureImpl *impl;
1976 /* Check if the texture is bound, if yes dirtify the sampler to force a re-upload of the texture
1977 * Can't load the texture here because PreLoad may destroy and recreate the gl texture, so sampler
1978 * states need resetting
1980 if(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&impl) == WINED3D_OK) {
1981 if (impl->baseTexture.bindCount)
1982 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_SAMPLER(impl->baseTexture.sampler));
1983 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *) impl);
1987 unlock_end:
1988 This->Flags &= ~SFLAG_LOCKED;
1989 memset(&This->lockedRect, 0, sizeof(RECT));
1991 /* Overlays have to be redrawn manually after changes with the GL implementation */
1992 if(This->overlay_dest) {
1993 IWineD3DSurface_DrawOverlay(iface);
1995 return WINED3D_OK;
1998 static void surface_release_client_storage(IWineD3DSurfaceImpl *surface)
2000 struct wined3d_context *context;
2002 context = context_acquire(surface->resource.device, NULL);
2004 ENTER_GL();
2005 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
2006 if (surface->texture_name)
2008 surface_bind_and_dirtify(surface, FALSE);
2009 glTexImage2D(surface->texture_target, surface->texture_level,
2010 GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
2012 if (surface->texture_name_srgb)
2014 surface_bind_and_dirtify(surface, TRUE);
2015 glTexImage2D(surface->texture_target, surface->texture_level,
2016 GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
2018 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
2020 LEAVE_GL();
2021 context_release(context);
2023 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)surface, SFLAG_INSRGBTEX, FALSE);
2024 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)surface, SFLAG_INTEXTURE, FALSE);
2025 surface_force_reload(surface);
2028 static HRESULT WINAPI IWineD3DSurfaceImpl_GetDC(IWineD3DSurface *iface, HDC *pHDC)
2030 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2031 WINED3DLOCKED_RECT lock;
2032 HRESULT hr;
2033 RGBQUAD col[256];
2035 TRACE("(%p)->(%p)\n",This,pHDC);
2037 if(This->Flags & SFLAG_USERPTR) {
2038 ERR("Not supported on surfaces with an application-provided surfaces\n");
2039 return WINEDDERR_NODC;
2042 /* Give more detailed info for ddraw */
2043 if (This->Flags & SFLAG_DCINUSE)
2044 return WINEDDERR_DCALREADYCREATED;
2046 /* Can't GetDC if the surface is locked */
2047 if (This->Flags & SFLAG_LOCKED)
2048 return WINED3DERR_INVALIDCALL;
2050 memset(&lock, 0, sizeof(lock)); /* To be sure */
2052 /* Create a DIB section if there isn't a hdc yet */
2053 if(!This->hDC) {
2054 if(This->Flags & SFLAG_CLIENT) {
2055 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
2056 surface_release_client_storage(This);
2058 hr = IWineD3DBaseSurfaceImpl_CreateDIBSection(iface);
2059 if(FAILED(hr)) return WINED3DERR_INVALIDCALL;
2061 /* Use the dib section from now on if we are not using a PBO */
2062 if(!(This->Flags & SFLAG_PBO))
2063 This->resource.allocatedMemory = This->dib.bitmap_data;
2066 /* Lock the surface */
2067 hr = IWineD3DSurface_LockRect(iface,
2068 &lock,
2069 NULL,
2072 if(This->Flags & SFLAG_PBO) {
2073 /* Sync the DIB with the PBO. This can't be done earlier because LockRect activates the allocatedMemory */
2074 memcpy(This->dib.bitmap_data, This->resource.allocatedMemory, This->dib.bitmap_size);
2077 if(FAILED(hr)) {
2078 ERR("IWineD3DSurface_LockRect failed with hr = %08x\n", hr);
2079 /* keep the dib section */
2080 return hr;
2083 if (This->resource.format_desc->format == WINED3DFMT_P8_UINT
2084 || This->resource.format_desc->format == WINED3DFMT_P8_UINT_A8_UNORM)
2086 /* GetDC on palettized formats is unsupported in D3D9, and the method is missing in
2087 D3D8, so this should only be used for DX <=7 surfaces (with non-device palettes) */
2088 unsigned int n;
2089 const PALETTEENTRY *pal = NULL;
2091 if(This->palette) {
2092 pal = This->palette->palents;
2093 } else {
2094 IWineD3DSurfaceImpl *dds_primary;
2095 IWineD3DSwapChainImpl *swapchain;
2096 swapchain = (IWineD3DSwapChainImpl *)This->resource.device->swapchains[0];
2097 dds_primary = swapchain->front_buffer;
2098 if (dds_primary && dds_primary->palette)
2099 pal = dds_primary->palette->palents;
2102 if (pal) {
2103 for (n=0; n<256; n++) {
2104 col[n].rgbRed = pal[n].peRed;
2105 col[n].rgbGreen = pal[n].peGreen;
2106 col[n].rgbBlue = pal[n].peBlue;
2107 col[n].rgbReserved = 0;
2109 SetDIBColorTable(This->hDC, 0, 256, col);
2113 *pHDC = This->hDC;
2114 TRACE("returning %p\n",*pHDC);
2115 This->Flags |= SFLAG_DCINUSE;
2117 return WINED3D_OK;
2120 static HRESULT WINAPI IWineD3DSurfaceImpl_ReleaseDC(IWineD3DSurface *iface, HDC hDC)
2122 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2124 TRACE("(%p)->(%p)\n",This,hDC);
2126 if (!(This->Flags & SFLAG_DCINUSE))
2127 return WINEDDERR_NODC;
2129 if (This->hDC !=hDC) {
2130 WARN("Application tries to release an invalid DC(%p), surface dc is %p\n", hDC, This->hDC);
2131 return WINEDDERR_NODC;
2134 if((This->Flags & SFLAG_PBO) && This->resource.allocatedMemory) {
2135 /* Copy the contents of the DIB over to the PBO */
2136 memcpy(This->resource.allocatedMemory, This->dib.bitmap_data, This->dib.bitmap_size);
2139 /* we locked first, so unlock now */
2140 IWineD3DSurface_UnlockRect(iface);
2142 This->Flags &= ~SFLAG_DCINUSE;
2144 return WINED3D_OK;
2147 /* ******************************************************
2148 IWineD3DSurface Internal (No mapping to directx api) parts follow
2149 ****************************************************** */
2151 HRESULT d3dfmt_get_conv(IWineD3DSurfaceImpl *This, BOOL need_alpha_ck, BOOL use_texturing, struct wined3d_format_desc *desc, CONVERT_TYPES *convert)
2153 BOOL colorkey_active = need_alpha_ck && (This->CKeyFlags & WINEDDSD_CKSRCBLT);
2154 IWineD3DDeviceImpl *device = This->resource.device;
2155 BOOL blit_supported = FALSE;
2156 RECT rect = {0, 0, This->pow2Width, This->pow2Height};
2158 /* Copy the default values from the surface. Below we might perform fixups */
2159 /* TODO: get rid of color keying desc fixups by using e.g. a table. */
2160 *desc = *This->resource.format_desc;
2161 *convert = NO_CONVERSION;
2163 /* Ok, now look if we have to do any conversion */
2164 switch(This->resource.format_desc->format)
2166 case WINED3DFMT_P8_UINT:
2167 /* ****************
2168 Paletted Texture
2169 **************** */
2171 blit_supported = device->blitter->blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
2172 &rect, This->resource.usage, This->resource.pool,
2173 This->resource.format_desc, &rect, This->resource.usage,
2174 This->resource.pool, This->resource.format_desc);
2176 /* Use conversion when the blit_shader backend supports it. It only supports this in case of
2177 * texturing. Further also use conversion in case of color keying.
2178 * Paletted textures can be emulated using shaders but only do that for 2D purposes e.g. situations
2179 * in which the main render target uses p8. Some games like GTA Vice City use P8 for texturing which
2180 * conflicts with this.
2182 if (!((blit_supported && device->render_targets && This == device->render_targets[0]))
2183 || colorkey_active || !use_texturing)
2185 desc->glFormat = GL_RGBA;
2186 desc->glInternal = GL_RGBA;
2187 desc->glType = GL_UNSIGNED_BYTE;
2188 desc->conv_byte_count = 4;
2189 if(colorkey_active) {
2190 *convert = CONVERT_PALETTED_CK;
2191 } else {
2192 *convert = CONVERT_PALETTED;
2195 break;
2197 case WINED3DFMT_B2G3R3_UNORM:
2198 /* **********************
2199 GL_UNSIGNED_BYTE_3_3_2
2200 ********************** */
2201 if (colorkey_active) {
2202 /* This texture format will never be used.. So do not care about color keying
2203 up until the point in time it will be needed :-) */
2204 FIXME(" ColorKeying not supported in the RGB 332 format !\n");
2206 break;
2208 case WINED3DFMT_B5G6R5_UNORM:
2209 if (colorkey_active) {
2210 *convert = CONVERT_CK_565;
2211 desc->glFormat = GL_RGBA;
2212 desc->glInternal = GL_RGB5_A1;
2213 desc->glType = GL_UNSIGNED_SHORT_5_5_5_1;
2214 desc->conv_byte_count = 2;
2216 break;
2218 case WINED3DFMT_B5G5R5X1_UNORM:
2219 if (colorkey_active) {
2220 *convert = CONVERT_CK_5551;
2221 desc->glFormat = GL_BGRA;
2222 desc->glInternal = GL_RGB5_A1;
2223 desc->glType = GL_UNSIGNED_SHORT_1_5_5_5_REV;
2224 desc->conv_byte_count = 2;
2226 break;
2228 case WINED3DFMT_B8G8R8_UNORM:
2229 if (colorkey_active) {
2230 *convert = CONVERT_CK_RGB24;
2231 desc->glFormat = GL_RGBA;
2232 desc->glInternal = GL_RGBA8;
2233 desc->glType = GL_UNSIGNED_INT_8_8_8_8;
2234 desc->conv_byte_count = 4;
2236 break;
2238 case WINED3DFMT_B8G8R8X8_UNORM:
2239 if (colorkey_active) {
2240 *convert = CONVERT_RGB32_888;
2241 desc->glFormat = GL_RGBA;
2242 desc->glInternal = GL_RGBA8;
2243 desc->glType = GL_UNSIGNED_INT_8_8_8_8;
2244 desc->conv_byte_count = 4;
2246 break;
2248 default:
2249 break;
2252 return WINED3D_OK;
2255 void d3dfmt_p8_init_palette(IWineD3DSurfaceImpl *This, BYTE table[256][4], BOOL colorkey)
2257 IWineD3DDeviceImpl *device = This->resource.device;
2258 IWineD3DPaletteImpl *pal = This->palette;
2259 BOOL index_in_alpha = FALSE;
2260 unsigned int i;
2262 /* Old games like StarCraft, C&C, Red Alert and others use P8 render targets.
2263 * Reading back the RGB output each lockrect (each frame as they lock the whole screen)
2264 * is slow. Further RGB->P8 conversion is not possible because palettes can have
2265 * duplicate entries. Store the color key in the unused alpha component to speed the
2266 * download up and to make conversion unneeded. */
2267 index_in_alpha = primary_render_target_is_p8(device);
2269 if (!pal)
2271 UINT dxVersion = ((IWineD3DImpl *)device->wined3d)->dxVersion;
2273 /* In DirectDraw the palette is a property of the surface, there are no such things as device palettes. */
2274 if (dxVersion <= 7)
2276 ERR("This code should never get entered for DirectDraw!, expect problems\n");
2277 if (index_in_alpha)
2279 /* Guarantees that memory representation remains correct after sysmem<->texture transfers even if
2280 * there's no palette at this time. */
2281 for (i = 0; i < 256; i++) table[i][3] = i;
2284 else
2286 /* Direct3D >= 8 palette usage style: P8 textures use device palettes, palette entry format is A8R8G8B8,
2287 * alpha is stored in peFlags and may be used by the app if D3DPTEXTURECAPS_ALPHAPALETTE device
2288 * capability flag is present (wine does advertise this capability) */
2289 for (i = 0; i < 256; ++i)
2291 table[i][0] = device->palettes[device->currentPalette][i].peRed;
2292 table[i][1] = device->palettes[device->currentPalette][i].peGreen;
2293 table[i][2] = device->palettes[device->currentPalette][i].peBlue;
2294 table[i][3] = device->palettes[device->currentPalette][i].peFlags;
2298 else
2300 TRACE("Using surface palette %p\n", pal);
2301 /* Get the surface's palette */
2302 for (i = 0; i < 256; ++i)
2304 table[i][0] = pal->palents[i].peRed;
2305 table[i][1] = pal->palents[i].peGreen;
2306 table[i][2] = pal->palents[i].peBlue;
2308 /* When index_in_alpha is set the palette index is stored in the
2309 * alpha component. In case of a readback we can then read
2310 * GL_ALPHA. Color keying is handled in BltOverride using a
2311 * GL_ALPHA_TEST using GL_NOT_EQUAL. In case of index_in_alpha the
2312 * color key itself is passed to glAlphaFunc in other cases the
2313 * alpha component of pixels that should be masked away is set to 0. */
2314 if (index_in_alpha)
2316 table[i][3] = i;
2318 else if (colorkey && (i >= This->SrcBltCKey.dwColorSpaceLowValue)
2319 && (i <= This->SrcBltCKey.dwColorSpaceHighValue))
2321 table[i][3] = 0x00;
2323 else if(pal->Flags & WINEDDPCAPS_ALPHA)
2325 table[i][3] = pal->palents[i].peFlags;
2327 else
2329 table[i][3] = 0xFF;
2335 static HRESULT d3dfmt_convert_surface(const BYTE *src, BYTE *dst, UINT pitch, UINT width,
2336 UINT height, UINT outpitch, CONVERT_TYPES convert, IWineD3DSurfaceImpl *This)
2338 const BYTE *source;
2339 BYTE *dest;
2340 TRACE("(%p)->(%p),(%d,%d,%d,%d,%p)\n", src, dst, pitch, height, outpitch, convert,This);
2342 switch (convert) {
2343 case NO_CONVERSION:
2345 memcpy(dst, src, pitch * height);
2346 break;
2348 case CONVERT_PALETTED:
2349 case CONVERT_PALETTED_CK:
2351 IWineD3DPaletteImpl* pal = This->palette;
2352 BYTE table[256][4];
2353 unsigned int x, y;
2355 if( pal == NULL) {
2356 /* TODO: If we are a sublevel, try to get the palette from level 0 */
2359 d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
2361 for (y = 0; y < height; y++)
2363 source = src + pitch * y;
2364 dest = dst + outpitch * y;
2365 /* This is an 1 bpp format, using the width here is fine */
2366 for (x = 0; x < width; x++) {
2367 BYTE color = *source++;
2368 *dest++ = table[color][0];
2369 *dest++ = table[color][1];
2370 *dest++ = table[color][2];
2371 *dest++ = table[color][3];
2375 break;
2377 case CONVERT_CK_565:
2379 /* Converting the 565 format in 5551 packed to emulate color-keying.
2381 Note : in all these conversion, it would be best to average the averaging
2382 pixels to get the color of the pixel that will be color-keyed to
2383 prevent 'color bleeding'. This will be done later on if ever it is
2384 too visible.
2386 Note2: Nvidia documents say that their driver does not support alpha + color keying
2387 on the same surface and disables color keying in such a case
2389 unsigned int x, y;
2390 const WORD *Source;
2391 WORD *Dest;
2393 TRACE("Color keyed 565\n");
2395 for (y = 0; y < height; y++) {
2396 Source = (const WORD *)(src + y * pitch);
2397 Dest = (WORD *) (dst + y * outpitch);
2398 for (x = 0; x < width; x++ ) {
2399 WORD color = *Source++;
2400 *Dest = ((color & 0xFFC0) | ((color & 0x1F) << 1));
2401 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2402 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2403 *Dest |= 0x0001;
2405 Dest++;
2409 break;
2411 case CONVERT_CK_5551:
2413 /* Converting X1R5G5B5 format to R5G5B5A1 to emulate color-keying. */
2414 unsigned int x, y;
2415 const WORD *Source;
2416 WORD *Dest;
2417 TRACE("Color keyed 5551\n");
2418 for (y = 0; y < height; y++) {
2419 Source = (const WORD *)(src + y * pitch);
2420 Dest = (WORD *) (dst + y * outpitch);
2421 for (x = 0; x < width; x++ ) {
2422 WORD color = *Source++;
2423 *Dest = color;
2424 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2425 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2426 *Dest |= (1 << 15);
2428 else {
2429 *Dest &= ~(1 << 15);
2431 Dest++;
2435 break;
2437 case CONVERT_CK_RGB24:
2439 /* Converting R8G8B8 format to R8G8B8A8 with color-keying. */
2440 unsigned int x, y;
2441 for (y = 0; y < height; y++)
2443 source = src + pitch * y;
2444 dest = dst + outpitch * y;
2445 for (x = 0; x < width; x++) {
2446 DWORD color = ((DWORD)source[0] << 16) + ((DWORD)source[1] << 8) + (DWORD)source[2] ;
2447 DWORD dstcolor = color << 8;
2448 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2449 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2450 dstcolor |= 0xff;
2452 *(DWORD*)dest = dstcolor;
2453 source += 3;
2454 dest += 4;
2458 break;
2460 case CONVERT_RGB32_888:
2462 /* Converting X8R8G8B8 format to R8G8B8A8 with color-keying. */
2463 unsigned int x, y;
2464 for (y = 0; y < height; y++)
2466 source = src + pitch * y;
2467 dest = dst + outpitch * y;
2468 for (x = 0; x < width; x++) {
2469 DWORD color = 0xffffff & *(const DWORD*)source;
2470 DWORD dstcolor = color << 8;
2471 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
2472 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
2473 dstcolor |= 0xff;
2475 *(DWORD*)dest = dstcolor;
2476 source += 4;
2477 dest += 4;
2481 break;
2483 default:
2484 ERR("Unsupported conversion type %#x.\n", convert);
2486 return WINED3D_OK;
2489 BOOL palette9_changed(IWineD3DSurfaceImpl *This)
2491 IWineD3DDeviceImpl *device = This->resource.device;
2493 if (This->palette || (This->resource.format_desc->format != WINED3DFMT_P8_UINT
2494 && This->resource.format_desc->format != WINED3DFMT_P8_UINT_A8_UNORM))
2496 /* If a ddraw-style palette is attached assume no d3d9 palette change.
2497 * Also the palette isn't interesting if the surface format isn't P8 or A8P8
2499 return FALSE;
2502 if (This->palette9)
2504 if (!memcmp(This->palette9, device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256))
2506 return FALSE;
2508 } else {
2509 This->palette9 = HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY) * 256);
2511 memcpy(This->palette9, device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256);
2512 return TRUE;
2515 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadTexture(IWineD3DSurface *iface, BOOL srgb_mode) {
2516 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2517 DWORD flag = srgb_mode ? SFLAG_INSRGBTEX : SFLAG_INTEXTURE;
2519 if (!(This->Flags & flag)) {
2520 TRACE("Reloading because surface is dirty\n");
2521 } else if(/* Reload: gl texture has ck, now no ckey is set OR */
2522 ((This->Flags & SFLAG_GLCKEY) && (!(This->CKeyFlags & WINEDDSD_CKSRCBLT))) ||
2523 /* Reload: vice versa OR */
2524 ((!(This->Flags & SFLAG_GLCKEY)) && (This->CKeyFlags & WINEDDSD_CKSRCBLT)) ||
2525 /* Also reload: Color key is active AND the color key has changed */
2526 ((This->CKeyFlags & WINEDDSD_CKSRCBLT) && (
2527 (This->glCKey.dwColorSpaceLowValue != This->SrcBltCKey.dwColorSpaceLowValue) ||
2528 (This->glCKey.dwColorSpaceHighValue != This->SrcBltCKey.dwColorSpaceHighValue)))) {
2529 TRACE("Reloading because of color keying\n");
2530 /* To perform the color key conversion we need a sysmem copy of
2531 * the surface. Make sure we have it
2534 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
2535 /* Make sure the texture is reloaded because of the color key change, this kills performance though :( */
2536 /* TODO: This is not necessarily needed with hw palettized texture support */
2537 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2538 } else {
2539 TRACE("surface is already in texture\n");
2540 return WINED3D_OK;
2543 /* Resources are placed in system RAM and do not need to be recreated when a device is lost.
2544 * These resources are not bound by device size or format restrictions. Because of this,
2545 * these resources cannot be accessed by the Direct3D device nor set as textures or render targets.
2546 * However, these resources can always be created, locked, and copied.
2548 if (This->resource.pool == WINED3DPOOL_SCRATCH )
2550 FIXME("(%p) Operation not supported for scratch textures\n",This);
2551 return WINED3DERR_INVALIDCALL;
2554 IWineD3DSurface_LoadLocation(iface, flag, NULL /* no partial locking for textures yet */);
2556 #if 0
2558 static unsigned int gen = 0;
2559 char buffer[4096];
2560 ++gen;
2561 if ((gen % 10) == 0) {
2562 snprintf(buffer, sizeof(buffer), "/tmp/surface%p_type%u_level%u_%u.ppm",
2563 This, This->texture_target, This->texture_level, gen);
2564 IWineD3DSurfaceImpl_SaveSnapshot(iface, buffer);
2567 * debugging crash code
2568 if (gen == 250) {
2569 void** test = NULL;
2570 *test = 0;
2574 #endif
2576 if (!(This->Flags & SFLAG_DONOTFREE)) {
2577 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
2578 This->resource.allocatedMemory = NULL;
2579 This->resource.heapMemory = NULL;
2580 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, FALSE);
2583 return WINED3D_OK;
2586 /* Context activation is done by the caller. */
2587 static void WINAPI IWineD3DSurfaceImpl_BindTexture(IWineD3DSurface *iface, BOOL srgb) {
2588 /* TODO: check for locks */
2589 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2590 IWineD3DBaseTexture *baseTexture = NULL;
2592 TRACE("(%p)Checking to see if the container is a base texture\n", This);
2593 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
2594 TRACE("Passing to container\n");
2595 IWineD3DBaseTexture_BindTexture(baseTexture, srgb);
2596 IWineD3DBaseTexture_Release(baseTexture);
2598 else
2600 GLuint *name;
2602 TRACE("(%p) : Binding surface\n", This);
2604 name = srgb ? &This->texture_name_srgb : &This->texture_name;
2606 ENTER_GL();
2608 if (!This->texture_level)
2610 if (!*name) {
2611 glGenTextures(1, name);
2612 checkGLcall("glGenTextures");
2613 TRACE("Surface %p given name %d\n", This, *name);
2615 glBindTexture(This->texture_target, *name);
2616 checkGLcall("glBindTexture");
2617 glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2618 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)");
2619 glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2620 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)");
2621 glTexParameteri(This->texture_target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
2622 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE)");
2623 glTexParameteri(This->texture_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2624 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_MIN_FILTER, GL_NEAREST)");
2625 glTexParameteri(This->texture_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2626 checkGLcall("glTexParameteri(dimension, GL_TEXTURE_MAG_FILTER, GL_NEAREST)");
2628 /* This is where we should be reducing the amount of GLMemoryUsed */
2629 } else if (*name) {
2630 /* Mipmap surfaces should have a base texture container */
2631 ERR("Mipmap surface has a glTexture bound to it!\n");
2634 glBindTexture(This->texture_target, *name);
2635 checkGLcall("glBindTexture");
2637 LEAVE_GL();
2641 #include <errno.h>
2642 #include <stdio.h>
2643 static HRESULT WINAPI IWineD3DSurfaceImpl_SaveSnapshot(IWineD3DSurface *iface, const char* filename)
2645 FILE* f = NULL;
2646 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2647 char *allocatedMemory;
2648 const char *textureRow;
2649 IWineD3DSwapChain *swapChain = NULL;
2650 int width, height, i, y;
2651 GLuint tmpTexture = 0;
2652 DWORD color;
2653 /*FIXME:
2654 Textures may not be stored in ->allocatedgMemory and a GlTexture
2655 so we should lock the surface before saving a snapshot, or at least check that
2657 /* TODO: Compressed texture images can be obtained from the GL in uncompressed form
2658 by calling GetTexImage and in compressed form by calling
2659 GetCompressedTexImageARB. Queried compressed images can be saved and
2660 later reused by calling CompressedTexImage[123]DARB. Pre-compressed
2661 texture images do not need to be processed by the GL and should
2662 significantly improve texture loading performance relative to uncompressed
2663 images. */
2665 /* Setup the width and height to be the internal texture width and height. */
2666 width = This->pow2Width;
2667 height = This->pow2Height;
2668 /* check to see if we're a 'virtual' texture, e.g. we're not a pbuffer of texture, we're a back buffer*/
2669 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapChain);
2671 if (This->Flags & SFLAG_INDRAWABLE && !(This->Flags & SFLAG_INTEXTURE)) {
2672 /* if were not a real texture then read the back buffer into a real texture */
2673 /* we don't want to interfere with the back buffer so read the data into a temporary
2674 * texture and then save the data out of the temporary texture
2676 GLint prevRead;
2677 ENTER_GL();
2678 TRACE("(%p) Reading render target into texture\n", This);
2680 glGenTextures(1, &tmpTexture);
2681 glBindTexture(GL_TEXTURE_2D, tmpTexture);
2683 glTexImage2D(GL_TEXTURE_2D,
2685 GL_RGBA,
2686 width,
2687 height,
2688 0/*border*/,
2689 GL_RGBA,
2690 GL_UNSIGNED_INT_8_8_8_8_REV,
2691 NULL);
2693 glGetIntegerv(GL_READ_BUFFER, &prevRead);
2694 checkGLcall("glGetIntegerv");
2695 glReadBuffer(swapChain ? GL_BACK : This->resource.device->offscreenBuffer);
2696 checkGLcall("glReadBuffer");
2697 glCopyTexImage2D(GL_TEXTURE_2D,
2699 GL_RGBA,
2702 width,
2703 height,
2706 checkGLcall("glCopyTexImage2D");
2707 glReadBuffer(prevRead);
2708 LEAVE_GL();
2710 } else { /* bind the real texture, and make sure it up to date */
2711 surface_internal_preload(This, SRGB_RGB);
2712 surface_bind_and_dirtify(This, FALSE);
2714 allocatedMemory = HeapAlloc(GetProcessHeap(), 0, width * height * 4);
2715 ENTER_GL();
2716 FIXME("Saving texture level %d width %d height %d\n", This->texture_level, width, height);
2717 glGetTexImage(GL_TEXTURE_2D, This->texture_level, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, allocatedMemory);
2718 checkGLcall("glGetTexImage");
2719 if (tmpTexture) {
2720 glBindTexture(GL_TEXTURE_2D, 0);
2721 glDeleteTextures(1, &tmpTexture);
2723 LEAVE_GL();
2725 f = fopen(filename, "w+");
2726 if (NULL == f) {
2727 ERR("opening of %s failed with: %s\n", filename, strerror(errno));
2728 return WINED3DERR_INVALIDCALL;
2730 /* Save the data out to a TGA file because 1: it's an easy raw format, 2: it supports an alpha channel */
2731 TRACE("(%p) opened %s with format %s\n", This, filename, debug_d3dformat(This->resource.format_desc->format));
2732 /* TGA header */
2733 fputc(0,f);
2734 fputc(0,f);
2735 fputc(2,f);
2736 fputc(0,f);
2737 fputc(0,f);
2738 fputc(0,f);
2739 fputc(0,f);
2740 fputc(0,f);
2741 fputc(0,f);
2742 fputc(0,f);
2743 fputc(0,f);
2744 fputc(0,f);
2745 /* short width*/
2746 fwrite(&width,2,1,f);
2747 /* short height */
2748 fwrite(&height,2,1,f);
2749 /* format rgba */
2750 fputc(0x20,f);
2751 fputc(0x28,f);
2752 /* raw data */
2753 /* if the data is upside down if we've fetched it from a back buffer, so it needs flipping again to make it the correct way up */
2754 if(swapChain)
2755 textureRow = allocatedMemory + (width * (height - 1) *4);
2756 else
2757 textureRow = allocatedMemory;
2758 for (y = 0 ; y < height; y++) {
2759 for (i = 0; i < width; i++) {
2760 color = *((const DWORD*)textureRow);
2761 fputc((color >> 16) & 0xFF, f); /* B */
2762 fputc((color >> 8) & 0xFF, f); /* G */
2763 fputc((color >> 0) & 0xFF, f); /* R */
2764 fputc((color >> 24) & 0xFF, f); /* A */
2765 textureRow += 4;
2767 /* take two rows of the pointer to the texture memory */
2768 if(swapChain)
2769 (textureRow-= width << 3);
2772 TRACE("Closing file\n");
2773 fclose(f);
2775 if(swapChain) {
2776 IWineD3DSwapChain_Release(swapChain);
2778 HeapFree(GetProcessHeap(), 0, allocatedMemory);
2779 return WINED3D_OK;
2782 static HRESULT WINAPI IWineD3DSurfaceImpl_SetFormat(IWineD3DSurface *iface, WINED3DFORMAT format) {
2783 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2784 HRESULT hr;
2786 TRACE("(%p) : Calling base function first\n", This);
2787 hr = IWineD3DBaseSurfaceImpl_SetFormat(iface, format);
2788 if(SUCCEEDED(hr)) {
2789 This->Flags &= ~(SFLAG_ALLOCATED | SFLAG_SRGBALLOCATED);
2790 TRACE("(%p) : glFormat %d, glFormatInternal %d, glType %d\n", This, This->resource.format_desc->glFormat,
2791 This->resource.format_desc->glInternal, This->resource.format_desc->glType);
2793 return hr;
2796 static HRESULT WINAPI IWineD3DSurfaceImpl_SetMem(IWineD3DSurface *iface, void *Mem) {
2797 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
2799 if(This->Flags & (SFLAG_LOCKED | SFLAG_DCINUSE)) {
2800 WARN("Surface is locked or the HDC is in use\n");
2801 return WINED3DERR_INVALIDCALL;
2804 if(Mem && Mem != This->resource.allocatedMemory) {
2805 void *release = NULL;
2807 /* Do I have to copy the old surface content? */
2808 if(This->Flags & SFLAG_DIBSECTION) {
2809 /* Release the DC. No need to hold the critical section for the update
2810 * Thread because this thread runs only on front buffers, but this method
2811 * fails for render targets in the check above.
2813 SelectObject(This->hDC, This->dib.holdbitmap);
2814 DeleteDC(This->hDC);
2815 /* Release the DIB section */
2816 DeleteObject(This->dib.DIBsection);
2817 This->dib.bitmap_data = NULL;
2818 This->resource.allocatedMemory = NULL;
2819 This->hDC = NULL;
2820 This->Flags &= ~SFLAG_DIBSECTION;
2821 } else if(!(This->Flags & SFLAG_USERPTR)) {
2822 release = This->resource.heapMemory;
2823 This->resource.heapMemory = NULL;
2825 This->resource.allocatedMemory = Mem;
2826 This->Flags |= SFLAG_USERPTR | SFLAG_INSYSMEM;
2828 /* Now the surface memory is most up do date. Invalidate drawable and texture */
2829 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2831 /* For client textures opengl has to be notified */
2832 if (This->Flags & SFLAG_CLIENT)
2833 surface_release_client_storage(This);
2835 /* Now free the old memory if any */
2836 HeapFree(GetProcessHeap(), 0, release);
2837 } else if(This->Flags & SFLAG_USERPTR) {
2838 /* LockRect and GetDC will re-create the dib section and allocated memory */
2839 This->resource.allocatedMemory = NULL;
2840 /* HeapMemory should be NULL already */
2841 if(This->resource.heapMemory != NULL) ERR("User pointer surface has heap memory allocated\n");
2842 This->Flags &= ~SFLAG_USERPTR;
2844 if (This->Flags & SFLAG_CLIENT)
2845 surface_release_client_storage(This);
2847 return WINED3D_OK;
2850 void flip_surface(IWineD3DSurfaceImpl *front, IWineD3DSurfaceImpl *back) {
2852 /* Flip the surface contents */
2853 /* Flip the DC */
2855 HDC tmp;
2856 tmp = front->hDC;
2857 front->hDC = back->hDC;
2858 back->hDC = tmp;
2861 /* Flip the DIBsection */
2863 HBITMAP tmp;
2864 BOOL hasDib = front->Flags & SFLAG_DIBSECTION;
2865 tmp = front->dib.DIBsection;
2866 front->dib.DIBsection = back->dib.DIBsection;
2867 back->dib.DIBsection = tmp;
2869 if(back->Flags & SFLAG_DIBSECTION) front->Flags |= SFLAG_DIBSECTION;
2870 else front->Flags &= ~SFLAG_DIBSECTION;
2871 if(hasDib) back->Flags |= SFLAG_DIBSECTION;
2872 else back->Flags &= ~SFLAG_DIBSECTION;
2875 /* Flip the surface data */
2877 void* tmp;
2879 tmp = front->dib.bitmap_data;
2880 front->dib.bitmap_data = back->dib.bitmap_data;
2881 back->dib.bitmap_data = tmp;
2883 tmp = front->resource.allocatedMemory;
2884 front->resource.allocatedMemory = back->resource.allocatedMemory;
2885 back->resource.allocatedMemory = tmp;
2887 tmp = front->resource.heapMemory;
2888 front->resource.heapMemory = back->resource.heapMemory;
2889 back->resource.heapMemory = tmp;
2892 /* Flip the PBO */
2894 GLuint tmp_pbo = front->pbo;
2895 front->pbo = back->pbo;
2896 back->pbo = tmp_pbo;
2899 /* client_memory should not be different, but just in case */
2901 BOOL tmp;
2902 tmp = front->dib.client_memory;
2903 front->dib.client_memory = back->dib.client_memory;
2904 back->dib.client_memory = tmp;
2907 /* Flip the opengl texture */
2909 GLuint tmp;
2911 tmp = back->texture_name;
2912 back->texture_name = front->texture_name;
2913 front->texture_name = tmp;
2915 tmp = back->texture_name_srgb;
2916 back->texture_name_srgb = front->texture_name_srgb;
2917 front->texture_name_srgb = tmp;
2921 DWORD tmp_flags = back->Flags;
2922 back->Flags = front->Flags;
2923 front->Flags = tmp_flags;
2927 static HRESULT WINAPI IWineD3DSurfaceImpl_Flip(IWineD3DSurface *iface, IWineD3DSurface *override, DWORD Flags) {
2928 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2929 IWineD3DSwapChainImpl *swapchain = NULL;
2930 HRESULT hr;
2931 TRACE("(%p)->(%p,%x)\n", This, override, Flags);
2933 /* Flipping is only supported on RenderTargets and overlays*/
2934 if( !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_OVERLAY)) ) {
2935 WARN("Tried to flip a non-render target, non-overlay surface\n");
2936 return WINEDDERR_NOTFLIPPABLE;
2939 if(This->resource.usage & WINED3DUSAGE_OVERLAY) {
2940 flip_surface(This, (IWineD3DSurfaceImpl *) override);
2942 /* Update the overlay if it is visible */
2943 if(This->overlay_dest) {
2944 return IWineD3DSurface_DrawOverlay((IWineD3DSurface *) This);
2945 } else {
2946 return WINED3D_OK;
2950 if(override) {
2951 /* DDraw sets this for the X11 surfaces, so don't confuse the user
2952 * FIXME("(%p) Target override is not supported by now\n", This);
2953 * Additionally, it isn't really possible to support triple-buffering
2954 * properly on opengl at all
2958 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **) &swapchain);
2959 if(!swapchain) {
2960 ERR("Flipped surface is not on a swapchain\n");
2961 return WINEDDERR_NOTFLIPPABLE;
2964 /* Just overwrite the swapchain presentation interval. This is ok because only ddraw apps can call Flip,
2965 * and only d3d8 and d3d9 apps specify the presentation interval
2967 if((Flags & (WINEDDFLIP_NOVSYNC | WINEDDFLIP_INTERVAL2 | WINEDDFLIP_INTERVAL3 | WINEDDFLIP_INTERVAL4)) == 0) {
2968 /* Most common case first to avoid wasting time on all the other cases */
2969 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_ONE;
2970 } else if(Flags & WINEDDFLIP_NOVSYNC) {
2971 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
2972 } else if(Flags & WINEDDFLIP_INTERVAL2) {
2973 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_TWO;
2974 } else if(Flags & WINEDDFLIP_INTERVAL3) {
2975 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_THREE;
2976 } else {
2977 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_FOUR;
2980 /* Flipping a OpenGL surface -> Use WineD3DDevice::Present */
2981 hr = IWineD3DSwapChain_Present((IWineD3DSwapChain *)swapchain,
2982 NULL, NULL, swapchain->win_handle, NULL, 0);
2983 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
2984 return hr;
2987 /* Does a direct frame buffer -> texture copy. Stretching is done
2988 * with single pixel copy calls
2990 static void fb_copy_to_texture_direct(IWineD3DSurfaceImpl *dst_surface, IWineD3DSurfaceImpl *src_surface,
2991 const RECT *src_rect, const RECT *dst_rect_in, WINED3DTEXTUREFILTERTYPE Filter)
2993 IWineD3DDeviceImpl *device = dst_surface->resource.device;
2994 float xrel, yrel;
2995 UINT row;
2996 struct wined3d_context *context;
2997 BOOL upsidedown = FALSE;
2998 RECT dst_rect = *dst_rect_in;
3000 /* Make sure that the top pixel is always above the bottom pixel, and keep a separate upside down flag
3001 * glCopyTexSubImage is a bit picky about the parameters we pass to it
3003 if(dst_rect.top > dst_rect.bottom) {
3004 UINT tmp = dst_rect.bottom;
3005 dst_rect.bottom = dst_rect.top;
3006 dst_rect.top = tmp;
3007 upsidedown = TRUE;
3010 context = context_acquire(device, src_surface);
3011 context_apply_blit_state(context, device);
3012 surface_internal_preload(dst_surface, SRGB_RGB);
3013 ENTER_GL();
3015 /* Bind the target texture */
3016 glBindTexture(dst_surface->texture_target, dst_surface->texture_name);
3017 checkGLcall("glBindTexture");
3018 if (surface_is_offscreen(src_surface))
3020 TRACE("Reading from an offscreen target\n");
3021 upsidedown = !upsidedown;
3022 glReadBuffer(device->offscreenBuffer);
3024 else
3026 glReadBuffer(surface_get_gl_buffer(src_surface));
3028 checkGLcall("glReadBuffer");
3030 xrel = (float) (src_rect->right - src_rect->left) / (float) (dst_rect.right - dst_rect.left);
3031 yrel = (float) (src_rect->bottom - src_rect->top) / (float) (dst_rect.bottom - dst_rect.top);
3033 if ((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
3035 FIXME("Doing a pixel by pixel copy from the framebuffer to a texture, expect major performance issues\n");
3037 if(Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) {
3038 ERR("Texture filtering not supported in direct blit\n");
3041 else if ((Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT)
3042 && ((yrel - 1.0f < -eps) || (yrel - 1.0f > eps)))
3044 ERR("Texture filtering not supported in direct blit\n");
3047 if (upsidedown
3048 && !((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
3049 && !((yrel - 1.0f < -eps) || (yrel - 1.0f > eps)))
3051 /* Upside down copy without stretching is nice, one glCopyTexSubImage call will do */
3053 glCopyTexSubImage2D(dst_surface->texture_target, dst_surface->texture_level,
3054 dst_rect.left /*xoffset */, dst_rect.top /* y offset */,
3055 src_rect->left, src_surface->currentDesc.Height - src_rect->bottom,
3056 dst_rect.right - dst_rect.left, dst_rect.bottom - dst_rect.top);
3057 } else {
3058 UINT yoffset = src_surface->currentDesc.Height - src_rect->top + dst_rect.top - 1;
3059 /* I have to process this row by row to swap the image,
3060 * otherwise it would be upside down, so stretching in y direction
3061 * doesn't cost extra time
3063 * However, stretching in x direction can be avoided if not necessary
3065 for(row = dst_rect.top; row < dst_rect.bottom; row++) {
3066 if ((xrel - 1.0f < -eps) || (xrel - 1.0f > eps))
3068 /* Well, that stuff works, but it's very slow.
3069 * find a better way instead
3071 UINT col;
3073 for (col = dst_rect.left; col < dst_rect.right; ++col)
3075 glCopyTexSubImage2D(dst_surface->texture_target, dst_surface->texture_level,
3076 dst_rect.left + col /* x offset */, row /* y offset */,
3077 src_rect->left + col * xrel, yoffset - (int) (row * yrel), 1, 1);
3080 else
3082 glCopyTexSubImage2D(dst_surface->texture_target, dst_surface->texture_level,
3083 dst_rect.left /* x offset */, row /* y offset */,
3084 src_rect->left, yoffset - (int) (row * yrel), dst_rect.right - dst_rect.left, 1);
3088 checkGLcall("glCopyTexSubImage2D");
3090 LEAVE_GL();
3091 context_release(context);
3093 /* The texture is now most up to date - If the surface is a render target and has a drawable, this
3094 * path is never entered
3096 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)dst_surface, SFLAG_INTEXTURE, TRUE);
3099 /* Uses the hardware to stretch and flip the image */
3100 static void fb_copy_to_texture_hwstretch(IWineD3DSurfaceImpl *dst_surface, IWineD3DSurfaceImpl *src_surface,
3101 const RECT *src_rect, const RECT *dst_rect_in, WINED3DTEXTUREFILTERTYPE Filter)
3103 IWineD3DDeviceImpl *device = dst_surface->resource.device;
3104 GLuint src, backup = 0;
3105 IWineD3DSwapChainImpl *src_swapchain = NULL;
3106 float left, right, top, bottom; /* Texture coordinates */
3107 UINT fbwidth = src_surface->currentDesc.Width;
3108 UINT fbheight = src_surface->currentDesc.Height;
3109 struct wined3d_context *context;
3110 GLenum drawBuffer = GL_BACK;
3111 GLenum texture_target;
3112 BOOL noBackBufferBackup;
3113 BOOL src_offscreen;
3114 BOOL upsidedown = FALSE;
3115 RECT dst_rect = *dst_rect_in;
3117 TRACE("Using hwstretch blit\n");
3118 /* Activate the Proper context for reading from the source surface, set it up for blitting */
3119 context = context_acquire(device, src_surface);
3120 context_apply_blit_state(context, device);
3121 surface_internal_preload(dst_surface, SRGB_RGB);
3123 src_offscreen = surface_is_offscreen(src_surface);
3124 noBackBufferBackup = src_offscreen && wined3d_settings.offscreen_rendering_mode == ORM_FBO;
3125 if (!noBackBufferBackup && !src_surface->texture_name)
3127 /* Get it a description */
3128 surface_internal_preload(src_surface, SRGB_RGB);
3130 ENTER_GL();
3132 /* Try to use an aux buffer for drawing the rectangle. This way it doesn't need restoring.
3133 * This way we don't have to wait for the 2nd readback to finish to leave this function.
3135 if (context->aux_buffers >= 2)
3137 /* Got more than one aux buffer? Use the 2nd aux buffer */
3138 drawBuffer = GL_AUX1;
3140 else if ((!src_offscreen || device->offscreenBuffer == GL_BACK) && context->aux_buffers >= 1)
3142 /* Only one aux buffer, but it isn't used (Onscreen rendering, or non-aux orm)? Use it! */
3143 drawBuffer = GL_AUX0;
3146 if(noBackBufferBackup) {
3147 glGenTextures(1, &backup);
3148 checkGLcall("glGenTextures");
3149 glBindTexture(GL_TEXTURE_2D, backup);
3150 checkGLcall("glBindTexture(GL_TEXTURE_2D, backup)");
3151 texture_target = GL_TEXTURE_2D;
3152 } else {
3153 /* Backup the back buffer and copy the source buffer into a texture to draw an upside down stretched quad. If
3154 * we are reading from the back buffer, the backup can be used as source texture
3156 texture_target = src_surface->texture_target;
3157 glBindTexture(texture_target, src_surface->texture_name);
3158 checkGLcall("glBindTexture(texture_target, src_surface->texture_name)");
3159 glEnable(texture_target);
3160 checkGLcall("glEnable(texture_target)");
3162 /* For now invalidate the texture copy of the back buffer. Drawable and sysmem copy are untouched */
3163 src_surface->Flags &= ~SFLAG_INTEXTURE;
3166 /* Make sure that the top pixel is always above the bottom pixel, and keep a separate upside down flag
3167 * glCopyTexSubImage is a bit picky about the parameters we pass to it
3169 if(dst_rect.top > dst_rect.bottom) {
3170 UINT tmp = dst_rect.bottom;
3171 dst_rect.bottom = dst_rect.top;
3172 dst_rect.top = tmp;
3173 upsidedown = TRUE;
3176 if (src_offscreen)
3178 TRACE("Reading from an offscreen target\n");
3179 upsidedown = !upsidedown;
3180 glReadBuffer(device->offscreenBuffer);
3182 else
3184 glReadBuffer(surface_get_gl_buffer(src_surface));
3187 /* TODO: Only back up the part that will be overwritten */
3188 glCopyTexSubImage2D(texture_target, 0,
3189 0, 0 /* read offsets */,
3190 0, 0,
3191 fbwidth,
3192 fbheight);
3194 checkGLcall("glCopyTexSubImage2D");
3196 /* No issue with overriding these - the sampler is dirty due to blit usage */
3197 glTexParameteri(texture_target, GL_TEXTURE_MAG_FILTER,
3198 wined3d_gl_mag_filter(magLookup, Filter));
3199 checkGLcall("glTexParameteri");
3200 glTexParameteri(texture_target, GL_TEXTURE_MIN_FILTER,
3201 wined3d_gl_min_mip_filter(minMipLookup, Filter, WINED3DTEXF_NONE));
3202 checkGLcall("glTexParameteri");
3204 IWineD3DSurface_GetContainer((IWineD3DSurface *)src_surface, &IID_IWineD3DSwapChain, (void **)&src_swapchain);
3205 if (src_swapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *)src_swapchain);
3206 if (!src_swapchain || src_surface == src_swapchain->back_buffers[0])
3208 src = backup ? backup : src_surface->texture_name;
3210 else
3212 glReadBuffer(GL_FRONT);
3213 checkGLcall("glReadBuffer(GL_FRONT)");
3215 glGenTextures(1, &src);
3216 checkGLcall("glGenTextures(1, &src)");
3217 glBindTexture(GL_TEXTURE_2D, src);
3218 checkGLcall("glBindTexture(GL_TEXTURE_2D, src)");
3220 /* TODO: Only copy the part that will be read. Use src_rect->left, src_rect->bottom as origin, but with the width watch
3221 * out for power of 2 sizes
3223 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, src_surface->pow2Width,
3224 src_surface->pow2Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
3225 checkGLcall("glTexImage2D");
3226 glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
3227 0, 0 /* read offsets */,
3228 0, 0,
3229 fbwidth,
3230 fbheight);
3232 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
3233 checkGLcall("glTexParameteri");
3234 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
3235 checkGLcall("glTexParameteri");
3237 glReadBuffer(GL_BACK);
3238 checkGLcall("glReadBuffer(GL_BACK)");
3240 if(texture_target != GL_TEXTURE_2D) {
3241 glDisable(texture_target);
3242 glEnable(GL_TEXTURE_2D);
3243 texture_target = GL_TEXTURE_2D;
3246 checkGLcall("glEnd and previous");
3248 left = src_rect->left;
3249 right = src_rect->right;
3251 if (upsidedown)
3253 top = src_surface->currentDesc.Height - src_rect->top;
3254 bottom = src_surface->currentDesc.Height - src_rect->bottom;
3256 else
3258 top = src_surface->currentDesc.Height - src_rect->bottom;
3259 bottom = src_surface->currentDesc.Height - src_rect->top;
3262 if (src_surface->Flags & SFLAG_NORMCOORD)
3264 left /= src_surface->pow2Width;
3265 right /= src_surface->pow2Width;
3266 top /= src_surface->pow2Height;
3267 bottom /= src_surface->pow2Height;
3270 /* draw the source texture stretched and upside down. The correct surface is bound already */
3271 glTexParameteri(texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
3272 glTexParameteri(texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP);
3274 context_set_draw_buffer(context, drawBuffer);
3275 glReadBuffer(drawBuffer);
3277 glBegin(GL_QUADS);
3278 /* bottom left */
3279 glTexCoord2f(left, bottom);
3280 glVertex2i(0, fbheight);
3282 /* top left */
3283 glTexCoord2f(left, top);
3284 glVertex2i(0, fbheight - dst_rect.bottom - dst_rect.top);
3286 /* top right */
3287 glTexCoord2f(right, top);
3288 glVertex2i(dst_rect.right - dst_rect.left, fbheight - dst_rect.bottom - dst_rect.top);
3290 /* bottom right */
3291 glTexCoord2f(right, bottom);
3292 glVertex2i(dst_rect.right - dst_rect.left, fbheight);
3293 glEnd();
3294 checkGLcall("glEnd and previous");
3296 if (texture_target != dst_surface->texture_target)
3298 glDisable(texture_target);
3299 glEnable(dst_surface->texture_target);
3300 texture_target = dst_surface->texture_target;
3303 /* Now read the stretched and upside down image into the destination texture */
3304 glBindTexture(texture_target, dst_surface->texture_name);
3305 checkGLcall("glBindTexture");
3306 glCopyTexSubImage2D(texture_target,
3308 dst_rect.left, dst_rect.top, /* xoffset, yoffset */
3309 0, 0, /* We blitted the image to the origin */
3310 dst_rect.right - dst_rect.left, dst_rect.bottom - dst_rect.top);
3311 checkGLcall("glCopyTexSubImage2D");
3313 if(drawBuffer == GL_BACK) {
3314 /* Write the back buffer backup back */
3315 if(backup) {
3316 if(texture_target != GL_TEXTURE_2D) {
3317 glDisable(texture_target);
3318 glEnable(GL_TEXTURE_2D);
3319 texture_target = GL_TEXTURE_2D;
3321 glBindTexture(GL_TEXTURE_2D, backup);
3322 checkGLcall("glBindTexture(GL_TEXTURE_2D, backup)");
3324 else
3326 if (texture_target != src_surface->texture_target)
3328 glDisable(texture_target);
3329 glEnable(src_surface->texture_target);
3330 texture_target = src_surface->texture_target;
3332 glBindTexture(src_surface->texture_target, src_surface->texture_name);
3333 checkGLcall("glBindTexture(src_surface->texture_target, src_surface->texture_name)");
3336 glBegin(GL_QUADS);
3337 /* top left */
3338 glTexCoord2f(0.0f, (float)fbheight / (float)src_surface->pow2Height);
3339 glVertex2i(0, 0);
3341 /* bottom left */
3342 glTexCoord2f(0.0f, 0.0f);
3343 glVertex2i(0, fbheight);
3345 /* bottom right */
3346 glTexCoord2f((float)fbwidth / (float)src_surface->pow2Width, 0.0f);
3347 glVertex2i(fbwidth, src_surface->currentDesc.Height);
3349 /* top right */
3350 glTexCoord2f((float)fbwidth / (float)src_surface->pow2Width,
3351 (float)fbheight / (float)src_surface->pow2Height);
3352 glVertex2i(fbwidth, 0);
3353 glEnd();
3355 glDisable(texture_target);
3356 checkGLcall("glDisable(texture_target)");
3358 /* Cleanup */
3359 if (src != src_surface->texture_name && src != backup)
3361 glDeleteTextures(1, &src);
3362 checkGLcall("glDeleteTextures(1, &src)");
3364 if(backup) {
3365 glDeleteTextures(1, &backup);
3366 checkGLcall("glDeleteTextures(1, &backup)");
3369 LEAVE_GL();
3371 if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
3373 context_release(context);
3375 /* The texture is now most up to date - If the surface is a render target and has a drawable, this
3376 * path is never entered
3378 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)dst_surface, SFLAG_INTEXTURE, TRUE);
3381 /* Until the blit_shader is ready, define some prototypes here. */
3382 static BOOL fbo_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
3383 const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool,
3384 const struct wined3d_format_desc *src_format_desc,
3385 const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool,
3386 const struct wined3d_format_desc *dst_format_desc);
3388 /* Not called from the VTable */
3389 static HRESULT IWineD3DSurfaceImpl_BltOverride(IWineD3DSurfaceImpl *dst_surface, const RECT *DestRect,
3390 IWineD3DSurfaceImpl *src_surface, const RECT *SrcRect, DWORD Flags, const WINEDDBLTFX *DDBltFx,
3391 WINED3DTEXTUREFILTERTYPE Filter)
3393 IWineD3DDeviceImpl *device = dst_surface->resource.device;
3394 IWineD3DSwapChainImpl *srcSwapchain = NULL, *dstSwapchain = NULL;
3395 RECT dst_rect, src_rect;
3397 TRACE("dst_surface %p, dst_rect %s, src_surface %p, src_rect %s, flags %#x, blt_fx %p, filter %s.\n",
3398 dst_surface, wine_dbgstr_rect(DestRect), src_surface, wine_dbgstr_rect(SrcRect),
3399 Flags, DDBltFx, debug_d3dtexturefiltertype(Filter));
3401 /* Get the swapchain. One of the surfaces has to be a primary surface */
3402 if (dst_surface->resource.pool == WINED3DPOOL_SYSTEMMEM)
3404 WARN("Destination is in sysmem, rejecting gl blt\n");
3405 return WINED3DERR_INVALIDCALL;
3407 IWineD3DSurface_GetContainer((IWineD3DSurface *)dst_surface, &IID_IWineD3DSwapChain, (void **)&dstSwapchain);
3408 if (dstSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *)dstSwapchain);
3409 if (src_surface)
3411 if (src_surface->resource.pool == WINED3DPOOL_SYSTEMMEM)
3413 WARN("Src is in sysmem, rejecting gl blt\n");
3414 return WINED3DERR_INVALIDCALL;
3416 IWineD3DSurface_GetContainer((IWineD3DSurface *)src_surface, &IID_IWineD3DSwapChain, (void **)&srcSwapchain);
3417 if (srcSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *)srcSwapchain);
3420 /* Early sort out of cases where no render target is used */
3421 if (!dstSwapchain && !srcSwapchain
3422 && src_surface != device->render_targets[0]
3423 && dst_surface != device->render_targets[0])
3425 TRACE("No surface is render target, not using hardware blit.\n");
3426 return WINED3DERR_INVALIDCALL;
3429 /* No destination color keying supported */
3430 if(Flags & (WINEDDBLT_KEYDEST | WINEDDBLT_KEYDESTOVERRIDE)) {
3431 /* Can we support that with glBlendFunc if blitting to the frame buffer? */
3432 TRACE("Destination color key not supported in accelerated Blit, falling back to software\n");
3433 return WINED3DERR_INVALIDCALL;
3436 surface_get_rect(dst_surface, DestRect, &dst_rect);
3437 if (src_surface) surface_get_rect(src_surface, SrcRect, &src_rect);
3439 /* The only case where both surfaces on a swapchain are supported is a back buffer -> front buffer blit on the same swapchain */
3440 if (dstSwapchain && dstSwapchain == srcSwapchain && dstSwapchain->back_buffers
3441 && dst_surface == dstSwapchain->front_buffer
3442 && src_surface == dstSwapchain->back_buffers[0])
3444 /* Half-life does a Blt from the back buffer to the front buffer,
3445 * Full surface size, no flags... Use present instead
3447 * This path will only be entered for d3d7 and ddraw apps, because d3d8/9 offer no way to blit TO the front buffer
3450 /* Check rects - IWineD3DDevice_Present doesn't handle them */
3451 while(1)
3453 TRACE("Looking if a Present can be done...\n");
3454 /* Source Rectangle must be full surface */
3455 if (src_rect.left || src_rect.top
3456 || src_rect.right != src_surface->currentDesc.Width
3457 || src_rect.bottom != src_surface->currentDesc.Height)
3459 TRACE("No, Source rectangle doesn't match\n");
3460 break;
3463 /* No stretching may occur */
3464 if(src_rect.right != dst_rect.right - dst_rect.left ||
3465 src_rect.bottom != dst_rect.bottom - dst_rect.top) {
3466 TRACE("No, stretching is done\n");
3467 break;
3470 /* Destination must be full surface or match the clipping rectangle */
3471 if (dst_surface->clipper && ((IWineD3DClipperImpl *)dst_surface->clipper)->hWnd)
3473 RECT cliprect;
3474 POINT pos[2];
3475 GetClientRect(((IWineD3DClipperImpl *)dst_surface->clipper)->hWnd, &cliprect);
3476 pos[0].x = dst_rect.left;
3477 pos[0].y = dst_rect.top;
3478 pos[1].x = dst_rect.right;
3479 pos[1].y = dst_rect.bottom;
3480 MapWindowPoints(GetDesktopWindow(), ((IWineD3DClipperImpl *)dst_surface->clipper)->hWnd, pos, 2);
3482 if(pos[0].x != cliprect.left || pos[0].y != cliprect.top ||
3483 pos[1].x != cliprect.right || pos[1].y != cliprect.bottom)
3485 TRACE("No, dest rectangle doesn't match(clipper)\n");
3486 TRACE("Clip rect at %s\n", wine_dbgstr_rect(&cliprect));
3487 TRACE("Blt dest: %s\n", wine_dbgstr_rect(&dst_rect));
3488 break;
3491 else if (dst_rect.left || dst_rect.top
3492 || dst_rect.right != dst_surface->currentDesc.Width
3493 || dst_rect.bottom != dst_surface->currentDesc.Height)
3495 TRACE("No, dest rectangle doesn't match(surface size)\n");
3496 break;
3499 TRACE("Yes\n");
3501 /* These flags are unimportant for the flag check, remove them */
3502 if((Flags & ~(WINEDDBLT_DONOTWAIT | WINEDDBLT_WAIT)) == 0) {
3503 WINED3DSWAPEFFECT orig_swap = dstSwapchain->presentParms.SwapEffect;
3505 /* The idea behind this is that a glReadPixels and a glDrawPixels call
3506 * take very long, while a flip is fast.
3507 * This applies to Half-Life, which does such Blts every time it finished
3508 * a frame, and to Prince of Persia 3D, which uses this to draw at least the main
3509 * menu. This is also used by all apps when they do windowed rendering
3511 * The problem is that flipping is not really the same as copying. After a
3512 * Blt the front buffer is a copy of the back buffer, and the back buffer is
3513 * untouched. Therefore it's necessary to override the swap effect
3514 * and to set it back after the flip.
3516 * Windowed Direct3D < 7 apps do the same. The D3D7 sdk demos are nice
3517 * testcases.
3520 dstSwapchain->presentParms.SwapEffect = WINED3DSWAPEFFECT_COPY;
3521 dstSwapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
3523 TRACE("Full screen back buffer -> front buffer blt, performing a flip instead\n");
3524 IWineD3DSwapChain_Present((IWineD3DSwapChain *)dstSwapchain,
3525 NULL, NULL, dstSwapchain->win_handle, NULL, 0);
3527 dstSwapchain->presentParms.SwapEffect = orig_swap;
3529 return WINED3D_OK;
3531 break;
3534 TRACE("Unsupported blit between buffers on the same swapchain\n");
3535 return WINED3DERR_INVALIDCALL;
3536 } else if(dstSwapchain && dstSwapchain == srcSwapchain) {
3537 FIXME("Implement hardware blit between two surfaces on the same swapchain\n");
3538 return WINED3DERR_INVALIDCALL;
3539 } else if(dstSwapchain && srcSwapchain) {
3540 FIXME("Implement hardware blit between two different swapchains\n");
3541 return WINED3DERR_INVALIDCALL;
3543 else if (dstSwapchain)
3545 /* Handled with regular texture -> swapchain blit */
3546 if (src_surface == device->render_targets[0])
3547 TRACE("Blit from active render target to a swapchain\n");
3549 else if (srcSwapchain && dst_surface == device->render_targets[0])
3551 FIXME("Implement blit from a swapchain to the active render target\n");
3552 return WINED3DERR_INVALIDCALL;
3555 if ((srcSwapchain || src_surface == device->render_targets[0]) && !dstSwapchain)
3557 /* Blit from render target to texture */
3558 BOOL stretchx;
3560 /* P8 read back is not implemented */
3561 if (src_surface->resource.format_desc->format == WINED3DFMT_P8_UINT
3562 || dst_surface->resource.format_desc->format == WINED3DFMT_P8_UINT)
3564 TRACE("P8 read back not supported by frame buffer to texture blit\n");
3565 return WINED3DERR_INVALIDCALL;
3568 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3569 TRACE("Color keying not supported by frame buffer to texture blit\n");
3570 return WINED3DERR_INVALIDCALL;
3571 /* Destination color key is checked above */
3574 if(dst_rect.right - dst_rect.left != src_rect.right - src_rect.left) {
3575 stretchx = TRUE;
3576 } else {
3577 stretchx = FALSE;
3580 /* Blt is a pretty powerful call, while glCopyTexSubImage2D is not. glCopyTexSubImage cannot
3581 * flip the image nor scale it.
3583 * -> If the app asks for a unscaled, upside down copy, just perform one glCopyTexSubImage2D call
3584 * -> If the app wants a image width an unscaled width, copy it line per line
3585 * -> If the app wants a image that is scaled on the x axis, and the destination rectangle is smaller
3586 * than the frame buffer, draw an upside down scaled image onto the fb, read it back and restore the
3587 * back buffer. This is slower than reading line per line, thus not used for flipping
3588 * -> If the app wants a scaled image with a dest rect that is bigger than the fb, it has to be copied
3589 * pixel by pixel
3591 * If EXT_framebuffer_blit is supported that can be used instead. Note that EXT_framebuffer_blit implies
3592 * FBO support, so it doesn't really make sense to try and make it work with different offscreen rendering
3593 * backends.
3595 if (fbo_blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
3596 &src_rect, src_surface->resource.usage, src_surface->resource.pool, src_surface->resource.format_desc,
3597 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool, dst_surface->resource.format_desc))
3599 stretch_rect_fbo(device, src_surface, &src_rect, dst_surface, &dst_rect, Filter);
3601 else if (!stretchx || dst_rect.right - dst_rect.left > src_surface->currentDesc.Width
3602 || dst_rect.bottom - dst_rect.top > src_surface->currentDesc.Height)
3604 TRACE("No stretching in x direction, using direct framebuffer -> texture copy\n");
3605 fb_copy_to_texture_direct(dst_surface, src_surface, &src_rect, &dst_rect, Filter);
3606 } else {
3607 TRACE("Using hardware stretching to flip / stretch the texture\n");
3608 fb_copy_to_texture_hwstretch(dst_surface, src_surface, &src_rect, &dst_rect, Filter);
3611 if (!(dst_surface->Flags & SFLAG_DONOTFREE))
3613 HeapFree(GetProcessHeap(), 0, dst_surface->resource.heapMemory);
3614 dst_surface->resource.allocatedMemory = NULL;
3615 dst_surface->resource.heapMemory = NULL;
3617 else
3619 dst_surface->Flags &= ~SFLAG_INSYSMEM;
3622 return WINED3D_OK;
3624 else if (src_surface)
3626 /* Blit from offscreen surface to render target */
3627 DWORD oldCKeyFlags = src_surface->CKeyFlags;
3628 WINEDDCOLORKEY oldBltCKey = src_surface->SrcBltCKey;
3629 struct wined3d_context *context;
3631 TRACE("Blt from surface %p to rendertarget %p\n", src_surface, dst_surface);
3633 if (!(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE))
3634 && fbo_blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
3635 &src_rect, src_surface->resource.usage, src_surface->resource.pool,
3636 src_surface->resource.format_desc,
3637 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool,
3638 dst_surface->resource.format_desc))
3640 TRACE("Using stretch_rect_fbo\n");
3641 /* The source is always a texture, but never the currently active render target, and the texture
3642 * contents are never upside down. */
3643 stretch_rect_fbo(device, src_surface, &src_rect, dst_surface, &dst_rect, Filter);
3644 return WINED3D_OK;
3647 if (!(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE))
3648 && arbfp_blit.blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
3649 &src_rect, src_surface->resource.usage, src_surface->resource.pool,
3650 src_surface->resource.format_desc,
3651 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool,
3652 dst_surface->resource.format_desc))
3654 return arbfp_blit_surface(device, src_surface, &src_rect, dst_surface, &dst_rect, BLIT_OP_BLIT, Filter);
3657 /* Color keying: Check if we have to do a color keyed blt,
3658 * and if not check if a color key is activated.
3660 * Just modify the color keying parameters in the surface and restore them afterwards
3661 * The surface keeps track of the color key last used to load the opengl surface.
3662 * PreLoad will catch the change to the flags and color key and reload if necessary.
3664 if(Flags & WINEDDBLT_KEYSRC) {
3665 /* Use color key from surface */
3666 } else if(Flags & WINEDDBLT_KEYSRCOVERRIDE) {
3667 /* Use color key from DDBltFx */
3668 src_surface->CKeyFlags |= WINEDDSD_CKSRCBLT;
3669 src_surface->SrcBltCKey = DDBltFx->ddckSrcColorkey;
3670 } else {
3671 /* Do not use color key */
3672 src_surface->CKeyFlags &= ~WINEDDSD_CKSRCBLT;
3675 /* Now load the surface */
3676 surface_internal_preload(src_surface, SRGB_RGB);
3678 /* Activate the destination context, set it up for blitting */
3679 context = context_acquire(device, dst_surface);
3680 context_apply_blit_state(context, device);
3682 /* The coordinates of the ddraw front buffer are always fullscreen ('screen coordinates',
3683 * while OpenGL coordinates are window relative.
3684 * Also beware of the origin difference(top left vs bottom left).
3685 * Also beware that the front buffer's surface size is screen width x screen height,
3686 * whereas the real gl drawable size is the size of the window.
3688 if (dstSwapchain && dst_surface == dstSwapchain->front_buffer)
3690 RECT windowsize;
3691 POINT offset = {0,0};
3692 UINT h;
3693 ClientToScreen(context->win_handle, &offset);
3694 GetClientRect(context->win_handle, &windowsize);
3695 h = windowsize.bottom - windowsize.top;
3696 dst_rect.left -= offset.x; dst_rect.right -=offset.x;
3697 dst_rect.top -= offset.y; dst_rect.bottom -=offset.y;
3698 dst_rect.top += dst_surface->currentDesc.Height - h;
3699 dst_rect.bottom += dst_surface->currentDesc.Height - h;
3702 if (!device->blitter->blit_supported(&device->adapter->gl_info, BLIT_OP_BLIT,
3703 &src_rect, src_surface->resource.usage, src_surface->resource.pool, src_surface->resource.format_desc,
3704 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool, dst_surface->resource.format_desc))
3706 FIXME("Unsupported blit operation falling back to software\n");
3707 return WINED3DERR_INVALIDCALL;
3710 device->blitter->set_shader((IWineD3DDevice *)device, src_surface);
3712 ENTER_GL();
3714 /* This is for color keying */
3715 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3716 glEnable(GL_ALPHA_TEST);
3717 checkGLcall("glEnable(GL_ALPHA_TEST)");
3719 /* When the primary render target uses P8, the alpha component contains the palette index.
3720 * Which means that the colorkey is one of the palette entries. In other cases pixels that
3721 * should be masked away have alpha set to 0. */
3722 if (primary_render_target_is_p8(device))
3723 glAlphaFunc(GL_NOTEQUAL, (float)src_surface->SrcBltCKey.dwColorSpaceLowValue / 256.0f);
3724 else
3725 glAlphaFunc(GL_NOTEQUAL, 0.0f);
3726 checkGLcall("glAlphaFunc");
3727 } else {
3728 glDisable(GL_ALPHA_TEST);
3729 checkGLcall("glDisable(GL_ALPHA_TEST)");
3732 /* Draw a textured quad
3734 draw_textured_quad(src_surface, &src_rect, &dst_rect, Filter);
3736 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3737 glDisable(GL_ALPHA_TEST);
3738 checkGLcall("glDisable(GL_ALPHA_TEST)");
3741 /* Restore the color key parameters */
3742 src_surface->CKeyFlags = oldCKeyFlags;
3743 src_surface->SrcBltCKey = oldBltCKey;
3745 LEAVE_GL();
3747 /* Leave the opengl state valid for blitting */
3748 device->blitter->unset_shader((IWineD3DDevice *)device);
3750 if (wined3d_settings.strict_draw_ordering || (dstSwapchain
3751 && (dst_surface == dstSwapchain->front_buffer
3752 || dstSwapchain->num_contexts > 1)))
3753 wglFlush(); /* Flush to ensure ordering across contexts. */
3755 context_release(context);
3757 /* TODO: If the surface is locked often, perform the Blt in software on the memory instead */
3758 /* The surface is now in the drawable. On onscreen surfaces or without fbos the texture
3759 * is outdated now
3761 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)dst_surface, SFLAG_INDRAWABLE, TRUE);
3763 return WINED3D_OK;
3764 } else {
3765 /* Source-Less Blit to render target */
3766 if (Flags & WINEDDBLT_COLORFILL) {
3767 DWORD color;
3769 TRACE("Colorfill\n");
3771 /* The color as given in the Blt function is in the format of the frame-buffer...
3772 * 'clear' expect it in ARGB format => we need to do some conversion :-)
3774 if (!surface_convert_color_to_argb(dst_surface, DDBltFx->u5.dwFillColor, &color))
3776 /* The color conversion function already prints an error, so need to do it here */
3777 return WINED3DERR_INVALIDCALL;
3780 if (ffp_blit.blit_supported(&device->adapter->gl_info, BLIT_OP_COLOR_FILL,
3781 NULL, 0, 0, NULL,
3782 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool,
3783 dst_surface->resource.format_desc))
3785 return ffp_blit.color_fill(device, dst_surface, &dst_rect, color);
3787 else if (cpu_blit.blit_supported(&device->adapter->gl_info, BLIT_OP_COLOR_FILL,
3788 NULL, 0, 0, NULL,
3789 &dst_rect, dst_surface->resource.usage, dst_surface->resource.pool,
3790 dst_surface->resource.format_desc))
3792 return cpu_blit.color_fill(device, dst_surface, &dst_rect, color);
3794 return WINED3DERR_INVALIDCALL;
3798 /* Default: Fall back to the generic blt. Not an error, a TRACE is enough */
3799 TRACE("Didn't find any usable render target setup for hw blit, falling back to software\n");
3800 return WINED3DERR_INVALIDCALL;
3803 static HRESULT IWineD3DSurfaceImpl_BltZ(IWineD3DSurfaceImpl *This, const RECT *DestRect,
3804 IWineD3DSurface *SrcSurface, const RECT *SrcRect, DWORD Flags, const WINEDDBLTFX *DDBltFx)
3806 IWineD3DDeviceImpl *device = This->resource.device;
3807 float depth;
3809 if (Flags & WINEDDBLT_DEPTHFILL) {
3810 switch(This->resource.format_desc->format)
3812 case WINED3DFMT_D16_UNORM:
3813 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000ffff;
3814 break;
3815 case WINED3DFMT_S1_UINT_D15_UNORM:
3816 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000fffe;
3817 break;
3818 case WINED3DFMT_D24_UNORM_S8_UINT:
3819 case WINED3DFMT_X8D24_UNORM:
3820 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x00ffffff;
3821 break;
3822 case WINED3DFMT_D32_UNORM:
3823 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0xffffffff;
3824 break;
3825 default:
3826 depth = 0.0f;
3827 ERR("Unexpected format for depth fill: %s\n", debug_d3dformat(This->resource.format_desc->format));
3830 return IWineD3DDevice_Clear((IWineD3DDevice *)device, DestRect ? 1 : 0, (const WINED3DRECT *)DestRect,
3831 WINED3DCLEAR_ZBUFFER, 0x00000000, depth, 0x00000000);
3834 FIXME("(%p): Unsupp depthstencil blit\n", This);
3835 return WINED3DERR_INVALIDCALL;
3838 static HRESULT WINAPI IWineD3DSurfaceImpl_Blt(IWineD3DSurface *iface, const RECT *DestRect, IWineD3DSurface *SrcSurface,
3839 const RECT *SrcRect, DWORD Flags, const WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter) {
3840 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3841 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
3842 IWineD3DDeviceImpl *device = This->resource.device;
3844 TRACE("(%p)->(%p,%p,%p,%x,%p)\n", This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx);
3845 TRACE("(%p): Usage is %s\n", This, debug_d3dusage(This->resource.usage));
3847 if ( (This->Flags & SFLAG_LOCKED) || ((Src != NULL) && (Src->Flags & SFLAG_LOCKED)))
3849 WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
3850 return WINEDDERR_SURFACEBUSY;
3853 /* Accessing the depth stencil is supposed to fail between a BeginScene and EndScene pair,
3854 * except depth blits, which seem to work
3856 if (This == device->depth_stencil || (Src && Src == device->depth_stencil))
3858 if (device->inScene && !(Flags & WINEDDBLT_DEPTHFILL))
3860 TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3861 return WINED3DERR_INVALIDCALL;
3862 } else if(IWineD3DSurfaceImpl_BltZ(This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx) == WINED3D_OK) {
3863 TRACE("Z Blit override handled the blit\n");
3864 return WINED3D_OK;
3868 /* Special cases for RenderTargets */
3869 if ((This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3870 || (Src && (Src->resource.usage & WINED3DUSAGE_RENDERTARGET)))
3872 if (SUCCEEDED(IWineD3DSurfaceImpl_BltOverride(This, DestRect, Src, SrcRect, Flags, DDBltFx, Filter)))
3873 return WINED3D_OK;
3876 /* For the rest call the X11 surface implementation.
3877 * For RenderTargets this should be implemented OpenGL accelerated in BltOverride,
3878 * other Blts are rather rare
3880 return IWineD3DBaseSurfaceImpl_Blt(iface, DestRect, SrcSurface, SrcRect, Flags, DDBltFx, Filter);
3883 static HRESULT WINAPI IWineD3DSurfaceImpl_BltFast(IWineD3DSurface *iface, DWORD dstx, DWORD dsty,
3884 IWineD3DSurface *Source, const RECT *rsrc, DWORD trans)
3886 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3887 IWineD3DSurfaceImpl *srcImpl = (IWineD3DSurfaceImpl *) Source;
3888 IWineD3DDeviceImpl *device = This->resource.device;
3890 TRACE("(%p)->(%d, %d, %p, %p, %08x\n", iface, dstx, dsty, Source, rsrc, trans);
3892 if ( (This->Flags & SFLAG_LOCKED) || (srcImpl->Flags & SFLAG_LOCKED))
3894 WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
3895 return WINEDDERR_SURFACEBUSY;
3898 if (device->inScene && (This == device->depth_stencil || srcImpl == device->depth_stencil))
3900 TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3901 return WINED3DERR_INVALIDCALL;
3904 /* Special cases for RenderTargets */
3905 if( (This->resource.usage & WINED3DUSAGE_RENDERTARGET) ||
3906 (srcImpl->resource.usage & WINED3DUSAGE_RENDERTARGET) ) {
3908 RECT SrcRect, DstRect;
3909 DWORD Flags=0;
3911 surface_get_rect(srcImpl, rsrc, &SrcRect);
3913 DstRect.left = dstx;
3914 DstRect.top=dsty;
3915 DstRect.right = dstx + SrcRect.right - SrcRect.left;
3916 DstRect.bottom = dsty + SrcRect.bottom - SrcRect.top;
3918 /* Convert BltFast flags into Btl ones because it is called from SurfaceImpl_Blt as well */
3919 if(trans & WINEDDBLTFAST_SRCCOLORKEY)
3920 Flags |= WINEDDBLT_KEYSRC;
3921 if(trans & WINEDDBLTFAST_DESTCOLORKEY)
3922 Flags |= WINEDDBLT_KEYDEST;
3923 if(trans & WINEDDBLTFAST_WAIT)
3924 Flags |= WINEDDBLT_WAIT;
3925 if(trans & WINEDDBLTFAST_DONOTWAIT)
3926 Flags |= WINEDDBLT_DONOTWAIT;
3928 if (SUCCEEDED(IWineD3DSurfaceImpl_BltOverride(This,
3929 &DstRect, srcImpl, &SrcRect, Flags, NULL, WINED3DTEXF_POINT)))
3930 return WINED3D_OK;
3934 return IWineD3DBaseSurfaceImpl_BltFast(iface, dstx, dsty, Source, rsrc, trans);
3937 static HRESULT WINAPI IWineD3DSurfaceImpl_RealizePalette(IWineD3DSurface *iface)
3939 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3940 RGBQUAD col[256];
3941 IWineD3DPaletteImpl *pal = This->palette;
3942 unsigned int n;
3943 TRACE("(%p)\n", This);
3945 if (!pal) return WINED3D_OK;
3947 if (This->resource.format_desc->format == WINED3DFMT_P8_UINT
3948 || This->resource.format_desc->format == WINED3DFMT_P8_UINT_A8_UNORM)
3950 if(This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3952 /* Make sure the texture is up to date. This call doesn't do anything if the texture is already up to date. */
3953 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL);
3955 /* We want to force a palette refresh, so mark the drawable as not being up to date */
3956 IWineD3DSurface_ModifyLocation(iface, SFLAG_INDRAWABLE, FALSE);
3957 } else {
3958 if(!(This->Flags & SFLAG_INSYSMEM)) {
3959 TRACE("Palette changed with surface that does not have an up to date system memory copy\n");
3960 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
3962 TRACE("Dirtifying surface\n");
3963 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
3967 if(This->Flags & SFLAG_DIBSECTION) {
3968 TRACE("(%p): Updating the hdc's palette\n", This);
3969 for (n=0; n<256; n++) {
3970 col[n].rgbRed = pal->palents[n].peRed;
3971 col[n].rgbGreen = pal->palents[n].peGreen;
3972 col[n].rgbBlue = pal->palents[n].peBlue;
3973 col[n].rgbReserved = 0;
3975 SetDIBColorTable(This->hDC, 0, 256, col);
3978 /* Propagate the changes to the drawable when we have a palette. */
3979 if(This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3980 IWineD3DSurface_LoadLocation(iface, SFLAG_INDRAWABLE, NULL);
3982 return WINED3D_OK;
3985 static HRESULT WINAPI IWineD3DSurfaceImpl_PrivateSetup(IWineD3DSurface *iface) {
3986 /** Check against the maximum texture sizes supported by the video card **/
3987 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3988 const struct wined3d_gl_info *gl_info = &This->resource.device->adapter->gl_info;
3989 unsigned int pow2Width, pow2Height;
3991 This->texture_name = 0;
3992 This->texture_target = GL_TEXTURE_2D;
3994 /* Non-power2 support */
3995 if (gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] || gl_info->supported[WINE_NORMALIZED_TEXRECT])
3997 pow2Width = This->currentDesc.Width;
3998 pow2Height = This->currentDesc.Height;
4000 else
4002 /* Find the nearest pow2 match */
4003 pow2Width = pow2Height = 1;
4004 while (pow2Width < This->currentDesc.Width) pow2Width <<= 1;
4005 while (pow2Height < This->currentDesc.Height) pow2Height <<= 1;
4007 This->pow2Width = pow2Width;
4008 This->pow2Height = pow2Height;
4010 if (pow2Width > This->currentDesc.Width || pow2Height > This->currentDesc.Height) {
4011 /** TODO: add support for non power two compressed textures **/
4012 if (This->resource.format_desc->Flags & WINED3DFMT_FLAG_COMPRESSED)
4014 FIXME("(%p) Compressed non-power-two textures are not supported w(%d) h(%d)\n",
4015 This, This->currentDesc.Width, This->currentDesc.Height);
4016 return WINED3DERR_NOTAVAILABLE;
4020 if(pow2Width != This->currentDesc.Width ||
4021 pow2Height != This->currentDesc.Height) {
4022 This->Flags |= SFLAG_NONPOW2;
4025 TRACE("%p\n", This);
4026 if ((This->pow2Width > gl_info->limits.texture_size || This->pow2Height > gl_info->limits.texture_size)
4027 && !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL)))
4029 /* one of three options
4030 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)
4031 2: Set the texture to the maximum size (bad idea)
4032 3: WARN and return WINED3DERR_NOTAVAILABLE;
4033 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.
4035 if(This->resource.pool == WINED3DPOOL_DEFAULT || This->resource.pool == WINED3DPOOL_MANAGED)
4037 WARN("(%p) Unable to allocate a surface which exceeds the maximum OpenGL texture size\n", This);
4038 return WINED3DERR_NOTAVAILABLE;
4041 /* We should never use this surface in combination with OpenGL! */
4042 TRACE("(%p) Creating an oversized surface: %ux%u\n", This, This->pow2Width, This->pow2Height);
4044 else
4046 /* Don't use ARB_TEXTURE_RECTANGLE in case the surface format is P8 and EXT_PALETTED_TEXTURE
4047 is used in combination with texture uploads (RTL_READTEX/RTL_TEXTEX). The reason is that EXT_PALETTED_TEXTURE
4048 doesn't work in combination with ARB_TEXTURE_RECTANGLE.
4050 if (This->Flags & SFLAG_NONPOW2 && gl_info->supported[ARB_TEXTURE_RECTANGLE]
4051 && !(This->resource.format_desc->format == WINED3DFMT_P8_UINT
4052 && gl_info->supported[EXT_PALETTED_TEXTURE]
4053 && wined3d_settings.rendertargetlock_mode == RTL_READTEX))
4055 This->texture_target = GL_TEXTURE_RECTANGLE_ARB;
4056 This->pow2Width = This->currentDesc.Width;
4057 This->pow2Height = This->currentDesc.Height;
4058 This->Flags &= ~(SFLAG_NONPOW2 | SFLAG_NORMCOORD);
4062 if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
4063 switch(wined3d_settings.offscreen_rendering_mode) {
4064 case ORM_FBO: This->get_drawable_size = get_drawable_size_fbo; break;
4065 case ORM_BACKBUFFER: This->get_drawable_size = get_drawable_size_backbuffer; break;
4069 This->Flags |= SFLAG_INSYSMEM;
4071 return WINED3D_OK;
4074 /* GL locking is done by the caller */
4075 static void surface_depth_blt(IWineD3DSurfaceImpl *This, const struct wined3d_gl_info *gl_info,
4076 GLuint texture, GLsizei w, GLsizei h, GLenum target)
4078 IWineD3DDeviceImpl *device = This->resource.device;
4079 struct blt_info info;
4080 GLint old_binding = 0;
4082 glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_VIEWPORT_BIT);
4084 glDisable(GL_CULL_FACE);
4085 glDisable(GL_BLEND);
4086 glDisable(GL_ALPHA_TEST);
4087 glDisable(GL_SCISSOR_TEST);
4088 glDisable(GL_STENCIL_TEST);
4089 glEnable(GL_DEPTH_TEST);
4090 glDepthFunc(GL_ALWAYS);
4091 glDepthMask(GL_TRUE);
4092 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
4093 glViewport(0, 0, w, h);
4095 surface_get_blt_info(target, NULL, w, h, &info);
4096 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
4097 glGetIntegerv(info.binding, &old_binding);
4098 glBindTexture(info.bind_target, texture);
4100 device->shader_backend->shader_select_depth_blt((IWineD3DDevice *)device,
4101 info.tex_type, &This->ds_current_size);
4103 glBegin(GL_TRIANGLE_STRIP);
4104 glTexCoord3fv(info.coords[0]);
4105 glVertex2f(-1.0f, -1.0f);
4106 glTexCoord3fv(info.coords[1]);
4107 glVertex2f(1.0f, -1.0f);
4108 glTexCoord3fv(info.coords[2]);
4109 glVertex2f(-1.0f, 1.0f);
4110 glTexCoord3fv(info.coords[3]);
4111 glVertex2f(1.0f, 1.0f);
4112 glEnd();
4114 glBindTexture(info.bind_target, old_binding);
4116 glPopAttrib();
4118 device->shader_backend->shader_deselect_depth_blt((IWineD3DDevice *)device);
4121 void surface_modify_ds_location(IWineD3DSurfaceImpl *surface,
4122 DWORD location, UINT w, UINT h)
4124 TRACE("surface %p, new location %#x, w %u, h %u.\n", surface, location, w, h);
4126 if (location & ~SFLAG_DS_LOCATIONS)
4127 FIXME("Invalid location (%#x) specified.\n", location);
4129 surface->ds_current_size.cx = w;
4130 surface->ds_current_size.cy = h;
4131 surface->Flags &= ~SFLAG_DS_LOCATIONS;
4132 surface->Flags |= location;
4135 /* Context activation is done by the caller. */
4136 void surface_load_ds_location(IWineD3DSurfaceImpl *surface, struct wined3d_context *context, DWORD location)
4138 IWineD3DDeviceImpl *device = surface->resource.device;
4139 const struct wined3d_gl_info *gl_info = context->gl_info;
4141 TRACE("surface %p, new location %#x.\n", surface, location);
4143 /* TODO: Make this work for modes other than FBO */
4144 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return;
4146 if (!(surface->Flags & location))
4148 surface->ds_current_size.cx = 0;
4149 surface->ds_current_size.cy = 0;
4152 if (surface->ds_current_size.cx == surface->currentDesc.Width
4153 && surface->ds_current_size.cy == surface->currentDesc.Height)
4155 TRACE("Location (%#x) is already up to date.\n", location);
4156 return;
4159 if (surface->current_renderbuffer)
4161 FIXME("Not supported with fixed up depth stencil.\n");
4162 return;
4165 if (!(surface->Flags & SFLAG_LOCATIONS))
4167 FIXME("No up to date depth stencil location.\n");
4168 surface->Flags |= location;
4169 return;
4172 if (location == SFLAG_DS_OFFSCREEN)
4174 GLint old_binding = 0;
4175 GLenum bind_target;
4177 TRACE("Copying onscreen depth buffer to depth texture.\n");
4179 ENTER_GL();
4181 if (!device->depth_blt_texture)
4183 glGenTextures(1, &device->depth_blt_texture);
4186 /* Note that we use depth_blt here as well, rather than glCopyTexImage2D
4187 * directly on the FBO texture. That's because we need to flip. */
4188 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
4189 if (surface->texture_target == GL_TEXTURE_RECTANGLE_ARB)
4191 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
4192 bind_target = GL_TEXTURE_RECTANGLE_ARB;
4194 else
4196 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
4197 bind_target = GL_TEXTURE_2D;
4199 glBindTexture(bind_target, device->depth_blt_texture);
4200 glCopyTexImage2D(bind_target, surface->texture_level, surface->resource.format_desc->glInternal,
4201 0, 0, surface->currentDesc.Width, surface->currentDesc.Height, 0);
4202 glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
4203 glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
4204 glTexParameteri(bind_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
4205 glTexParameteri(bind_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
4206 glTexParameteri(bind_target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
4207 glTexParameteri(bind_target, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE);
4208 glBindTexture(bind_target, old_binding);
4210 /* Setup the destination */
4211 if (!device->depth_blt_rb)
4213 gl_info->fbo_ops.glGenRenderbuffers(1, &device->depth_blt_rb);
4214 checkGLcall("glGenRenderbuffersEXT");
4216 if (device->depth_blt_rb_w != surface->currentDesc.Width
4217 || device->depth_blt_rb_h != surface->currentDesc.Height)
4219 gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, device->depth_blt_rb);
4220 checkGLcall("glBindRenderbufferEXT");
4221 gl_info->fbo_ops.glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8,
4222 surface->currentDesc.Width, surface->currentDesc.Height);
4223 checkGLcall("glRenderbufferStorageEXT");
4224 device->depth_blt_rb_w = surface->currentDesc.Width;
4225 device->depth_blt_rb_h = surface->currentDesc.Height;
4228 context_bind_fbo(context, GL_FRAMEBUFFER, &context->dst_fbo);
4229 gl_info->fbo_ops.glFramebufferRenderbuffer(GL_FRAMEBUFFER,
4230 GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, device->depth_blt_rb);
4231 checkGLcall("glFramebufferRenderbufferEXT");
4232 context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER, surface, FALSE);
4234 /* Do the actual blit */
4235 surface_depth_blt(surface, gl_info, device->depth_blt_texture,
4236 surface->currentDesc.Width, surface->currentDesc.Height, bind_target);
4237 checkGLcall("depth_blt");
4239 if (context->current_fbo) context_bind_fbo(context, GL_FRAMEBUFFER, &context->current_fbo->id);
4240 else context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
4242 LEAVE_GL();
4244 if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
4246 else if (location == SFLAG_DS_ONSCREEN)
4248 TRACE("Copying depth texture to onscreen depth buffer.\n");
4250 ENTER_GL();
4252 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
4253 surface_depth_blt(surface, gl_info, surface->texture_name,
4254 surface->currentDesc.Width, surface->currentDesc.Height, surface->texture_target);
4255 checkGLcall("depth_blt");
4257 if (context->current_fbo) context_bind_fbo(context, GL_FRAMEBUFFER, &context->current_fbo->id);
4259 LEAVE_GL();
4261 if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
4263 else
4265 ERR("Invalid location (%#x) specified.\n", location);
4268 surface->Flags |= location;
4269 surface->ds_current_size.cx = surface->currentDesc.Width;
4270 surface->ds_current_size.cy = surface->currentDesc.Height;
4273 static void WINAPI IWineD3DSurfaceImpl_ModifyLocation(IWineD3DSurface *iface, DWORD flag, BOOL persistent) {
4274 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4275 IWineD3DBaseTexture *texture;
4276 IWineD3DSurfaceImpl *overlay;
4278 TRACE("(%p)->(%s, %s)\n", iface, debug_surflocation(flag),
4279 persistent ? "TRUE" : "FALSE");
4281 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
4283 if (surface_is_offscreen(This))
4285 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
4286 if (flag & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE)) flag |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4288 else
4290 TRACE("Surface %p is an onscreen surface\n", iface);
4294 if(persistent) {
4295 if(((This->Flags & SFLAG_INTEXTURE) && !(flag & SFLAG_INTEXTURE)) ||
4296 ((This->Flags & SFLAG_INSRGBTEX) && !(flag & SFLAG_INSRGBTEX))) {
4297 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&texture) == WINED3D_OK) {
4298 TRACE("Passing to container\n");
4299 IWineD3DBaseTexture_SetDirty(texture, TRUE);
4300 IWineD3DBaseTexture_Release(texture);
4303 This->Flags &= ~SFLAG_LOCATIONS;
4304 This->Flags |= flag;
4306 /* Redraw emulated overlays, if any */
4307 if(flag & SFLAG_INDRAWABLE && !list_empty(&This->overlays)) {
4308 LIST_FOR_EACH_ENTRY(overlay, &This->overlays, IWineD3DSurfaceImpl, overlay_entry) {
4309 IWineD3DSurface_DrawOverlay((IWineD3DSurface *) overlay);
4312 } else {
4313 if((This->Flags & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)) && (flag & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX))) {
4314 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&texture) == WINED3D_OK) {
4315 TRACE("Passing to container\n");
4316 IWineD3DBaseTexture_SetDirty(texture, TRUE);
4317 IWineD3DBaseTexture_Release(texture);
4320 This->Flags &= ~flag;
4323 if(!(This->Flags & SFLAG_LOCATIONS)) {
4324 ERR("%p: Surface does not have any up to date location\n", This);
4328 static inline void surface_blt_to_drawable(IWineD3DSurfaceImpl *This, const RECT *rect_in)
4330 IWineD3DDeviceImpl *device = This->resource.device;
4331 IWineD3DSwapChainImpl *swapchain;
4332 struct wined3d_context *context;
4333 RECT src_rect, dst_rect;
4335 surface_get_rect(This, rect_in, &src_rect);
4337 context = context_acquire(device, This);
4338 context_apply_blit_state(context, device);
4339 if (context->render_offscreen)
4341 dst_rect.left = src_rect.left;
4342 dst_rect.right = src_rect.right;
4343 dst_rect.top = src_rect.bottom;
4344 dst_rect.bottom = src_rect.top;
4346 else
4348 dst_rect = src_rect;
4351 device->blitter->set_shader((IWineD3DDevice *) device, This);
4353 ENTER_GL();
4354 draw_textured_quad(This, &src_rect, &dst_rect, WINED3DTEXF_POINT);
4355 LEAVE_GL();
4357 device->blitter->set_shader((IWineD3DDevice *) device, This);
4359 swapchain = (This->Flags & SFLAG_SWAPCHAIN) ? (IWineD3DSwapChainImpl *)This->container : NULL;
4360 if (wined3d_settings.strict_draw_ordering || (swapchain
4361 && (This == swapchain->front_buffer || swapchain->num_contexts > 1)))
4362 wglFlush(); /* Flush to ensure ordering across contexts. */
4364 context_release(context);
4367 /*****************************************************************************
4368 * IWineD3DSurface::LoadLocation
4370 * Copies the current surface data from wherever it is to the requested
4371 * location. The location is one of the surface flags, SFLAG_INSYSMEM,
4372 * SFLAG_INTEXTURE and SFLAG_INDRAWABLE. When the surface is current in
4373 * multiple locations, the gl texture is preferred over the drawable, which is
4374 * preferred over system memory. The PBO counts as system memory. If rect is
4375 * not NULL, only the specified rectangle is copied (only supported for
4376 * sysmem<->drawable copies at the moment). If rect is NULL, the destination
4377 * location is marked up to date after the copy.
4379 * Parameters:
4380 * flag: Surface location flag to be updated
4381 * rect: rectangle to be copied
4383 * Returns:
4384 * WINED3D_OK on success
4385 * WINED3DERR_DEVICELOST on an internal error
4387 *****************************************************************************/
4388 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadLocation(IWineD3DSurface *iface, DWORD flag, const RECT *rect) {
4389 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4390 IWineD3DDeviceImpl *device = This->resource.device;
4391 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4392 struct wined3d_format_desc desc;
4393 CONVERT_TYPES convert;
4394 int width, pitch, outpitch;
4395 BYTE *mem;
4396 BOOL drawable_read_ok = TRUE;
4397 BOOL in_fbo = FALSE;
4399 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
4401 if (surface_is_offscreen(This))
4403 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets.
4404 * Prefer SFLAG_INTEXTURE. */
4405 if (flag == SFLAG_INDRAWABLE) flag = SFLAG_INTEXTURE;
4406 drawable_read_ok = FALSE;
4407 in_fbo = TRUE;
4409 else
4411 TRACE("Surface %p is an onscreen surface\n", iface);
4415 TRACE("(%p)->(%s, %p)\n", iface, debug_surflocation(flag), rect);
4416 if(rect) {
4417 TRACE("Rectangle: (%d,%d)-(%d,%d)\n", rect->left, rect->top, rect->right, rect->bottom);
4420 if(This->Flags & flag) {
4421 TRACE("Location already up to date\n");
4422 return WINED3D_OK;
4425 if(!(This->Flags & SFLAG_LOCATIONS)) {
4426 ERR("%p: Surface does not have any up to date location\n", This);
4427 This->Flags |= SFLAG_LOST;
4428 return WINED3DERR_DEVICELOST;
4431 if(flag == SFLAG_INSYSMEM) {
4432 surface_prepare_system_memory(This);
4434 /* Download the surface to system memory */
4435 if (This->Flags & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX))
4437 struct wined3d_context *context = NULL;
4439 if (!device->isInDraw) context = context_acquire(device, NULL);
4441 surface_bind_and_dirtify(This, !(This->Flags & SFLAG_INTEXTURE));
4442 surface_download_data(This, gl_info);
4444 if (context) context_release(context);
4446 else
4448 /* Note: It might be faster to download into a texture first. */
4449 read_from_framebuffer(This, rect,
4450 This->resource.allocatedMemory,
4451 IWineD3DSurface_GetPitch(iface));
4453 } else if(flag == SFLAG_INDRAWABLE) {
4454 if(This->Flags & SFLAG_INTEXTURE) {
4455 surface_blt_to_drawable(This, rect);
4456 } else {
4457 int byte_count;
4458 if((This->Flags & SFLAG_LOCATIONS) == SFLAG_INSRGBTEX) {
4459 /* This needs a shader to convert the srgb data sampled from the GL texture into RGB
4460 * values, otherwise we get incorrect values in the target. For now go the slow way
4461 * via a system memory copy
4463 IWineD3DSurfaceImpl_LoadLocation(iface, SFLAG_INSYSMEM, rect);
4466 d3dfmt_get_conv(This, FALSE /* We need color keying */, FALSE /* We won't use textures */, &desc, &convert);
4468 /* The width is in 'length' not in bytes */
4469 width = This->currentDesc.Width;
4470 pitch = IWineD3DSurface_GetPitch(iface);
4472 /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
4473 * but it isn't set (yet) in all cases it is getting called. */
4474 if ((convert != NO_CONVERSION) && (This->Flags & SFLAG_PBO))
4476 struct wined3d_context *context = NULL;
4478 TRACE("Removing the pbo attached to surface %p\n", This);
4480 if (!device->isInDraw) context = context_acquire(device, NULL);
4481 surface_remove_pbo(This, gl_info);
4482 if (context) context_release(context);
4485 if((convert != NO_CONVERSION) && This->resource.allocatedMemory) {
4486 int height = This->currentDesc.Height;
4487 byte_count = desc.conv_byte_count;
4489 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4490 outpitch = width * byte_count;
4491 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4493 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4494 if(!mem) {
4495 ERR("Out of memory %d, %d!\n", outpitch, height);
4496 return WINED3DERR_OUTOFVIDEOMEMORY;
4498 d3dfmt_convert_surface(This->resource.allocatedMemory, mem, pitch, width, height, outpitch, convert, This);
4500 This->Flags |= SFLAG_CONVERTED;
4501 } else {
4502 This->Flags &= ~SFLAG_CONVERTED;
4503 mem = This->resource.allocatedMemory;
4504 byte_count = desc.byte_count;
4507 flush_to_framebuffer_drawpixels(This, desc.glFormat, desc.glType, byte_count, mem);
4509 /* Don't delete PBO memory */
4510 if((mem != This->resource.allocatedMemory) && !(This->Flags & SFLAG_PBO))
4511 HeapFree(GetProcessHeap(), 0, mem);
4513 } else /* if(flag & (SFLAG_INTEXTURE | SFLAG_INSRGBTEX)) */ {
4514 if (drawable_read_ok && (This->Flags & SFLAG_INDRAWABLE)) {
4515 read_from_framebuffer_texture(This, flag == SFLAG_INSRGBTEX);
4517 else
4519 /* Upload from system memory */
4520 BOOL srgb = flag == SFLAG_INSRGBTEX;
4521 struct wined3d_context *context = NULL;
4523 d3dfmt_get_conv(This, TRUE /* We need color keying */, TRUE /* We will use textures */,
4524 &desc, &convert);
4526 if(srgb) {
4527 if((This->Flags & (SFLAG_INTEXTURE | SFLAG_INSYSMEM)) == SFLAG_INTEXTURE) {
4528 /* Performance warning ... */
4529 FIXME("%p: Downloading rgb texture to reload it as srgb\n", This);
4530 IWineD3DSurfaceImpl_LoadLocation(iface, SFLAG_INSYSMEM, rect);
4532 } else {
4533 if((This->Flags & (SFLAG_INSRGBTEX | SFLAG_INSYSMEM)) == SFLAG_INSRGBTEX) {
4534 /* Performance warning ... */
4535 FIXME("%p: Downloading srgb texture to reload it as rgb\n", This);
4536 IWineD3DSurfaceImpl_LoadLocation(iface, SFLAG_INSYSMEM, rect);
4539 if(!(This->Flags & SFLAG_INSYSMEM)) {
4540 /* Should not happen */
4541 ERR("Trying to load a texture from sysmem, but SFLAG_INSYSMEM is not set\n");
4542 /* Lets hope we get it from somewhere... */
4543 IWineD3DSurfaceImpl_LoadLocation(iface, SFLAG_INSYSMEM, rect);
4546 if (!device->isInDraw) context = context_acquire(device, NULL);
4548 surface_prepare_texture(This, gl_info, srgb);
4549 surface_bind_and_dirtify(This, srgb);
4551 if(This->CKeyFlags & WINEDDSD_CKSRCBLT) {
4552 This->Flags |= SFLAG_GLCKEY;
4553 This->glCKey = This->SrcBltCKey;
4555 else This->Flags &= ~SFLAG_GLCKEY;
4557 /* The width is in 'length' not in bytes */
4558 width = This->currentDesc.Width;
4559 pitch = IWineD3DSurface_GetPitch(iface);
4561 /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
4562 * but it isn't set (yet) in all cases it is getting called. */
4563 if((convert != NO_CONVERSION) && (This->Flags & SFLAG_PBO)) {
4564 TRACE("Removing the pbo attached to surface %p\n", This);
4565 surface_remove_pbo(This, gl_info);
4568 if(desc.convert) {
4569 /* This code is entered for texture formats which need a fixup. */
4570 int height = This->currentDesc.Height;
4572 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4573 outpitch = width * desc.conv_byte_count;
4574 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4576 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4577 if(!mem) {
4578 ERR("Out of memory %d, %d!\n", outpitch, height);
4579 if (context) context_release(context);
4580 return WINED3DERR_OUTOFVIDEOMEMORY;
4582 desc.convert(This->resource.allocatedMemory, mem, pitch, width, height);
4583 } else if((convert != NO_CONVERSION) && This->resource.allocatedMemory) {
4584 /* This code is only entered for color keying fixups */
4585 int height = This->currentDesc.Height;
4587 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4588 outpitch = width * desc.conv_byte_count;
4589 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4591 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4592 if(!mem) {
4593 ERR("Out of memory %d, %d!\n", outpitch, height);
4594 if (context) context_release(context);
4595 return WINED3DERR_OUTOFVIDEOMEMORY;
4597 d3dfmt_convert_surface(This->resource.allocatedMemory, mem, pitch, width, height, outpitch, convert, This);
4598 } else {
4599 mem = This->resource.allocatedMemory;
4602 /* Make sure the correct pitch is used */
4603 ENTER_GL();
4604 glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
4605 LEAVE_GL();
4607 if (mem || (This->Flags & SFLAG_PBO))
4608 surface_upload_data(This, gl_info, &desc, srgb, mem);
4610 /* Restore the default pitch */
4611 ENTER_GL();
4612 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
4613 LEAVE_GL();
4615 if (context) context_release(context);
4617 /* Don't delete PBO memory */
4618 if((mem != This->resource.allocatedMemory) && !(This->Flags & SFLAG_PBO))
4619 HeapFree(GetProcessHeap(), 0, mem);
4623 if(rect == NULL) {
4624 This->Flags |= flag;
4627 if (in_fbo && (This->Flags & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE))) {
4628 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
4629 This->Flags |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4632 return WINED3D_OK;
4635 static HRESULT WINAPI IWineD3DSurfaceImpl_SetContainer(IWineD3DSurface *iface, IWineD3DBase *container)
4637 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4638 IWineD3DSwapChain *swapchain = NULL;
4640 /* Update the drawable size method */
4641 if(container) {
4642 IWineD3DBase_QueryInterface(container, &IID_IWineD3DSwapChain, (void **) &swapchain);
4644 if(swapchain) {
4645 This->get_drawable_size = get_drawable_size_swapchain;
4646 IWineD3DSwapChain_Release(swapchain);
4647 } else if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
4648 switch(wined3d_settings.offscreen_rendering_mode) {
4649 case ORM_FBO: This->get_drawable_size = get_drawable_size_fbo; break;
4650 case ORM_BACKBUFFER: This->get_drawable_size = get_drawable_size_backbuffer; break;
4654 return IWineD3DBaseSurfaceImpl_SetContainer(iface, container);
4657 static WINED3DSURFTYPE WINAPI IWineD3DSurfaceImpl_GetImplType(IWineD3DSurface *iface) {
4658 return SURFACE_OPENGL;
4661 static HRESULT WINAPI IWineD3DSurfaceImpl_DrawOverlay(IWineD3DSurface *iface) {
4662 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4663 HRESULT hr;
4665 /* If there's no destination surface there is nothing to do */
4666 if(!This->overlay_dest) return WINED3D_OK;
4668 /* Blt calls ModifyLocation on the dest surface, which in turn calls DrawOverlay to
4669 * update the overlay. Prevent an endless recursion
4671 if(This->overlay_dest->Flags & SFLAG_INOVERLAYDRAW) {
4672 return WINED3D_OK;
4674 This->overlay_dest->Flags |= SFLAG_INOVERLAYDRAW;
4675 hr = IWineD3DSurfaceImpl_Blt((IWineD3DSurface *) This->overlay_dest, &This->overlay_destrect,
4676 iface, &This->overlay_srcrect, WINEDDBLT_WAIT,
4677 NULL, WINED3DTEXF_LINEAR);
4678 This->overlay_dest->Flags &= ~SFLAG_INOVERLAYDRAW;
4680 return hr;
4683 BOOL surface_is_offscreen(IWineD3DSurfaceImpl *surface)
4685 IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)surface->container;
4687 /* Not on a swapchain - must be offscreen */
4688 if (!(surface->Flags & SFLAG_SWAPCHAIN)) return TRUE;
4690 /* The front buffer is always onscreen */
4691 if (surface == swapchain->front_buffer) return FALSE;
4693 /* If the swapchain is rendered to an FBO, the backbuffer is
4694 * offscreen, otherwise onscreen */
4695 return swapchain->render_to_fbo;
4698 const IWineD3DSurfaceVtbl IWineD3DSurface_Vtbl =
4700 /* IUnknown */
4701 IWineD3DBaseSurfaceImpl_QueryInterface,
4702 IWineD3DBaseSurfaceImpl_AddRef,
4703 IWineD3DSurfaceImpl_Release,
4704 /* IWineD3DResource */
4705 IWineD3DBaseSurfaceImpl_GetParent,
4706 IWineD3DBaseSurfaceImpl_SetPrivateData,
4707 IWineD3DBaseSurfaceImpl_GetPrivateData,
4708 IWineD3DBaseSurfaceImpl_FreePrivateData,
4709 IWineD3DBaseSurfaceImpl_SetPriority,
4710 IWineD3DBaseSurfaceImpl_GetPriority,
4711 IWineD3DSurfaceImpl_PreLoad,
4712 IWineD3DSurfaceImpl_UnLoad,
4713 IWineD3DBaseSurfaceImpl_GetType,
4714 /* IWineD3DSurface */
4715 IWineD3DBaseSurfaceImpl_GetContainer,
4716 IWineD3DBaseSurfaceImpl_GetDesc,
4717 IWineD3DSurfaceImpl_LockRect,
4718 IWineD3DSurfaceImpl_UnlockRect,
4719 IWineD3DSurfaceImpl_GetDC,
4720 IWineD3DSurfaceImpl_ReleaseDC,
4721 IWineD3DSurfaceImpl_Flip,
4722 IWineD3DSurfaceImpl_Blt,
4723 IWineD3DBaseSurfaceImpl_GetBltStatus,
4724 IWineD3DBaseSurfaceImpl_GetFlipStatus,
4725 IWineD3DBaseSurfaceImpl_IsLost,
4726 IWineD3DBaseSurfaceImpl_Restore,
4727 IWineD3DSurfaceImpl_BltFast,
4728 IWineD3DBaseSurfaceImpl_GetPalette,
4729 IWineD3DBaseSurfaceImpl_SetPalette,
4730 IWineD3DSurfaceImpl_RealizePalette,
4731 IWineD3DBaseSurfaceImpl_SetColorKey,
4732 IWineD3DBaseSurfaceImpl_GetPitch,
4733 IWineD3DSurfaceImpl_SetMem,
4734 IWineD3DBaseSurfaceImpl_SetOverlayPosition,
4735 IWineD3DBaseSurfaceImpl_GetOverlayPosition,
4736 IWineD3DBaseSurfaceImpl_UpdateOverlayZOrder,
4737 IWineD3DBaseSurfaceImpl_UpdateOverlay,
4738 IWineD3DBaseSurfaceImpl_SetClipper,
4739 IWineD3DBaseSurfaceImpl_GetClipper,
4740 /* Internal use: */
4741 IWineD3DSurfaceImpl_LoadTexture,
4742 IWineD3DSurfaceImpl_BindTexture,
4743 IWineD3DSurfaceImpl_SaveSnapshot,
4744 IWineD3DSurfaceImpl_SetContainer,
4745 IWineD3DBaseSurfaceImpl_GetData,
4746 IWineD3DSurfaceImpl_SetFormat,
4747 IWineD3DSurfaceImpl_PrivateSetup,
4748 IWineD3DSurfaceImpl_ModifyLocation,
4749 IWineD3DSurfaceImpl_LoadLocation,
4750 IWineD3DSurfaceImpl_GetImplType,
4751 IWineD3DSurfaceImpl_DrawOverlay
4754 static HRESULT ffp_blit_alloc(IWineD3DDevice *iface) { return WINED3D_OK; }
4755 /* Context activation is done by the caller. */
4756 static void ffp_blit_free(IWineD3DDevice *iface) { }
4758 /* This function is used in case of 8bit paletted textures using GL_EXT_paletted_texture */
4759 /* Context activation is done by the caller. */
4760 static void ffp_blit_p8_upload_palette(IWineD3DSurfaceImpl *surface, const struct wined3d_gl_info *gl_info)
4762 BYTE table[256][4];
4763 BOOL colorkey_active = (surface->CKeyFlags & WINEDDSD_CKSRCBLT) ? TRUE : FALSE;
4765 d3dfmt_p8_init_palette(surface, table, colorkey_active);
4767 TRACE("Using GL_EXT_PALETTED_TEXTURE for 8-bit paletted texture support\n");
4768 ENTER_GL();
4769 GL_EXTCALL(glColorTableEXT(surface->texture_target, GL_RGBA, 256, GL_RGBA, GL_UNSIGNED_BYTE, table));
4770 LEAVE_GL();
4773 /* Context activation is done by the caller. */
4774 static HRESULT ffp_blit_set(IWineD3DDevice *iface, IWineD3DSurfaceImpl *surface)
4776 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
4777 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4778 enum complex_fixup fixup = get_complex_fixup(surface->resource.format_desc->color_fixup);
4780 /* When EXT_PALETTED_TEXTURE is around, palette conversion is done by the GPU
4781 * else the surface is converted in software at upload time in LoadLocation.
4783 if(fixup == COMPLEX_FIXUP_P8 && gl_info->supported[EXT_PALETTED_TEXTURE])
4784 ffp_blit_p8_upload_palette(surface, gl_info);
4786 ENTER_GL();
4787 glEnable(surface->texture_target);
4788 checkGLcall("glEnable(surface->texture_target)");
4789 LEAVE_GL();
4790 return WINED3D_OK;
4793 /* Context activation is done by the caller. */
4794 static void ffp_blit_unset(IWineD3DDevice *iface)
4796 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
4797 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4799 ENTER_GL();
4800 glDisable(GL_TEXTURE_2D);
4801 checkGLcall("glDisable(GL_TEXTURE_2D)");
4802 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
4804 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
4805 checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
4807 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
4809 glDisable(GL_TEXTURE_RECTANGLE_ARB);
4810 checkGLcall("glDisable(GL_TEXTURE_RECTANGLE_ARB)");
4812 LEAVE_GL();
4815 static BOOL ffp_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
4816 const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool,
4817 const struct wined3d_format_desc *src_format_desc,
4818 const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool,
4819 const struct wined3d_format_desc *dst_format_desc)
4821 enum complex_fixup src_fixup;
4823 if (blit_op == BLIT_OP_COLOR_FILL)
4825 if (!(dst_usage & WINED3DUSAGE_RENDERTARGET))
4827 TRACE("Color fill not supported\n");
4828 return FALSE;
4831 return TRUE;
4834 src_fixup = get_complex_fixup(src_format_desc->color_fixup);
4835 if (TRACE_ON(d3d_surface) && TRACE_ON(d3d))
4837 TRACE("Checking support for fixup:\n");
4838 dump_color_fixup_desc(src_format_desc->color_fixup);
4841 if (blit_op != BLIT_OP_BLIT)
4843 TRACE("Unsupported blit_op=%d\n", blit_op);
4844 return FALSE;
4847 if (!is_identity_fixup(dst_format_desc->color_fixup))
4849 TRACE("Destination fixups are not supported\n");
4850 return FALSE;
4853 if (src_fixup == COMPLEX_FIXUP_P8 && gl_info->supported[EXT_PALETTED_TEXTURE])
4855 TRACE("P8 fixup supported\n");
4856 return TRUE;
4859 /* We only support identity conversions. */
4860 if (is_identity_fixup(src_format_desc->color_fixup))
4862 TRACE("[OK]\n");
4863 return TRUE;
4866 TRACE("[FAILED]\n");
4867 return FALSE;
4870 static HRESULT ffp_blit_color_fill(IWineD3DDeviceImpl *device, IWineD3DSurfaceImpl *dst_surface, const RECT *dst_rect, DWORD fill_color)
4872 return IWineD3DDeviceImpl_ClearSurface(device, dst_surface, 1 /* Number of rectangles */,
4873 (const WINED3DRECT*)dst_rect, WINED3DCLEAR_TARGET, fill_color, 0.0f /* Z */, 0 /* Stencil */);
4876 const struct blit_shader ffp_blit = {
4877 ffp_blit_alloc,
4878 ffp_blit_free,
4879 ffp_blit_set,
4880 ffp_blit_unset,
4881 ffp_blit_supported,
4882 ffp_blit_color_fill
4885 static HRESULT cpu_blit_alloc(IWineD3DDevice *iface)
4887 return WINED3D_OK;
4890 /* Context activation is done by the caller. */
4891 static void cpu_blit_free(IWineD3DDevice *iface)
4895 /* Context activation is done by the caller. */
4896 static HRESULT cpu_blit_set(IWineD3DDevice *iface, IWineD3DSurfaceImpl *surface)
4898 return WINED3D_OK;
4901 /* Context activation is done by the caller. */
4902 static void cpu_blit_unset(IWineD3DDevice *iface)
4906 static BOOL cpu_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
4907 const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool,
4908 const struct wined3d_format_desc *src_format_desc,
4909 const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool,
4910 const struct wined3d_format_desc *dst_format_desc)
4912 if (blit_op == BLIT_OP_COLOR_FILL)
4914 return TRUE;
4917 return FALSE;
4920 static HRESULT cpu_blit_color_fill(IWineD3DDeviceImpl *device, IWineD3DSurfaceImpl *dst_surface, const RECT *dst_rect, DWORD fill_color)
4922 WINEDDBLTFX BltFx;
4923 memset(&BltFx, 0, sizeof(BltFx));
4924 BltFx.dwSize = sizeof(BltFx);
4925 BltFx.u5.dwFillColor = color_convert_argb_to_fmt(fill_color, dst_surface->resource.format_desc->format);
4926 return IWineD3DBaseSurfaceImpl_Blt((IWineD3DSurface*)dst_surface, dst_rect, NULL, NULL, WINEDDBLT_COLORFILL, &BltFx, WINED3DTEXF_POINT);
4929 const struct blit_shader cpu_blit = {
4930 cpu_blit_alloc,
4931 cpu_blit_free,
4932 cpu_blit_set,
4933 cpu_blit_unset,
4934 cpu_blit_supported,
4935 cpu_blit_color_fill
4938 static BOOL fbo_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
4939 const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool,
4940 const struct wined3d_format_desc *src_format_desc,
4941 const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool,
4942 const struct wined3d_format_desc *dst_format_desc)
4944 if ((wined3d_settings.offscreen_rendering_mode != ORM_FBO) || !gl_info->fbo_ops.glBlitFramebuffer)
4945 return FALSE;
4947 /* We only support blitting. Things like color keying / color fill should
4948 * be handled by other blitters.
4950 if (blit_op != BLIT_OP_BLIT)
4951 return FALSE;
4953 /* Source and/or destination need to be on the GL side */
4954 if (src_pool == WINED3DPOOL_SYSTEMMEM || dst_pool == WINED3DPOOL_SYSTEMMEM)
4955 return FALSE;
4957 if(!((src_format_desc->Flags & WINED3DFMT_FLAG_FBO_ATTACHABLE) || (src_usage & WINED3DUSAGE_RENDERTARGET))
4958 && ((dst_format_desc->Flags & WINED3DFMT_FLAG_FBO_ATTACHABLE) || (dst_usage & WINED3DUSAGE_RENDERTARGET)))
4959 return FALSE;
4961 if (!is_identity_fixup(src_format_desc->color_fixup) ||
4962 !is_identity_fixup(dst_format_desc->color_fixup))
4963 return FALSE;
4965 if (!(src_format_desc->format == dst_format_desc->format
4966 || (is_identity_fixup(src_format_desc->color_fixup)
4967 && is_identity_fixup(dst_format_desc->color_fixup))))
4968 return FALSE;
4970 return TRUE;