push 0a0aa53cd365a71ca6121b6df157ca635450378f
[wine/hacks.git] / dlls / wined3d / context.c
blobba1e100bb5b425abde212cf840371b482447a221
1 /*
2 * Context and render target management in wined3d
4 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include <stdio.h>
23 #ifdef HAVE_FLOAT_H
24 # include <float.h>
25 #endif
26 #include "wined3d_private.h"
28 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
30 #define GLINFO_LOCATION This->adapter->gl_info
32 /* The last used device.
34 * If the application creates multiple devices and switches between them, ActivateContext has to
35 * change the opengl context. This flag allows to keep track which device is active
37 static IWineD3DDeviceImpl *last_device;
39 /* FBO helper functions */
41 /* GL locking is done by the caller */
42 void context_bind_fbo(IWineD3DDevice *iface, GLenum target, GLuint *fbo)
44 const IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
46 if (!*fbo)
48 GL_EXTCALL(glGenFramebuffersEXT(1, fbo));
49 checkGLcall("glGenFramebuffersEXT()");
50 TRACE("Created FBO %d\n", *fbo);
53 GL_EXTCALL(glBindFramebufferEXT(target, *fbo));
54 checkGLcall("glBindFramebuffer()");
57 /* GL locking is done by the caller */
58 static void context_clean_fbo_attachments(IWineD3DDeviceImpl *This)
60 unsigned int i;
62 for (i = 0; i < GL_LIMITS(buffers); ++i)
64 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i, GL_TEXTURE_2D, 0, 0));
65 checkGLcall("glFramebufferTexture2D()");
67 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
68 checkGLcall("glFramebufferTexture2D()");
71 /* GL locking is done by the caller */
72 static void context_destroy_fbo(IWineD3DDeviceImpl *This, const GLuint *fbo)
74 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, *fbo));
75 checkGLcall("glBindFramebuffer()");
77 context_clean_fbo_attachments(This);
79 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
80 checkGLcall("glBindFramebuffer()");
81 GL_EXTCALL(glDeleteFramebuffersEXT(1, fbo));
82 checkGLcall("glDeleteFramebuffers()");
85 /* GL locking is done by the caller */
86 static void context_apply_attachment_filter_states(IWineD3DDevice *iface, IWineD3DSurface *surface, BOOL force_preload)
88 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
89 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
90 IWineD3DBaseTextureImpl *texture_impl;
91 BOOL update_minfilter = FALSE;
92 BOOL update_magfilter = FALSE;
94 /* Update base texture states array */
95 if (SUCCEEDED(IWineD3DSurface_GetContainer(surface, &IID_IWineD3DBaseTexture, (void **)&texture_impl)))
97 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT
98 || texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] != WINED3DTEXF_NONE)
100 texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
101 texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
102 update_minfilter = TRUE;
105 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
107 texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
108 update_magfilter = TRUE;
111 if (texture_impl->baseTexture.bindCount)
113 WARN("Render targets should not be bound to a sampler\n");
114 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(texture_impl->baseTexture.sampler));
117 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
120 if (update_minfilter || update_magfilter || force_preload)
122 GLenum target, bind_target;
123 GLint old_binding;
125 target = surface_impl->glDescription.target;
126 if (target == GL_TEXTURE_2D)
128 bind_target = GL_TEXTURE_2D;
129 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
130 } else if (target == GL_TEXTURE_RECTANGLE_ARB) {
131 bind_target = GL_TEXTURE_RECTANGLE_ARB;
132 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
133 } else {
134 bind_target = GL_TEXTURE_CUBE_MAP_ARB;
135 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
138 surface_internal_preload(surface, SRGB_RGB);
140 glBindTexture(bind_target, surface_impl->glDescription.textureName);
141 if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
142 if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
143 glBindTexture(bind_target, old_binding);
146 checkGLcall("apply_attachment_filter_states()");
149 /* TODO: Handle stencil attachments */
150 /* GL locking is done by the caller */
151 void context_attach_depth_stencil_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, IWineD3DSurface *depth_stencil, BOOL use_render_buffer)
153 IWineD3DSurfaceImpl *depth_stencil_impl = (IWineD3DSurfaceImpl *)depth_stencil;
155 TRACE("Attach depth stencil %p\n", depth_stencil);
157 if (depth_stencil)
159 if (use_render_buffer && depth_stencil_impl->current_renderbuffer)
161 GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_stencil_impl->current_renderbuffer->id));
162 checkGLcall("glFramebufferRenderbufferEXT()");
163 } else {
164 context_apply_attachment_filter_states((IWineD3DDevice *)This, depth_stencil, TRUE);
166 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, depth_stencil_impl->glDescription.target,
167 depth_stencil_impl->glDescription.textureName, depth_stencil_impl->glDescription.level));
168 checkGLcall("glFramebufferTexture2DEXT()");
170 } else {
171 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
172 checkGLcall("glFramebufferTexture2DEXT()");
176 /* GL locking is done by the caller */
177 void context_attach_surface_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, DWORD idx, IWineD3DSurface *surface)
179 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
181 TRACE("Attach surface %p to %u\n", surface, idx);
183 if (surface)
185 context_apply_attachment_filter_states((IWineD3DDevice *)This, surface, TRUE);
187 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, surface_impl->glDescription.target,
188 surface_impl->glDescription.textureName, surface_impl->glDescription.level));
189 checkGLcall("glFramebufferTexture2DEXT()");
190 } else {
191 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, GL_TEXTURE_2D, 0, 0));
192 checkGLcall("glFramebufferTexture2DEXT()");
196 /* GL locking is done by the caller */
197 static void context_check_fbo_status(IWineD3DDevice *iface)
199 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
200 GLenum status;
202 status = GL_EXTCALL(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
203 if (status == GL_FRAMEBUFFER_COMPLETE_EXT)
205 TRACE("FBO complete\n");
206 } else {
207 IWineD3DSurfaceImpl *attachment;
208 unsigned int i;
209 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
211 /* Dump the FBO attachments */
212 for (i = 0; i < GL_LIMITS(buffers); ++i)
214 attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->render_targets[i];
215 if (attachment)
217 FIXME("\tColor attachment %d: (%p) %s %ux%u\n",
218 i, attachment, debug_d3dformat(attachment->resource.format_desc->format),
219 attachment->pow2Width, attachment->pow2Height);
222 attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->depth_stencil;
223 if (attachment)
225 FIXME("\tDepth attachment: (%p) %s %ux%u\n",
226 attachment, debug_d3dformat(attachment->resource.format_desc->format),
227 attachment->pow2Width, attachment->pow2Height);
232 static struct fbo_entry *context_create_fbo_entry(IWineD3DDevice *iface)
234 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
235 struct fbo_entry *entry;
237 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
238 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
239 memcpy(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
240 entry->depth_stencil = This->stencilBufferTarget;
241 entry->attached = FALSE;
242 entry->id = 0;
244 return entry;
247 /* GL locking is done by the caller */
248 static void context_reuse_fbo_entry(IWineD3DDevice *iface, struct fbo_entry *entry)
250 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
252 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, entry->id));
253 checkGLcall("glBindFramebuffer()");
254 context_clean_fbo_attachments(This);
256 memcpy(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
257 entry->depth_stencil = This->stencilBufferTarget;
258 entry->attached = FALSE;
261 /* GL locking is done by the caller */
262 static void context_destroy_fbo_entry(IWineD3DDeviceImpl *This, WineD3DContext *context, struct fbo_entry *entry)
264 if (entry->id)
266 TRACE("Destroy FBO %d\n", entry->id);
267 context_destroy_fbo(This, &entry->id);
269 --context->fbo_entry_count;
270 list_remove(&entry->entry);
271 HeapFree(GetProcessHeap(), 0, entry->render_targets);
272 HeapFree(GetProcessHeap(), 0, entry);
276 /* GL locking is done by the caller */
277 static struct fbo_entry *context_find_fbo_entry(IWineD3DDevice *iface, WineD3DContext *context)
279 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
280 struct fbo_entry *entry;
282 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
284 if (!memcmp(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets))
285 && entry->depth_stencil == This->stencilBufferTarget)
287 list_remove(&entry->entry);
288 list_add_head(&context->fbo_list, &entry->entry);
289 return entry;
293 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
295 entry = context_create_fbo_entry(iface);
296 list_add_head(&context->fbo_list, &entry->entry);
297 ++context->fbo_entry_count;
299 else
301 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
302 context_reuse_fbo_entry(iface, entry);
303 list_remove(&entry->entry);
304 list_add_head(&context->fbo_list, &entry->entry);
307 return entry;
310 /* GL locking is done by the caller */
311 static void context_apply_fbo_entry(IWineD3DDevice *iface, struct fbo_entry *entry)
313 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
314 unsigned int i;
316 context_bind_fbo(iface, GL_FRAMEBUFFER_EXT, &entry->id);
318 if (!entry->attached)
320 /* Apply render targets */
321 for (i = 0; i < GL_LIMITS(buffers); ++i)
323 IWineD3DSurface *render_target = This->render_targets[i];
324 context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, i, render_target);
327 /* Apply depth targets */
328 if (This->stencilBufferTarget) {
329 unsigned int w = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Width;
330 unsigned int h = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Height;
332 surface_set_compatible_renderbuffer(This->stencilBufferTarget, w, h);
334 context_attach_depth_stencil_fbo(This, GL_FRAMEBUFFER_EXT, This->stencilBufferTarget, TRUE);
336 entry->attached = TRUE;
337 } else {
338 for (i = 0; i < GL_LIMITS(buffers); ++i)
340 if (This->render_targets[i])
341 context_apply_attachment_filter_states(iface, This->render_targets[i], FALSE);
343 if (This->stencilBufferTarget)
344 context_apply_attachment_filter_states(iface, This->stencilBufferTarget, FALSE);
347 for (i = 0; i < GL_LIMITS(buffers); ++i)
349 if (This->render_targets[i])
350 This->draw_buffers[i] = GL_COLOR_ATTACHMENT0_EXT + i;
351 else
352 This->draw_buffers[i] = GL_NONE;
356 /* GL locking is done by the caller */
357 static void context_apply_fbo_state(IWineD3DDevice *iface)
359 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
360 WineD3DContext *context = This->activeContext;
362 if (This->render_offscreen)
364 context->current_fbo = context_find_fbo_entry(iface, context);
365 context_apply_fbo_entry(iface, context->current_fbo);
366 } else {
367 context->current_fbo = NULL;
368 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
371 context_check_fbo_status(iface);
374 void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
376 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
377 UINT i;
379 switch(type)
381 case WINED3DRTYPE_SURFACE:
383 for (i = 0; i < This->numContexts; ++i)
385 WineD3DContext *context = This->contexts[i];
386 struct fbo_entry *entry, *entry2;
388 ENTER_GL();
390 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
392 BOOL destroyed = FALSE;
393 UINT j;
395 for (j = 0; !destroyed && j < GL_LIMITS(buffers); ++j)
397 if (entry->render_targets[j] == (IWineD3DSurface *)resource)
399 context_destroy_fbo_entry(This, context, entry);
400 destroyed = TRUE;
404 if (!destroyed && entry->depth_stencil == (IWineD3DSurface *)resource)
405 context_destroy_fbo_entry(This, context, entry);
408 LEAVE_GL();
411 break;
414 default:
415 break;
419 /*****************************************************************************
420 * Context_MarkStateDirty
422 * Marks a state in a context dirty. Only one context, opposed to
423 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
424 * contexts
426 * Params:
427 * context: Context to mark the state dirty in
428 * state: State to mark dirty
429 * StateTable: Pointer to the state table in use(for state grouping)
431 *****************************************************************************/
432 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
433 DWORD rep = StateTable[state].representative;
434 DWORD idx;
435 BYTE shift;
437 if(!rep || isStateDirty(context, rep)) return;
439 context->dirtyArray[context->numDirtyEntries++] = rep;
440 idx = rep >> 5;
441 shift = rep & 0x1f;
442 context->isStateDirty[idx] |= (1 << shift);
445 /*****************************************************************************
446 * AddContextToArray
448 * Adds a context to the context array. Helper function for CreateContext
450 * This method is not called in performance-critical code paths, only when a
451 * new render target or swapchain is created. Thus performance is not an issue
452 * here.
454 * Params:
455 * This: Device to add the context for
456 * hdc: device context
457 * glCtx: WGL context to add
458 * pbuffer: optional pbuffer used with this context
460 *****************************************************************************/
461 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
462 WineD3DContext **oldArray = This->contexts;
463 DWORD state;
465 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
466 if(This->contexts == NULL) {
467 ERR("Unable to grow the context array\n");
468 This->contexts = oldArray;
469 return NULL;
471 if(oldArray) {
472 memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
475 This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
476 if(This->contexts[This->numContexts] == NULL) {
477 ERR("Unable to allocate a new context\n");
478 HeapFree(GetProcessHeap(), 0, This->contexts);
479 This->contexts = oldArray;
480 return NULL;
483 This->contexts[This->numContexts]->hdc = hdc;
484 This->contexts[This->numContexts]->glCtx = glCtx;
485 This->contexts[This->numContexts]->pbuffer = pbuffer;
486 This->contexts[This->numContexts]->win_handle = win_handle;
487 HeapFree(GetProcessHeap(), 0, oldArray);
489 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
491 for(state = 0; state <= STATE_HIGHEST; state++) {
492 Context_MarkStateDirty(This->contexts[This->numContexts], state, This->StateTable);
495 This->numContexts++;
496 TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
497 return This->contexts[This->numContexts - 1];
500 /* This function takes care of WineD3D pixel format selection. */
501 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc,
502 const struct GlPixelFormatDesc *color_format_desc, const struct GlPixelFormatDesc *ds_format_desc,
503 BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
505 int iPixelFormat=0;
506 unsigned int matchtry;
507 short redBits, greenBits, blueBits, alphaBits, colorBits;
508 short depthBits=0, stencilBits=0;
510 struct match_type {
511 BOOL require_aux;
512 BOOL exact_alpha;
513 BOOL exact_color;
514 } matches[] = {
515 /* First, try without alpha match buffers. MacOS supports aux buffers only
516 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
517 * Then try without aux buffers - this is the most common cause for not
518 * finding a pixel format. Also some drivers(the open source ones)
519 * only offer 32 bit ARB pixel formats. First try without an exact alpha
520 * match, then try without an exact alpha and color match.
522 { TRUE, TRUE, TRUE },
523 { TRUE, FALSE, TRUE },
524 { FALSE, TRUE, TRUE },
525 { FALSE, FALSE, TRUE },
526 { TRUE, FALSE, FALSE },
527 { FALSE, FALSE, FALSE },
530 int i = 0;
531 int nCfgs = This->adapter->nCfgs;
533 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
534 debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format),
535 auxBuffers, numSamples, pbuffer, findCompatible);
537 if (!getColorBits(color_format_desc, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
539 ERR("Unable to get color bits for format %s (%#x)!\n",
540 debug_d3dformat(color_format_desc->format), color_format_desc->format);
541 return 0;
544 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
545 * You are able to add a depth + stencil surface at a later stage when you need it.
546 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
547 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
548 * context, need torecreate shaders, textures and other resources.
550 * The context manager already takes care of the state problem and for the other tasks code from Reset
551 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
552 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
553 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
554 * issue needs to be fixed. */
555 if (ds_format_desc->format != WINED3DFMT_D24S8)
557 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
558 ds_format_desc = getFormatDescEntry(WINED3DFMT_D24S8, &This->adapter->gl_info);
561 getDepthStencilBits(ds_format_desc, &depthBits, &stencilBits);
563 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
564 for(i=0; i<nCfgs; i++) {
565 BOOL exactDepthMatch = TRUE;
566 WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
568 /* For now only accept RGBA formats. Perhaps some day we will
569 * allow floating point formats for pbuffers. */
570 if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
571 continue;
573 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
574 if(!pbuffer && !(cfg->windowDrawable && cfg->doubleBuffer))
575 continue;
577 /* We like to have aux buffers in backbuffer mode */
578 if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
579 continue;
581 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
582 if(pbuffer && (!cfg->pbufferDrawable || cfg->doubleBuffer))
583 continue;
585 if(matches[matchtry].exact_color) {
586 if(cfg->redSize != redBits)
587 continue;
588 if(cfg->greenSize != greenBits)
589 continue;
590 if(cfg->blueSize != blueBits)
591 continue;
592 } else {
593 if(cfg->redSize < redBits)
594 continue;
595 if(cfg->greenSize < greenBits)
596 continue;
597 if(cfg->blueSize < blueBits)
598 continue;
600 if(matches[matchtry].exact_alpha) {
601 if(cfg->alphaSize != alphaBits)
602 continue;
603 } else {
604 if(cfg->alphaSize < alphaBits)
605 continue;
608 /* We try to locate a format which matches our requirements exactly. In case of
609 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
610 if(cfg->depthSize < depthBits)
611 continue;
612 else if(cfg->depthSize > depthBits)
613 exactDepthMatch = FALSE;
615 /* In all cases make sure the number of stencil bits matches our requirements
616 * even when we don't need stencil because it could affect performance EXCEPT
617 * on cards which don't offer depth formats without stencil like the i915 drivers
618 * on Linux. */
619 if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
620 continue;
622 /* Check multisampling support */
623 if(cfg->numSamples != numSamples)
624 continue;
626 /* When we have passed all the checks then we have found a format which matches our
627 * requirements. Note that we only check for a limit number of capabilities right now,
628 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
629 * can still differ in things like multisampling, stereo, SRGB and other flags.
632 /* Exit the loop as we have found a format :) */
633 if(exactDepthMatch) {
634 iPixelFormat = cfg->iPixelFormat;
635 break;
636 } else if(!iPixelFormat) {
637 /* In the end we might end up with a format which doesn't exactly match our depth
638 * requirements. Accept the first format we found because formats with higher iPixelFormat
639 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
640 iPixelFormat = cfg->iPixelFormat;
645 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
646 if(!iPixelFormat && !findCompatible) {
647 ERR("Can't find a suitable iPixelFormat\n");
648 return FALSE;
649 } else if(!iPixelFormat) {
650 PIXELFORMATDESCRIPTOR pfd;
652 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
653 /* PixelFormat selection */
654 ZeroMemory(&pfd, sizeof(pfd));
655 pfd.nSize = sizeof(pfd);
656 pfd.nVersion = 1;
657 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
658 pfd.iPixelType = PFD_TYPE_RGBA;
659 pfd.cAlphaBits = alphaBits;
660 pfd.cColorBits = colorBits;
661 pfd.cDepthBits = depthBits;
662 pfd.cStencilBits = stencilBits;
663 pfd.iLayerType = PFD_MAIN_PLANE;
665 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
666 if(!iPixelFormat) {
667 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
668 ERR("Can't find a suitable iPixelFormat\n");
669 return FALSE;
673 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
674 iPixelFormat, debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format));
675 return iPixelFormat;
678 /*****************************************************************************
679 * CreateContext
681 * Creates a new context for a window, or a pbuffer context.
683 * * Params:
684 * This: Device to activate the context for
685 * target: Surface this context will render to
686 * win_handle: handle to the window which we are drawing to
687 * create_pbuffer: tells whether to create a pbuffer or not
688 * pPresentParameters: contains the pixelformats to use for onscreen rendering
690 *****************************************************************************/
691 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
692 HDC oldDrawable, hdc;
693 HPBUFFERARB pbuffer = NULL;
694 HGLRC ctx = NULL, oldCtx;
695 WineD3DContext *ret = NULL;
696 unsigned int s;
698 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
700 if(create_pbuffer) {
701 HDC hdc_parent = GetDC(win_handle);
702 int iPixelFormat = 0;
704 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
705 const struct GlPixelFormatDesc *ds_format_desc = StencilSurface
706 ? ((IWineD3DSurfaceImpl *)StencilSurface)->resource.format_desc
707 : getFormatDescEntry(WINED3DFMT_UNKNOWN, &This->adapter->gl_info);
709 /* Try to find a pixel format with pbuffer support. */
710 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
711 ds_format_desc, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */,
712 FALSE /* findCompatible */);
713 if(!iPixelFormat) {
714 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
716 /* For some reason we weren't able to find a format, try to find something instead of crashing.
717 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
718 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
719 ds_format_desc, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */,
720 TRUE /* findCompatible */);
723 /* This shouldn't happen as ChoosePixelFormat always returns something */
724 if(!iPixelFormat) {
725 ERR("Unable to locate a pixel format for a pbuffer\n");
726 ReleaseDC(win_handle, hdc_parent);
727 goto out;
730 TRACE("Creating a pBuffer drawable for the new context\n");
731 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
732 if(!pbuffer) {
733 ERR("Cannot create a pbuffer\n");
734 ReleaseDC(win_handle, hdc_parent);
735 goto out;
738 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
739 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
740 if(!hdc) {
741 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
742 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
743 ReleaseDC(win_handle, hdc_parent);
744 goto out;
746 ReleaseDC(win_handle, hdc_parent);
747 } else {
748 PIXELFORMATDESCRIPTOR pfd;
749 int iPixelFormat;
750 int res;
751 const struct GlPixelFormatDesc *color_format_desc = target->resource.format_desc;
752 const struct GlPixelFormatDesc *ds_format_desc = getFormatDescEntry(WINED3DFMT_UNKNOWN,
753 &This->adapter->gl_info);
754 BOOL auxBuffers = FALSE;
755 int numSamples = 0;
757 hdc = GetDC(win_handle);
758 if(hdc == NULL) {
759 ERR("Cannot retrieve a device context!\n");
760 goto out;
763 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
764 if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
765 auxBuffers = TRUE;
767 if (color_format_desc->format == WINED3DFMT_X4R4G4B4)
768 color_format_desc = getFormatDescEntry(WINED3DFMT_A4R4G4B4, &This->adapter->gl_info);
769 else if (color_format_desc->format == WINED3DFMT_X8R8G8B8)
770 color_format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->adapter->gl_info);
773 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
774 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
775 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
776 * a format with 8bit alpha, so request A8R8G8B8. */
777 if (color_format_desc->format == WINED3DFMT_P8)
778 color_format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->adapter->gl_info);
780 /* Retrieve the depth stencil format from the present parameters.
781 * The choice of the proper format can give a nice performance boost
782 * in case of GPU limited programs. */
783 if(pPresentParms->EnableAutoDepthStencil) {
784 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
785 ds_format_desc = getFormatDescEntry(pPresentParms->AutoDepthStencilFormat, &This->adapter->gl_info);
788 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
789 if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
790 if(!GL_SUPPORT(ARB_MULTISAMPLE))
791 ERR("The program is requesting multisampling without support!\n");
792 else {
793 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
794 numSamples = pPresentParms->MultiSampleType;
798 /* Try to find a pixel format which matches our requirements */
799 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
800 auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
802 /* Try to locate a compatible format if we weren't able to find anything */
803 if(!iPixelFormat) {
804 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
805 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
806 auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
809 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
810 if(!iPixelFormat) {
811 ERR("Can't find a suitable iPixelFormat\n");
812 return FALSE;
815 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
816 res = SetPixelFormat(hdc, iPixelFormat, NULL);
817 if(!res) {
818 int oldPixelFormat = GetPixelFormat(hdc);
820 /* By default WGL doesn't allow pixel format adjustments but we need it here.
821 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
822 * set the pixel format multiple times. Only use it when it is really needed. */
824 if(oldPixelFormat == iPixelFormat) {
825 /* We don't have to do anything as the formats are the same :) */
826 } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
827 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
829 if(!res) {
830 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
831 return FALSE;
833 } else if(oldPixelFormat) {
834 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
835 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
836 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
837 } else {
838 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
839 return FALSE;
844 ctx = pwglCreateContext(hdc);
845 if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
847 if(!ctx) {
848 ERR("Failed to create a WGL context\n");
849 if(create_pbuffer) {
850 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
851 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
853 goto out;
855 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
856 if(!ret) {
857 ERR("Failed to add the newly created context to the context list\n");
858 pwglDeleteContext(ctx);
859 if(create_pbuffer) {
860 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
861 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
863 goto out;
865 ret->surface = (IWineD3DSurface *) target;
866 ret->isPBuffer = create_pbuffer;
867 ret->tid = GetCurrentThreadId();
868 if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
869 /* Create the dirty constants array and initialize them to dirty */
870 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
871 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
872 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
873 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
874 memset(ret->vshader_const_dirty, 1,
875 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
876 memset(ret->pshader_const_dirty, 1,
877 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
880 TRACE("Successfully created new context %p\n", ret);
882 list_init(&ret->fbo_list);
884 /* Set up the context defaults */
885 oldCtx = pwglGetCurrentContext();
886 oldDrawable = pwglGetCurrentDC();
887 if(oldCtx && oldDrawable) {
888 /* See comment in ActivateContext context switching */
889 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
891 if(pwglMakeCurrent(hdc, ctx) == FALSE) {
892 ERR("Cannot activate context to set up defaults\n");
893 goto out;
896 ENTER_GL();
898 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
900 TRACE("Setting up the screen\n");
901 /* Clear the screen */
902 glClearColor(1.0, 0.0, 0.0, 0.0);
903 checkGLcall("glClearColor");
904 glClearIndex(0);
905 glClearDepth(1);
906 glClearStencil(0xffff);
908 checkGLcall("glClear");
910 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
911 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
913 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
914 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
916 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
917 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
919 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
920 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
921 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
922 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
924 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
925 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
926 * and textures in DIB sections(due to the memory protection).
928 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
929 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
931 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
932 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
933 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
934 * GL_VERTEX_BLEND_ARB isn't enabled too
936 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
937 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
939 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
940 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
941 * the previous texture where to source the offset from is always unit - 1.
943 for(s = 1; s < GL_LIMITS(textures); s++) {
944 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
945 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
946 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
949 if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
950 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
951 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
952 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
953 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
954 * is ever assigned.
956 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
957 * program and the dummy program is destroyed when the context is destroyed.
959 const char *dummy_program =
960 "!!ARBfp1.0\n"
961 "MOV result.color, fragment.color.primary;\n"
962 "END\n";
963 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
964 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
965 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
968 for(s = 0; s < GL_LIMITS(point_sprite_units); s++) {
969 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
970 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
971 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
973 LEAVE_GL();
975 /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
976 * but enable it for the first context we create, and reenable it on the old context
978 if(oldDrawable && oldCtx) {
979 pwglMakeCurrent(oldDrawable, oldCtx);
980 } else {
981 last_device = This;
983 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
985 return ret;
987 out:
988 return NULL;
991 /*****************************************************************************
992 * RemoveContextFromArray
994 * Removes a context from the context manager. The opengl context is not
995 * destroyed or unset. context is not a valid pointer after that call.
997 * Similar to the former call this isn't a performance critical function. A
998 * helper function for DestroyContext.
1000 * Params:
1001 * This: Device to activate the context for
1002 * context: Context to remove
1004 *****************************************************************************/
1005 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
1006 WineD3DContext **new_array;
1007 BOOL found = FALSE;
1008 UINT i;
1010 TRACE("Removing ctx %p\n", context);
1012 for (i = 0; i < This->numContexts; ++i)
1014 if (This->contexts[i] == context)
1016 HeapFree(GetProcessHeap(), 0, context);
1017 found = TRUE;
1018 break;
1022 if (!found)
1024 ERR("Context %p doesn't exist in context array\n", context);
1025 return;
1028 while (i < This->numContexts - 1)
1030 This->contexts[i] = This->contexts[i + 1];
1031 ++i;
1034 --This->numContexts;
1035 if (!This->numContexts)
1037 HeapFree(GetProcessHeap(), 0, This->contexts);
1038 This->contexts = NULL;
1039 return;
1042 new_array = HeapReAlloc(GetProcessHeap(), 0, This->contexts, This->numContexts * sizeof(*This->contexts));
1043 if (!new_array)
1045 ERR("Failed to shrink context array. Oh well.\n");
1046 return;
1049 This->contexts = new_array;
1052 /*****************************************************************************
1053 * DestroyContext
1055 * Destroys a wineD3DContext
1057 * Params:
1058 * This: Device to activate the context for
1059 * context: Context to destroy
1061 *****************************************************************************/
1062 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
1063 struct fbo_entry *entry, *entry2;
1065 TRACE("Destroying ctx %p\n", context);
1067 /* The correct GL context needs to be active to cleanup the GL resources below */
1068 if(pwglGetCurrentContext() != context->glCtx){
1069 pwglMakeCurrent(context->hdc, context->glCtx);
1070 last_device = NULL;
1073 ENTER_GL();
1075 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry) {
1076 context_destroy_fbo_entry(This, context, entry);
1078 if (context->src_fbo) {
1079 TRACE("Destroy src FBO %d\n", context->src_fbo);
1080 context_destroy_fbo(This, &context->src_fbo);
1082 if (context->dst_fbo) {
1083 TRACE("Destroy dst FBO %d\n", context->dst_fbo);
1084 context_destroy_fbo(This, &context->dst_fbo);
1086 if(context->dummy_arbfp_prog) {
1087 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1090 LEAVE_GL();
1092 if (This->activeContext == context)
1094 This->activeContext = NULL;
1095 TRACE("Destroying the active context.\n");
1098 /* Cleanup the GL context */
1099 pwglMakeCurrent(NULL, NULL);
1100 if(context->isPBuffer) {
1101 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
1102 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
1103 } else ReleaseDC(context->win_handle, context->hdc);
1104 pwglDeleteContext(context->glCtx);
1106 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1107 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1108 RemoveContextFromArray(This, context);
1111 /* GL locking is done by the caller */
1112 static inline void set_blit_dimension(UINT width, UINT height) {
1113 glMatrixMode(GL_PROJECTION);
1114 checkGLcall("glMatrixMode(GL_PROJECTION)");
1115 glLoadIdentity();
1116 checkGLcall("glLoadIdentity()");
1117 glOrtho(0, width, height, 0, 0.0, -1.0);
1118 checkGLcall("glOrtho");
1119 glViewport(0, 0, width, height);
1120 checkGLcall("glViewport");
1123 /*****************************************************************************
1124 * SetupForBlit
1126 * Sets up a context for DirectDraw blitting.
1127 * All texture units are disabled, texture unit 0 is set as current unit
1128 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1129 * color writing enabled for all channels
1130 * register combiners disabled, shaders disabled
1131 * world matrix is set to identity, texture matrix 0 too
1132 * projection matrix is setup for drawing screen coordinates
1134 * Params:
1135 * This: Device to activate the context for
1136 * context: Context to setup
1137 * width: render target width
1138 * height: render target height
1140 *****************************************************************************/
1141 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
1142 int i, sampler;
1143 const struct StateEntry *StateTable = This->StateTable;
1145 TRACE("Setting up context %p for blitting\n", context);
1146 if(context->last_was_blit) {
1147 if(context->blit_w != width || context->blit_h != height) {
1148 ENTER_GL();
1149 set_blit_dimension(width, height);
1150 LEAVE_GL();
1151 context->blit_w = width; context->blit_h = height;
1152 /* No need to dirtify here, the states are still dirtified because they weren't
1153 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1154 * be set
1157 TRACE("Context is already set up for blitting, nothing to do\n");
1158 return;
1160 context->last_was_blit = TRUE;
1162 /* TODO: Use a display list */
1164 /* Disable shaders */
1165 ENTER_GL();
1166 This->shader_backend->shader_select((IWineD3DDevice *)This, FALSE, FALSE);
1167 LEAVE_GL();
1169 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1170 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1172 /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1173 * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1174 * which can safely be called from here, we only lock once instead locking/unlocking
1175 * after each GL call.
1177 ENTER_GL();
1179 /* Disable all textures. The caller can then bind a texture it wants to blit
1180 * from
1182 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1183 * function texture unit. No need to care for higher samplers
1185 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
1186 sampler = This->rev_tex_unit_map[i];
1187 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1188 checkGLcall("glActiveTextureARB");
1190 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1191 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1192 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1194 glDisable(GL_TEXTURE_3D);
1195 checkGLcall("glDisable GL_TEXTURE_3D");
1196 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1197 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1198 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1200 glDisable(GL_TEXTURE_2D);
1201 checkGLcall("glDisable GL_TEXTURE_2D");
1203 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1204 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1206 if (sampler != -1) {
1207 if (sampler < MAX_TEXTURES) {
1208 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1210 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1213 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1214 checkGLcall("glActiveTextureARB");
1216 sampler = This->rev_tex_unit_map[0];
1218 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1219 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1220 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1222 glDisable(GL_TEXTURE_3D);
1223 checkGLcall("glDisable GL_TEXTURE_3D");
1224 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1225 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1226 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1228 glDisable(GL_TEXTURE_2D);
1229 checkGLcall("glDisable GL_TEXTURE_2D");
1231 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1233 glMatrixMode(GL_TEXTURE);
1234 checkGLcall("glMatrixMode(GL_TEXTURE)");
1235 glLoadIdentity();
1236 checkGLcall("glLoadIdentity()");
1238 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
1239 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1240 GL_TEXTURE_LOD_BIAS_EXT,
1241 0.0);
1242 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1245 if (sampler != -1) {
1246 if (sampler < MAX_TEXTURES) {
1247 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1248 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1250 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1253 /* Other misc states */
1254 glDisable(GL_ALPHA_TEST);
1255 checkGLcall("glDisable(GL_ALPHA_TEST)");
1256 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1257 glDisable(GL_LIGHTING);
1258 checkGLcall("glDisable GL_LIGHTING");
1259 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1260 glDisable(GL_DEPTH_TEST);
1261 checkGLcall("glDisable GL_DEPTH_TEST");
1262 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1263 glDisableWINE(GL_FOG);
1264 checkGLcall("glDisable GL_FOG");
1265 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1266 glDisable(GL_BLEND);
1267 checkGLcall("glDisable GL_BLEND");
1268 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1269 glDisable(GL_CULL_FACE);
1270 checkGLcall("glDisable GL_CULL_FACE");
1271 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1272 glDisable(GL_STENCIL_TEST);
1273 checkGLcall("glDisable GL_STENCIL_TEST");
1274 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1275 glDisable(GL_SCISSOR_TEST);
1276 checkGLcall("glDisable GL_SCISSOR_TEST");
1277 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1278 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
1279 glDisable(GL_POINT_SPRITE_ARB);
1280 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1281 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1283 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1284 checkGLcall("glColorMask");
1285 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1286 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
1287 glDisable(GL_COLOR_SUM_EXT);
1288 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1289 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1292 /* Setup transforms */
1293 glMatrixMode(GL_MODELVIEW);
1294 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1295 glLoadIdentity();
1296 checkGLcall("glLoadIdentity()");
1297 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1299 context->last_was_rhw = TRUE;
1300 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1302 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1303 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1304 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1305 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1306 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1307 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1308 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1310 set_blit_dimension(width, height);
1312 LEAVE_GL();
1314 context->blit_w = width; context->blit_h = height;
1315 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1316 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1319 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1322 /*****************************************************************************
1323 * findThreadContextForSwapChain
1325 * Searches a swapchain for all contexts and picks one for the thread tid.
1326 * If none can be found the swapchain is requested to create a new context
1328 *****************************************************************************/
1329 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
1330 unsigned int i;
1332 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1333 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1334 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1339 /* Create a new context for the thread */
1340 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
1343 /*****************************************************************************
1344 * FindContext
1346 * Finds a context for the current render target and thread
1348 * Parameters:
1349 * target: Render target to find the context for
1350 * tid: Thread to activate the context for
1352 * Returns: The needed context
1354 *****************************************************************************/
1355 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
1356 IWineD3DSwapChain *swapchain = NULL;
1357 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
1358 WineD3DContext *context = This->activeContext;
1359 BOOL oldRenderOffscreen = This->render_offscreen;
1360 const struct GlPixelFormatDesc *old = ((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->resource.format_desc;
1361 const struct GlPixelFormatDesc *new = ((IWineD3DSurfaceImpl *)target)->resource.format_desc;
1362 const struct StateEntry *StateTable = This->StateTable;
1364 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
1365 * the alpha blend state changes with different render target formats
1367 if (old->format != new->format)
1369 /* Disable blending when the alpha mask has changed and when a format doesn't support blending */
1370 if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
1371 || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
1373 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1377 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
1378 TRACE("Rendering onscreen\n");
1380 context = findThreadContextForSwapChain(swapchain, tid);
1382 This->render_offscreen = FALSE;
1383 /* The context != This->activeContext will catch a NOP context change. This can occur
1384 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
1385 * rendering. No context change is needed in that case
1388 if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
1389 if(This->pbufferContext && tid == This->pbufferContext->tid) {
1390 This->pbufferContext->tid = 0;
1393 IWineD3DSwapChain_Release(swapchain);
1395 if(oldRenderOffscreen) {
1396 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1397 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1398 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1399 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1400 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1403 } else {
1404 TRACE("Rendering offscreen\n");
1405 This->render_offscreen = TRUE;
1407 switch(wined3d_settings.offscreen_rendering_mode) {
1408 case ORM_FBO:
1409 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
1410 if(This->activeContext && tid == This->lastThread) {
1411 context = This->activeContext;
1412 } else {
1413 /* This may happen if the app jumps straight into offscreen rendering
1414 * Start using the context of the primary swapchain. tid == 0 is no problem
1415 * for findThreadContextForSwapChain.
1417 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1418 * is perfect to call.
1420 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1422 break;
1424 case ORM_PBUFFER:
1426 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
1427 if(This->pbufferContext == NULL ||
1428 This->pbufferWidth < targetimpl->currentDesc.Width ||
1429 This->pbufferHeight < targetimpl->currentDesc.Height) {
1430 if(This->pbufferContext) {
1431 DestroyContext(This, This->pbufferContext);
1434 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
1435 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
1437 This->pbufferContext = CreateContext(This, targetimpl,
1438 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
1439 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
1440 This->pbufferWidth = targetimpl->currentDesc.Width;
1441 This->pbufferHeight = targetimpl->currentDesc.Height;
1444 if(This->pbufferContext) {
1445 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
1446 FIXME("The PBuffr context is only supported for one thread for now!\n");
1448 This->pbufferContext->tid = tid;
1449 context = This->pbufferContext;
1450 break;
1451 } else {
1452 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
1453 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
1457 case ORM_BACKBUFFER:
1458 /* Stay with the currently active context for back buffer rendering */
1459 if(This->activeContext && tid == This->lastThread) {
1460 context = This->activeContext;
1461 } else {
1462 /* This may happen if the app jumps straight into offscreen rendering
1463 * Start using the context of the primary swapchain. tid == 0 is no problem
1464 * for findThreadContextForSwapChain.
1466 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1467 * is perfect to call.
1469 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1471 break;
1474 if(!oldRenderOffscreen) {
1475 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1476 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1477 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1478 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1479 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1483 /* When switching away from an offscreen render target, and we're not using FBOs,
1484 * we have to read the drawable into the texture. This is done via PreLoad(and
1485 * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1486 * PreLoad needs a GL context, and FindContext is called before the context is activated.
1487 * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1488 * is read. This leads to these possible situations:
1490 * 0) lastActiveRenderTarget == target && oldTid == newTid:
1491 * Nothing to do, we don't even reach this code in this case...
1493 * 1) lastActiveRenderTarget != target && oldTid == newTid:
1494 * The currently active context is OK for readback. Call PreLoad, and it
1495 * performs the read
1497 * 2) lastActiveRenderTarget == target && oldTid != newTid:
1498 * Nothing to do - the drawable is unchanged
1500 * 3) lastActiveRenderTarget != target && oldTid != newTid:
1501 * This is tricky. We have to get a context with the old drawable from somewhere
1502 * before we can switch to the new context. In this case, PreLoad calls
1503 * ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1504 * is case (2) then. The old drawable is activated for the new thread, and the
1505 * readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1506 * After that, the outer ActivateContext(which calls PreLoad) can activate the new
1507 * target for the new thread
1509 if (readTexture && This->lastActiveRenderTarget != target) {
1510 BOOL oldInDraw = This->isInDraw;
1512 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1513 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1514 * when using offscreen rendering with multithreading
1516 This->isInDraw = TRUE;
1518 /* Do that before switching the context:
1519 * Read the back buffer of the old drawable into the destination texture
1521 if(((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->glDescription.srgbTextureName) {
1522 surface_internal_preload(This->lastActiveRenderTarget, SRGB_BOTH);
1523 } else {
1524 surface_internal_preload(This->lastActiveRenderTarget, SRGB_RGB);
1527 /* Assume that the drawable will be modified by some other things now */
1528 IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
1530 This->isInDraw = oldInDraw;
1533 return context;
1536 static void apply_draw_buffer(IWineD3DDeviceImpl *This, IWineD3DSurface *target, BOOL blit)
1538 IWineD3DSwapChain *swapchain;
1540 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain)))
1542 IWineD3DSwapChain_Release((IUnknown *)swapchain);
1543 ENTER_GL();
1544 glDrawBuffer(surface_get_gl_buffer(target, swapchain));
1545 checkGLcall("glDrawBuffers()");
1546 LEAVE_GL();
1548 else
1550 ENTER_GL();
1551 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1553 if (!blit)
1555 if (GL_SUPPORT(ARB_DRAW_BUFFERS))
1557 GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), This->draw_buffers));
1558 checkGLcall("glDrawBuffers()");
1560 else
1562 glDrawBuffer(This->draw_buffers[0]);
1563 checkGLcall("glDrawBuffer()");
1565 } else {
1566 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
1567 checkGLcall("glDrawBuffer()");
1570 else
1572 glDrawBuffer(This->offscreenBuffer);
1573 checkGLcall("glDrawBuffer()");
1575 LEAVE_GL();
1579 /*****************************************************************************
1580 * ActivateContext
1582 * Finds a rendering context and drawable matching the device and render
1583 * target for the current thread, activates them and puts them into the
1584 * requested state.
1586 * Params:
1587 * This: Device to activate the context for
1588 * target: Requested render target
1589 * usage: Prepares the context for blitting, drawing or other actions
1591 *****************************************************************************/
1592 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
1593 DWORD tid = GetCurrentThreadId();
1594 DWORD i, dirtyState, idx;
1595 BYTE shift;
1596 WineD3DContext *context;
1597 const struct StateEntry *StateTable = This->StateTable;
1599 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
1600 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
1601 context = FindContext(This, target, tid);
1602 context->draw_buffer_dirty = TRUE;
1603 This->lastActiveRenderTarget = target;
1604 This->lastThread = tid;
1605 } else {
1606 /* Stick to the old context */
1607 context = This->activeContext;
1610 /* Activate the opengl context */
1611 if(last_device != This || context != This->activeContext) {
1612 BOOL ret;
1614 /* Prevent an unneeded context switch as those are expensive */
1615 if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1616 TRACE("Already using gl context %p\n", context->glCtx);
1618 else {
1619 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1621 ret = pwglMakeCurrent(context->hdc, context->glCtx);
1622 if(ret == FALSE) {
1623 ERR("Failed to activate the new context\n");
1624 } else if(!context->last_was_blit) {
1625 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1626 } else {
1627 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1630 if(This->activeContext->vshader_const_dirty) {
1631 memset(This->activeContext->vshader_const_dirty, 1,
1632 sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1634 if(This->activeContext->pshader_const_dirty) {
1635 memset(This->activeContext->pshader_const_dirty, 1,
1636 sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1638 This->activeContext = context;
1639 last_device = This;
1642 switch (usage) {
1643 case CTXUSAGE_CLEAR:
1644 case CTXUSAGE_DRAWPRIM:
1645 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1646 ENTER_GL();
1647 context_apply_fbo_state((IWineD3DDevice *)This);
1648 LEAVE_GL();
1650 if (context->draw_buffer_dirty) {
1651 apply_draw_buffer(This, target, FALSE);
1652 context->draw_buffer_dirty = FALSE;
1654 break;
1656 case CTXUSAGE_BLIT:
1657 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1658 if (This->render_offscreen) {
1659 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
1660 ENTER_GL();
1661 context_bind_fbo((IWineD3DDevice *)This, GL_FRAMEBUFFER_EXT, &context->dst_fbo);
1662 context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, 0, target);
1663 GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0));
1664 checkGLcall("glFramebufferRenderbufferEXT");
1665 LEAVE_GL();
1666 } else {
1667 ENTER_GL();
1668 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
1669 checkGLcall("glFramebufferRenderbufferEXT");
1670 LEAVE_GL();
1672 context->draw_buffer_dirty = TRUE;
1674 if (context->draw_buffer_dirty) {
1675 apply_draw_buffer(This, target, TRUE);
1676 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1677 context->draw_buffer_dirty = FALSE;
1680 break;
1682 default:
1683 break;
1686 switch(usage) {
1687 case CTXUSAGE_RESOURCELOAD:
1688 /* This does not require any special states to be set up */
1689 break;
1691 case CTXUSAGE_CLEAR:
1692 if(context->last_was_blit) {
1693 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1696 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1697 * blending when clearing improves the clearing performance incredibly.
1699 ENTER_GL();
1700 glDisable(GL_BLEND);
1701 LEAVE_GL();
1702 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1704 ENTER_GL();
1705 glEnable(GL_SCISSOR_TEST);
1706 checkGLcall("glEnable GL_SCISSOR_TEST");
1707 LEAVE_GL();
1708 context->last_was_blit = FALSE;
1709 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1710 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1711 break;
1713 case CTXUSAGE_DRAWPRIM:
1714 /* This needs all dirty states applied */
1715 if(context->last_was_blit) {
1716 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1719 IWineD3DDeviceImpl_FindTexUnitMap(This);
1721 ENTER_GL();
1722 for(i=0; i < context->numDirtyEntries; i++) {
1723 dirtyState = context->dirtyArray[i];
1724 idx = dirtyState >> 5;
1725 shift = dirtyState & 0x1f;
1726 context->isStateDirty[idx] &= ~(1 << shift);
1727 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1729 LEAVE_GL();
1730 context->numDirtyEntries = 0; /* This makes the whole list clean */
1731 context->last_was_blit = FALSE;
1732 break;
1734 case CTXUSAGE_BLIT:
1735 SetupForBlit(This, context,
1736 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1737 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1738 break;
1740 default:
1741 FIXME("Unexpected context usage requested\n");
1745 WineD3DContext *getActiveContext(void) {
1746 return last_device->activeContext;