wined3d: Call glFlush outside the GL lock.
[wine/multimedia.git] / dlls / wined3d / surface.c
blob10c8ab1a0fcfc41236bd0526e2af637414fa4963
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 Henri Verbeet
12 * Copyright 2006-2008 Roderick Colenbrander
14 * This library is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Lesser General Public
16 * License as published by the Free Software Foundation; either
17 * version 2.1 of the License, or (at your option) any later version.
19 * This library is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 * Lesser General Public License for more details.
24 * You should have received a copy of the GNU Lesser General Public
25 * License along with this library; if not, write to the Free Software
26 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
29 #include "config.h"
30 #include "wine/port.h"
31 #include "wined3d_private.h"
33 WINE_DEFAULT_DEBUG_CHANNEL(d3d_surface);
34 #define GLINFO_LOCATION This->resource.wineD3DDevice->adapter->gl_info
36 HRESULT d3dfmt_convert_surface(BYTE *src, BYTE *dst, UINT pitch, UINT width, UINT height, UINT outpitch, CONVERT_TYPES convert, IWineD3DSurfaceImpl *surf);
37 static void d3dfmt_p8_init_palette(IWineD3DSurfaceImpl *This, BYTE table[256][4], BOOL colorkey);
38 static void d3dfmt_p8_upload_palette(IWineD3DSurface *iface, CONVERT_TYPES convert);
39 static inline void clear_unused_channels(IWineD3DSurfaceImpl *This);
40 static void surface_remove_pbo(IWineD3DSurfaceImpl *This);
42 static void surface_bind_and_dirtify(IWineD3DSurfaceImpl *This) {
43 int active_sampler;
45 /* We don't need a specific texture unit, but after binding the texture the current unit is dirty.
46 * Read the unit back instead of switching to 0, this avoids messing around with the state manager's
47 * gl states. The current texture unit should always be a valid one.
49 * TODO: Track the current active texture per GL context instead of using glGet
51 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
52 GLint active_texture;
53 ENTER_GL();
54 glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
55 LEAVE_GL();
56 active_sampler = This->resource.wineD3DDevice->rev_tex_unit_map[active_texture - GL_TEXTURE0_ARB];
57 } else {
58 active_sampler = 0;
61 if (active_sampler != -1) {
62 IWineD3DDeviceImpl_MarkStateDirty(This->resource.wineD3DDevice, STATE_SAMPLER(active_sampler));
64 IWineD3DSurface_BindTexture((IWineD3DSurface *)This);
67 /* This function checks if the primary render target uses the 8bit paletted format. */
68 static BOOL primary_render_target_is_p8(IWineD3DDeviceImpl *device)
70 if (device->render_targets && device->render_targets[0]) {
71 IWineD3DSurfaceImpl* render_target = (IWineD3DSurfaceImpl*)device->render_targets[0];
72 if((render_target->resource.usage & WINED3DUSAGE_RENDERTARGET) && (render_target->resource.format == WINED3DFMT_P8))
73 return TRUE;
75 return FALSE;
78 /* This call just downloads data, the caller is responsible for activating the
79 * right context and binding the correct texture. */
80 static void surface_download_data(IWineD3DSurfaceImpl *This) {
81 if (0 == This->glDescription.textureName) {
82 ERR("Surface does not have a texture, but SFLAG_INTEXTURE is set\n");
83 return;
86 /* Only support read back of converted P8 surfaces */
87 if(This->Flags & SFLAG_CONVERTED && (This->resource.format != WINED3DFMT_P8)) {
88 FIXME("Read back converted textures unsupported, format=%s\n", debug_d3dformat(This->resource.format));
89 return;
92 ENTER_GL();
94 if (This->resource.format == WINED3DFMT_DXT1 ||
95 This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
96 This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5 ||
97 This->resource.format == WINED3DFMT_ATI2N) {
98 if (!GL_SUPPORT(EXT_TEXTURE_COMPRESSION_S3TC)) { /* We can assume this as the texture would not have been created otherwise */
99 FIXME("(%p) : Attempting to lock a compressed texture when texture compression isn't supported by opengl\n", This);
100 } else {
101 TRACE("(%p) : Calling glGetCompressedTexImageARB level %d, format %#x, type %#x, data %p\n", This, This->glDescription.level,
102 This->glDescription.glFormat, This->glDescription.glType, This->resource.allocatedMemory);
104 if(This->Flags & SFLAG_PBO) {
105 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
106 checkGLcall("glBindBufferARB");
107 GL_EXTCALL(glGetCompressedTexImageARB(This->glDescription.target, This->glDescription.level, NULL));
108 checkGLcall("glGetCompressedTexImageARB()");
109 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
110 checkGLcall("glBindBufferARB");
111 } else {
112 GL_EXTCALL(glGetCompressedTexImageARB(This->glDescription.target, This->glDescription.level, This->resource.allocatedMemory));
113 checkGLcall("glGetCompressedTexImageARB()");
116 LEAVE_GL();
117 } else {
118 void *mem;
119 GLenum format = This->glDescription.glFormat;
120 GLenum type = This->glDescription.glType;
121 int src_pitch = 0;
122 int dst_pitch = 0;
124 /* In case of P8 the index is stored in the alpha component if the primary render target uses P8 */
125 if(This->resource.format == WINED3DFMT_P8 && primary_render_target_is_p8(This->resource.wineD3DDevice)) {
126 format = GL_ALPHA;
127 type = GL_UNSIGNED_BYTE;
130 if (This->Flags & SFLAG_NONPOW2) {
131 unsigned char alignment = This->resource.wineD3DDevice->surface_alignment;
132 src_pitch = This->bytesPerPixel * This->pow2Width;
133 dst_pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This);
134 src_pitch = (src_pitch + alignment - 1) & ~(alignment - 1);
135 mem = HeapAlloc(GetProcessHeap(), 0, src_pitch * This->pow2Height);
136 } else {
137 mem = This->resource.allocatedMemory;
140 TRACE("(%p) : Calling glGetTexImage level %d, format %#x, type %#x, data %p\n", This, This->glDescription.level,
141 format, type, mem);
143 if(This->Flags & SFLAG_PBO) {
144 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
145 checkGLcall("glBindBufferARB");
147 glGetTexImage(This->glDescription.target, This->glDescription.level, format,
148 type, NULL);
149 checkGLcall("glGetTexImage()");
151 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
152 checkGLcall("glBindBufferARB");
153 } else {
154 glGetTexImage(This->glDescription.target, This->glDescription.level, format,
155 type, mem);
156 checkGLcall("glGetTexImage()");
158 LEAVE_GL();
160 if (This->Flags & SFLAG_NONPOW2) {
161 LPBYTE src_data, dst_data;
162 int y;
164 * Some games (e.g. warhammer 40k) don't work properly with the odd pitches, preventing
165 * the surface pitch from being used to box non-power2 textures. Instead we have to use a hack to
166 * repack the texture so that the bpp * width pitch can be used instead of bpp * pow2width.
168 * We're doing this...
170 * instead of boxing the texture :
171 * |<-texture width ->| -->pow2width| /\
172 * |111111111111111111| | |
173 * |222 Texture 222222| boxed empty | texture height
174 * |3333 Data 33333333| | |
175 * |444444444444444444| | \/
176 * ----------------------------------- |
177 * | boxed empty | boxed empty | pow2height
178 * | | | \/
179 * -----------------------------------
182 * we're repacking the data to the expected texture width
184 * |<-texture width ->| -->pow2width| /\
185 * |111111111111111111222222222222222| |
186 * |222333333333333333333444444444444| texture height
187 * |444444 | |
188 * | | \/
189 * | | |
190 * | empty | pow2height
191 * | | \/
192 * -----------------------------------
194 * == is the same as
196 * |<-texture width ->| /\
197 * |111111111111111111|
198 * |222222222222222222|texture height
199 * |333333333333333333|
200 * |444444444444444444| \/
201 * --------------------
203 * this also means that any references to allocatedMemory should work with the data as if were a
204 * standard texture with a non-power2 width instead of texture boxed up to be a power2 texture.
206 * internally the texture is still stored in a boxed format so any references to textureName will
207 * get a boxed texture with width pow2width and not a texture of width currentDesc.Width.
209 * Performance should not be an issue, because applications normally do not lock the surfaces when
210 * rendering. If an app does, the SFLAG_DYNLOCK flag will kick in and the memory copy won't be released,
211 * and doesn't have to be re-read.
213 src_data = mem;
214 dst_data = This->resource.allocatedMemory;
215 TRACE("(%p) : Repacking the surface data from pitch %d to pitch %d\n", This, src_pitch, dst_pitch);
216 for (y = 1 ; y < This->currentDesc.Height; y++) {
217 /* skip the first row */
218 src_data += src_pitch;
219 dst_data += dst_pitch;
220 memcpy(dst_data, src_data, dst_pitch);
223 HeapFree(GetProcessHeap(), 0, mem);
227 /* Surface has now been downloaded */
228 This->Flags |= SFLAG_INSYSMEM;
231 /* This call just uploads data, the caller is responsible for activating the
232 * right context and binding the correct texture. */
233 static void surface_upload_data(IWineD3DSurfaceImpl *This, GLenum internal, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *data) {
234 if (This->resource.format == WINED3DFMT_DXT1 ||
235 This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
236 This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5 ||
237 This->resource.format == WINED3DFMT_ATI2N) {
238 if (!GL_SUPPORT(EXT_TEXTURE_COMPRESSION_S3TC)) {
239 FIXME("Using DXT1/3/5 without advertized support\n");
240 } else {
241 /* glCompressedTexSubImage2D for uploading and glTexImage2D for allocating does not work well on some drivers(r200 dri, MacOS ATI driver)
242 * glCompressedTexImage2D does not accept NULL pointers. So for compressed textures surface_allocate_surface does nothing, and this
243 * function uses glCompressedTexImage2D instead of the SubImage call
245 TRACE("(%p) : Calling glCompressedTexSubImage2D w %d, h %d, data %p\n", This, width, height, data);
246 ENTER_GL();
248 if(This->Flags & SFLAG_PBO) {
249 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
250 checkGLcall("glBindBufferARB");
251 TRACE("(%p) pbo: %#x, data: %p\n", This, This->pbo, data);
253 GL_EXTCALL(glCompressedTexImage2DARB(This->glDescription.target, This->glDescription.level, internal,
254 width, height, 0 /* border */, This->resource.size, NULL));
255 checkGLcall("glCompressedTexSubImage2D");
257 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
258 checkGLcall("glBindBufferARB");
259 } else {
260 GL_EXTCALL(glCompressedTexImage2DARB(This->glDescription.target, This->glDescription.level, internal,
261 width, height, 0 /* border */, This->resource.size, data));
262 checkGLcall("glCompressedTexSubImage2D");
264 LEAVE_GL();
266 } else {
267 TRACE("(%p) : Calling glTexSubImage2D w %d, h %d, data, %p\n", This, width, height, data);
268 ENTER_GL();
270 if(This->Flags & SFLAG_PBO) {
271 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
272 checkGLcall("glBindBufferARB");
273 TRACE("(%p) pbo: %#x, data: %p\n", This, This->pbo, data);
275 glTexSubImage2D(This->glDescription.target, This->glDescription.level, 0, 0, width, height, format, type, NULL);
276 checkGLcall("glTexSubImage2D");
278 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
279 checkGLcall("glBindBufferARB");
281 else {
282 glTexSubImage2D(This->glDescription.target, This->glDescription.level, 0, 0, width, height, format, type, data);
283 checkGLcall("glTexSubImage2D");
286 LEAVE_GL();
290 /* This call just allocates the texture, the caller is responsible for
291 * activating the right context and binding the correct texture. */
292 static void surface_allocate_surface(IWineD3DSurfaceImpl *This, GLenum internal, GLsizei width, GLsizei height, GLenum format, GLenum type) {
293 BOOL enable_client_storage = FALSE;
294 BYTE *mem = NULL;
296 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", This,
297 This->glDescription.target, This->glDescription.level, debug_d3dformat(This->resource.format), internal, width, height, format, type);
299 if (This->resource.format == WINED3DFMT_DXT1 ||
300 This->resource.format == WINED3DFMT_DXT2 || This->resource.format == WINED3DFMT_DXT3 ||
301 This->resource.format == WINED3DFMT_DXT4 || This->resource.format == WINED3DFMT_DXT5 ||
302 This->resource.format == WINED3DFMT_ATI2N) {
303 /* glCompressedTexImage2D does not accept NULL pointers, so we cannot allocate a compressed texture without uploading data */
304 TRACE("Not allocating compressed surfaces, surface_upload_data will specify them\n");
306 /* We have to point GL to the client storage memory here, because upload_data might use a PBO. This means a double upload
307 * once, unfortunately
309 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
310 /* Neither NONPOW2, DIBSECTION nor OVERSIZE flags can be set on compressed textures */
311 This->Flags |= SFLAG_CLIENT;
312 mem = (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
313 ENTER_GL();
314 GL_EXTCALL(glCompressedTexImage2DARB(This->glDescription.target, This->glDescription.level, internal,
315 width, height, 0 /* border */, This->resource.size, mem));
316 LEAVE_GL();
319 return;
322 ENTER_GL();
324 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
325 if(This->Flags & (SFLAG_NONPOW2 | SFLAG_DIBSECTION | SFLAG_OVERSIZE | SFLAG_CONVERTED) || This->resource.allocatedMemory == NULL) {
326 /* In some cases we want to disable client storage.
327 * SFLAG_NONPOW2 has a bigger opengl texture than the client memory, and different pitches
328 * SFLAG_DIBSECTION: Dibsections may have read / write protections on the memory. Avoid issues...
329 * SFLAG_OVERSIZE: The gl texture is smaller than the allocated memory
330 * SFLAG_CONVERTED: The conversion destination memory is freed after loading the surface
331 * allocatedMemory == NULL: Not defined in the extension. Seems to disable client storage effectively
333 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
334 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
335 This->Flags &= ~SFLAG_CLIENT;
336 enable_client_storage = TRUE;
337 } else {
338 This->Flags |= SFLAG_CLIENT;
340 /* Point opengl to our allocated texture memory. Do not use resource.allocatedMemory here because
341 * it might point into a pbo. Instead use heapMemory, but get the alignment right.
343 mem = (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
346 glTexImage2D(This->glDescription.target, This->glDescription.level, internal, width, height, 0, format, type, mem);
347 checkGLcall("glTexImage2D");
349 if(enable_client_storage) {
350 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
351 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
353 LEAVE_GL();
355 This->Flags |= SFLAG_ALLOCATED;
358 /* In D3D the depth stencil dimensions have to be greater than or equal to the
359 * render target dimensions. With FBOs, the dimensions have to be an exact match. */
360 /* TODO: We should synchronize the renderbuffer's content with the texture's content. */
361 void surface_set_compatible_renderbuffer(IWineD3DSurface *iface, unsigned int width, unsigned int height) {
362 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
363 renderbuffer_entry_t *entry;
364 GLuint renderbuffer = 0;
365 unsigned int src_width, src_height;
367 src_width = This->pow2Width;
368 src_height = This->pow2Height;
370 /* A depth stencil smaller than the render target is not valid */
371 if (width > src_width || height > src_height) return;
373 /* Remove any renderbuffer set if the sizes match */
374 if (width == src_width && height == src_height) {
375 This->current_renderbuffer = NULL;
376 return;
379 /* Look if we've already got a renderbuffer of the correct dimensions */
380 LIST_FOR_EACH_ENTRY(entry, &This->renderbuffers, renderbuffer_entry_t, entry) {
381 if (entry->width == width && entry->height == height) {
382 renderbuffer = entry->id;
383 This->current_renderbuffer = entry;
384 break;
388 if (!renderbuffer) {
389 const GlPixelFormatDesc *glDesc;
390 getFormatDescEntry(This->resource.format, &GLINFO_LOCATION, &glDesc);
392 GL_EXTCALL(glGenRenderbuffersEXT(1, &renderbuffer));
393 GL_EXTCALL(glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, renderbuffer));
394 GL_EXTCALL(glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, glDesc->glFormat, width, height));
396 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(renderbuffer_entry_t));
397 entry->width = width;
398 entry->height = height;
399 entry->id = renderbuffer;
400 list_add_head(&This->renderbuffers, &entry->entry);
402 This->current_renderbuffer = entry;
405 checkGLcall("set_compatible_renderbuffer");
408 GLenum surface_get_gl_buffer(IWineD3DSurface *iface, IWineD3DSwapChain *swapchain) {
409 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
410 IWineD3DSwapChainImpl *swapchain_impl = (IWineD3DSwapChainImpl *)swapchain;
412 TRACE("(%p) : swapchain %p\n", This, swapchain);
414 if (swapchain_impl->backBuffer && swapchain_impl->backBuffer[0] == iface) {
415 TRACE("Returning GL_BACK\n");
416 return GL_BACK;
417 } else if (swapchain_impl->frontBuffer == iface) {
418 TRACE("Returning GL_FRONT\n");
419 return GL_FRONT;
422 FIXME("Higher back buffer, returning GL_BACK\n");
423 return GL_BACK;
426 ULONG WINAPI IWineD3DSurfaceImpl_Release(IWineD3DSurface *iface) {
427 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
428 ULONG ref = InterlockedDecrement(&This->resource.ref);
429 TRACE("(%p) : Releasing from %d\n", This, ref + 1);
430 if (ref == 0) {
431 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
432 renderbuffer_entry_t *entry, *entry2;
433 TRACE("(%p) : cleaning up\n", This);
435 /* Need a context to destroy the texture. Use the currently active render target, but only if
436 * the primary render target exists. Otherwise lastActiveRenderTarget is garbage, see above.
437 * When destroying the primary rt, Uninit3D will activate a context before doing anything
439 if(device->render_targets && device->render_targets[0]) {
440 ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
443 ENTER_GL();
444 if (This->glDescription.textureName != 0) { /* release the openGL texture.. */
445 TRACE("Deleting texture %d\n", This->glDescription.textureName);
446 glDeleteTextures(1, &This->glDescription.textureName);
449 if(This->Flags & SFLAG_PBO) {
450 /* Delete the PBO */
451 GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
454 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry) {
455 GL_EXTCALL(glDeleteRenderbuffersEXT(1, &entry->id));
456 HeapFree(GetProcessHeap(), 0, entry);
458 LEAVE_GL();
460 if(This->Flags & SFLAG_DIBSECTION) {
461 /* Release the DC */
462 SelectObject(This->hDC, This->dib.holdbitmap);
463 DeleteDC(This->hDC);
464 /* Release the DIB section */
465 DeleteObject(This->dib.DIBsection);
466 This->dib.bitmap_data = NULL;
467 This->resource.allocatedMemory = NULL;
469 if(This->Flags & SFLAG_USERPTR) IWineD3DSurface_SetMem(iface, NULL);
471 HeapFree(GetProcessHeap(), 0, This->palette9);
473 IWineD3DResourceImpl_CleanUp((IWineD3DResource *)iface);
474 if(iface == device->ddraw_primary)
475 device->ddraw_primary = NULL;
477 TRACE("(%p) Released\n", This);
478 HeapFree(GetProcessHeap(), 0, This);
481 return ref;
484 /* ****************************************************
485 IWineD3DSurface IWineD3DResource parts follow
486 **************************************************** */
488 void WINAPI IWineD3DSurfaceImpl_PreLoad(IWineD3DSurface *iface) {
489 /* TODO: check for locks */
490 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
491 IWineD3DBaseTexture *baseTexture = NULL;
492 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
494 TRACE("(%p)Checking to see if the container is a base texture\n", This);
495 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
496 TRACE("Passing to container\n");
497 IWineD3DBaseTexture_PreLoad(baseTexture);
498 IWineD3DBaseTexture_Release(baseTexture);
499 } else {
500 TRACE("(%p) : About to load surface\n", This);
502 if(!device->isInDraw) {
503 ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
506 if (This->resource.format == WINED3DFMT_P8 || This->resource.format == WINED3DFMT_A8P8) {
507 if(palette9_changed(This)) {
508 TRACE("Reloading surface because the d3d8/9 palette was changed\n");
509 /* TODO: This is not necessarily needed with hw palettized texture support */
510 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
511 /* Make sure the texture is reloaded because of the palette change, this kills performance though :( */
512 IWineD3DSurface_ModifyLocation(iface, SFLAG_INTEXTURE, FALSE);
515 ENTER_GL();
516 glEnable(This->glDescription.target);/* make sure texture support is enabled in this context */
517 if (!This->glDescription.level) {
518 if (!This->glDescription.textureName) {
519 glGenTextures(1, &This->glDescription.textureName);
520 checkGLcall("glGenTextures");
521 TRACE("Surface %p given name %d\n", This, This->glDescription.textureName);
523 glBindTexture(This->glDescription.target, This->glDescription.textureName);
524 checkGLcall("glBindTexture");
525 LEAVE_GL();
526 IWineD3DSurface_LoadTexture(iface, FALSE);
527 /* This is where we should be reducing the amount of GLMemoryUsed */
528 } else if (This->glDescription.textureName) { /* NOTE: the level 0 surface of a mpmapped texture must be loaded first! */
529 /* assume this is a coding error not a real error for now */
530 FIXME("Mipmap surface has a glTexture bound to it!\n");
531 LEAVE_GL();
533 if (This->resource.pool == WINED3DPOOL_DEFAULT) {
534 /* Tell opengl to try and keep this texture in video ram (well mostly) */
535 GLclampf tmp;
536 tmp = 0.9f;
537 ENTER_GL();
538 glPrioritizeTextures(1, &This->glDescription.textureName, &tmp);
539 LEAVE_GL();
542 return;
545 static void surface_remove_pbo(IWineD3DSurfaceImpl *This) {
546 This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
547 This->resource.allocatedMemory =
548 (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
550 ENTER_GL();
551 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
552 checkGLcall("glBindBuffer(GL_PIXEL_UNPACK_BUFFER, This->pbo)");
553 GL_EXTCALL(glGetBufferSubDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0, This->resource.size, This->resource.allocatedMemory));
554 checkGLcall("glGetBufferSubData");
555 GL_EXTCALL(glDeleteBuffersARB(1, &This->pbo));
556 checkGLcall("glDeleteBuffers");
557 LEAVE_GL();
559 This->pbo = 0;
560 This->Flags &= ~SFLAG_PBO;
563 static void WINAPI IWineD3DSurfaceImpl_UnLoad(IWineD3DSurface *iface) {
564 IWineD3DBaseTexture *texture = NULL;
565 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
566 renderbuffer_entry_t *entry, *entry2;
567 TRACE("(%p)\n", iface);
569 if(This->resource.pool == WINED3DPOOL_DEFAULT) {
570 /* Default pool resources are supposed to be destroyed before Reset is called.
571 * Implicit resources stay however. So this means we have an implicit render target
572 * or depth stencil. The content may be destroyed, but we still have to tear down
573 * opengl resources, so we cannot leave early.
575 * Put the most up to date surface location into the drawable. D3D-wise this content
576 * is undefined, so it would be nowhere, but that would make the location management
577 * more complicated. The drawable is a sane location, because if we mark sysmem or
578 * texture up to date, drawPrim will copy the uninitialized texture or sysmem to the
579 * uninitialized drawable. That's pointless and we'd have to allocate the texture /
580 * sysmem copy here.
582 if (This->resource.usage & WINED3DUSAGE_DEPTHSTENCIL) {
583 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
584 } else {
585 IWineD3DSurface_ModifyLocation(iface, SFLAG_INDRAWABLE, TRUE);
587 } else {
588 /* Load the surface into system memory */
589 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
590 IWineD3DSurface_ModifyLocation(iface, SFLAG_INDRAWABLE, FALSE);
592 IWineD3DSurface_ModifyLocation(iface, SFLAG_INTEXTURE, FALSE);
593 This->Flags &= ~SFLAG_ALLOCATED;
595 /* Destroy PBOs, but load them into real sysmem before */
596 if(This->Flags & SFLAG_PBO) {
597 surface_remove_pbo(This);
600 /* Destroy fbo render buffers. This is needed for implicit render targets, for
601 * all application-created targets the application has to release the surface
602 * before calling _Reset
604 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->renderbuffers, renderbuffer_entry_t, entry) {
605 ENTER_GL();
606 GL_EXTCALL(glDeleteRenderbuffersEXT(1, &entry->id));
607 LEAVE_GL();
608 list_remove(&entry->entry);
609 HeapFree(GetProcessHeap(), 0, entry);
611 list_init(&This->renderbuffers);
612 This->current_renderbuffer = NULL;
614 /* If we're in a texture, the texture name belongs to the texture. Otherwise,
615 * destroy it
617 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **) &texture);
618 if(!texture) {
619 ENTER_GL();
620 glDeleteTextures(1, &This->glDescription.textureName);
621 This->glDescription.textureName = 0;
622 LEAVE_GL();
623 } else {
624 IWineD3DBaseTexture_Release(texture);
626 return;
629 /* ******************************************************
630 IWineD3DSurface IWineD3DSurface parts follow
631 ****************************************************** */
633 void WINAPI IWineD3DSurfaceImpl_SetGlTextureDesc(IWineD3DSurface *iface, UINT textureName, int target) {
634 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
635 TRACE("(%p) : setting textureName %u, target %i\n", This, textureName, target);
636 if (This->glDescription.textureName == 0 && textureName != 0) {
637 IWineD3DSurface_ModifyLocation(iface, SFLAG_INTEXTURE, FALSE);
638 if((This->Flags & SFLAG_LOCATIONS) == 0) {
639 /* In 1.0-rc4 and earlier, AddDirtyRect was called in the place of this if condition.
640 * This had the problem that a correctly set INDRAWABLE flag was removed if the PreLoad
641 * during the offscreen rendering readback triggered the creation of the GL texture.
642 * The change intended to keep the INDRAWABLE intact. To prevent unintended side effects
643 * before release, set the INSYSMEM flag like the old AddDirtyRect did.
645 WARN("Wine 1.0 safety path hit\n");
646 This->Flags |= SFLAG_INSYSMEM;
649 if(target == GL_TEXTURE_RECTANGLE_ARB && This->glDescription.target != target) {
650 This->Flags &= ~SFLAG_NORMCOORD;
651 } else if(This->glDescription.target == GL_TEXTURE_RECTANGLE_ARB && target != GL_TEXTURE_RECTANGLE_ARB) {
652 This->Flags |= SFLAG_NORMCOORD;
654 This->glDescription.textureName = textureName;
655 This->glDescription.target = target;
656 This->Flags &= ~SFLAG_ALLOCATED;
659 void WINAPI IWineD3DSurfaceImpl_GetGlDesc(IWineD3DSurface *iface, glDescriptor **glDescription) {
660 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
661 TRACE("(%p) : returning %p\n", This, &This->glDescription);
662 *glDescription = &This->glDescription;
665 /* TODO: think about moving this down to resource? */
666 const void *WINAPI IWineD3DSurfaceImpl_GetData(IWineD3DSurface *iface) {
667 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
668 /* This should only be called for sysmem textures, it may be a good idea to extend this to all pools at some point in the future */
669 if (This->resource.pool != WINED3DPOOL_SYSTEMMEM) {
670 FIXME(" (%p)Attempting to get system memory for a non-system memory texture\n", iface);
672 return (CONST void*)(This->resource.allocatedMemory);
675 /* Read the framebuffer back into the surface */
676 static void read_from_framebuffer(IWineD3DSurfaceImpl *This, CONST RECT *rect, void *dest, UINT pitch) {
677 IWineD3DSwapChainImpl *swapchain;
678 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
679 BYTE *mem;
680 GLint fmt;
681 GLint type;
682 BYTE *row, *top, *bottom;
683 int i;
684 BOOL bpp;
685 RECT local_rect;
686 BOOL srcIsUpsideDown;
688 if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
689 static BOOL warned = FALSE;
690 if(!warned) {
691 ERR("The application tries to lock the render target, but render target locking is disabled\n");
692 warned = TRUE;
694 return;
697 IWineD3DSurface_GetContainer((IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&swapchain);
698 /* Activate the surface. Set it up for blitting now, although not necessarily needed for LockRect.
699 * Certain graphics drivers seem to dislike some enabled states when reading from opengl, the blitting usage
700 * should help here. Furthermore unlockrect will need the context set up for blitting. The context manager will find
701 * context->last_was_blit set on the unlock.
703 ActivateContext(myDevice, (IWineD3DSurface *) This, CTXUSAGE_BLIT);
704 ENTER_GL();
706 /* Select the correct read buffer, and give some debug output.
707 * There is no need to keep track of the current read buffer or reset it, every part of the code
708 * that reads sets the read buffer as desired.
710 if(!swapchain) {
711 /* Locking the primary render target which is not on a swapchain(=offscreen render target).
712 * Read from the back buffer
714 TRACE("Locking offscreen render target\n");
715 glReadBuffer(myDevice->offscreenBuffer);
716 srcIsUpsideDown = TRUE;
717 } else {
718 GLenum buffer = surface_get_gl_buffer((IWineD3DSurface *) This, (IWineD3DSwapChain *)swapchain);
719 TRACE("Locking %#x buffer\n", buffer);
720 glReadBuffer(buffer);
721 checkGLcall("glReadBuffer");
723 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
724 srcIsUpsideDown = FALSE;
727 /* TODO: Get rid of the extra rectangle comparison and construction of a full surface rectangle */
728 if(!rect) {
729 local_rect.left = 0;
730 local_rect.top = 0;
731 local_rect.right = This->currentDesc.Width;
732 local_rect.bottom = This->currentDesc.Height;
733 } else {
734 local_rect = *rect;
736 /* TODO: Get rid of the extra GetPitch call, LockRect does that too. Cache the pitch */
738 switch(This->resource.format)
740 case WINED3DFMT_P8:
742 if(primary_render_target_is_p8(myDevice)) {
743 /* In case of P8 render targets the index is stored in the alpha component */
744 fmt = GL_ALPHA;
745 type = GL_UNSIGNED_BYTE;
746 mem = dest;
747 bpp = This->bytesPerPixel;
748 } else {
749 /* GL can't return palettized data, so read ARGB pixels into a
750 * separate block of memory and convert them into palettized format
751 * in software. Slow, but if the app means to use palettized render
752 * targets and locks it...
754 * Use GL_RGB, GL_UNSIGNED_BYTE to read the surface for performance reasons
755 * Don't use GL_BGR as in the WINED3DFMT_R8G8B8 case, instead watch out
756 * for the color channels when palettizing the colors.
758 fmt = GL_RGB;
759 type = GL_UNSIGNED_BYTE;
760 pitch *= 3;
761 mem = HeapAlloc(GetProcessHeap(), 0, This->resource.size * 3);
762 if(!mem) {
763 ERR("Out of memory\n");
764 LEAVE_GL();
765 return;
767 bpp = This->bytesPerPixel * 3;
770 break;
772 default:
773 mem = dest;
774 fmt = This->glDescription.glFormat;
775 type = This->glDescription.glType;
776 bpp = This->bytesPerPixel;
779 if(This->Flags & SFLAG_PBO) {
780 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, This->pbo));
781 checkGLcall("glBindBufferARB");
784 glReadPixels(local_rect.left, local_rect.top,
785 local_rect.right - local_rect.left,
786 local_rect.bottom - local_rect.top,
787 fmt, type, mem);
788 vcheckGLcall("glReadPixels");
790 if(This->Flags & SFLAG_PBO) {
791 GL_EXTCALL(glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0));
792 checkGLcall("glBindBufferARB");
794 /* Check if we need to flip the image. If we need to flip use glMapBufferARB
795 * to get a pointer to it and perform the flipping in software. This is a lot
796 * faster than calling glReadPixels for each line. In case we want more speed
797 * we should rerender it flipped in a FBO and read the data back from the FBO. */
798 if(!srcIsUpsideDown) {
799 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
800 checkGLcall("glBindBufferARB");
802 mem = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
803 checkGLcall("glMapBufferARB");
807 /* TODO: Merge this with the palettization loop below for P8 targets */
808 if(!srcIsUpsideDown) {
809 UINT len, off;
810 /* glReadPixels returns the image upside down, and there is no way to prevent this.
811 Flip the lines in software */
812 len = (local_rect.right - local_rect.left) * bpp;
813 off = local_rect.left * bpp;
815 row = HeapAlloc(GetProcessHeap(), 0, len);
816 if(!row) {
817 ERR("Out of memory\n");
818 if(This->resource.format == WINED3DFMT_P8) HeapFree(GetProcessHeap(), 0, mem);
819 LEAVE_GL();
820 return;
823 top = mem + pitch * local_rect.top;
824 bottom = mem + pitch * ( local_rect.bottom - local_rect.top - 1);
825 for(i = 0; i < (local_rect.bottom - local_rect.top) / 2; i++) {
826 memcpy(row, top + off, len);
827 memcpy(top + off, bottom + off, len);
828 memcpy(bottom + off, row, len);
829 top += pitch;
830 bottom -= pitch;
832 HeapFree(GetProcessHeap(), 0, row);
834 /* Unmap the temp PBO buffer */
835 if(This->Flags & SFLAG_PBO) {
836 GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
837 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
841 LEAVE_GL();
843 /* For P8 textures we need to perform an inverse palette lookup. This is done by searching for a palette
844 * index which matches the RGB value. Note this isn't guaranteed to work when there are multiple entries for
845 * the same color but we have no choice.
846 * In case of P8 render targets, the index is stored in the alpha component so no conversion is needed.
848 if((This->resource.format == WINED3DFMT_P8) && !primary_render_target_is_p8(myDevice)) {
849 PALETTEENTRY *pal = NULL;
850 DWORD width = pitch / 3;
851 int x, y, c;
853 if(This->palette) {
854 pal = This->palette->palents;
855 } else {
856 ERR("Palette is missing, cannot perform inverse palette lookup\n");
857 HeapFree(GetProcessHeap(), 0, mem);
858 return ;
861 for(y = local_rect.top; y < local_rect.bottom; y++) {
862 for(x = local_rect.left; x < local_rect.right; x++) {
863 /* start lines pixels */
864 BYTE *blue = mem + y * pitch + x * (sizeof(BYTE) * 3);
865 BYTE *green = blue + 1;
866 BYTE *red = green + 1;
868 for(c = 0; c < 256; c++) {
869 if(*red == pal[c].peRed &&
870 *green == pal[c].peGreen &&
871 *blue == pal[c].peBlue)
873 *((BYTE *) dest + y * width + x) = c;
874 break;
879 HeapFree(GetProcessHeap(), 0, mem);
883 /* Read the framebuffer contents into a texture */
884 static void read_from_framebuffer_texture(IWineD3DSurfaceImpl *This)
886 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
887 IWineD3DSwapChainImpl *swapchain;
888 int bpp;
889 GLenum format, internal, type;
890 CONVERT_TYPES convert;
891 GLint prevRead;
893 d3dfmt_get_conv(This, TRUE /* We need color keying */, TRUE /* We will use textures */, &format, &internal, &type, &convert, &bpp, This->srgb);
895 IWineD3DSurface_GetContainer((IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&swapchain);
896 /* Activate the surface to read from. In some situations it isn't the currently active target(e.g. backbuffer
897 * locking during offscreen rendering). RESOURCELOAD is ok because glCopyTexSubImage2D isn't affected by any
898 * states in the stateblock, and no driver was found yet that had bugs in that regard.
900 ActivateContext(device, (IWineD3DSurface *) This, CTXUSAGE_RESOURCELOAD);
901 surface_bind_and_dirtify(This);
902 ENTER_GL();
904 glGetIntegerv(GL_READ_BUFFER, &prevRead);
906 /* Select the correct read buffer, and give some debug output.
907 * There is no need to keep track of the current read buffer or reset it, every part of the code
908 * that reads sets the read buffer as desired.
910 if(!swapchain) {
911 /* Locking the primary render target which is not on a swapchain(=offscreen render target).
912 * Read from the back buffer
914 TRACE("Locking offscreen render target\n");
915 glReadBuffer(device->offscreenBuffer);
916 } else {
917 GLenum buffer = surface_get_gl_buffer((IWineD3DSurface *) This, (IWineD3DSwapChain *)swapchain);
918 TRACE("Locking %#x buffer\n", buffer);
919 glReadBuffer(buffer);
920 checkGLcall("glReadBuffer");
922 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
925 if(!(This->Flags & SFLAG_ALLOCATED)) {
926 surface_allocate_surface(This, internal, This->pow2Width,
927 This->pow2Height, format, type);
930 clear_unused_channels(This);
932 /* If !SrcIsUpsideDown we should flip the surface.
933 * This can be done using glCopyTexSubImage2D but this
934 * is VERY slow, so don't do that. We should prevent
935 * this code from getting called in such cases or perhaps
936 * we can use FBOs */
938 glCopyTexSubImage2D(This->glDescription.target,
939 This->glDescription.level,
940 0, 0, 0, 0,
941 This->currentDesc.Width,
942 This->currentDesc.Height);
943 checkGLcall("glCopyTexSubImage2D");
945 glReadBuffer(prevRead);
946 vcheckGLcall("glReadBuffer");
948 LEAVE_GL();
949 TRACE("Updated target %d\n", This->glDescription.target);
952 static void surface_prepare_system_memory(IWineD3DSurfaceImpl *This) {
953 /* Performance optimization: Count how often a surface is locked, if it is locked regularly do not throw away the system memory copy.
954 * This avoids the need to download the surface from opengl all the time. The surface is still downloaded if the opengl texture is
955 * changed
957 if(!(This->Flags & SFLAG_DYNLOCK)) {
958 This->lockCount++;
959 /* MAXLOCKCOUNT is defined in wined3d_private.h */
960 if(This->lockCount > MAXLOCKCOUNT) {
961 TRACE("Surface is locked regularly, not freeing the system memory copy any more\n");
962 This->Flags |= SFLAG_DYNLOCK;
966 /* Create a PBO for dynamically locked surfaces but don't do it for converted or non-pow2 surfaces.
967 * Also don't create a PBO for systemmem surfaces.
969 if(GL_SUPPORT(ARB_PIXEL_BUFFER_OBJECT) && (This->Flags & SFLAG_DYNLOCK) && !(This->Flags & (SFLAG_PBO | SFLAG_CONVERTED | SFLAG_NONPOW2)) && (This->resource.pool != WINED3DPOOL_SYSTEMMEM)) {
970 GLenum error;
971 ENTER_GL();
973 GL_EXTCALL(glGenBuffersARB(1, &This->pbo));
974 error = glGetError();
975 if(This->pbo == 0 || error != GL_NO_ERROR) {
976 ERR("Failed to bind the PBO with error %s (%#x)\n", debug_glerror(error), error);
979 TRACE("Attaching pbo=%#x to (%p)\n", This->pbo, This);
981 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
982 checkGLcall("glBindBufferARB");
984 GL_EXTCALL(glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->resource.size + 4, This->resource.allocatedMemory, GL_STREAM_DRAW_ARB));
985 checkGLcall("glBufferDataARB");
987 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
988 checkGLcall("glBindBufferARB");
990 /* We don't need the system memory anymore and we can't even use it for PBOs */
991 if(!(This->Flags & SFLAG_CLIENT)) {
992 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
993 This->resource.heapMemory = NULL;
995 This->resource.allocatedMemory = NULL;
996 This->Flags |= SFLAG_PBO;
997 LEAVE_GL();
998 } else if(!(This->resource.allocatedMemory || This->Flags & SFLAG_PBO)) {
999 /* Whatever surface we have, make sure that there is memory allocated for the downloaded copy,
1000 * or a pbo to map
1002 if(!This->resource.heapMemory) {
1003 This->resource.heapMemory = HeapAlloc(GetProcessHeap() ,0 , This->resource.size + RESOURCE_ALIGNMENT);
1005 This->resource.allocatedMemory =
1006 (BYTE *)(((ULONG_PTR) This->resource.heapMemory + (RESOURCE_ALIGNMENT - 1)) & ~(RESOURCE_ALIGNMENT - 1));
1007 if(This->Flags & SFLAG_INSYSMEM) {
1008 ERR("Surface without memory or pbo has SFLAG_INSYSMEM set!\n");
1013 static HRESULT WINAPI IWineD3DSurfaceImpl_LockRect(IWineD3DSurface *iface, WINED3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags) {
1014 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1015 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
1016 IWineD3DSwapChain *swapchain = NULL;
1018 TRACE("(%p) : rect@%p flags(%08x), output lockedRect@%p, memory@%p\n", This, pRect, Flags, pLockedRect, This->resource.allocatedMemory);
1020 /* This is also done in the base class, but we have to verify this before loading any data from
1021 * gl into the sysmem copy. The PBO may be mapped, a different rectangle locked, the discard flag
1022 * may interfere, and all other bad things may happen
1024 if (This->Flags & SFLAG_LOCKED) {
1025 WARN("Surface is already locked, returning D3DERR_INVALIDCALL\n");
1026 return WINED3DERR_INVALIDCALL;
1028 This->Flags |= SFLAG_LOCKED;
1030 if (!(This->Flags & SFLAG_LOCKABLE))
1032 TRACE("Warning: trying to lock unlockable surf@%p\n", This);
1035 if (Flags & WINED3DLOCK_DISCARD) {
1036 /* Set SFLAG_INSYSMEM, so we'll never try to download the data from the texture. */
1037 TRACE("WINED3DLOCK_DISCARD flag passed, marking local copy as up to date\n");
1038 surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1039 This->Flags |= SFLAG_INSYSMEM;
1040 goto lock_end;
1043 if (This->Flags & SFLAG_INSYSMEM) {
1044 TRACE("Local copy is up to date, not downloading data\n");
1045 surface_prepare_system_memory(This); /* Makes sure memory is allocated */
1046 goto lock_end;
1049 /* Now download the surface content from opengl
1050 * Use the render target readback if the surface is on a swapchain(=onscreen render target) or the current primary target
1051 * Offscreen targets which are not active at the moment or are higher targets(FBOs) can be locked with the texture path
1053 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain);
1054 if(swapchain || iface == myDevice->render_targets[0]) {
1055 const RECT *pass_rect = pRect;
1057 /* IWineD3DSurface_LoadLocation does not check if the rectangle specifies the full surfaces
1058 * because most caller functions do not need that. So do that here
1060 if(pRect &&
1061 pRect->top == 0 &&
1062 pRect->left == 0 &&
1063 pRect->right == This->currentDesc.Width &&
1064 pRect->bottom == This->currentDesc.Height) {
1065 pass_rect = NULL;
1068 switch(wined3d_settings.rendertargetlock_mode) {
1069 case RTL_TEXDRAW:
1070 case RTL_TEXTEX:
1071 FIXME("Reading from render target with a texture isn't implemented yet, falling back to framebuffer reading\n");
1072 #if 0
1073 /* Disabled for now. LoadLocation prefers the texture over the drawable as the source. So if we copy to the
1074 * texture first, then to sysmem, we'll avoid glReadPixels and use glCopyTexImage and glGetTexImage2D instead.
1075 * This may be faster on some cards
1077 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL /* No partial texture copy yet */);
1078 #endif
1079 /* drop through */
1081 case RTL_AUTO:
1082 case RTL_READDRAW:
1083 case RTL_READTEX:
1084 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, pRect);
1085 break;
1087 case RTL_DISABLE:
1088 break;
1090 if(swapchain) IWineD3DSwapChain_Release(swapchain);
1092 } else if(iface == myDevice->stencilBufferTarget) {
1093 /** the depth stencil in openGL has a format of GL_FLOAT
1094 * which should be good for WINED3DFMT_D16_LOCKABLE
1095 * and WINED3DFMT_D16
1096 * it is unclear what format the stencil buffer is in except.
1097 * 'Each index is converted to fixed point...
1098 * If GL_MAP_STENCIL is GL_TRUE, indices are replaced by their
1099 * mappings in the table GL_PIXEL_MAP_S_TO_S.
1100 * glReadPixels(This->lockedRect.left,
1101 * This->lockedRect.bottom - j - 1,
1102 * This->lockedRect.right - This->lockedRect.left,
1103 * 1,
1104 * GL_DEPTH_COMPONENT,
1105 * type,
1106 * (char *)pLockedRect->pBits + (pLockedRect->Pitch * (j-This->lockedRect.top)));
1108 * Depth Stencil surfaces which are not the current depth stencil target should have their data in a
1109 * gl texture(next path), or in local memory(early return because of set SFLAG_INSYSMEM above). If
1110 * none of that is the case the problem is not in this function :-)
1111 ********************************************/
1112 FIXME("Depth stencil locking not supported yet\n");
1113 } else {
1114 /* This path is for normal surfaces, offscreen render targets and everything else that is in a gl texture */
1115 TRACE("locking an ordinary surface\n");
1116 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL /* no partial locking for textures yet */);
1119 lock_end:
1120 if(This->Flags & SFLAG_PBO) {
1121 ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
1122 ENTER_GL();
1123 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1124 checkGLcall("glBindBufferARB");
1126 /* This shouldn't happen but could occur if some other function didn't handle the PBO properly */
1127 if(This->resource.allocatedMemory) {
1128 ERR("The surface already has PBO memory allocated!\n");
1131 This->resource.allocatedMemory = GL_EXTCALL(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_READ_WRITE_ARB));
1132 checkGLcall("glMapBufferARB");
1134 /* Make sure the pbo isn't set anymore in order not to break non-pbo calls */
1135 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1136 checkGLcall("glBindBufferARB");
1138 LEAVE_GL();
1141 if (Flags & (WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY)) {
1142 /* Don't dirtify */
1143 } else {
1144 IWineD3DBaseTexture *pBaseTexture;
1146 * Dirtify on lock
1147 * as seen in msdn docs
1149 IWineD3DSurface_AddDirtyRect(iface, pRect);
1151 /** Dirtify Container if needed */
1152 if (WINED3D_OK == IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&pBaseTexture) && pBaseTexture != NULL) {
1153 TRACE("Making container dirty\n");
1154 IWineD3DBaseTexture_SetDirty(pBaseTexture, TRUE);
1155 IWineD3DBaseTexture_Release(pBaseTexture);
1156 } else {
1157 TRACE("Surface is standalone, no need to dirty the container\n");
1161 return IWineD3DBaseSurfaceImpl_LockRect(iface, pLockedRect, pRect, Flags);
1164 static void flush_to_framebuffer_drawpixels(IWineD3DSurfaceImpl *This, GLenum fmt, GLenum type, UINT bpp, const BYTE *mem) {
1165 GLint prev_store;
1166 GLint prev_rasterpos[4];
1167 GLint skipBytes = 0;
1168 UINT pitch = IWineD3DSurface_GetPitch((IWineD3DSurface *) This); /* target is argb, 4 byte */
1169 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
1170 IWineD3DSwapChainImpl *swapchain;
1172 /* Activate the correct context for the render target */
1173 ActivateContext(myDevice, (IWineD3DSurface *) This, CTXUSAGE_BLIT);
1174 ENTER_GL();
1176 IWineD3DSurface_GetContainer((IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&swapchain);
1177 if(!swapchain) {
1178 /* Primary offscreen render target */
1179 TRACE("Offscreen render target\n");
1180 glDrawBuffer(myDevice->offscreenBuffer);
1181 checkGLcall("glDrawBuffer(myDevice->offscreenBuffer)");
1182 } else {
1183 GLenum buffer = surface_get_gl_buffer((IWineD3DSurface *) This, (IWineD3DSwapChain *)swapchain);
1184 TRACE("Unlocking %#x buffer\n", buffer);
1185 glDrawBuffer(buffer);
1186 checkGLcall("glDrawBuffer");
1188 IWineD3DSwapChain_Release((IWineD3DSwapChain *)swapchain);
1191 glFlush();
1192 vcheckGLcall("glFlush");
1193 glGetIntegerv(GL_PACK_SWAP_BYTES, &prev_store);
1194 vcheckGLcall("glIntegerv");
1195 glGetIntegerv(GL_CURRENT_RASTER_POSITION, &prev_rasterpos[0]);
1196 vcheckGLcall("glIntegerv");
1197 glPixelZoom(1.0, -1.0);
1198 vcheckGLcall("glPixelZoom");
1200 /* If not fullscreen, we need to skip a number of bytes to find the next row of data */
1201 glGetIntegerv(GL_UNPACK_ROW_LENGTH, &skipBytes);
1202 glPixelStorei(GL_UNPACK_ROW_LENGTH, This->currentDesc.Width);
1204 glRasterPos3i(This->lockedRect.left, This->lockedRect.top, 1);
1205 vcheckGLcall("glRasterPos2f");
1207 /* Some drivers(radeon dri, others?) don't like exceptions during
1208 * glDrawPixels. If the surface is a DIB section, it might be in GDIMode
1209 * after ReleaseDC. Reading it will cause an exception, which x11drv will
1210 * catch to put the dib section in InSync mode, which leads to a crash
1211 * and a blocked x server on my radeon card.
1213 * The following lines read the dib section so it is put in InSync mode
1214 * before glDrawPixels is called and the crash is prevented. There won't
1215 * be any interfering gdi accesses, because UnlockRect is called from
1216 * ReleaseDC, and the app won't use the dc any more afterwards.
1218 if((This->Flags & SFLAG_DIBSECTION) && !(This->Flags & SFLAG_PBO)) {
1219 volatile BYTE read;
1220 read = This->resource.allocatedMemory[0];
1223 if(This->Flags & SFLAG_PBO) {
1224 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1225 checkGLcall("glBindBufferARB");
1228 /* When the surface is locked we only have to refresh the locked part else we need to update the whole image */
1229 if(This->Flags & SFLAG_LOCKED) {
1230 glDrawPixels(This->lockedRect.right - This->lockedRect.left,
1231 (This->lockedRect.bottom - This->lockedRect.top)-1,
1232 fmt, type,
1233 mem + bpp * This->lockedRect.left + pitch * This->lockedRect.top);
1234 checkGLcall("glDrawPixels");
1235 } else {
1236 glDrawPixels(This->currentDesc.Width,
1237 This->currentDesc.Height,
1238 fmt, type, mem);
1239 checkGLcall("glDrawPixels");
1242 if(This->Flags & SFLAG_PBO) {
1243 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1244 checkGLcall("glBindBufferARB");
1247 glPixelZoom(1.0,1.0);
1248 vcheckGLcall("glPixelZoom");
1250 glRasterPos3iv(&prev_rasterpos[0]);
1251 vcheckGLcall("glRasterPos3iv");
1253 /* Reset to previous pack row length */
1254 glPixelStorei(GL_UNPACK_ROW_LENGTH, skipBytes);
1255 vcheckGLcall("glPixelStorei GL_UNPACK_ROW_LENGTH");
1257 if(!swapchain) {
1258 glDrawBuffer(myDevice->offscreenBuffer);
1259 checkGLcall("glDrawBuffer(myDevice->offscreenBuffer)");
1260 } else if(swapchain->backBuffer) {
1261 glDrawBuffer(GL_BACK);
1262 checkGLcall("glDrawBuffer(GL_BACK)");
1263 } else {
1264 glDrawBuffer(GL_FRONT);
1265 checkGLcall("glDrawBuffer(GL_FRONT)");
1267 LEAVE_GL();
1269 return;
1272 static HRESULT WINAPI IWineD3DSurfaceImpl_UnlockRect(IWineD3DSurface *iface) {
1273 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1274 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
1275 IWineD3DSwapChainImpl *swapchain = NULL;
1276 BOOL fullsurface;
1278 if (!(This->Flags & SFLAG_LOCKED)) {
1279 WARN("trying to Unlock an unlocked surf@%p\n", This);
1280 return WINED3DERR_INVALIDCALL;
1283 if (This->Flags & SFLAG_PBO) {
1284 TRACE("Freeing PBO memory\n");
1285 ActivateContext(myDevice, myDevice->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
1286 ENTER_GL();
1287 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, This->pbo));
1288 GL_EXTCALL(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB));
1289 GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
1290 checkGLcall("glUnmapBufferARB");
1291 LEAVE_GL();
1292 This->resource.allocatedMemory = NULL;
1295 TRACE("(%p) : dirtyfied(%d)\n", This, This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE) ? 0 : 1);
1297 if (This->Flags & (SFLAG_INDRAWABLE | SFLAG_INTEXTURE)) {
1298 TRACE("(%p) : Not Dirtified so nothing to do, return now\n", This);
1299 goto unlock_end;
1302 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain);
1303 if(swapchain || (myDevice->render_targets && iface == myDevice->render_targets[0])) {
1304 if(swapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
1306 if(wined3d_settings.rendertargetlock_mode == RTL_DISABLE) {
1307 static BOOL warned = FALSE;
1308 if(!warned) {
1309 ERR("The application tries to write to the render target, but render target locking is disabled\n");
1310 warned = TRUE;
1312 goto unlock_end;
1315 if(This->dirtyRect.left == 0 &&
1316 This->dirtyRect.top == 0 &&
1317 This->dirtyRect.right == This->currentDesc.Width &&
1318 This->dirtyRect.bottom == This->currentDesc.Height) {
1319 fullsurface = TRUE;
1320 } else {
1321 /* TODO: Proper partial rectangle tracking */
1322 fullsurface = FALSE;
1323 This->Flags |= SFLAG_INSYSMEM;
1326 switch(wined3d_settings.rendertargetlock_mode) {
1327 case RTL_READTEX:
1328 case RTL_TEXTEX:
1329 ActivateContext(myDevice, iface, CTXUSAGE_BLIT);
1330 ENTER_GL();
1331 if (This->glDescription.textureName == 0) {
1332 glGenTextures(1, &This->glDescription.textureName);
1333 checkGLcall("glGenTextures");
1335 glBindTexture(This->glDescription.target, This->glDescription.textureName);
1336 checkGLcall("glBindTexture(This->glDescription.target, This->glDescription.textureName)");
1337 LEAVE_GL();
1338 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL /* partial texture loading not supported yet */);
1339 /* drop through */
1341 case RTL_AUTO:
1342 case RTL_READDRAW:
1343 case RTL_TEXDRAW:
1344 IWineD3DSurface_LoadLocation(iface, SFLAG_INDRAWABLE, fullsurface ? NULL : &This->dirtyRect);
1345 break;
1348 if(!fullsurface) {
1349 /* Partial rectangle tracking is not commonly implemented, it is only done for render targets. Overwrite
1350 * the flags to bring them back into a sane state. INSYSMEM was set before to tell LoadLocation where
1351 * to read the rectangle from. Indrawable is set because all modifications from the partial sysmem copy
1352 * are written back to the drawable, thus the surface is merged again in the drawable. The sysmem copy is
1353 * not fully up to date because only a subrectangle was read in LockRect.
1355 This->Flags &= ~SFLAG_INSYSMEM;
1356 This->Flags |= SFLAG_INDRAWABLE;
1359 This->dirtyRect.left = This->currentDesc.Width;
1360 This->dirtyRect.top = This->currentDesc.Height;
1361 This->dirtyRect.right = 0;
1362 This->dirtyRect.bottom = 0;
1363 } else if(iface == myDevice->stencilBufferTarget) {
1364 FIXME("Depth Stencil buffer locking is not implemented\n");
1365 } else {
1366 /* The rest should be a normal texture */
1367 IWineD3DBaseTextureImpl *impl;
1368 /* Check if the texture is bound, if yes dirtify the sampler to force a re-upload of the texture
1369 * Can't load the texture here because PreLoad may destroy and recreate the gl texture, so sampler
1370 * states need resetting
1372 if(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&impl) == WINED3D_OK) {
1373 if(impl->baseTexture.bindCount) {
1374 IWineD3DDeviceImpl_MarkStateDirty(myDevice, STATE_SAMPLER(impl->baseTexture.sampler));
1376 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *) impl);
1380 unlock_end:
1381 This->Flags &= ~SFLAG_LOCKED;
1382 memset(&This->lockedRect, 0, sizeof(RECT));
1383 return WINED3D_OK;
1386 HRESULT WINAPI IWineD3DSurfaceImpl_GetDC(IWineD3DSurface *iface, HDC *pHDC) {
1387 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1388 WINED3DLOCKED_RECT lock;
1389 HRESULT hr;
1390 RGBQUAD col[256];
1392 TRACE("(%p)->(%p)\n",This,pHDC);
1394 if(This->Flags & SFLAG_USERPTR) {
1395 ERR("Not supported on surfaces with an application-provided surfaces\n");
1396 return WINEDDERR_NODC;
1399 /* Give more detailed info for ddraw */
1400 if (This->Flags & SFLAG_DCINUSE)
1401 return WINEDDERR_DCALREADYCREATED;
1403 /* Can't GetDC if the surface is locked */
1404 if (This->Flags & SFLAG_LOCKED)
1405 return WINED3DERR_INVALIDCALL;
1407 /* According to Direct3D9 docs, only these formats are supported */
1408 if (((IWineD3DImpl *)This->resource.wineD3DDevice->wineD3D)->dxVersion > 7) {
1409 if (This->resource.format != WINED3DFMT_R5G6B5 &&
1410 This->resource.format != WINED3DFMT_X1R5G5B5 &&
1411 This->resource.format != WINED3DFMT_R8G8B8 &&
1412 This->resource.format != WINED3DFMT_X8R8G8B8) return WINED3DERR_INVALIDCALL;
1415 memset(&lock, 0, sizeof(lock)); /* To be sure */
1417 /* Create a DIB section if there isn't a hdc yet */
1418 if(!This->hDC) {
1419 IWineD3DBaseSurfaceImpl_CreateDIBSection(iface);
1420 if(This->Flags & SFLAG_CLIENT) {
1421 IWineD3DSurface_PreLoad(iface);
1424 /* Use the dib section from now on if we are not using a PBO */
1425 if(!(This->Flags & SFLAG_PBO))
1426 This->resource.allocatedMemory = This->dib.bitmap_data;
1429 /* Lock the surface */
1430 hr = IWineD3DSurface_LockRect(iface,
1431 &lock,
1432 NULL,
1435 if(This->Flags & SFLAG_PBO) {
1436 /* Sync the DIB with the PBO. This can't be done earlier because LockRect activates the allocatedMemory */
1437 memcpy(This->dib.bitmap_data, This->resource.allocatedMemory, This->dib.bitmap_size);
1440 if(FAILED(hr)) {
1441 ERR("IWineD3DSurface_LockRect failed with hr = %08x\n", hr);
1442 /* keep the dib section */
1443 return hr;
1446 if(This->resource.format == WINED3DFMT_P8 ||
1447 This->resource.format == WINED3DFMT_A8P8) {
1448 /* GetDC on palettized formats is unsupported in D3D9, and the method is missing in
1449 D3D8, so this should only be used for DX <=7 surfaces (with non-device palettes) */
1450 unsigned int n;
1451 PALETTEENTRY *pal = NULL;
1453 if(This->palette) {
1454 pal = This->palette->palents;
1455 } else {
1456 IWineD3DSurfaceImpl *dds_primary = (IWineD3DSurfaceImpl *)This->resource.wineD3DDevice->ddraw_primary;
1457 if (dds_primary && dds_primary->palette)
1458 pal = dds_primary->palette->palents;
1461 if (pal) {
1462 for (n=0; n<256; n++) {
1463 col[n].rgbRed = pal[n].peRed;
1464 col[n].rgbGreen = pal[n].peGreen;
1465 col[n].rgbBlue = pal[n].peBlue;
1466 col[n].rgbReserved = 0;
1468 SetDIBColorTable(This->hDC, 0, 256, col);
1472 *pHDC = This->hDC;
1473 TRACE("returning %p\n",*pHDC);
1474 This->Flags |= SFLAG_DCINUSE;
1476 return WINED3D_OK;
1479 HRESULT WINAPI IWineD3DSurfaceImpl_ReleaseDC(IWineD3DSurface *iface, HDC hDC) {
1480 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
1482 TRACE("(%p)->(%p)\n",This,hDC);
1484 if (!(This->Flags & SFLAG_DCINUSE))
1485 return WINED3DERR_INVALIDCALL;
1487 if (This->hDC !=hDC) {
1488 WARN("Application tries to release an invalid DC(%p), surface dc is %p\n", hDC, This->hDC);
1489 return WINED3DERR_INVALIDCALL;
1492 if((This->Flags & SFLAG_PBO) && This->resource.allocatedMemory) {
1493 /* Copy the contents of the DIB over to the PBO */
1494 memcpy(This->resource.allocatedMemory, This->dib.bitmap_data, This->dib.bitmap_size);
1497 /* we locked first, so unlock now */
1498 IWineD3DSurface_UnlockRect(iface);
1500 This->Flags &= ~SFLAG_DCINUSE;
1502 return WINED3D_OK;
1505 /* ******************************************************
1506 IWineD3DSurface Internal (No mapping to directx api) parts follow
1507 ****************************************************** */
1509 HRESULT d3dfmt_get_conv(IWineD3DSurfaceImpl *This, BOOL need_alpha_ck, BOOL use_texturing, GLenum *format, GLenum *internal, GLenum *type, CONVERT_TYPES *convert, int *target_bpp, BOOL srgb_mode) {
1510 BOOL colorkey_active = need_alpha_ck && (This->CKeyFlags & WINEDDSD_CKSRCBLT);
1511 const GlPixelFormatDesc *glDesc;
1512 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
1513 getFormatDescEntry(This->resource.format, &GLINFO_LOCATION, &glDesc);
1515 /* Default values: From the surface */
1516 *format = glDesc->glFormat;
1517 *type = glDesc->glType;
1518 *convert = NO_CONVERSION;
1519 *target_bpp = This->bytesPerPixel;
1521 if(srgb_mode) {
1522 *internal = glDesc->glGammaInternal;
1523 } else if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
1524 *internal = glDesc->rtInternal;
1525 } else {
1526 *internal = glDesc->glInternal;
1529 /* Ok, now look if we have to do any conversion */
1530 switch(This->resource.format) {
1531 case WINED3DFMT_P8:
1532 /* ****************
1533 Paletted Texture
1534 **************** */
1536 /* Use conversion when the paletted texture extension OR fragment shaders are available. When either
1537 * of the two is available make sure texturing is requested as neither of the two works in
1538 * conjunction with calls like glDraw-/glReadPixels. Further also use conversion in case of color keying.
1539 * Paletted textures can be emulated using shaders but only do that for 2D purposes e.g. situations
1540 * in which the main render target uses p8. Some games like GTA Vice City use P8 for texturing which
1541 * conflicts with this.
1543 if( !(GL_SUPPORT(EXT_PALETTED_TEXTURE) || (GL_SUPPORT(ARB_FRAGMENT_PROGRAM) && primary_render_target_is_p8(device))) || colorkey_active || !use_texturing ) {
1544 *format = GL_RGBA;
1545 *internal = GL_RGBA;
1546 *type = GL_UNSIGNED_BYTE;
1547 *target_bpp = 4;
1548 if(colorkey_active) {
1549 *convert = CONVERT_PALETTED_CK;
1550 } else {
1551 *convert = CONVERT_PALETTED;
1554 else if(!GL_SUPPORT(EXT_PALETTED_TEXTURE) && GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
1555 *format = GL_ALPHA;
1556 *internal = GL_RGBA;
1557 *type = GL_UNSIGNED_BYTE;
1558 *target_bpp = 1;
1561 break;
1563 case WINED3DFMT_R3G3B2:
1564 /* **********************
1565 GL_UNSIGNED_BYTE_3_3_2
1566 ********************** */
1567 if (colorkey_active) {
1568 /* This texture format will never be used.. So do not care about color keying
1569 up until the point in time it will be needed :-) */
1570 FIXME(" ColorKeying not supported in the RGB 332 format !\n");
1572 break;
1574 case WINED3DFMT_R5G6B5:
1575 if (colorkey_active) {
1576 *convert = CONVERT_CK_565;
1577 *format = GL_RGBA;
1578 *internal = GL_RGBA;
1579 *type = GL_UNSIGNED_SHORT_5_5_5_1;
1581 break;
1583 case WINED3DFMT_X1R5G5B5:
1584 if (colorkey_active) {
1585 *convert = CONVERT_CK_5551;
1586 *format = GL_BGRA;
1587 *internal = GL_RGBA;
1588 *type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
1590 break;
1592 case WINED3DFMT_R8G8B8:
1593 if (colorkey_active) {
1594 *convert = CONVERT_CK_RGB24;
1595 *format = GL_RGBA;
1596 *internal = GL_RGBA;
1597 *type = GL_UNSIGNED_INT_8_8_8_8;
1598 *target_bpp = 4;
1600 break;
1602 case WINED3DFMT_X8R8G8B8:
1603 if (colorkey_active) {
1604 *convert = CONVERT_RGB32_888;
1605 *format = GL_RGBA;
1606 *internal = GL_RGBA;
1607 *type = GL_UNSIGNED_INT_8_8_8_8;
1609 break;
1611 case WINED3DFMT_V8U8:
1612 if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1613 else if(GL_SUPPORT(ATI_ENVMAP_BUMPMAP)) {
1614 *format = GL_DUDV_ATI;
1615 *internal = GL_DU8DV8_ATI;
1616 *type = GL_BYTE;
1617 /* No conversion - Just change the gl type */
1618 break;
1620 *convert = CONVERT_V8U8;
1621 *format = GL_BGR;
1622 *internal = GL_RGB8;
1623 *type = GL_UNSIGNED_BYTE;
1624 *target_bpp = 3;
1625 break;
1627 case WINED3DFMT_L6V5U5:
1628 *convert = CONVERT_L6V5U5;
1629 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1630 *target_bpp = 3;
1631 /* Use format and types from table */
1632 } else {
1633 /* Load it into unsigned R5G6B5, swap L and V channels, and revert that in the shader */
1634 *target_bpp = 2;
1635 *format = GL_RGB;
1636 *internal = GL_RGB5;
1637 *type = GL_UNSIGNED_SHORT_5_6_5;
1639 break;
1641 case WINED3DFMT_X8L8V8U8:
1642 *convert = CONVERT_X8L8V8U8;
1643 *target_bpp = 4;
1644 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1645 /* Use formats from gl table. It is a bit unfortunate, but the conversion
1646 * is needed to set the X format to 255 to get 1.0 for alpha when sampling
1647 * the texture. OpenGL can't use GL_DSDT8_MAG8_NV as internal format with
1648 * the needed type and format parameter, so the internal format contains a
1649 * 4th component, which is returned as alpha
1651 } else {
1652 /* Not supported by GL_ATI_envmap_bumpmap */
1653 *format = GL_BGRA;
1654 *internal = GL_RGB8;
1655 *type = GL_UNSIGNED_INT_8_8_8_8_REV;
1657 break;
1659 case WINED3DFMT_Q8W8V8U8:
1660 if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1661 *convert = CONVERT_Q8W8V8U8;
1662 *format = GL_BGRA;
1663 *internal = GL_RGBA8;
1664 *type = GL_UNSIGNED_BYTE;
1665 *target_bpp = 4;
1666 /* Not supported by GL_ATI_envmap_bumpmap */
1667 break;
1669 case WINED3DFMT_V16U16:
1670 if(GL_SUPPORT(NV_TEXTURE_SHADER3)) break;
1671 *convert = CONVERT_V16U16;
1672 *format = GL_BGR;
1673 *internal = GL_RGB16_EXT;
1674 *type = GL_UNSIGNED_SHORT;
1675 *target_bpp = 6;
1676 /* What should I do here about GL_ATI_envmap_bumpmap?
1677 * Convert it or allow data loss by loading it into a 8 bit / channel texture?
1679 break;
1681 case WINED3DFMT_A4L4:
1682 /* A4L4 exists as an internal gl format, but for some reason there is not
1683 * format+type combination to load it. Thus convert it to A8L8, then load it
1684 * with A4L4 internal, but A8L8 format+type
1686 *convert = CONVERT_A4L4;
1687 *format = GL_LUMINANCE_ALPHA;
1688 *internal = GL_LUMINANCE4_ALPHA4;
1689 *type = GL_UNSIGNED_BYTE;
1690 *target_bpp = 2;
1691 break;
1693 case WINED3DFMT_R32F:
1694 /* Can be loaded in theory with fmt=GL_RED, type=GL_FLOAT, but this fails. The reason
1695 * is that D3D expects the undefined green, blue and alpha channels to return 1.0
1696 * when sampling, but OpenGL sets green and blue to 0.0 instead. Thus we have to inject
1697 * 1.0 instead.
1699 * The alpha channel defaults to 1.0 in opengl, so nothing has to be done about it.
1701 *convert = CONVERT_R32F;
1702 *format = GL_RGB;
1703 *internal = GL_RGB32F_ARB;
1704 *type = GL_FLOAT;
1705 *target_bpp = 12;
1706 break;
1708 case WINED3DFMT_R16F:
1709 /* Similar to R32F */
1710 *convert = CONVERT_R16F;
1711 *format = GL_RGB;
1712 *internal = GL_RGB16F_ARB;
1713 *type = GL_HALF_FLOAT_ARB;
1714 *target_bpp = 6;
1715 break;
1717 case WINED3DFMT_G16R16:
1718 *convert = CONVERT_G16R16;
1719 *format = GL_RGB;
1720 *internal = GL_RGB16_EXT;
1721 *type = GL_UNSIGNED_SHORT;
1722 *target_bpp = 6;
1723 break;
1725 default:
1726 break;
1729 return WINED3D_OK;
1732 HRESULT d3dfmt_convert_surface(BYTE *src, BYTE *dst, UINT pitch, UINT width, UINT height, UINT outpitch, CONVERT_TYPES convert, IWineD3DSurfaceImpl *This) {
1733 BYTE *source, *dest;
1734 TRACE("(%p)->(%p),(%d,%d,%d,%d,%p)\n", src, dst, pitch, height, outpitch, convert,This);
1736 switch (convert) {
1737 case NO_CONVERSION:
1739 memcpy(dst, src, pitch * height);
1740 break;
1742 case CONVERT_PALETTED:
1743 case CONVERT_PALETTED_CK:
1745 IWineD3DPaletteImpl* pal = This->palette;
1746 BYTE table[256][4];
1747 unsigned int x, y;
1749 if( pal == NULL) {
1750 /* TODO: If we are a sublevel, try to get the palette from level 0 */
1753 d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
1755 for (y = 0; y < height; y++)
1757 source = src + pitch * y;
1758 dest = dst + outpitch * y;
1759 /* This is an 1 bpp format, using the width here is fine */
1760 for (x = 0; x < width; x++) {
1761 BYTE color = *source++;
1762 *dest++ = table[color][0];
1763 *dest++ = table[color][1];
1764 *dest++ = table[color][2];
1765 *dest++ = table[color][3];
1769 break;
1771 case CONVERT_CK_565:
1773 /* Converting the 565 format in 5551 packed to emulate color-keying.
1775 Note : in all these conversion, it would be best to average the averaging
1776 pixels to get the color of the pixel that will be color-keyed to
1777 prevent 'color bleeding'. This will be done later on if ever it is
1778 too visible.
1780 Note2: Nvidia documents say that their driver does not support alpha + color keying
1781 on the same surface and disables color keying in such a case
1783 unsigned int x, y;
1784 WORD *Source;
1785 WORD *Dest;
1787 TRACE("Color keyed 565\n");
1789 for (y = 0; y < height; y++) {
1790 Source = (WORD *) (src + y * pitch);
1791 Dest = (WORD *) (dst + y * outpitch);
1792 for (x = 0; x < width; x++ ) {
1793 WORD color = *Source++;
1794 *Dest = ((color & 0xFFC0) | ((color & 0x1F) << 1));
1795 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
1796 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
1797 *Dest |= 0x0001;
1799 Dest++;
1803 break;
1805 case CONVERT_CK_5551:
1807 /* Converting X1R5G5B5 format to R5G5B5A1 to emulate color-keying. */
1808 unsigned int x, y;
1809 WORD *Source;
1810 WORD *Dest;
1811 TRACE("Color keyed 5551\n");
1812 for (y = 0; y < height; y++) {
1813 Source = (WORD *) (src + y * pitch);
1814 Dest = (WORD *) (dst + y * outpitch);
1815 for (x = 0; x < width; x++ ) {
1816 WORD color = *Source++;
1817 *Dest = color;
1818 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
1819 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
1820 *Dest |= (1 << 15);
1822 else {
1823 *Dest &= ~(1 << 15);
1825 Dest++;
1829 break;
1831 case CONVERT_RGB32_888:
1833 /* Converting X8R8G8B8 format to R8G8B8A8 with color-keying. */
1834 unsigned int x, y;
1835 for (y = 0; y < height; y++)
1837 source = src + pitch * y;
1838 dest = dst + outpitch * y;
1839 for (x = 0; x < width; x++) {
1840 DWORD color = 0xffffff & *(DWORD*)source;
1841 DWORD dstcolor = color << 8;
1842 if ((color < This->SrcBltCKey.dwColorSpaceLowValue) ||
1843 (color > This->SrcBltCKey.dwColorSpaceHighValue)) {
1844 dstcolor |= 0xff;
1846 *(DWORD*)dest = dstcolor;
1847 source += 4;
1848 dest += 4;
1852 break;
1854 case CONVERT_V8U8:
1856 unsigned int x, y;
1857 short *Source;
1858 unsigned char *Dest;
1859 for(y = 0; y < height; y++) {
1860 Source = (short *) (src + y * pitch);
1861 Dest = dst + y * outpitch;
1862 for (x = 0; x < width; x++ ) {
1863 long color = (*Source++);
1864 /* B */ Dest[0] = 0xff;
1865 /* G */ Dest[1] = (color >> 8) + 128; /* V */
1866 /* R */ Dest[2] = (color) + 128; /* U */
1867 Dest += 3;
1870 break;
1873 case CONVERT_V16U16:
1875 unsigned int x, y;
1876 DWORD *Source;
1877 unsigned short *Dest;
1878 for(y = 0; y < height; y++) {
1879 Source = (DWORD *) (src + y * pitch);
1880 Dest = (unsigned short *) (dst + y * outpitch);
1881 for (x = 0; x < width; x++ ) {
1882 DWORD color = (*Source++);
1883 /* B */ Dest[0] = 0xffff;
1884 /* G */ Dest[1] = (color >> 16) + 32768; /* V */
1885 /* R */ Dest[2] = (color ) + 32768; /* U */
1886 Dest += 3;
1889 break;
1892 case CONVERT_Q8W8V8U8:
1894 unsigned int x, y;
1895 DWORD *Source;
1896 unsigned char *Dest;
1897 for(y = 0; y < height; y++) {
1898 Source = (DWORD *) (src + y * pitch);
1899 Dest = dst + y * outpitch;
1900 for (x = 0; x < width; x++ ) {
1901 long color = (*Source++);
1902 /* B */ Dest[0] = ((color >> 16) & 0xff) + 128; /* W */
1903 /* G */ Dest[1] = ((color >> 8 ) & 0xff) + 128; /* V */
1904 /* R */ Dest[2] = (color & 0xff) + 128; /* U */
1905 /* A */ Dest[3] = ((color >> 24) & 0xff) + 128; /* Q */
1906 Dest += 4;
1909 break;
1912 case CONVERT_L6V5U5:
1914 unsigned int x, y;
1915 WORD *Source;
1916 unsigned char *Dest;
1918 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1919 /* This makes the gl surface bigger(24 bit instead of 16), but it works with
1920 * fixed function and shaders without further conversion once the surface is
1921 * loaded
1923 for(y = 0; y < height; y++) {
1924 Source = (WORD *) (src + y * pitch);
1925 Dest = dst + y * outpitch;
1926 for (x = 0; x < width; x++ ) {
1927 short color = (*Source++);
1928 unsigned char l = ((color >> 10) & 0xfc);
1929 char v = ((color >> 5) & 0x3e);
1930 char u = ((color ) & 0x1f);
1932 /* 8 bits destination, 6 bits source, 8th bit is the sign. gl ignores the sign
1933 * and doubles the positive range. Thus shift left only once, gl does the 2nd
1934 * shift. GL reads a signed value and converts it into an unsigned value.
1936 /* M */ Dest[2] = l << 1;
1938 /* Those are read as signed, but kept signed. Just left-shift 3 times to scale
1939 * from 5 bit values to 8 bit values.
1941 /* V */ Dest[1] = v << 3;
1942 /* U */ Dest[0] = u << 3;
1943 Dest += 3;
1946 } else {
1947 for(y = 0; y < height; y++) {
1948 unsigned short *Dest_s = (unsigned short *) (dst + y * outpitch);
1949 Source = (WORD *) (src + y * pitch);
1950 for (x = 0; x < width; x++ ) {
1951 short color = (*Source++);
1952 unsigned char l = ((color >> 10) & 0xfc);
1953 short v = ((color >> 5) & 0x3e);
1954 short u = ((color ) & 0x1f);
1955 short v_conv = v + 16;
1956 short u_conv = u + 16;
1958 *Dest_s = ((v_conv << 11) & 0xf800) | ((l << 5) & 0x7e0) | (u_conv & 0x1f);
1959 Dest_s += 1;
1963 break;
1966 case CONVERT_X8L8V8U8:
1968 unsigned int x, y;
1969 DWORD *Source;
1970 unsigned char *Dest;
1972 if(GL_SUPPORT(NV_TEXTURE_SHADER)) {
1973 /* This implementation works with the fixed function pipeline and shaders
1974 * without further modification after converting the surface.
1976 for(y = 0; y < height; y++) {
1977 Source = (DWORD *) (src + y * pitch);
1978 Dest = dst + y * outpitch;
1979 for (x = 0; x < width; x++ ) {
1980 long color = (*Source++);
1981 /* L */ Dest[2] = ((color >> 16) & 0xff); /* L */
1982 /* V */ Dest[1] = ((color >> 8 ) & 0xff); /* V */
1983 /* U */ Dest[0] = (color & 0xff); /* U */
1984 /* I */ Dest[3] = 255; /* X */
1985 Dest += 4;
1988 } else {
1989 /* Doesn't work correctly with the fixed function pipeline, but can work in
1990 * shaders if the shader is adjusted. (There's no use for this format in gl's
1991 * standard fixed function pipeline anyway).
1993 for(y = 0; y < height; y++) {
1994 Source = (DWORD *) (src + y * pitch);
1995 Dest = dst + y * outpitch;
1996 for (x = 0; x < width; x++ ) {
1997 long color = (*Source++);
1998 /* B */ Dest[0] = ((color >> 16) & 0xff); /* L */
1999 /* G */ Dest[1] = ((color >> 8 ) & 0xff) + 128; /* V */
2000 /* R */ Dest[2] = (color & 0xff) + 128; /* U */
2001 Dest += 4;
2005 break;
2008 case CONVERT_A4L4:
2010 unsigned int x, y;
2011 unsigned char *Source;
2012 unsigned char *Dest;
2013 for(y = 0; y < height; y++) {
2014 Source = src + y * pitch;
2015 Dest = dst + y * outpitch;
2016 for (x = 0; x < width; x++ ) {
2017 unsigned char color = (*Source++);
2018 /* A */ Dest[1] = (color & 0xf0) << 0;
2019 /* L */ Dest[0] = (color & 0x0f) << 4;
2020 Dest += 2;
2023 break;
2026 case CONVERT_R32F:
2028 unsigned int x, y;
2029 float *Source;
2030 float *Dest;
2031 for(y = 0; y < height; y++) {
2032 Source = (float *) (src + y * pitch);
2033 Dest = (float *) (dst + y * outpitch);
2034 for (x = 0; x < width; x++ ) {
2035 float color = (*Source++);
2036 Dest[0] = color;
2037 Dest[1] = 1.0;
2038 Dest[2] = 1.0;
2039 Dest += 3;
2042 break;
2045 case CONVERT_R16F:
2047 unsigned int x, y;
2048 WORD *Source;
2049 WORD *Dest;
2050 WORD one = 0x3c00;
2051 for(y = 0; y < height; y++) {
2052 Source = (WORD *) (src + y * pitch);
2053 Dest = (WORD *) (dst + y * outpitch);
2054 for (x = 0; x < width; x++ ) {
2055 WORD color = (*Source++);
2056 Dest[0] = color;
2057 Dest[1] = one;
2058 Dest[2] = one;
2059 Dest += 3;
2062 break;
2065 case CONVERT_G16R16:
2067 unsigned int x, y;
2068 WORD *Source;
2069 WORD *Dest;
2071 for(y = 0; y < height; y++) {
2072 Source = (WORD *) (src + y * pitch);
2073 Dest = (WORD *) (dst + y * outpitch);
2074 for (x = 0; x < width; x++ ) {
2075 WORD green = (*Source++);
2076 WORD red = (*Source++);
2077 Dest[0] = green;
2078 Dest[1] = red;
2079 Dest[2] = 0xffff;
2080 Dest += 3;
2083 break;
2086 default:
2087 ERR("Unsupported conversation type %d\n", convert);
2089 return WINED3D_OK;
2092 static void d3dfmt_p8_init_palette(IWineD3DSurfaceImpl *This, BYTE table[256][4], BOOL colorkey) {
2093 IWineD3DPaletteImpl* pal = This->palette;
2094 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2095 BOOL index_in_alpha = FALSE;
2096 int dxVersion = ( (IWineD3DImpl *) device->wineD3D)->dxVersion;
2097 int i;
2099 /* Old games like StarCraft, C&C, Red Alert and others use P8 render targets.
2100 * Reading back the RGB output each lockrect (each frame as they lock the whole screen)
2101 * is slow. Further RGB->P8 conversion is not possible because palettes can have
2102 * duplicate entries. Store the color key in the unused alpha component to speed the
2103 * download up and to make conversion unneeded. */
2104 index_in_alpha = primary_render_target_is_p8(device);
2106 if (pal == NULL) {
2107 /* In DirectDraw the palette is a property of the surface, there are no such things as device palettes. */
2108 if(dxVersion <= 7) {
2109 ERR("This code should never get entered for DirectDraw!, expect problems\n");
2110 if(index_in_alpha) {
2111 /* Guarantees that memory representation remains correct after sysmem<->texture transfers even if
2112 there's no palette at this time. */
2113 for (i = 0; i < 256; i++) table[i][3] = i;
2115 } else {
2116 /* Direct3D >= 8 palette usage style: P8 textures use device palettes, palette entry format is A8R8G8B8,
2117 alpha is stored in peFlags and may be used by the app if D3DPTEXTURECAPS_ALPHAPALETTE device
2118 capability flag is present (wine does advertise this capability) */
2119 for (i = 0; i < 256; i++) {
2120 table[i][0] = device->palettes[device->currentPalette][i].peRed;
2121 table[i][1] = device->palettes[device->currentPalette][i].peGreen;
2122 table[i][2] = device->palettes[device->currentPalette][i].peBlue;
2123 table[i][3] = device->palettes[device->currentPalette][i].peFlags;
2126 } else {
2127 TRACE("Using surface palette %p\n", pal);
2128 /* Get the surface's palette */
2129 for (i = 0; i < 256; i++) {
2130 table[i][0] = pal->palents[i].peRed;
2131 table[i][1] = pal->palents[i].peGreen;
2132 table[i][2] = pal->palents[i].peBlue;
2134 /* When index_in_alpha is the palette index is stored in the alpha component. In case of a readback
2135 we can then read GL_ALPHA. Color keying is handled in BltOverride using a GL_ALPHA_TEST using GL_NOT_EQUAL.
2136 In case of index_in_alpha the color key itself is passed to glAlphaFunc in other cases the alpha component
2137 of pixels that should be masked away is set to 0. */
2138 if(index_in_alpha) {
2139 table[i][3] = i;
2140 } else if(colorkey && (i >= This->SrcBltCKey.dwColorSpaceLowValue) && (i <= This->SrcBltCKey.dwColorSpaceHighValue)) {
2141 table[i][3] = 0x00;
2142 } else if(pal->Flags & WINEDDPCAPS_ALPHA) {
2143 table[i][3] = pal->palents[i].peFlags;
2144 } else {
2145 table[i][3] = 0xFF;
2151 const char *fragment_palette_conversion =
2152 "!!ARBfp1.0\n"
2153 "TEMP index;\n"
2154 "PARAM constants = { 0.996, 0.00195, 0, 0 };\n" /* { 255/256, 0.5/255*255/256, 0, 0 } */
2155 "TEX index, fragment.texcoord[0], texture[0], 2D;\n" /* The alpha-component contains the palette index */
2156 "MAD index.a, index.a, constants.x, constants.y;\n" /* Scale the index by 255/256 and add a bias of '0.5' in order to sample in the middle */
2157 "TEX result.color, index.a, texture[1], 1D;\n" /* use the alpha-component as a index in the palette to get the final color */
2158 "END";
2160 /* This function is used in case of 8bit paletted textures to upload the palette.
2161 It supports GL_EXT_paletted_texture and GL_ARB_fragment_program, support for other
2162 extensions like ATI_fragment_shaders is possible.
2164 static void d3dfmt_p8_upload_palette(IWineD3DSurface *iface, CONVERT_TYPES convert) {
2165 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2166 BYTE table[256][4];
2167 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2169 d3dfmt_p8_init_palette(This, table, (convert == CONVERT_PALETTED_CK));
2171 /* Try to use the paletted texture extension */
2172 if(GL_SUPPORT(EXT_PALETTED_TEXTURE))
2174 TRACE("Using GL_EXT_PALETTED_TEXTURE for 8-bit paletted texture support\n");
2175 GL_EXTCALL(glColorTableEXT(This->glDescription.target,GL_RGBA,256,GL_RGBA,GL_UNSIGNED_BYTE, table));
2177 else
2179 /* Let a fragment shader do the color conversion by uploading the palette to a 1D texture.
2180 * The 8bit pixel data will be used as an index in this palette texture to retrieve the final color. */
2181 TRACE("Using fragment shaders for emulating 8-bit paletted texture support\n");
2183 /* Create the fragment program if we don't have it */
2184 if(!device->paletteConversionShader)
2186 glEnable(GL_FRAGMENT_PROGRAM_ARB);
2187 GL_EXTCALL(glGenProgramsARB(1, &device->paletteConversionShader));
2188 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, device->paletteConversionShader));
2189 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(fragment_palette_conversion), (const GLbyte *)fragment_palette_conversion));
2190 glDisable(GL_FRAGMENT_PROGRAM_ARB);
2193 glEnable(GL_FRAGMENT_PROGRAM_ARB);
2194 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, device->paletteConversionShader));
2196 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE1));
2197 glEnable(GL_TEXTURE_1D);
2198 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2200 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2201 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); /* Make sure we have discrete color levels. */
2202 glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2203 glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, table); /* Upload the palette */
2205 /* Switch back to unit 0 in which the 2D texture will be stored. */
2206 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0));
2208 /* Rebind the texture because it isn't bound anymore */
2209 glBindTexture(This->glDescription.target, This->glDescription.textureName);
2213 BOOL palette9_changed(IWineD3DSurfaceImpl *This) {
2214 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2216 if(This->palette || (This->resource.format != WINED3DFMT_P8 && This->resource.format != WINED3DFMT_A8P8)) {
2217 /* If a ddraw-style palette is attached assume no d3d9 palette change.
2218 * Also the palette isn't interesting if the surface format isn't P8 or A8P8
2220 return FALSE;
2223 if(This->palette9) {
2224 if(memcmp(This->palette9, &device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256) == 0) {
2225 return FALSE;
2227 } else {
2228 This->palette9 = HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY) * 256);
2230 memcpy(This->palette9, &device->palettes[device->currentPalette], sizeof(PALETTEENTRY) * 256);
2231 return TRUE;
2234 static inline void clear_unused_channels(IWineD3DSurfaceImpl *This) {
2235 GLboolean oldwrite[4];
2237 /* Some formats have only some color channels, and the others are 1.0.
2238 * since our rendering renders to all channels, and those pixel formats
2239 * are emulated by using a full texture with the other channels set to 1.0
2240 * manually, clear the unused channels.
2242 * This could be done with hacking colorwriteenable to mask the colors,
2243 * but before drawing the buffer would have to be cleared too, so there's
2244 * no gain in that
2246 switch(This->resource.format) {
2247 case WINED3DFMT_R16F:
2248 case WINED3DFMT_R32F:
2249 TRACE("R16F or R32F format, clearing green, blue and alpha to 1.0\n");
2250 /* Do not activate a context, the correct drawable is active already
2251 * though just the read buffer is set, make sure to have the correct draw
2252 * buffer too
2254 glDrawBuffer(This->resource.wineD3DDevice->offscreenBuffer);
2255 glDisable(GL_SCISSOR_TEST);
2256 glGetBooleanv(GL_COLOR_WRITEMASK, oldwrite);
2257 glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_TRUE);
2258 glClearColor(0.0, 1.0, 1.0, 1.0);
2259 glClear(GL_COLOR_BUFFER_BIT);
2260 glColorMask(oldwrite[0], oldwrite[1], oldwrite[2], oldwrite[3]);
2261 if(!This->resource.wineD3DDevice->render_offscreen) glDrawBuffer(GL_BACK);
2262 checkGLcall("Unused channel clear\n");
2263 break;
2265 default: break;
2269 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadTexture(IWineD3DSurface *iface, BOOL srgb_mode) {
2270 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2272 if (!(This->Flags & SFLAG_INTEXTURE)) {
2273 TRACE("Reloading because surface is dirty\n");
2274 } else if(/* Reload: gl texture has ck, now no ckey is set OR */
2275 ((This->Flags & SFLAG_GLCKEY) && (!(This->CKeyFlags & WINEDDSD_CKSRCBLT))) ||
2276 /* Reload: vice versa OR */
2277 ((!(This->Flags & SFLAG_GLCKEY)) && (This->CKeyFlags & WINEDDSD_CKSRCBLT)) ||
2278 /* Also reload: Color key is active AND the color key has changed */
2279 ((This->CKeyFlags & WINEDDSD_CKSRCBLT) && (
2280 (This->glCKey.dwColorSpaceLowValue != This->SrcBltCKey.dwColorSpaceLowValue) ||
2281 (This->glCKey.dwColorSpaceHighValue != This->SrcBltCKey.dwColorSpaceHighValue)))) {
2282 TRACE("Reloading because of color keying\n");
2283 /* To perform the color key conversion we need a sysmem copy of
2284 * the surface. Make sure we have it
2287 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
2288 /* Make sure the texture is reloaded because of the color key change, this kills performance though :( */
2289 /* TODO: This is not necessarily needed with hw palettized texture support */
2290 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2291 } else {
2292 TRACE("surface is already in texture\n");
2293 return WINED3D_OK;
2296 /* Resources are placed in system RAM and do not need to be recreated when a device is lost.
2297 * These resources are not bound by device size or format restrictions. Because of this,
2298 * these resources cannot be accessed by the Direct3D device nor set as textures or render targets.
2299 * However, these resources can always be created, locked, and copied.
2301 if (This->resource.pool == WINED3DPOOL_SCRATCH )
2303 FIXME("(%p) Operation not supported for scratch textures\n",This);
2304 return WINED3DERR_INVALIDCALL;
2307 This->srgb = srgb_mode;
2308 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL /* no partial locking for textures yet */);
2310 #if 0
2312 static unsigned int gen = 0;
2313 char buffer[4096];
2314 ++gen;
2315 if ((gen % 10) == 0) {
2316 snprintf(buffer, sizeof(buffer), "/tmp/surface%p_type%u_level%u_%u.ppm", This, This->glDescription.target, This->glDescription.level, gen);
2317 IWineD3DSurfaceImpl_SaveSnapshot(iface, buffer);
2320 * debugging crash code
2321 if (gen == 250) {
2322 void** test = NULL;
2323 *test = 0;
2327 #endif
2329 if (!(This->Flags & SFLAG_DONOTFREE)) {
2330 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
2331 This->resource.allocatedMemory = NULL;
2332 This->resource.heapMemory = NULL;
2333 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, FALSE);
2336 return WINED3D_OK;
2339 static void WINAPI IWineD3DSurfaceImpl_BindTexture(IWineD3DSurface *iface) {
2340 /* TODO: check for locks */
2341 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2342 IWineD3DBaseTexture *baseTexture = NULL;
2343 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
2345 TRACE("(%p)Checking to see if the container is a base texture\n", This);
2346 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
2347 TRACE("Passing to container\n");
2348 IWineD3DBaseTexture_BindTexture(baseTexture);
2349 IWineD3DBaseTexture_Release(baseTexture);
2350 } else {
2351 TRACE("(%p) : Binding surface\n", This);
2353 if(!device->isInDraw) {
2354 ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
2356 ENTER_GL();
2357 glBindTexture(This->glDescription.target, This->glDescription.textureName);
2358 LEAVE_GL();
2360 return;
2363 #include <errno.h>
2364 #include <stdio.h>
2365 HRESULT WINAPI IWineD3DSurfaceImpl_SaveSnapshot(IWineD3DSurface *iface, const char* filename) {
2366 FILE* f = NULL;
2367 UINT i, y;
2368 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2369 char *allocatedMemory;
2370 char *textureRow;
2371 IWineD3DSwapChain *swapChain = NULL;
2372 int width, height;
2373 GLuint tmpTexture = 0;
2374 DWORD color;
2375 /*FIXME:
2376 Textures may not be stored in ->allocatedgMemory and a GlTexture
2377 so we should lock the surface before saving a snapshot, or at least check that
2379 /* TODO: Compressed texture images can be obtained from the GL in uncompressed form
2380 by calling GetTexImage and in compressed form by calling
2381 GetCompressedTexImageARB. Queried compressed images can be saved and
2382 later reused by calling CompressedTexImage[123]DARB. Pre-compressed
2383 texture images do not need to be processed by the GL and should
2384 significantly improve texture loading performance relative to uncompressed
2385 images. */
2387 /* Setup the width and height to be the internal texture width and height. */
2388 width = This->pow2Width;
2389 height = This->pow2Height;
2390 /* check to see if we're a 'virtual' texture, e.g. we're not a pbuffer of texture, we're a back buffer*/
2391 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapChain);
2393 if (This->Flags & SFLAG_INDRAWABLE && !(This->Flags & SFLAG_INTEXTURE)) {
2394 /* if were not a real texture then read the back buffer into a real texture */
2395 /* we don't want to interfere with the back buffer so read the data into a temporary
2396 * texture and then save the data out of the temporary texture
2398 GLint prevRead;
2399 ENTER_GL();
2400 TRACE("(%p) Reading render target into texture\n", This);
2401 glEnable(GL_TEXTURE_2D);
2403 glGenTextures(1, &tmpTexture);
2404 glBindTexture(GL_TEXTURE_2D, tmpTexture);
2406 glTexImage2D(GL_TEXTURE_2D,
2408 GL_RGBA,
2409 width,
2410 height,
2411 0/*border*/,
2412 GL_RGBA,
2413 GL_UNSIGNED_INT_8_8_8_8_REV,
2414 NULL);
2416 glGetIntegerv(GL_READ_BUFFER, &prevRead);
2417 vcheckGLcall("glGetIntegerv");
2418 glReadBuffer(swapChain ? GL_BACK : This->resource.wineD3DDevice->offscreenBuffer);
2419 vcheckGLcall("glReadBuffer");
2420 glCopyTexImage2D(GL_TEXTURE_2D,
2422 GL_RGBA,
2425 width,
2426 height,
2429 checkGLcall("glCopyTexImage2D");
2430 glReadBuffer(prevRead);
2431 LEAVE_GL();
2433 } else { /* bind the real texture, and make sure it up to date */
2434 IWineD3DSurface_PreLoad(iface);
2436 allocatedMemory = HeapAlloc(GetProcessHeap(), 0, width * height * 4);
2437 ENTER_GL();
2438 FIXME("Saving texture level %d width %d height %d\n", This->glDescription.level, width, height);
2439 glGetTexImage(GL_TEXTURE_2D,
2440 This->glDescription.level,
2441 GL_RGBA,
2442 GL_UNSIGNED_INT_8_8_8_8_REV,
2443 allocatedMemory);
2444 checkGLcall("glTexImage2D");
2445 if (tmpTexture) {
2446 glBindTexture(GL_TEXTURE_2D, 0);
2447 glDeleteTextures(1, &tmpTexture);
2449 LEAVE_GL();
2451 f = fopen(filename, "w+");
2452 if (NULL == f) {
2453 ERR("opening of %s failed with: %s\n", filename, strerror(errno));
2454 return WINED3DERR_INVALIDCALL;
2456 /* Save the data out to a TGA file because 1: it's an easy raw format, 2: it supports an alpha channel */
2457 TRACE("(%p) opened %s with format %s\n", This, filename, debug_d3dformat(This->resource.format));
2458 /* TGA header */
2459 fputc(0,f);
2460 fputc(0,f);
2461 fputc(2,f);
2462 fputc(0,f);
2463 fputc(0,f);
2464 fputc(0,f);
2465 fputc(0,f);
2466 fputc(0,f);
2467 fputc(0,f);
2468 fputc(0,f);
2469 fputc(0,f);
2470 fputc(0,f);
2471 /* short width*/
2472 fwrite(&width,2,1,f);
2473 /* short height */
2474 fwrite(&height,2,1,f);
2475 /* format rgba */
2476 fputc(0x20,f);
2477 fputc(0x28,f);
2478 /* raw data */
2479 /* 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 */
2480 if(swapChain)
2481 textureRow = allocatedMemory + (width * (height - 1) *4);
2482 else
2483 textureRow = allocatedMemory;
2484 for (y = 0 ; y < height; y++) {
2485 for (i = 0; i < width; i++) {
2486 color = *((DWORD*)textureRow);
2487 fputc((color >> 16) & 0xFF, f); /* B */
2488 fputc((color >> 8) & 0xFF, f); /* G */
2489 fputc((color >> 0) & 0xFF, f); /* R */
2490 fputc((color >> 24) & 0xFF, f); /* A */
2491 textureRow += 4;
2493 /* take two rows of the pointer to the texture memory */
2494 if(swapChain)
2495 (textureRow-= width << 3);
2498 TRACE("Closing file\n");
2499 fclose(f);
2501 if(swapChain) {
2502 IWineD3DSwapChain_Release(swapChain);
2504 HeapFree(GetProcessHeap(), 0, allocatedMemory);
2505 return WINED3D_OK;
2509 * Slightly inefficient way to handle multiple dirty rects but it works :)
2511 HRESULT WINAPI IWineD3DSurfaceImpl_AddDirtyRect(IWineD3DSurface *iface, CONST RECT* pDirtyRect) {
2512 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2513 IWineD3DBaseTexture *baseTexture = NULL;
2515 if (!(This->Flags & SFLAG_INSYSMEM) && (This->Flags & SFLAG_INTEXTURE))
2516 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL /* no partial locking for textures yet */);
2518 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2519 if (NULL != pDirtyRect) {
2520 This->dirtyRect.left = min(This->dirtyRect.left, pDirtyRect->left);
2521 This->dirtyRect.top = min(This->dirtyRect.top, pDirtyRect->top);
2522 This->dirtyRect.right = max(This->dirtyRect.right, pDirtyRect->right);
2523 This->dirtyRect.bottom = max(This->dirtyRect.bottom, pDirtyRect->bottom);
2524 } else {
2525 This->dirtyRect.left = 0;
2526 This->dirtyRect.top = 0;
2527 This->dirtyRect.right = This->currentDesc.Width;
2528 This->dirtyRect.bottom = This->currentDesc.Height;
2530 TRACE("(%p) : Dirty: yes, Rect:(%d,%d,%d,%d)\n", This, This->dirtyRect.left,
2531 This->dirtyRect.top, This->dirtyRect.right, This->dirtyRect.bottom);
2532 /* if the container is a basetexture then mark it dirty. */
2533 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&baseTexture) == WINED3D_OK) {
2534 TRACE("Passing to container\n");
2535 IWineD3DBaseTexture_SetDirty(baseTexture, TRUE);
2536 IWineD3DBaseTexture_Release(baseTexture);
2538 return WINED3D_OK;
2541 HRESULT WINAPI IWineD3DSurfaceImpl_SetFormat(IWineD3DSurface *iface, WINED3DFORMAT format) {
2542 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2543 HRESULT hr;
2544 const GlPixelFormatDesc *glDesc;
2545 getFormatDescEntry(format, &GLINFO_LOCATION, &glDesc);
2547 TRACE("(%p) : Calling base function first\n", This);
2548 hr = IWineD3DBaseSurfaceImpl_SetFormat(iface, format);
2549 if(SUCCEEDED(hr)) {
2550 /* Setup some glformat defaults */
2551 This->glDescription.glFormat = glDesc->glFormat;
2552 This->glDescription.glFormatInternal = glDesc->glInternal;
2553 This->glDescription.glType = glDesc->glType;
2555 This->Flags &= ~SFLAG_ALLOCATED;
2556 TRACE("(%p) : glFormat %d, glFotmatInternal %d, glType %d\n", This,
2557 This->glDescription.glFormat, This->glDescription.glFormatInternal, This->glDescription.glType);
2559 return hr;
2562 HRESULT WINAPI IWineD3DSurfaceImpl_SetMem(IWineD3DSurface *iface, void *Mem) {
2563 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
2565 if(This->Flags & (SFLAG_LOCKED | SFLAG_DCINUSE)) {
2566 WARN("Surface is locked or the HDC is in use\n");
2567 return WINED3DERR_INVALIDCALL;
2570 if(Mem && Mem != This->resource.allocatedMemory) {
2571 void *release = NULL;
2573 /* Do I have to copy the old surface content? */
2574 if(This->Flags & SFLAG_DIBSECTION) {
2575 /* Release the DC. No need to hold the critical section for the update
2576 * Thread because this thread runs only on front buffers, but this method
2577 * fails for render targets in the check above.
2579 SelectObject(This->hDC, This->dib.holdbitmap);
2580 DeleteDC(This->hDC);
2581 /* Release the DIB section */
2582 DeleteObject(This->dib.DIBsection);
2583 This->dib.bitmap_data = NULL;
2584 This->resource.allocatedMemory = NULL;
2585 This->hDC = NULL;
2586 This->Flags &= ~SFLAG_DIBSECTION;
2587 } else if(!(This->Flags & SFLAG_USERPTR)) {
2588 release = This->resource.heapMemory;
2589 This->resource.heapMemory = NULL;
2591 This->resource.allocatedMemory = Mem;
2592 This->Flags |= SFLAG_USERPTR | SFLAG_INSYSMEM;
2594 /* Now the surface memory is most up do date. Invalidate drawable and texture */
2595 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
2597 /* For client textures opengl has to be notified */
2598 if(This->Flags & SFLAG_CLIENT) {
2599 This->Flags &= ~SFLAG_ALLOCATED;
2600 IWineD3DSurface_PreLoad(iface);
2601 /* And hope that the app behaves correctly and did not free the old surface memory before setting a new pointer */
2604 /* Now free the old memory if any */
2605 HeapFree(GetProcessHeap(), 0, release);
2606 } else if(This->Flags & SFLAG_USERPTR) {
2607 /* LockRect and GetDC will re-create the dib section and allocated memory */
2608 This->resource.allocatedMemory = NULL;
2609 /* HeapMemory should be NULL already */
2610 if(This->resource.heapMemory != NULL) ERR("User pointer surface has heap memory allocated\n");
2611 This->Flags &= ~SFLAG_USERPTR;
2613 if(This->Flags & SFLAG_CLIENT) {
2614 This->Flags &= ~SFLAG_ALLOCATED;
2615 /* This respecifies an empty texture and opengl knows that the old memory is gone */
2616 IWineD3DSurface_PreLoad(iface);
2619 return WINED3D_OK;
2622 static HRESULT WINAPI IWineD3DSurfaceImpl_Flip(IWineD3DSurface *iface, IWineD3DSurface *override, DWORD Flags) {
2623 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
2624 IWineD3DSwapChainImpl *swapchain = NULL;
2625 HRESULT hr;
2626 TRACE("(%p)->(%p,%x)\n", This, override, Flags);
2628 /* Flipping is only supported on RenderTargets */
2629 if( !(This->resource.usage & WINED3DUSAGE_RENDERTARGET) ) return WINEDDERR_NOTFLIPPABLE;
2631 if(override) {
2632 /* DDraw sets this for the X11 surfaces, so don't confuse the user
2633 * FIXME("(%p) Target override is not supported by now\n", This);
2634 * Additionally, it isn't really possible to support triple-buffering
2635 * properly on opengl at all
2639 IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **) &swapchain);
2640 if(!swapchain) {
2641 ERR("Flipped surface is not on a swapchain\n");
2642 return WINEDDERR_NOTFLIPPABLE;
2645 /* Just overwrite the swapchain presentation interval. This is ok because only ddraw apps can call Flip,
2646 * and only d3d8 and d3d9 apps specify the presentation interval
2648 if((Flags & (WINEDDFLIP_NOVSYNC | WINEDDFLIP_INTERVAL2 | WINEDDFLIP_INTERVAL3 | WINEDDFLIP_INTERVAL4)) == 0) {
2649 /* Most common case first to avoid wasting time on all the other cases */
2650 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_ONE;
2651 } else if(Flags & WINEDDFLIP_NOVSYNC) {
2652 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
2653 } else if(Flags & WINEDDFLIP_INTERVAL2) {
2654 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_TWO;
2655 } else if(Flags & WINEDDFLIP_INTERVAL3) {
2656 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_THREE;
2657 } else {
2658 swapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_FOUR;
2661 /* Flipping a OpenGL surface -> Use WineD3DDevice::Present */
2662 hr = IWineD3DSwapChain_Present((IWineD3DSwapChain *) swapchain, NULL, NULL, 0, NULL, 0);
2663 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
2664 return hr;
2667 /* Does a direct frame buffer -> texture copy. Stretching is done
2668 * with single pixel copy calls
2670 static inline void fb_copy_to_texture_direct(IWineD3DSurfaceImpl *This, IWineD3DSurface *SrcSurface, IWineD3DSwapChainImpl *swapchain, WINED3DRECT *srect, WINED3DRECT *drect, BOOL upsidedown, WINED3DTEXTUREFILTERTYPE Filter) {
2671 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
2672 float xrel, yrel;
2673 UINT row;
2674 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
2677 ActivateContext(myDevice, SrcSurface, CTXUSAGE_BLIT);
2678 IWineD3DSurface_PreLoad((IWineD3DSurface *) This);
2679 ENTER_GL();
2681 /* TODO: Do we need GL_TEXTURE_2D enabled fpr copyteximage? */
2682 glEnable(This->glDescription.target);
2683 checkGLcall("glEnable(This->glDescription.target)");
2685 /* Bind the target texture */
2686 glBindTexture(This->glDescription.target, This->glDescription.textureName);
2687 checkGLcall("glBindTexture");
2688 if(!swapchain) {
2689 TRACE("Reading from an offscreen target\n");
2690 upsidedown = !upsidedown;
2691 glReadBuffer(myDevice->offscreenBuffer);
2692 } else {
2693 GLenum buffer = surface_get_gl_buffer(SrcSurface, (IWineD3DSwapChain *)swapchain);
2694 glReadBuffer(buffer);
2696 checkGLcall("glReadBuffer");
2698 xrel = (float) (srect->x2 - srect->x1) / (float) (drect->x2 - drect->x1);
2699 yrel = (float) (srect->y2 - srect->y1) / (float) (drect->y2 - drect->y1);
2701 if( (xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) {
2702 FIXME("Doing a pixel by pixel copy from the framebuffer to a texture, expect major performance issues\n");
2704 if(Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) {
2705 ERR("Texture filtering not supported in direct blit\n");
2707 } else if((Filter != WINED3DTEXF_NONE && Filter != WINED3DTEXF_POINT) && ((yrel - 1.0 < -eps) || (yrel - 1.0 > eps))) {
2708 ERR("Texture filtering not supported in direct blit\n");
2711 if(upsidedown &&
2712 !((xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) &&
2713 !((yrel - 1.0 < -eps) || (yrel - 1.0 > eps))) {
2714 /* Upside down copy without stretching is nice, one glCopyTexSubImage call will do */
2716 glCopyTexSubImage2D(This->glDescription.target,
2717 This->glDescription.level,
2718 drect->x1, drect->y1, /* xoffset, yoffset */
2719 srect->x1, Src->currentDesc.Height - srect->y2,
2720 drect->x2 - drect->x1, drect->y2 - drect->y1);
2721 } else {
2722 UINT yoffset = Src->currentDesc.Height - srect->y1 + drect->y1 - 1;
2723 /* I have to process this row by row to swap the image,
2724 * otherwise it would be upside down, so stretching in y direction
2725 * doesn't cost extra time
2727 * However, stretching in x direction can be avoided if not necessary
2729 for(row = drect->y1; row < drect->y2; row++) {
2730 if( (xrel - 1.0 < -eps) || (xrel - 1.0 > eps)) {
2731 /* Well, that stuff works, but it's very slow.
2732 * find a better way instead
2734 UINT col;
2736 for(col = drect->x1; col < drect->x2; col++) {
2737 glCopyTexSubImage2D(This->glDescription.target,
2738 This->glDescription.level,
2739 drect->x1 + col, row, /* xoffset, yoffset */
2740 srect->x1 + col * xrel, yoffset - (int) (row * yrel),
2741 1, 1);
2743 } else {
2744 glCopyTexSubImage2D(This->glDescription.target,
2745 This->glDescription.level,
2746 drect->x1, row, /* xoffset, yoffset */
2747 srect->x1, yoffset - (int) (row * yrel),
2748 drect->x2-drect->x1, 1);
2752 vcheckGLcall("glCopyTexSubImage2D");
2754 /* Leave the opengl state valid for blitting */
2755 glDisable(This->glDescription.target);
2756 checkGLcall("glDisable(This->glDescription.target)");
2758 LEAVE_GL();
2761 /* Uses the hardware to stretch and flip the image */
2762 static inline void fb_copy_to_texture_hwstretch(IWineD3DSurfaceImpl *This, IWineD3DSurface *SrcSurface, IWineD3DSwapChainImpl *swapchain, WINED3DRECT *srect, WINED3DRECT *drect, BOOL upsidedown, WINED3DTEXTUREFILTERTYPE Filter) {
2763 GLuint src, backup = 0;
2764 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
2765 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
2766 float left, right, top, bottom; /* Texture coordinates */
2767 UINT fbwidth = Src->currentDesc.Width;
2768 UINT fbheight = Src->currentDesc.Height;
2769 GLenum drawBuffer = GL_BACK;
2770 GLenum texture_target;
2771 BOOL noBackBufferBackup;
2773 TRACE("Using hwstretch blit\n");
2774 /* Activate the Proper context for reading from the source surface, set it up for blitting */
2775 ActivateContext(myDevice, SrcSurface, CTXUSAGE_BLIT);
2776 IWineD3DSurface_PreLoad((IWineD3DSurface *) This);
2778 noBackBufferBackup = !swapchain && wined3d_settings.offscreen_rendering_mode == ORM_FBO;
2779 if(!noBackBufferBackup && Src->glDescription.textureName == 0) {
2780 /* Get it a description */
2781 IWineD3DSurface_PreLoad(SrcSurface);
2783 ENTER_GL();
2785 /* Try to use an aux buffer for drawing the rectangle. This way it doesn't need restoring.
2786 * This way we don't have to wait for the 2nd readback to finish to leave this function.
2788 if(myDevice->activeContext->aux_buffers >= 2) {
2789 /* Got more than one aux buffer? Use the 2nd aux buffer */
2790 drawBuffer = GL_AUX1;
2791 } else if((swapchain || myDevice->offscreenBuffer == GL_BACK) && myDevice->activeContext->aux_buffers >= 1) {
2792 /* Only one aux buffer, but it isn't used (Onscreen rendering, or non-aux orm)? Use it! */
2793 drawBuffer = GL_AUX0;
2796 if(noBackBufferBackup) {
2797 glGenTextures(1, &backup);
2798 checkGLcall("glGenTextures\n");
2799 glBindTexture(GL_TEXTURE_2D, backup);
2800 checkGLcall("glBindTexture(Src->glDescription.target, Src->glDescription.textureName)");
2801 texture_target = GL_TEXTURE_2D;
2802 } else {
2803 /* Backup the back buffer and copy the source buffer into a texture to draw an upside down stretched quad. If
2804 * we are reading from the back buffer, the backup can be used as source texture
2806 texture_target = Src->glDescription.target;
2807 glBindTexture(texture_target, Src->glDescription.textureName);
2808 checkGLcall("glBindTexture(texture_target, Src->glDescription.textureName)");
2809 glEnable(texture_target);
2810 checkGLcall("glEnable(texture_target)");
2812 /* For now invalidate the texture copy of the back buffer. Drawable and sysmem copy are untouched */
2813 Src->Flags &= ~SFLAG_INTEXTURE;
2816 if(swapchain) {
2817 glReadBuffer(surface_get_gl_buffer(SrcSurface, (IWineD3DSwapChain *)swapchain));
2818 } else {
2819 TRACE("Reading from an offscreen target\n");
2820 upsidedown = !upsidedown;
2821 glReadBuffer(myDevice->offscreenBuffer);
2824 /* TODO: Only back up the part that will be overwritten */
2825 glCopyTexSubImage2D(texture_target, 0,
2826 0, 0 /* read offsets */,
2827 0, 0,
2828 fbwidth,
2829 fbheight);
2831 checkGLcall("glCopyTexSubImage2D");
2833 /* No issue with overriding these - the sampler is dirty due to blit usage */
2834 glTexParameteri(texture_target, GL_TEXTURE_MAG_FILTER,
2835 magLookup[Filter - WINED3DTEXF_NONE]);
2836 checkGLcall("glTexParameteri");
2837 glTexParameteri(texture_target, GL_TEXTURE_MIN_FILTER,
2838 minMipLookup[Filter][WINED3DTEXF_NONE]);
2839 checkGLcall("glTexParameteri");
2841 if(!swapchain || (IWineD3DSurface *) Src == swapchain->backBuffer[0]) {
2842 src = backup ? backup : Src->glDescription.textureName;
2843 } else {
2844 glReadBuffer(GL_FRONT);
2845 checkGLcall("glReadBuffer(GL_FRONT)");
2847 glGenTextures(1, &src);
2848 checkGLcall("glGenTextures(1, &src)");
2849 glBindTexture(GL_TEXTURE_2D, src);
2850 checkGLcall("glBindTexture(GL_TEXTURE_2D, src)");
2852 /* TODO: Only copy the part that will be read. Use srect->x1, srect->y2 as origin, but with the width watch
2853 * out for power of 2 sizes
2855 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, Src->pow2Width, Src->pow2Height, 0,
2856 GL_RGBA, GL_UNSIGNED_BYTE, NULL);
2857 checkGLcall("glTexImage2D");
2858 glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
2859 0, 0 /* read offsets */,
2860 0, 0,
2861 fbwidth,
2862 fbheight);
2864 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2865 checkGLcall("glTexParameteri");
2866 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2867 checkGLcall("glTexParameteri");
2869 glReadBuffer(GL_BACK);
2870 checkGLcall("glReadBuffer(GL_BACK)");
2872 if(texture_target != GL_TEXTURE_2D) {
2873 glDisable(texture_target);
2874 glEnable(GL_TEXTURE_2D);
2875 texture_target = GL_TEXTURE_2D;
2878 checkGLcall("glEnd and previous");
2880 left = srect->x1;
2881 right = srect->x2;
2883 if(upsidedown) {
2884 top = Src->currentDesc.Height - srect->y1;
2885 bottom = Src->currentDesc.Height - srect->y2;
2886 } else {
2887 top = Src->currentDesc.Height - srect->y2;
2888 bottom = Src->currentDesc.Height - srect->y1;
2891 if(Src->Flags & SFLAG_NORMCOORD) {
2892 left /= Src->pow2Width;
2893 right /= Src->pow2Width;
2894 top /= Src->pow2Height;
2895 bottom /= Src->pow2Height;
2898 /* draw the source texture stretched and upside down. The correct surface is bound already */
2899 glTexParameteri(texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP);
2900 glTexParameteri(texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP);
2902 glDrawBuffer(drawBuffer);
2903 glReadBuffer(drawBuffer);
2905 glBegin(GL_QUADS);
2906 /* bottom left */
2907 glTexCoord2f(left, bottom);
2908 glVertex2i(0, fbheight);
2910 /* top left */
2911 glTexCoord2f(left, top);
2912 glVertex2i(0, fbheight - drect->y2 - drect->y1);
2914 /* top right */
2915 glTexCoord2f(right, top);
2916 glVertex2i(drect->x2 - drect->x1, fbheight - drect->y2 - drect->y1);
2918 /* bottom right */
2919 glTexCoord2f(right, bottom);
2920 glVertex2i(drect->x2 - drect->x1, fbheight);
2921 glEnd();
2922 checkGLcall("glEnd and previous");
2924 if(texture_target != This->glDescription.target) {
2925 glDisable(texture_target);
2926 glEnable(This->glDescription.target);
2927 texture_target = This->glDescription.target;
2930 /* Now read the stretched and upside down image into the destination texture */
2931 glBindTexture(texture_target, This->glDescription.textureName);
2932 checkGLcall("glBindTexture");
2933 glCopyTexSubImage2D(texture_target,
2935 drect->x1, drect->y1, /* xoffset, yoffset */
2936 0, 0, /* We blitted the image to the origin */
2937 drect->x2 - drect->x1, drect->y2 - drect->y1);
2938 checkGLcall("glCopyTexSubImage2D");
2940 if(drawBuffer == GL_BACK) {
2941 /* Write the back buffer backup back */
2942 if(backup) {
2943 if(texture_target != GL_TEXTURE_2D) {
2944 glDisable(texture_target);
2945 glEnable(GL_TEXTURE_2D);
2946 texture_target = GL_TEXTURE_2D;
2948 glBindTexture(GL_TEXTURE_2D, backup);
2949 checkGLcall("glBindTexture(GL_TEXTURE_2D, backup)");
2950 } else {
2951 if(texture_target != Src->glDescription.target) {
2952 glDisable(texture_target);
2953 glEnable(Src->glDescription.target);
2954 texture_target = Src->glDescription.target;
2956 glBindTexture(Src->glDescription.target, Src->glDescription.textureName);
2957 checkGLcall("glBindTexture(Src->glDescription.target, Src->glDescription.textureName)");
2960 glBegin(GL_QUADS);
2961 /* top left */
2962 glTexCoord2f(0.0, (float) fbheight / (float) Src->pow2Height);
2963 glVertex2i(0, 0);
2965 /* bottom left */
2966 glTexCoord2f(0.0, 0.0);
2967 glVertex2i(0, fbheight);
2969 /* bottom right */
2970 glTexCoord2f((float) fbwidth / (float) Src->pow2Width, 0.0);
2971 glVertex2i(fbwidth, Src->currentDesc.Height);
2973 /* top right */
2974 glTexCoord2f((float) fbwidth / (float) Src->pow2Width, (float) fbheight / (float) Src->pow2Height);
2975 glVertex2i(fbwidth, 0);
2976 glEnd();
2977 } else {
2978 /* Restore the old draw buffer */
2979 glDrawBuffer(GL_BACK);
2981 glDisable(texture_target);
2982 checkGLcall("glDisable(texture_target)");
2984 /* Cleanup */
2985 if(src != Src->glDescription.textureName && src != backup) {
2986 glDeleteTextures(1, &src);
2987 checkGLcall("glDeleteTextures(1, &src)");
2989 if(backup) {
2990 glDeleteTextures(1, &backup);
2991 checkGLcall("glDeleteTextures(1, &backup)");
2994 LEAVE_GL();
2997 /* Not called from the VTable */
2998 static HRESULT IWineD3DSurfaceImpl_BltOverride(IWineD3DSurfaceImpl *This, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter) {
2999 WINED3DRECT rect;
3000 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3001 IWineD3DSwapChainImpl *srcSwapchain = NULL, *dstSwapchain = NULL;
3002 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
3004 TRACE("(%p)->(%p,%p,%p,%08x,%p)\n", This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx);
3006 /* Get the swapchain. One of the surfaces has to be a primary surface */
3007 if(This->resource.pool == WINED3DPOOL_SYSTEMMEM) {
3008 WARN("Destination is in sysmem, rejecting gl blt\n");
3009 return WINED3DERR_INVALIDCALL;
3011 IWineD3DSurface_GetContainer( (IWineD3DSurface *) This, &IID_IWineD3DSwapChain, (void **)&dstSwapchain);
3012 if(dstSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) dstSwapchain);
3013 if(Src) {
3014 if(Src->resource.pool == WINED3DPOOL_SYSTEMMEM) {
3015 WARN("Src is in sysmem, rejecting gl blt\n");
3016 return WINED3DERR_INVALIDCALL;
3018 IWineD3DSurface_GetContainer( (IWineD3DSurface *) Src, &IID_IWineD3DSwapChain, (void **)&srcSwapchain);
3019 if(srcSwapchain) IWineD3DSwapChain_Release((IWineD3DSwapChain *) srcSwapchain);
3022 /* Early sort out of cases where no render target is used */
3023 if(!dstSwapchain && !srcSwapchain &&
3024 SrcSurface != myDevice->render_targets[0] && This != (IWineD3DSurfaceImpl *) myDevice->render_targets[0]) {
3025 TRACE("No surface is render target, not using hardware blit. Src = %p, dst = %p\n", Src, This);
3026 return WINED3DERR_INVALIDCALL;
3029 /* No destination color keying supported */
3030 if(Flags & (WINEDDBLT_KEYDEST | WINEDDBLT_KEYDESTOVERRIDE)) {
3031 /* Can we support that with glBlendFunc if blitting to the frame buffer? */
3032 TRACE("Destination color key not supported in accelerated Blit, falling back to software\n");
3033 return WINED3DERR_INVALIDCALL;
3036 if (DestRect) {
3037 rect.x1 = DestRect->left;
3038 rect.y1 = DestRect->top;
3039 rect.x2 = DestRect->right;
3040 rect.y2 = DestRect->bottom;
3041 } else {
3042 rect.x1 = 0;
3043 rect.y1 = 0;
3044 rect.x2 = This->currentDesc.Width;
3045 rect.y2 = This->currentDesc.Height;
3048 /* The only case where both surfaces on a swapchain are supported is a back buffer -> front buffer blit on the same swapchain */
3049 if(dstSwapchain && dstSwapchain == srcSwapchain && dstSwapchain->backBuffer &&
3050 ((IWineD3DSurface *) This == dstSwapchain->frontBuffer) && SrcSurface == dstSwapchain->backBuffer[0]) {
3051 /* Half-life does a Blt from the back buffer to the front buffer,
3052 * Full surface size, no flags... Use present instead
3054 * This path will only be entered for d3d7 and ddraw apps, because d3d8/9 offer no way to blit TO the front buffer
3057 /* Check rects - IWineD3DDevice_Present doesn't handle them */
3058 while(1)
3060 RECT mySrcRect;
3061 TRACE("Looking if a Present can be done...\n");
3062 /* Source Rectangle must be full surface */
3063 if( SrcRect ) {
3064 if(SrcRect->left != 0 || SrcRect->top != 0 ||
3065 SrcRect->right != Src->currentDesc.Width || SrcRect->bottom != Src->currentDesc.Height) {
3066 TRACE("No, Source rectangle doesn't match\n");
3067 break;
3070 mySrcRect.left = 0;
3071 mySrcRect.top = 0;
3072 mySrcRect.right = Src->currentDesc.Width;
3073 mySrcRect.bottom = Src->currentDesc.Height;
3075 /* No stretching may occur */
3076 if(mySrcRect.right != rect.x2 - rect.x1 ||
3077 mySrcRect.bottom != rect.y2 - rect.y1) {
3078 TRACE("No, stretching is done\n");
3079 break;
3082 /* Destination must be full surface or match the clipping rectangle */
3083 if(This->clipper && ((IWineD3DClipperImpl *) This->clipper)->hWnd)
3085 RECT cliprect;
3086 POINT pos[2];
3087 GetClientRect(((IWineD3DClipperImpl *) This->clipper)->hWnd, &cliprect);
3088 pos[0].x = rect.x1;
3089 pos[0].y = rect.y1;
3090 pos[1].x = rect.x2;
3091 pos[1].y = rect.y2;
3092 MapWindowPoints(GetDesktopWindow(), ((IWineD3DClipperImpl *) This->clipper)->hWnd,
3093 pos, 2);
3095 if(pos[0].x != cliprect.left || pos[0].y != cliprect.top ||
3096 pos[1].x != cliprect.right || pos[1].y != cliprect.bottom)
3098 TRACE("No, dest rectangle doesn't match(clipper)\n");
3099 TRACE("Clip rect at (%d,%d)-(%d,%d)\n", cliprect.left, cliprect.top, cliprect.right, cliprect.bottom);
3100 TRACE("Blt dest: (%d,%d)-(%d,%d)\n", rect.x1, rect.y1, rect.x2, rect.y2);
3101 break;
3104 else
3106 if(rect.x1 != 0 || rect.y1 != 0 ||
3107 rect.x2 != This->currentDesc.Width || rect.y2 != This->currentDesc.Height) {
3108 TRACE("No, dest rectangle doesn't match(surface size)\n");
3109 break;
3113 TRACE("Yes\n");
3115 /* These flags are unimportant for the flag check, remove them */
3116 if((Flags & ~(WINEDDBLT_DONOTWAIT | WINEDDBLT_WAIT)) == 0) {
3117 WINED3DSWAPEFFECT orig_swap = dstSwapchain->presentParms.SwapEffect;
3119 /* The idea behind this is that a glReadPixels and a glDrawPixels call
3120 * take very long, while a flip is fast.
3121 * This applies to Half-Life, which does such Blts every time it finished
3122 * a frame, and to Prince of Persia 3D, which uses this to draw at least the main
3123 * menu. This is also used by all apps when they do windowed rendering
3125 * The problem is that flipping is not really the same as copying. After a
3126 * Blt the front buffer is a copy of the back buffer, and the back buffer is
3127 * untouched. Therefore it's necessary to override the swap effect
3128 * and to set it back after the flip.
3130 * Windowed Direct3D < 7 apps do the same. The D3D7 sdk demos are nice
3131 * testcases.
3134 dstSwapchain->presentParms.SwapEffect = WINED3DSWAPEFFECT_COPY;
3135 dstSwapchain->presentParms.PresentationInterval = WINED3DPRESENT_INTERVAL_IMMEDIATE;
3137 TRACE("Full screen back buffer -> front buffer blt, performing a flip instead\n");
3138 IWineD3DSwapChain_Present((IWineD3DSwapChain *) dstSwapchain, NULL, NULL, 0, NULL, 0);
3140 dstSwapchain->presentParms.SwapEffect = orig_swap;
3142 return WINED3D_OK;
3144 break;
3147 TRACE("Unsupported blit between buffers on the same swapchain\n");
3148 return WINED3DERR_INVALIDCALL;
3149 } else if(dstSwapchain && dstSwapchain == srcSwapchain) {
3150 FIXME("Implement hardware blit between two surfaces on the same swapchain\n");
3151 return WINED3DERR_INVALIDCALL;
3152 } else if(dstSwapchain && srcSwapchain) {
3153 FIXME("Implement hardware blit between two different swapchains\n");
3154 return WINED3DERR_INVALIDCALL;
3155 } else if(dstSwapchain) {
3156 if(SrcSurface == myDevice->render_targets[0]) {
3157 TRACE("Blit from active render target to a swapchain\n");
3158 /* Handled with regular texture -> swapchain blit */
3160 } else if(srcSwapchain && This == (IWineD3DSurfaceImpl *) myDevice->render_targets[0]) {
3161 FIXME("Implement blit from a swapchain to the active render target\n");
3162 return WINED3DERR_INVALIDCALL;
3165 if((srcSwapchain || SrcSurface == myDevice->render_targets[0]) && !dstSwapchain) {
3166 /* Blit from render target to texture */
3167 WINED3DRECT srect;
3168 BOOL upsideDown, stretchx;
3169 BOOL paletteOverride = FALSE;
3171 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3172 TRACE("Color keying not supported by frame buffer to texture blit\n");
3173 return WINED3DERR_INVALIDCALL;
3174 /* Destination color key is checked above */
3177 /* Make sure that the top pixel is always above the bottom pixel, and keep a separate upside down flag
3178 * glCopyTexSubImage is a bit picky about the parameters we pass to it
3180 if(SrcRect) {
3181 if(SrcRect->top < SrcRect->bottom) {
3182 srect.y1 = SrcRect->top;
3183 srect.y2 = SrcRect->bottom;
3184 upsideDown = FALSE;
3185 } else {
3186 srect.y1 = SrcRect->bottom;
3187 srect.y2 = SrcRect->top;
3188 upsideDown = TRUE;
3190 srect.x1 = SrcRect->left;
3191 srect.x2 = SrcRect->right;
3192 } else {
3193 srect.x1 = 0;
3194 srect.y1 = 0;
3195 srect.x2 = Src->currentDesc.Width;
3196 srect.y2 = Src->currentDesc.Height;
3197 upsideDown = FALSE;
3199 if(rect.x1 > rect.x2) {
3200 UINT tmp = rect.x2;
3201 rect.x2 = rect.x1;
3202 rect.x1 = tmp;
3203 upsideDown = !upsideDown;
3206 if(rect.x2 - rect.x1 != srect.x2 - srect.x1) {
3207 stretchx = TRUE;
3208 } else {
3209 stretchx = FALSE;
3212 /* When blitting from a render target a texture, the texture isn't required to have a palette.
3213 * In this case grab the palette from the render target. */
3214 if((This->resource.format == WINED3DFMT_P8) && (This->palette == NULL)) {
3215 paletteOverride = TRUE;
3216 TRACE("Source surface (%p) lacks palette, overriding palette with palette %p of destination surface (%p)\n", Src, This->palette, This);
3217 This->palette = Src->palette;
3220 /* Blt is a pretty powerful call, while glCopyTexSubImage2D is not. glCopyTexSubImage cannot
3221 * flip the image nor scale it.
3223 * -> If the app asks for a unscaled, upside down copy, just perform one glCopyTexSubImage2D call
3224 * -> If the app wants a image width an unscaled width, copy it line per line
3225 * -> If the app wants a image that is scaled on the x axis, and the destination rectangle is smaller
3226 * than the frame buffer, draw an upside down scaled image onto the fb, read it back and restore the
3227 * back buffer. This is slower than reading line per line, thus not used for flipping
3228 * -> If the app wants a scaled image with a dest rect that is bigger than the fb, it has to be copied
3229 * pixel by pixel
3231 * If EXT_framebuffer_blit is supported that can be used instead. Note that EXT_framebuffer_blit implies
3232 * FBO support, so it doesn't really make sense to try and make it work with different offscreen rendering
3233 * backends.
3235 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && GL_SUPPORT(EXT_FRAMEBUFFER_BLIT)) {
3236 stretch_rect_fbo((IWineD3DDevice *)myDevice, SrcSurface, &srect,
3237 (IWineD3DSurface *)This, &rect, Filter, upsideDown);
3238 } else if((!stretchx) || rect.x2 - rect.x1 > Src->currentDesc.Width ||
3239 rect.y2 - rect.y1 > Src->currentDesc.Height) {
3240 TRACE("No stretching in x direction, using direct framebuffer -> texture copy\n");
3241 fb_copy_to_texture_direct(This, SrcSurface, srcSwapchain, &srect, &rect, upsideDown, Filter);
3242 } else {
3243 TRACE("Using hardware stretching to flip / stretch the texture\n");
3244 fb_copy_to_texture_hwstretch(This, SrcSurface, srcSwapchain, &srect, &rect, upsideDown, Filter);
3247 /* Clear the palette as the surface didn't have a palette attached, it would confuse GetPalette and other calls */
3248 if(paletteOverride)
3249 This->palette = NULL;
3251 if(!(This->Flags & SFLAG_DONOTFREE)) {
3252 HeapFree(GetProcessHeap(), 0, This->resource.heapMemory);
3253 This->resource.allocatedMemory = NULL;
3254 This->resource.heapMemory = NULL;
3255 } else {
3256 This->Flags &= ~SFLAG_INSYSMEM;
3258 /* The texture is now most up to date - If the surface is a render target and has a drawable, this
3259 * path is never entered
3261 IWineD3DSurface_ModifyLocation((IWineD3DSurface *) This, SFLAG_INTEXTURE, TRUE);
3263 return WINED3D_OK;
3264 } else if(Src) {
3265 /* Blit from offscreen surface to render target */
3266 float glTexCoord[4];
3267 DWORD oldCKeyFlags = Src->CKeyFlags;
3268 WINEDDCOLORKEY oldBltCKey = Src->SrcBltCKey;
3269 RECT SourceRectangle;
3270 BOOL paletteOverride = FALSE;
3271 GLenum buffer;
3273 TRACE("Blt from surface %p to rendertarget %p\n", Src, This);
3275 if(SrcRect) {
3276 SourceRectangle.left = SrcRect->left;
3277 SourceRectangle.right = SrcRect->right;
3278 SourceRectangle.top = SrcRect->top;
3279 SourceRectangle.bottom = SrcRect->bottom;
3280 } else {
3281 SourceRectangle.left = 0;
3282 SourceRectangle.right = Src->currentDesc.Width;
3283 SourceRectangle.top = 0;
3284 SourceRectangle.bottom = Src->currentDesc.Height;
3287 /* When blitting from an offscreen surface to a rendertarget, the source
3288 * surface is not required to have a palette. Our rendering / conversion
3289 * code further down the road retrieves the palette from the surface, so
3290 * it must have a palette set. */
3291 if((Src->resource.format == WINED3DFMT_P8) && (Src->palette == NULL)) {
3292 paletteOverride = TRUE;
3293 TRACE("Source surface (%p) lacks palette, overriding palette with palette %p of destination surface (%p)\n", Src, This->palette, This);
3294 Src->palette = This->palette;
3297 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && GL_SUPPORT(EXT_FRAMEBUFFER_BLIT) &&
3298 (Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) == 0) {
3299 TRACE("Using stretch_rect_fbo\n");
3300 /* The source is always a texture, but never the currently active render target, and the texture
3301 * contents are never upside down
3303 stretch_rect_fbo((IWineD3DDevice *)myDevice, SrcSurface, (WINED3DRECT *) &SourceRectangle,
3304 (IWineD3DSurface *)This, &rect, Filter, FALSE);
3306 /* Clear the palette as the surface didn't have a palette attached, it would confuse GetPalette and other calls */
3307 if(paletteOverride)
3308 Src->palette = NULL;
3309 return WINED3D_OK;
3312 if(!CalculateTexRect(Src, &SourceRectangle, glTexCoord)) {
3313 /* Fall back to software */
3314 WARN("(%p) Source texture area (%d,%d)-(%d,%d) is too big\n", Src,
3315 SourceRectangle.left, SourceRectangle.top,
3316 SourceRectangle.right, SourceRectangle.bottom);
3317 return WINED3DERR_INVALIDCALL;
3320 /* Color keying: Check if we have to do a color keyed blt,
3321 * and if not check if a color key is activated.
3323 * Just modify the color keying parameters in the surface and restore them afterwards
3324 * The surface keeps track of the color key last used to load the opengl surface.
3325 * PreLoad will catch the change to the flags and color key and reload if necessary.
3327 if(Flags & WINEDDBLT_KEYSRC) {
3328 /* Use color key from surface */
3329 } else if(Flags & WINEDDBLT_KEYSRCOVERRIDE) {
3330 /* Use color key from DDBltFx */
3331 Src->CKeyFlags |= WINEDDSD_CKSRCBLT;
3332 Src->SrcBltCKey = DDBltFx->ddckSrcColorkey;
3333 } else {
3334 /* Do not use color key */
3335 Src->CKeyFlags &= ~WINEDDSD_CKSRCBLT;
3338 /* Now load the surface */
3339 IWineD3DSurface_PreLoad((IWineD3DSurface *) Src);
3342 /* Activate the destination context, set it up for blitting */
3343 ActivateContext(myDevice, (IWineD3DSurface *) This, CTXUSAGE_BLIT);
3345 if(!dstSwapchain) {
3346 TRACE("Drawing to offscreen buffer\n");
3347 buffer = myDevice->offscreenBuffer;
3348 } else {
3349 buffer = surface_get_gl_buffer((IWineD3DSurface *)This, (IWineD3DSwapChain *)dstSwapchain);
3351 /* Front buffer coordinates are screen coordinates, while OpenGL coordinates are
3352 * window relative. Also beware of the origin difference(top left vs bottom left).
3353 * Also beware that the front buffer's surface size is screen width x screen height,
3354 * whereas the real gl drawable size is the size of the window.
3356 if(buffer == GL_FRONT) {
3357 RECT windowsize;
3358 POINT offset = {0,0};
3359 UINT h;
3360 ClientToScreen(myDevice->ddraw_window, &offset);
3361 GetClientRect(myDevice->ddraw_window, &windowsize);
3362 h = windowsize.bottom - windowsize.top;
3363 rect.x1 -= offset.x; rect.x2 -=offset.x;
3364 rect.y1 -= offset.y; rect.y2 -=offset.y;
3365 rect.y1 += This->currentDesc.Height - h; rect.y2 += This->currentDesc.Height - h;
3367 TRACE("Drawing to %#x buffer\n", buffer);
3370 ENTER_GL();
3371 glDrawBuffer(buffer);
3372 checkGLcall("glDrawBuffer");
3374 glEnable(Src->glDescription.target);
3375 checkGLcall("glEnable(Src->glDescription.target)");
3377 /* Bind the texture */
3378 glBindTexture(Src->glDescription.target, Src->glDescription.textureName);
3379 checkGLcall("glBindTexture");
3381 /* Filtering for StretchRect */
3382 glTexParameteri(Src->glDescription.target, GL_TEXTURE_MAG_FILTER,
3383 magLookup[Filter - WINED3DTEXF_NONE]);
3384 checkGLcall("glTexParameteri");
3385 glTexParameteri(Src->glDescription.target, GL_TEXTURE_MIN_FILTER,
3386 minMipLookup[Filter][WINED3DTEXF_NONE]);
3387 checkGLcall("glTexParameteri");
3388 glTexParameteri(Src->glDescription.target, GL_TEXTURE_WRAP_S, GL_CLAMP);
3389 glTexParameteri(Src->glDescription.target, GL_TEXTURE_WRAP_T, GL_CLAMP);
3390 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
3391 checkGLcall("glTexEnvi");
3393 /* This is for color keying */
3394 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3395 glEnable(GL_ALPHA_TEST);
3396 checkGLcall("glEnable GL_ALPHA_TEST");
3398 /* When the primary render target uses P8, the alpha component contains the palette index.
3399 * Which means that the colorkey is one of the palette entries. In other cases pixels that
3400 * should be masked away have alpha set to 0. */
3401 if(primary_render_target_is_p8(myDevice))
3402 glAlphaFunc(GL_NOTEQUAL, (float)Src->SrcBltCKey.dwColorSpaceLowValue / 256.0);
3403 else
3404 glAlphaFunc(GL_NOTEQUAL, 0.0);
3405 checkGLcall("glAlphaFunc\n");
3406 } else {
3407 glDisable(GL_ALPHA_TEST);
3408 checkGLcall("glDisable GL_ALPHA_TEST");
3411 /* Draw a textured quad
3413 glBegin(GL_QUADS);
3415 glColor3d(1.0f, 1.0f, 1.0f);
3416 glTexCoord2f(glTexCoord[0], glTexCoord[2]);
3417 glVertex3f(rect.x1,
3418 rect.y1,
3419 0.0);
3421 glTexCoord2f(glTexCoord[0], glTexCoord[3]);
3422 glVertex3f(rect.x1, rect.y2, 0.0);
3424 glTexCoord2f(glTexCoord[1], glTexCoord[3]);
3425 glVertex3f(rect.x2,
3426 rect.y2,
3427 0.0);
3429 glTexCoord2f(glTexCoord[1], glTexCoord[2]);
3430 glVertex3f(rect.x2,
3431 rect.y1,
3432 0.0);
3433 glEnd();
3434 checkGLcall("glEnd");
3436 if(Flags & (WINEDDBLT_KEYSRC | WINEDDBLT_KEYSRCOVERRIDE)) {
3437 glDisable(GL_ALPHA_TEST);
3438 checkGLcall("glDisable(GL_ALPHA_TEST)");
3441 glBindTexture(Src->glDescription.target, 0);
3442 checkGLcall("glBindTexture(Src->glDescription.target, 0)");
3443 /* Leave the opengl state valid for blitting */
3444 glDisable(Src->glDescription.target);
3445 checkGLcall("glDisable(Src->glDescription.target)");
3447 /* The draw buffer should only need to be restored if we were drawing to the front buffer, and there is a back buffer.
3448 * otherwise the context manager should choose between GL_BACK / offscreenDrawBuffer
3450 if(dstSwapchain && This == (IWineD3DSurfaceImpl *) dstSwapchain->frontBuffer && dstSwapchain->backBuffer) {
3451 glDrawBuffer(GL_BACK);
3452 checkGLcall("glDrawBuffer");
3454 /* Restore the color key parameters */
3455 Src->CKeyFlags = oldCKeyFlags;
3456 Src->SrcBltCKey = oldBltCKey;
3458 /* Clear the palette as the surface didn't have a palette attached, it would confuse GetPalette and other calls */
3459 if(paletteOverride)
3460 Src->palette = NULL;
3462 LEAVE_GL();
3464 /* Flush in case the drawable is used by multiple GL contexts */
3465 if(dstSwapchain && (This == (IWineD3DSurfaceImpl *) dstSwapchain->frontBuffer || dstSwapchain->num_contexts >= 2))
3466 glFlush();
3468 /* TODO: If the surface is locked often, perform the Blt in software on the memory instead */
3469 /* The surface is now in the drawable. On onscreen surfaces or without fbos the texture
3470 * is outdated now
3472 IWineD3DSurface_ModifyLocation((IWineD3DSurface *) This, SFLAG_INDRAWABLE, TRUE);
3473 /* TODO: This should be moved to ModifyLocation() */
3474 if(!(dstSwapchain || wined3d_settings.offscreen_rendering_mode != ORM_FBO)) {
3475 This->Flags |= SFLAG_INTEXTURE;
3478 return WINED3D_OK;
3479 } else {
3480 /* Source-Less Blit to render target */
3481 if (Flags & WINEDDBLT_COLORFILL) {
3482 /* This is easy to handle for the D3D Device... */
3483 DWORD color;
3485 TRACE("Colorfill\n");
3487 /* This == (IWineD3DSurfaceImpl *) myDevice->render_targets[0] || dstSwapchain
3488 must be true if we are here */
3489 if (This != (IWineD3DSurfaceImpl *) myDevice->render_targets[0] &&
3490 !(This == (IWineD3DSurfaceImpl*) dstSwapchain->frontBuffer ||
3491 (dstSwapchain->backBuffer && This == (IWineD3DSurfaceImpl*) dstSwapchain->backBuffer[0]))) {
3492 TRACE("Surface is higher back buffer, falling back to software\n");
3493 return WINED3DERR_INVALIDCALL;
3496 /* The color as given in the Blt function is in the format of the frame-buffer...
3497 * 'clear' expect it in ARGB format => we need to do some conversion :-)
3499 if (This->resource.format == WINED3DFMT_P8) {
3500 DWORD alpha;
3502 if (primary_render_target_is_p8(myDevice)) alpha = DDBltFx->u5.dwFillColor << 24;
3503 else alpha = 0xFF000000;
3505 if (This->palette) {
3506 color = (alpha |
3507 (This->palette->palents[DDBltFx->u5.dwFillColor].peRed << 16) |
3508 (This->palette->palents[DDBltFx->u5.dwFillColor].peGreen << 8) |
3509 (This->palette->palents[DDBltFx->u5.dwFillColor].peBlue));
3510 } else {
3511 color = alpha;
3514 else if (This->resource.format == WINED3DFMT_R5G6B5) {
3515 if (DDBltFx->u5.dwFillColor == 0xFFFF) {
3516 color = 0xFFFFFFFF;
3517 } else {
3518 color = ((0xFF000000) |
3519 ((DDBltFx->u5.dwFillColor & 0xF800) << 8) |
3520 ((DDBltFx->u5.dwFillColor & 0x07E0) << 5) |
3521 ((DDBltFx->u5.dwFillColor & 0x001F) << 3));
3524 else if ((This->resource.format == WINED3DFMT_R8G8B8) ||
3525 (This->resource.format == WINED3DFMT_X8R8G8B8) ) {
3526 color = 0xFF000000 | DDBltFx->u5.dwFillColor;
3528 else if (This->resource.format == WINED3DFMT_A8R8G8B8) {
3529 color = DDBltFx->u5.dwFillColor;
3531 else {
3532 ERR("Wrong surface type for BLT override(Format doesn't match) !\n");
3533 return WINED3DERR_INVALIDCALL;
3536 TRACE("(%p) executing Render Target override, color = %x\n", This, color);
3537 IWineD3DDeviceImpl_ClearSurface(myDevice, This,
3538 1, /* Number of rectangles */
3539 &rect, WINED3DCLEAR_TARGET, color,
3540 0.0 /* Z */,
3541 0 /* Stencil */);
3542 return WINED3D_OK;
3546 /* Default: Fall back to the generic blt. Not an error, a TRACE is enough */
3547 TRACE("Didn't find any usable render target setup for hw blit, falling back to software\n");
3548 return WINED3DERR_INVALIDCALL;
3551 static HRESULT WINAPI IWineD3DSurfaceImpl_BltZ(IWineD3DSurfaceImpl *This, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx)
3553 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3554 float depth;
3556 if (Flags & WINEDDBLT_DEPTHFILL) {
3557 switch(This->resource.format) {
3558 case WINED3DFMT_D16:
3559 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000ffff;
3560 break;
3561 case WINED3DFMT_D15S1:
3562 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x0000fffe;
3563 break;
3564 case WINED3DFMT_D24S8:
3565 case WINED3DFMT_D24X8:
3566 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0x00ffffff;
3567 break;
3568 case WINED3DFMT_D32:
3569 depth = (float) DDBltFx->u5.dwFillDepth / (float) 0xffffffff;
3570 break;
3571 default:
3572 depth = 0.0;
3573 ERR("Unexpected format for depth fill: %s\n", debug_d3dformat(This->resource.format));
3576 return IWineD3DDevice_Clear((IWineD3DDevice *) myDevice,
3577 DestRect == NULL ? 0 : 1,
3578 (WINED3DRECT *) DestRect,
3579 WINED3DCLEAR_ZBUFFER,
3580 0x00000000,
3581 depth,
3582 0x00000000);
3585 FIXME("(%p): Unsupp depthstencil blit\n", This);
3586 return WINED3DERR_INVALIDCALL;
3589 static HRESULT WINAPI IWineD3DSurfaceImpl_Blt(IWineD3DSurface *iface, RECT *DestRect, IWineD3DSurface *SrcSurface, RECT *SrcRect, DWORD Flags, WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter) {
3590 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3591 IWineD3DSurfaceImpl *Src = (IWineD3DSurfaceImpl *) SrcSurface;
3592 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3593 TRACE("(%p)->(%p,%p,%p,%x,%p)\n", This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx);
3594 TRACE("(%p): Usage is %s\n", This, debug_d3dusage(This->resource.usage));
3596 if ( (This->Flags & SFLAG_LOCKED) || ((Src != NULL) && (Src->Flags & SFLAG_LOCKED)))
3598 WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
3599 return WINEDDERR_SURFACEBUSY;
3602 /* Accessing the depth stencil is supposed to fail between a BeginScene and EndScene pair,
3603 * except depth blits, which seem to work
3605 if(iface == myDevice->stencilBufferTarget || (SrcSurface && SrcSurface == myDevice->stencilBufferTarget)) {
3606 if(myDevice->inScene && !(Flags & WINEDDBLT_DEPTHFILL)) {
3607 TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3608 return WINED3DERR_INVALIDCALL;
3609 } else if(IWineD3DSurfaceImpl_BltZ(This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx) == WINED3D_OK) {
3610 TRACE("Z Blit override handled the blit\n");
3611 return WINED3D_OK;
3615 /* Special cases for RenderTargets */
3616 if( (This->resource.usage & WINED3DUSAGE_RENDERTARGET) ||
3617 ( Src && (Src->resource.usage & WINED3DUSAGE_RENDERTARGET) )) {
3618 if(IWineD3DSurfaceImpl_BltOverride(This, DestRect, SrcSurface, SrcRect, Flags, DDBltFx, Filter) == WINED3D_OK) return WINED3D_OK;
3621 /* For the rest call the X11 surface implementation.
3622 * For RenderTargets this should be implemented OpenGL accelerated in BltOverride,
3623 * other Blts are rather rare
3625 return IWineD3DBaseSurfaceImpl_Blt(iface, DestRect, SrcSurface, SrcRect, Flags, DDBltFx, Filter);
3628 HRESULT WINAPI IWineD3DSurfaceImpl_BltFast(IWineD3DSurface *iface, DWORD dstx, DWORD dsty, IWineD3DSurface *Source, RECT *rsrc, DWORD trans) {
3629 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3630 IWineD3DSurfaceImpl *srcImpl = (IWineD3DSurfaceImpl *) Source;
3631 IWineD3DDeviceImpl *myDevice = This->resource.wineD3DDevice;
3632 TRACE("(%p)->(%d, %d, %p, %p, %08x\n", iface, dstx, dsty, Source, rsrc, trans);
3634 if ( (This->Flags & SFLAG_LOCKED) || ((srcImpl != NULL) && (srcImpl->Flags & SFLAG_LOCKED)))
3636 WARN(" Surface is busy, returning DDERR_SURFACEBUSY\n");
3637 return WINEDDERR_SURFACEBUSY;
3640 if(myDevice->inScene &&
3641 (iface == myDevice->stencilBufferTarget ||
3642 (Source && Source == myDevice->stencilBufferTarget))) {
3643 TRACE("Attempt to access the depth stencil surface in a BeginScene / EndScene pair, returning WINED3DERR_INVALIDCALL\n");
3644 return WINED3DERR_INVALIDCALL;
3647 /* Special cases for RenderTargets */
3648 if( (This->resource.usage & WINED3DUSAGE_RENDERTARGET) ||
3649 ( srcImpl && (srcImpl->resource.usage & WINED3DUSAGE_RENDERTARGET) )) {
3651 RECT SrcRect, DstRect;
3652 DWORD Flags=0;
3654 if(rsrc) {
3655 SrcRect.left = rsrc->left;
3656 SrcRect.top= rsrc->top;
3657 SrcRect.bottom = rsrc->bottom;
3658 SrcRect.right = rsrc->right;
3659 } else {
3660 SrcRect.left = 0;
3661 SrcRect.top = 0;
3662 SrcRect.right = srcImpl->currentDesc.Width;
3663 SrcRect.bottom = srcImpl->currentDesc.Height;
3666 DstRect.left = dstx;
3667 DstRect.top=dsty;
3668 DstRect.right = dstx + SrcRect.right - SrcRect.left;
3669 DstRect.bottom = dsty + SrcRect.bottom - SrcRect.top;
3671 /* Convert BltFast flags into Btl ones because it is called from SurfaceImpl_Blt as well */
3672 if(trans & WINEDDBLTFAST_SRCCOLORKEY)
3673 Flags |= WINEDDBLT_KEYSRC;
3674 if(trans & WINEDDBLTFAST_DESTCOLORKEY)
3675 Flags |= WINEDDBLT_KEYDEST;
3676 if(trans & WINEDDBLTFAST_WAIT)
3677 Flags |= WINEDDBLT_WAIT;
3678 if(trans & WINEDDBLTFAST_DONOTWAIT)
3679 Flags |= WINEDDBLT_DONOTWAIT;
3681 if(IWineD3DSurfaceImpl_BltOverride(This, &DstRect, Source, &SrcRect, Flags, NULL, WINED3DTEXF_POINT) == WINED3D_OK) return WINED3D_OK;
3685 return IWineD3DBaseSurfaceImpl_BltFast(iface, dstx, dsty, Source, rsrc, trans);
3688 HRESULT WINAPI IWineD3DSurfaceImpl_RealizePalette(IWineD3DSurface *iface) {
3689 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3690 RGBQUAD col[256];
3691 IWineD3DPaletteImpl *pal = This->palette;
3692 unsigned int n;
3693 TRACE("(%p)\n", This);
3695 if (!pal) return WINED3D_OK;
3697 if(This->resource.format == WINED3DFMT_P8 ||
3698 This->resource.format == WINED3DFMT_A8P8)
3700 int bpp;
3701 GLenum format, internal, type;
3702 CONVERT_TYPES convert;
3704 /* Check if we are using a RTL mode which uses texturing for uploads */
3705 BOOL use_texture = (wined3d_settings.rendertargetlock_mode == RTL_READTEX || wined3d_settings.rendertargetlock_mode == RTL_TEXTEX);
3707 /* Check if we have hardware palette conversion if we have convert is set to NO_CONVERSION */
3708 d3dfmt_get_conv(This, TRUE, use_texture, &format, &internal, &type, &convert, &bpp, This->srgb);
3710 if((This->resource.usage & WINED3DUSAGE_RENDERTARGET) && (convert == NO_CONVERSION))
3712 ENTER_GL();
3713 if (This->glDescription.textureName == 0) {
3714 glGenTextures(1, &This->glDescription.textureName);
3715 checkGLcall("glGenTextures");
3717 glBindTexture(This->glDescription.target, This->glDescription.textureName);
3718 checkGLcall("glBindTexture(This->glDescription.target, This->glDescription.textureName)");
3719 LEAVE_GL();
3721 /* Make sure the texture is up to date. This call doesn't do anything if the texture is already up to date. */
3722 IWineD3DSurface_LoadLocation(iface, SFLAG_INTEXTURE, NULL);
3724 /* We want to force a palette refresh, so mark the drawable as not being up to date */
3725 IWineD3DSurface_ModifyLocation(iface, SFLAG_INDRAWABLE, FALSE);
3727 /* Re-upload the palette */
3728 d3dfmt_p8_upload_palette(iface, convert);
3730 /* Without this some palette updates are missed. This at least happens on Nvidia drivers but
3731 * it works fine using Mesa. */
3732 glFlush();
3733 } else {
3734 if(!(This->Flags & SFLAG_INSYSMEM)) {
3735 TRACE("Palette changed with surface that does not have an up to date system memory copy\n");
3736 IWineD3DSurface_LoadLocation(iface, SFLAG_INSYSMEM, NULL);
3738 TRACE("Dirtifying surface\n");
3739 IWineD3DSurface_ModifyLocation(iface, SFLAG_INSYSMEM, TRUE);
3743 if(This->Flags & SFLAG_DIBSECTION) {
3744 TRACE("(%p): Updating the hdc's palette\n", This);
3745 for (n=0; n<256; n++) {
3746 col[n].rgbRed = pal->palents[n].peRed;
3747 col[n].rgbGreen = pal->palents[n].peGreen;
3748 col[n].rgbBlue = pal->palents[n].peBlue;
3749 col[n].rgbReserved = 0;
3751 SetDIBColorTable(This->hDC, 0, 256, col);
3754 /* Propagate the changes to the drawable when we have a palette. */
3755 if(This->resource.usage & WINED3DUSAGE_RENDERTARGET)
3756 IWineD3DSurface_LoadLocation(iface, SFLAG_INDRAWABLE, NULL);
3758 return WINED3D_OK;
3761 static HRESULT WINAPI IWineD3DSurfaceImpl_PrivateSetup(IWineD3DSurface *iface) {
3762 /** Check against the maximum texture sizes supported by the video card **/
3763 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3764 unsigned int pow2Width, pow2Height;
3765 const GlPixelFormatDesc *glDesc;
3767 getFormatDescEntry(This->resource.format, &GLINFO_LOCATION, &glDesc);
3768 /* Setup some glformat defaults */
3769 This->glDescription.glFormat = glDesc->glFormat;
3770 This->glDescription.glFormatInternal = glDesc->glInternal;
3771 This->glDescription.glType = glDesc->glType;
3773 This->glDescription.textureName = 0;
3774 This->glDescription.target = GL_TEXTURE_2D;
3776 /* Non-power2 support */
3777 if (GL_SUPPORT(ARB_TEXTURE_NON_POWER_OF_TWO) || GL_SUPPORT(WINE_NORMALIZED_TEXRECT)) {
3778 pow2Width = This->currentDesc.Width;
3779 pow2Height = This->currentDesc.Height;
3780 } else {
3781 /* Find the nearest pow2 match */
3782 pow2Width = pow2Height = 1;
3783 while (pow2Width < This->currentDesc.Width) pow2Width <<= 1;
3784 while (pow2Height < This->currentDesc.Height) pow2Height <<= 1;
3786 This->pow2Width = pow2Width;
3787 This->pow2Height = pow2Height;
3789 if (pow2Width > This->currentDesc.Width || pow2Height > This->currentDesc.Height) {
3790 WINED3DFORMAT Format = This->resource.format;
3791 /** TODO: add support for non power two compressed textures **/
3792 if (Format == WINED3DFMT_DXT1 || Format == WINED3DFMT_DXT2 || Format == WINED3DFMT_DXT3
3793 || Format == WINED3DFMT_DXT4 || Format == WINED3DFMT_DXT5
3794 || This->resource.format == WINED3DFMT_ATI2N) {
3795 FIXME("(%p) Compressed non-power-two textures are not supported w(%d) h(%d)\n",
3796 This, This->currentDesc.Width, This->currentDesc.Height);
3797 return WINED3DERR_NOTAVAILABLE;
3801 if(pow2Width != This->currentDesc.Width ||
3802 pow2Height != This->currentDesc.Height) {
3803 This->Flags |= SFLAG_NONPOW2;
3806 TRACE("%p\n", This);
3807 if ((This->pow2Width > GL_LIMITS(texture_size) || This->pow2Height > GL_LIMITS(texture_size)) && !(This->resource.usage & (WINED3DUSAGE_RENDERTARGET | WINED3DUSAGE_DEPTHSTENCIL))) {
3808 /* one of three options
3809 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)
3810 2: Set the texture to the maximum size (bad idea)
3811 3: WARN and return WINED3DERR_NOTAVAILABLE;
3812 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.
3814 WARN("(%p) Creating an oversized surface\n", This);
3815 This->Flags |= SFLAG_OVERSIZE;
3817 /* This will be initialized on the first blt */
3818 This->glRect.left = 0;
3819 This->glRect.top = 0;
3820 This->glRect.right = 0;
3821 This->glRect.bottom = 0;
3822 } else {
3823 /* Check this after the oversize check - do not make an oversized surface a texture_rectangle one.
3824 Second also don't use ARB_TEXTURE_RECTANGLE in case the surface format is P8 and EXT_PALETTED_TEXTURE
3825 is used in combination with texture uploads (RTL_READTEX/RTL_TEXTEX). The reason is that EXT_PALETTED_TEXTURE
3826 doesn't work in combination with ARB_TEXTURE_RECTANGLE.
3828 if(This->Flags & SFLAG_NONPOW2 && GL_SUPPORT(ARB_TEXTURE_RECTANGLE) &&
3829 !((This->resource.format == WINED3DFMT_P8) && GL_SUPPORT(EXT_PALETTED_TEXTURE) && (wined3d_settings.rendertargetlock_mode == RTL_READTEX || wined3d_settings.rendertargetlock_mode == RTL_TEXTEX)))
3831 This->glDescription.target = GL_TEXTURE_RECTANGLE_ARB;
3832 This->pow2Width = This->currentDesc.Width;
3833 This->pow2Height = This->currentDesc.Height;
3834 This->Flags &= ~(SFLAG_NONPOW2 | SFLAG_NORMCOORD);
3837 /* No oversize, gl rect is the full texture size */
3838 This->Flags &= ~SFLAG_OVERSIZE;
3839 This->glRect.left = 0;
3840 This->glRect.top = 0;
3841 This->glRect.right = This->pow2Width;
3842 This->glRect.bottom = This->pow2Height;
3845 if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
3846 switch(wined3d_settings.offscreen_rendering_mode) {
3847 case ORM_FBO: This->get_drawable_size = get_drawable_size_fbo; break;
3848 case ORM_PBUFFER: This->get_drawable_size = get_drawable_size_pbuffer; break;
3849 case ORM_BACKBUFFER: This->get_drawable_size = get_drawable_size_backbuffer; break;
3853 This->Flags |= SFLAG_INSYSMEM;
3855 return WINED3D_OK;
3858 void surface_modify_ds_location(IWineD3DSurface *iface, DWORD location) {
3859 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3861 TRACE("(%p) New location %#x\n", This, location);
3863 if (location & ~SFLAG_DS_LOCATIONS) {
3864 FIXME("(%p) Invalid location (%#x) specified\n", This, location);
3867 This->Flags &= ~SFLAG_DS_LOCATIONS;
3868 This->Flags |= location;
3871 void surface_load_ds_location(IWineD3DSurface *iface, DWORD location) {
3872 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *)iface;
3873 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
3875 TRACE("(%p) New location %#x\n", This, location);
3877 /* TODO: Make this work for modes other than FBO */
3878 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return;
3880 if (This->Flags & location) {
3881 TRACE("(%p) Location (%#x) is already up to date\n", This, location);
3882 return;
3885 if (This->current_renderbuffer) {
3886 FIXME("(%p) Not supported with fixed up depth stencil\n", This);
3887 return;
3890 if (location == SFLAG_DS_OFFSCREEN) {
3891 if (This->Flags & SFLAG_DS_ONSCREEN) {
3892 GLint old_binding = 0;
3894 TRACE("(%p) Copying onscreen depth buffer to depth texture\n", This);
3896 ENTER_GL();
3898 if (!device->depth_blt_texture) {
3899 glGenTextures(1, &device->depth_blt_texture);
3902 /* Note that we use depth_blt here as well, rather than glCopyTexImage2D
3903 * directly on the FBO texture. That's because we need to flip. */
3904 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
3905 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
3906 glBindTexture(GL_TEXTURE_2D, device->depth_blt_texture);
3907 glCopyTexImage2D(This->glDescription.target,
3908 This->glDescription.level,
3909 This->glDescription.glFormatInternal,
3912 This->currentDesc.Width,
3913 This->currentDesc.Height,
3915 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
3916 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
3917 glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE);
3918 glBindTexture(GL_TEXTURE_2D, old_binding);
3920 /* Setup the destination */
3921 if (!device->depth_blt_rb) {
3922 GL_EXTCALL(glGenRenderbuffersEXT(1, &device->depth_blt_rb));
3923 checkGLcall("glGenRenderbuffersEXT");
3925 if (device->depth_blt_rb_w != This->currentDesc.Width
3926 || device->depth_blt_rb_h != This->currentDesc.Height) {
3927 GL_EXTCALL(glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, device->depth_blt_rb));
3928 checkGLcall("glBindRenderbufferEXT");
3929 GL_EXTCALL(glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA8, This->currentDesc.Width, This->currentDesc.Height));
3930 checkGLcall("glRenderbufferStorageEXT");
3931 device->depth_blt_rb_w = This->currentDesc.Width;
3932 device->depth_blt_rb_h = This->currentDesc.Height;
3935 bind_fbo((IWineD3DDevice *)device, GL_FRAMEBUFFER_EXT, &device->dst_fbo);
3936 GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, device->depth_blt_rb));
3937 checkGLcall("glFramebufferRenderbufferEXT");
3938 attach_depth_stencil_fbo(device, GL_FRAMEBUFFER_EXT, iface, FALSE);
3940 /* Do the actual blit */
3941 depth_blt((IWineD3DDevice *)device, device->depth_blt_texture);
3942 checkGLcall("depth_blt");
3944 if (device->render_offscreen) {
3945 bind_fbo((IWineD3DDevice *)device, GL_FRAMEBUFFER_EXT, &device->fbo);
3946 } else {
3947 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
3948 checkGLcall("glBindFramebuffer()");
3951 LEAVE_GL();
3952 } else {
3953 FIXME("No up to date depth stencil location\n");
3955 } else if (location == SFLAG_DS_ONSCREEN) {
3956 if (This->Flags & SFLAG_DS_OFFSCREEN) {
3957 TRACE("(%p) Copying depth texture to onscreen depth buffer\n", This);
3959 ENTER_GL();
3961 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
3962 checkGLcall("glBindFramebuffer()");
3963 depth_blt((IWineD3DDevice *)device, This->glDescription.textureName);
3964 checkGLcall("depth_blt");
3966 if (device->render_offscreen) {
3967 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, device->fbo));
3968 checkGLcall("glBindFramebuffer()");
3971 LEAVE_GL();
3972 } else {
3973 FIXME("No up to date depth stencil location\n");
3975 } else {
3976 ERR("(%p) Invalid location (%#x) specified\n", This, location);
3979 This->Flags |= location;
3982 static void WINAPI IWineD3DSurfaceImpl_ModifyLocation(IWineD3DSurface *iface, DWORD flag, BOOL persistent) {
3983 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
3984 IWineD3DBaseTexture *texture;
3986 TRACE("(%p)->(%s, %s)\n", iface,
3987 flag == SFLAG_INSYSMEM ? "SFLAG_INSYSMEM" : flag == SFLAG_INDRAWABLE ? "SFLAG_INDRAWABLE" : "SFLAG_INTEXTURE",
3988 persistent ? "TRUE" : "FALSE");
3990 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
3991 IWineD3DSwapChain *swapchain = NULL;
3993 if (SUCCEEDED(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
3994 TRACE("Surface %p is an onscreen surface\n", iface);
3996 IWineD3DSwapChain_Release(swapchain);
3997 } else {
3998 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
3999 if (flag & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE)) flag |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4003 if(persistent) {
4004 if((This->Flags & SFLAG_INTEXTURE) && !(flag & SFLAG_INTEXTURE)) {
4005 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&texture) == WINED3D_OK) {
4006 TRACE("Passing to container\n");
4007 IWineD3DBaseTexture_SetDirty(texture, TRUE);
4008 IWineD3DBaseTexture_Release(texture);
4011 This->Flags &= ~SFLAG_LOCATIONS;
4012 This->Flags |= flag;
4013 } else {
4014 if((This->Flags & SFLAG_INTEXTURE) && (flag & SFLAG_INTEXTURE)) {
4015 if (IWineD3DSurface_GetContainer(iface, &IID_IWineD3DBaseTexture, (void **)&texture) == WINED3D_OK) {
4016 TRACE("Passing to container\n");
4017 IWineD3DBaseTexture_SetDirty(texture, TRUE);
4018 IWineD3DBaseTexture_Release(texture);
4021 This->Flags &= ~flag;
4025 struct coords {
4026 GLfloat x, y, z;
4029 static inline void surface_blt_to_drawable(IWineD3DSurfaceImpl *This, const RECT *rect_in) {
4030 struct coords coords[4];
4031 RECT rect;
4032 IWineD3DSwapChain *swapchain = NULL;
4033 IWineD3DBaseTexture *texture = NULL;
4034 HRESULT hr;
4035 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
4037 if(rect_in) {
4038 rect = *rect_in;
4039 } else {
4040 rect.left = 0;
4041 rect.top = 0;
4042 rect.right = This->currentDesc.Width;
4043 rect.bottom = This->currentDesc.Height;
4046 ActivateContext(device, (IWineD3DSurface*)This, CTXUSAGE_BLIT);
4047 ENTER_GL();
4049 if(This->glDescription.target == GL_TEXTURE_RECTANGLE_ARB) {
4050 glEnable(GL_TEXTURE_RECTANGLE_ARB);
4051 checkGLcall("glEnable(GL_TEXTURE_RECTANGLE_ARB)");
4052 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, This->glDescription.textureName);
4053 checkGLcall("GL_TEXTURE_RECTANGLE_ARB, This->glDescription.textureName)");
4054 glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
4055 checkGLcall("glTexParameteri");
4056 glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
4057 checkGLcall("glTexParameteri");
4059 coords[0].x = rect.left;
4060 coords[0].z = 0;
4062 coords[1].x = rect.left;
4063 coords[1].z = 0;
4065 coords[2].x = rect.right;
4066 coords[2].z = 0;
4068 coords[3].x = rect.right;
4069 coords[3].z = 0;
4071 coords[0].y = rect.top;
4072 coords[1].y = rect.bottom;
4073 coords[2].y = rect.bottom;
4074 coords[3].y = rect.top;
4075 } else if(This->glDescription.target == GL_TEXTURE_2D) {
4076 glEnable(GL_TEXTURE_2D);
4077 checkGLcall("glEnable(GL_TEXTURE_2D)");
4078 glBindTexture(GL_TEXTURE_2D, This->glDescription.textureName);
4079 checkGLcall("GL_TEXTURE_2D, This->glDescription.textureName)");
4080 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
4081 checkGLcall("glTexParameteri");
4082 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
4083 checkGLcall("glTexParameteri");
4085 coords[0].x = (float)rect.left / This->pow2Width;
4086 coords[0].z = 0;
4088 coords[1].x = (float)rect.left / This->pow2Width;
4089 coords[1].z = 0;
4091 coords[2].x = (float)rect.right / This->pow2Width;
4092 coords[2].z = 0;
4094 coords[3].x = (float)rect.right / This->pow2Width;
4095 coords[3].z = 0;
4097 coords[0].y = (float)rect.top / This->pow2Height;
4098 coords[1].y = (float)rect.bottom / This->pow2Height;
4099 coords[2].y = (float)rect.bottom / This->pow2Height;
4100 coords[3].y = (float)rect.top / This->pow2Height;
4101 } else {
4102 /* Must be a cube map */
4103 glEnable(GL_TEXTURE_CUBE_MAP_ARB);
4104 checkGLcall("glEnable(GL_TEXTURE_CUBE_MAP_ARB)");
4105 glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, This->glDescription.textureName);
4106 checkGLcall("GL_TEXTURE_CUBE_MAP_ARB, This->glDescription.textureName)");
4107 glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
4108 checkGLcall("glTexParameteri");
4109 glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
4110 checkGLcall("glTexParameteri");
4112 switch(This->glDescription.target) {
4113 case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
4114 coords[0].x = 1; coords[0].y = -1; coords[0].z = 1;
4115 coords[1].x = 1; coords[1].y = 1; coords[1].z = 1;
4116 coords[2].x = 1; coords[2].y = 1; coords[2].z = -1;
4117 coords[3].x = 1; coords[3].y = -1; coords[3].z = -1;
4118 break;
4120 case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
4121 coords[0].x = -1; coords[0].y = -1; coords[0].z = 1;
4122 coords[1].x = -1; coords[1].y = 1; coords[1].z = 1;
4123 coords[2].x = -1; coords[2].y = 1; coords[2].z = -1;
4124 coords[3].x = -1; coords[3].y = -1; coords[3].z = -1;
4125 break;
4127 case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
4128 coords[0].x = -1; coords[0].y = 1; coords[0].z = 1;
4129 coords[1].x = 1; coords[1].y = 1; coords[1].z = 1;
4130 coords[2].x = 1; coords[2].y = 1; coords[2].z = -1;
4131 coords[3].x = -1; coords[3].y = 1; coords[3].z = -1;
4132 break;
4134 case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
4135 coords[0].x = -1; coords[0].y = -1; coords[0].z = 1;
4136 coords[1].x = 1; coords[1].y = -1; coords[1].z = 1;
4137 coords[2].x = 1; coords[2].y = -1; coords[2].z = -1;
4138 coords[3].x = -1; coords[3].y = -1; coords[3].z = -1;
4139 break;
4141 case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
4142 coords[0].x = -1; coords[0].y = -1; coords[0].z = 1;
4143 coords[1].x = 1; coords[1].y = -1; coords[1].z = 1;
4144 coords[2].x = 1; coords[2].y = -1; coords[2].z = 1;
4145 coords[3].x = -1; coords[3].y = -1; coords[3].z = 1;
4146 break;
4148 case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
4149 coords[0].x = -1; coords[0].y = -1; coords[0].z = -1;
4150 coords[1].x = 1; coords[1].y = -1; coords[1].z = -1;
4151 coords[2].x = 1; coords[2].y = -1; coords[2].z = -1;
4152 coords[3].x = -1; coords[3].y = -1; coords[3].z = -1;
4153 break;
4155 default:
4156 ERR("Unexpected texture target\n");
4157 LEAVE_GL();
4158 return;
4162 glBegin(GL_QUADS);
4163 glTexCoord3fv(&coords[0].x);
4164 glVertex2i(rect.left, device->render_offscreen ? rect.bottom : rect.top);
4166 glTexCoord3fv(&coords[1].x);
4167 glVertex2i(rect.left, device->render_offscreen ? rect.top : rect.bottom);
4169 glTexCoord3fv(&coords[2].x);
4170 glVertex2i(rect.right, device->render_offscreen ? rect.top : rect.bottom);
4172 glTexCoord3fv(&coords[3].x);
4173 glVertex2i(rect.right, device->render_offscreen ? rect.bottom : rect.top);
4174 glEnd();
4175 checkGLcall("glEnd");
4177 if(This->glDescription.target != GL_TEXTURE_2D) {
4178 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
4179 checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
4180 } else {
4181 glDisable(GL_TEXTURE_2D);
4182 checkGLcall("glDisable(GL_TEXTURE_2D)");
4184 LEAVE_GL();
4186 hr = IWineD3DSurface_GetContainer((IWineD3DSurface*)This, &IID_IWineD3DSwapChain, (void **) &swapchain);
4187 if(hr == WINED3D_OK && swapchain) {
4188 /* Make sure to flush the buffers. This is needed in apps like Red Alert II and Tiberian SUN that use multiple WGL contexts. */
4189 if(((IWineD3DSwapChainImpl*)swapchain)->frontBuffer == (IWineD3DSurface*)This ||
4190 ((IWineD3DSwapChainImpl*)swapchain)->num_contexts >= 2)
4191 glFlush();
4193 IWineD3DSwapChain_Release(swapchain);
4194 } else {
4195 /* We changed the filtering settings on the texture. Inform the container about this to get the filters
4196 * reset properly next draw
4198 hr = IWineD3DSurface_GetContainer((IWineD3DSurface*)This, &IID_IWineD3DBaseTexture, (void **) &texture);
4199 if(hr == WINED3D_OK && texture) {
4200 ((IWineD3DBaseTextureImpl *) texture)->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
4201 ((IWineD3DBaseTextureImpl *) texture)->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
4202 ((IWineD3DBaseTextureImpl *) texture)->baseTexture.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
4203 IWineD3DBaseTexture_Release(texture);
4208 /*****************************************************************************
4209 * IWineD3DSurface::LoadLocation
4211 * Copies the current surface data from wherever it is to the requested
4212 * location. The location is one of the surface flags, SFLAG_INSYSMEM,
4213 * SFLAG_INTEXTURE and SFLAG_INDRAWABLE. When the surface is current in
4214 * multiple locations, the gl texture is preferred over the drawable, which is
4215 * preferred over system memory. The PBO counts as system memory. If rect is
4216 * not NULL, only the specified rectangle is copied (only supported for
4217 * sysmem<->drawable copies at the moment). If rect is NULL, the destination
4218 * location is marked up to date after the copy.
4220 * Parameters:
4221 * flag: Surface location flag to be updated
4222 * rect: rectangle to be copied
4224 * Returns:
4225 * WINED3D_OK on success
4226 * WINED3DERR_DEVICELOST on an internal error
4228 *****************************************************************************/
4229 static HRESULT WINAPI IWineD3DSurfaceImpl_LoadLocation(IWineD3DSurface *iface, DWORD flag, const RECT *rect) {
4230 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4231 IWineD3DDeviceImpl *device = This->resource.wineD3DDevice;
4232 IWineD3DSwapChain *swapchain = NULL;
4233 GLenum format, internal, type;
4234 CONVERT_TYPES convert;
4235 int bpp;
4236 int width, pitch, outpitch;
4237 BYTE *mem;
4239 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
4240 if (SUCCEEDED(IWineD3DSurface_GetContainer(iface, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
4241 TRACE("Surface %p is an onscreen surface\n", iface);
4243 IWineD3DSwapChain_Release(swapchain);
4244 } else {
4245 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets.
4246 * Prefer SFLAG_INTEXTURE. */
4247 if (flag == SFLAG_INDRAWABLE) flag = SFLAG_INTEXTURE;
4251 TRACE("(%p)->(%s, %p)\n", iface,
4252 flag == SFLAG_INSYSMEM ? "SFLAG_INSYSMEM" : flag == SFLAG_INDRAWABLE ? "SFLAG_INDRAWABLE" : "SFLAG_INTEXTURE",
4253 rect);
4254 if(rect) {
4255 TRACE("Rectangle: (%d,%d)-(%d,%d)\n", rect->left, rect->top, rect->right, rect->bottom);
4258 if(This->Flags & flag) {
4259 TRACE("Location already up to date\n");
4260 return WINED3D_OK;
4263 if(!(This->Flags & SFLAG_LOCATIONS)) {
4264 ERR("Surface does not have any up to date location\n");
4265 This->Flags |= SFLAG_LOST;
4266 return WINED3DERR_DEVICELOST;
4269 if(flag == SFLAG_INSYSMEM) {
4270 surface_prepare_system_memory(This);
4272 /* Download the surface to system memory */
4273 if(This->Flags & SFLAG_INTEXTURE) {
4274 if(!device->isInDraw) ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
4275 surface_bind_and_dirtify(This);
4277 surface_download_data(This);
4278 } else {
4279 read_from_framebuffer(This, rect,
4280 This->resource.allocatedMemory,
4281 IWineD3DSurface_GetPitch(iface));
4283 } else if(flag == SFLAG_INDRAWABLE) {
4284 if(This->Flags & SFLAG_INTEXTURE) {
4285 surface_blt_to_drawable(This, rect);
4286 } else {
4287 d3dfmt_get_conv(This, TRUE /* We need color keying */, FALSE /* We won't use textures */, &format, &internal, &type, &convert, &bpp, This->srgb);
4289 /* The width is in 'length' not in bytes */
4290 width = This->currentDesc.Width;
4291 pitch = IWineD3DSurface_GetPitch(iface);
4293 /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
4294 * but it isn't set (yet) in all cases it is getting called. */
4295 if((convert != NO_CONVERSION) && (This->Flags & SFLAG_PBO)) {
4296 TRACE("Removing the pbo attached to surface %p\n", This);
4297 surface_remove_pbo(This);
4300 if((convert != NO_CONVERSION) && This->resource.allocatedMemory) {
4301 int height = This->currentDesc.Height;
4303 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4304 outpitch = width * bpp;
4305 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4307 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4308 if(!mem) {
4309 ERR("Out of memory %d, %d!\n", outpitch, height);
4310 return WINED3DERR_OUTOFVIDEOMEMORY;
4312 d3dfmt_convert_surface(This->resource.allocatedMemory, mem, pitch, width, height, outpitch, convert, This);
4314 This->Flags |= SFLAG_CONVERTED;
4315 } else {
4316 This->Flags &= ~SFLAG_CONVERTED;
4317 mem = This->resource.allocatedMemory;
4320 flush_to_framebuffer_drawpixels(This, format, type, bpp, mem);
4322 /* Don't delete PBO memory */
4323 if((mem != This->resource.allocatedMemory) && !(This->Flags & SFLAG_PBO))
4324 HeapFree(GetProcessHeap(), 0, mem);
4326 } else /* if(flag == SFLAG_INTEXTURE) */ {
4327 if (This->Flags & SFLAG_INDRAWABLE) {
4328 read_from_framebuffer_texture(This);
4329 } else { /* Upload from system memory */
4330 d3dfmt_get_conv(This, TRUE /* We need color keying */, TRUE /* We will use textures */, &format, &internal, &type, &convert, &bpp, This->srgb);
4332 if(!device->isInDraw) ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
4333 surface_bind_and_dirtify(This);
4334 ENTER_GL();
4336 /* The only place where LoadTexture() might get called when isInDraw=1
4337 * is ActivateContext where lastActiveRenderTarget is preloaded.
4339 if(iface == device->lastActiveRenderTarget && device->isInDraw)
4340 ERR("Reading back render target but SFLAG_INDRAWABLE not set\n");
4342 /* Otherwise: System memory copy must be most up to date */
4344 if(This->CKeyFlags & WINEDDSD_CKSRCBLT) {
4345 This->Flags |= SFLAG_GLCKEY;
4346 This->glCKey = This->SrcBltCKey;
4348 else This->Flags &= ~SFLAG_GLCKEY;
4350 /* The width is in 'length' not in bytes */
4351 width = This->currentDesc.Width;
4352 pitch = IWineD3DSurface_GetPitch(iface);
4354 /* Don't use PBOs for converted surfaces. During PBO conversion we look at SFLAG_CONVERTED
4355 * but it isn't set (yet) in all cases it is getting called. */
4356 if((convert != NO_CONVERSION) && (This->Flags & SFLAG_PBO)) {
4357 TRACE("Removing the pbo attached to surface %p\n", This);
4358 surface_remove_pbo(This);
4361 if((convert != NO_CONVERSION) && This->resource.allocatedMemory) {
4362 int height = This->currentDesc.Height;
4364 /* Stick to the alignment for the converted surface too, makes it easier to load the surface */
4365 outpitch = width * bpp;
4366 outpitch = (outpitch + device->surface_alignment - 1) & ~(device->surface_alignment - 1);
4368 mem = HeapAlloc(GetProcessHeap(), 0, outpitch * height);
4369 if(!mem) {
4370 ERR("Out of memory %d, %d!\n", outpitch, height);
4371 return WINED3DERR_OUTOFVIDEOMEMORY;
4373 d3dfmt_convert_surface(This->resource.allocatedMemory, mem, pitch, width, height, outpitch, convert, This);
4375 This->Flags |= SFLAG_CONVERTED;
4376 } else if( (This->resource.format == WINED3DFMT_P8) && (GL_SUPPORT(EXT_PALETTED_TEXTURE) || GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) ) {
4377 d3dfmt_p8_upload_palette(iface, convert);
4378 This->Flags &= ~SFLAG_CONVERTED;
4379 mem = This->resource.allocatedMemory;
4380 } else {
4381 This->Flags &= ~SFLAG_CONVERTED;
4382 mem = This->resource.allocatedMemory;
4385 /* Make sure the correct pitch is used */
4386 glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
4388 if ((This->Flags & SFLAG_NONPOW2) && !(This->Flags & SFLAG_OVERSIZE)) {
4389 TRACE("non power of two support\n");
4390 if(!(This->Flags & SFLAG_ALLOCATED)) {
4391 surface_allocate_surface(This, internal, This->pow2Width, This->pow2Height, format, type);
4393 if (mem || (This->Flags & SFLAG_PBO)) {
4394 surface_upload_data(This, internal, This->currentDesc.Width, This->currentDesc.Height, format, type, mem);
4396 } else {
4397 /* When making the realloc conditional, keep in mind that GL_APPLE_client_storage may be in use, and This->resource.allocatedMemory
4398 * changed. So also keep track of memory changes. In this case the texture has to be reallocated
4400 if(!(This->Flags & SFLAG_ALLOCATED)) {
4401 surface_allocate_surface(This, internal, This->glRect.right - This->glRect.left, This->glRect.bottom - This->glRect.top, format, type);
4403 if (mem || (This->Flags & SFLAG_PBO)) {
4404 surface_upload_data(This, internal, This->glRect.right - This->glRect.left, This->glRect.bottom - This->glRect.top, format, type, mem);
4408 /* Restore the default pitch */
4409 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
4410 LEAVE_GL();
4412 /* Don't delete PBO memory */
4413 if((mem != This->resource.allocatedMemory) && !(This->Flags & SFLAG_PBO))
4414 HeapFree(GetProcessHeap(), 0, mem);
4418 if(rect == NULL) {
4419 This->Flags |= flag;
4422 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && !swapchain
4423 && (This->Flags & (SFLAG_INTEXTURE | SFLAG_INDRAWABLE))) {
4424 /* With ORM_FBO, SFLAG_INTEXTURE and SFLAG_INDRAWABLE are the same for offscreen targets. */
4425 This->Flags |= (SFLAG_INTEXTURE | SFLAG_INDRAWABLE);
4428 return WINED3D_OK;
4431 HRESULT WINAPI IWineD3DSurfaceImpl_SetContainer(IWineD3DSurface *iface, IWineD3DBase *container) {
4432 IWineD3DSurfaceImpl *This = (IWineD3DSurfaceImpl *) iface;
4433 IWineD3DSwapChain *swapchain = NULL;
4435 /* Update the drawable size method */
4436 if(container) {
4437 IWineD3DBase_QueryInterface(container, &IID_IWineD3DSwapChain, (void **) &swapchain);
4439 if(swapchain) {
4440 This->get_drawable_size = get_drawable_size_swapchain;
4441 IWineD3DSwapChain_Release(swapchain);
4442 } else if(This->resource.usage & WINED3DUSAGE_RENDERTARGET) {
4443 switch(wined3d_settings.offscreen_rendering_mode) {
4444 case ORM_FBO: This->get_drawable_size = get_drawable_size_fbo; break;
4445 case ORM_PBUFFER: This->get_drawable_size = get_drawable_size_pbuffer; break;
4446 case ORM_BACKBUFFER: This->get_drawable_size = get_drawable_size_backbuffer; break;
4450 return IWineD3DBaseSurfaceImpl_SetContainer(iface, container);
4453 static WINED3DSURFTYPE WINAPI IWineD3DSurfaceImpl_GetImplType(IWineD3DSurface *iface) {
4454 return SURFACE_OPENGL;
4457 const IWineD3DSurfaceVtbl IWineD3DSurface_Vtbl =
4459 /* IUnknown */
4460 IWineD3DBaseSurfaceImpl_QueryInterface,
4461 IWineD3DBaseSurfaceImpl_AddRef,
4462 IWineD3DSurfaceImpl_Release,
4463 /* IWineD3DResource */
4464 IWineD3DBaseSurfaceImpl_GetParent,
4465 IWineD3DBaseSurfaceImpl_GetDevice,
4466 IWineD3DBaseSurfaceImpl_SetPrivateData,
4467 IWineD3DBaseSurfaceImpl_GetPrivateData,
4468 IWineD3DBaseSurfaceImpl_FreePrivateData,
4469 IWineD3DBaseSurfaceImpl_SetPriority,
4470 IWineD3DBaseSurfaceImpl_GetPriority,
4471 IWineD3DSurfaceImpl_PreLoad,
4472 IWineD3DSurfaceImpl_UnLoad,
4473 IWineD3DBaseSurfaceImpl_GetType,
4474 /* IWineD3DSurface */
4475 IWineD3DBaseSurfaceImpl_GetContainer,
4476 IWineD3DBaseSurfaceImpl_GetDesc,
4477 IWineD3DSurfaceImpl_LockRect,
4478 IWineD3DSurfaceImpl_UnlockRect,
4479 IWineD3DSurfaceImpl_GetDC,
4480 IWineD3DSurfaceImpl_ReleaseDC,
4481 IWineD3DSurfaceImpl_Flip,
4482 IWineD3DSurfaceImpl_Blt,
4483 IWineD3DBaseSurfaceImpl_GetBltStatus,
4484 IWineD3DBaseSurfaceImpl_GetFlipStatus,
4485 IWineD3DBaseSurfaceImpl_IsLost,
4486 IWineD3DBaseSurfaceImpl_Restore,
4487 IWineD3DSurfaceImpl_BltFast,
4488 IWineD3DBaseSurfaceImpl_GetPalette,
4489 IWineD3DBaseSurfaceImpl_SetPalette,
4490 IWineD3DSurfaceImpl_RealizePalette,
4491 IWineD3DBaseSurfaceImpl_SetColorKey,
4492 IWineD3DBaseSurfaceImpl_GetPitch,
4493 IWineD3DSurfaceImpl_SetMem,
4494 IWineD3DBaseSurfaceImpl_SetOverlayPosition,
4495 IWineD3DBaseSurfaceImpl_GetOverlayPosition,
4496 IWineD3DBaseSurfaceImpl_UpdateOverlayZOrder,
4497 IWineD3DBaseSurfaceImpl_UpdateOverlay,
4498 IWineD3DBaseSurfaceImpl_SetClipper,
4499 IWineD3DBaseSurfaceImpl_GetClipper,
4500 /* Internal use: */
4501 IWineD3DSurfaceImpl_AddDirtyRect,
4502 IWineD3DSurfaceImpl_LoadTexture,
4503 IWineD3DSurfaceImpl_BindTexture,
4504 IWineD3DSurfaceImpl_SaveSnapshot,
4505 IWineD3DSurfaceImpl_SetContainer,
4506 IWineD3DSurfaceImpl_SetGlTextureDesc,
4507 IWineD3DSurfaceImpl_GetGlDesc,
4508 IWineD3DSurfaceImpl_GetData,
4509 IWineD3DSurfaceImpl_SetFormat,
4510 IWineD3DSurfaceImpl_PrivateSetup,
4511 IWineD3DSurfaceImpl_ModifyLocation,
4512 IWineD3DSurfaceImpl_LoadLocation,
4513 IWineD3DSurfaceImpl_GetImplType