comctl32/toolbar: Skip iString field for separators.
[wine/multimedia.git] / dlls / wined3d / context.c
bloba510d2e125b3975dbf1f04780e44676da5b9d7fa
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 void context_bind_fbo(IWineD3DDevice *iface, GLenum target, GLuint *fbo)
43 const IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
45 if (!*fbo)
47 GL_EXTCALL(glGenFramebuffersEXT(1, fbo));
48 checkGLcall("glGenFramebuffersEXT()");
49 TRACE("Created FBO %d\n", *fbo);
52 GL_EXTCALL(glBindFramebufferEXT(target, *fbo));
53 checkGLcall("glBindFramebuffer()");
56 static void context_destroy_fbo(IWineD3DDeviceImpl *This, const GLuint *fbo)
58 unsigned int i;
60 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, *fbo));
61 checkGLcall("glBindFramebuffer()");
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()");
69 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
70 checkGLcall("glBindFramebuffer()");
71 GL_EXTCALL(glDeleteFramebuffersEXT(1, fbo));
72 checkGLcall("glDeleteFramebuffers()");
75 static void context_apply_attachment_filter_states(IWineD3DDevice *iface, IWineD3DSurface *surface, BOOL force_preload)
77 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
78 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
79 IWineD3DBaseTextureImpl *texture_impl;
80 BOOL update_minfilter = FALSE;
81 BOOL update_magfilter = FALSE;
83 /* Update base texture states array */
84 if (SUCCEEDED(IWineD3DSurface_GetContainer(surface, &IID_IWineD3DBaseTexture, (void **)&texture_impl)))
86 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT
87 || texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] != WINED3DTEXF_NONE)
89 texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
90 texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
91 update_minfilter = TRUE;
94 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
96 texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
97 update_magfilter = TRUE;
100 if (texture_impl->baseTexture.bindCount)
102 WARN("Render targets should not be bound to a sampler\n");
103 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(texture_impl->baseTexture.sampler));
106 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
109 if (update_minfilter || update_magfilter || force_preload)
111 GLenum target, bind_target;
112 GLint old_binding;
114 target = surface_impl->glDescription.target;
115 if (target == GL_TEXTURE_2D)
117 bind_target = GL_TEXTURE_2D;
118 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
119 } else if (target == GL_TEXTURE_RECTANGLE_ARB) {
120 bind_target = GL_TEXTURE_RECTANGLE_ARB;
121 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
122 } else {
123 bind_target = GL_TEXTURE_CUBE_MAP_ARB;
124 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
127 surface_internal_preload(surface, SRGB_RGB);
129 glBindTexture(bind_target, surface_impl->glDescription.textureName);
130 if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
131 if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
132 glBindTexture(bind_target, old_binding);
135 checkGLcall("apply_attachment_filter_states()");
138 /* TODO: Handle stencil attachments */
139 void context_attach_depth_stencil_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, IWineD3DSurface *depth_stencil, BOOL use_render_buffer)
141 IWineD3DSurfaceImpl *depth_stencil_impl = (IWineD3DSurfaceImpl *)depth_stencil;
143 TRACE("Attach depth stencil %p\n", depth_stencil);
145 if (depth_stencil)
147 if (use_render_buffer && depth_stencil_impl->current_renderbuffer)
149 GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_stencil_impl->current_renderbuffer->id));
150 checkGLcall("glFramebufferRenderbufferEXT()");
151 } else {
152 context_apply_attachment_filter_states((IWineD3DDevice *)This, depth_stencil, TRUE);
154 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, depth_stencil_impl->glDescription.target,
155 depth_stencil_impl->glDescription.textureName, depth_stencil_impl->glDescription.level));
156 checkGLcall("glFramebufferTexture2DEXT()");
158 } else {
159 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
160 checkGLcall("glFramebufferTexture2DEXT()");
164 void context_attach_surface_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, DWORD idx, IWineD3DSurface *surface)
166 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
168 TRACE("Attach surface %p to %u\n", surface, idx);
170 if (surface)
172 context_apply_attachment_filter_states((IWineD3DDevice *)This, surface, TRUE);
174 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, surface_impl->glDescription.target,
175 surface_impl->glDescription.textureName, surface_impl->glDescription.level));
176 checkGLcall("glFramebufferTexture2DEXT()");
177 } else {
178 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, GL_TEXTURE_2D, 0, 0));
179 checkGLcall("glFramebufferTexture2DEXT()");
183 static void context_check_fbo_status(IWineD3DDevice *iface)
185 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
186 GLenum status;
188 status = GL_EXTCALL(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
189 if (status == GL_FRAMEBUFFER_COMPLETE_EXT)
191 TRACE("FBO complete\n");
192 } else {
193 IWineD3DSurfaceImpl *attachment;
194 unsigned int i;
195 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
197 /* Dump the FBO attachments */
198 for (i = 0; i < GL_LIMITS(buffers); ++i)
200 attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->render_targets[i];
201 if (attachment)
203 FIXME("\tColor attachment %d: (%p) %s %ux%u\n",
204 i, attachment, debug_d3dformat(attachment->resource.format_desc->format),
205 attachment->pow2Width, attachment->pow2Height);
208 attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->depth_stencil;
209 if (attachment)
211 FIXME("\tDepth attachment: (%p) %s %ux%u\n",
212 attachment, debug_d3dformat(attachment->resource.format_desc->format),
213 attachment->pow2Width, attachment->pow2Height);
218 static struct fbo_entry *context_create_fbo_entry(IWineD3DDevice *iface)
220 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
221 struct fbo_entry *entry;
223 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
224 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
225 memcpy(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
226 entry->depth_stencil = This->stencilBufferTarget;
227 entry->attached = FALSE;
228 entry->id = 0;
230 return entry;
233 static void context_destroy_fbo_entry(IWineD3DDeviceImpl *This, struct fbo_entry *entry)
235 if (entry->id)
237 TRACE("Destroy FBO %d\n", entry->id);
238 context_destroy_fbo(This, &entry->id);
240 list_remove(&entry->entry);
241 HeapFree(GetProcessHeap(), 0, entry->render_targets);
242 HeapFree(GetProcessHeap(), 0, entry);
246 static struct fbo_entry *context_find_fbo_entry(IWineD3DDevice *iface, WineD3DContext *context)
248 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
249 struct fbo_entry *entry;
251 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
253 if (!memcmp(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets))
254 && entry->depth_stencil == This->stencilBufferTarget)
256 return entry;
260 entry = context_create_fbo_entry(iface);
261 list_add_head(&context->fbo_list, &entry->entry);
262 return entry;
265 static void context_apply_fbo_entry(IWineD3DDevice *iface, struct fbo_entry *entry)
267 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
268 unsigned int i;
270 context_bind_fbo(iface, GL_FRAMEBUFFER_EXT, &entry->id);
272 if (!entry->attached)
274 /* Apply render targets */
275 for (i = 0; i < GL_LIMITS(buffers); ++i)
277 IWineD3DSurface *render_target = This->render_targets[i];
278 context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, i, render_target);
281 /* Apply depth targets */
282 if (This->stencilBufferTarget) {
283 unsigned int w = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Width;
284 unsigned int h = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Height;
286 surface_set_compatible_renderbuffer(This->stencilBufferTarget, w, h);
288 context_attach_depth_stencil_fbo(This, GL_FRAMEBUFFER_EXT, This->stencilBufferTarget, TRUE);
290 entry->attached = TRUE;
291 } else {
292 for (i = 0; i < GL_LIMITS(buffers); ++i)
294 if (This->render_targets[i])
295 context_apply_attachment_filter_states(iface, This->render_targets[i], FALSE);
297 if (This->stencilBufferTarget)
298 context_apply_attachment_filter_states(iface, This->stencilBufferTarget, FALSE);
301 for (i = 0; i < GL_LIMITS(buffers); ++i)
303 if (This->render_targets[i])
304 This->draw_buffers[i] = GL_COLOR_ATTACHMENT0_EXT + i;
305 else
306 This->draw_buffers[i] = GL_NONE;
310 static void context_apply_fbo_state(IWineD3DDevice *iface)
312 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
313 WineD3DContext *context = This->activeContext;
315 if (This->render_offscreen)
317 context->current_fbo = context_find_fbo_entry(iface, context);
318 context_apply_fbo_entry(iface, context->current_fbo);
319 } else {
320 context->current_fbo = NULL;
321 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
324 context_check_fbo_status(iface);
327 void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
329 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
330 UINT i;
332 switch(type)
334 case WINED3DRTYPE_SURFACE:
336 for (i = 0; i < This->numContexts; ++i)
338 struct fbo_entry *entry, *entry2;
340 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->contexts[i]->fbo_list, struct fbo_entry, entry)
342 BOOL destroyed = FALSE;
343 UINT j;
345 for (j = 0; !destroyed && j < GL_LIMITS(buffers); ++j)
347 if (entry->render_targets[j] == (IWineD3DSurface *)resource)
349 context_destroy_fbo_entry(This, entry);
350 destroyed = TRUE;
354 if (!destroyed && entry->depth_stencil == (IWineD3DSurface *)resource)
355 context_destroy_fbo_entry(This, entry);
359 break;
362 default:
363 break;
367 /*****************************************************************************
368 * Context_MarkStateDirty
370 * Marks a state in a context dirty. Only one context, opposed to
371 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
372 * contexts
374 * Params:
375 * context: Context to mark the state dirty in
376 * state: State to mark dirty
377 * StateTable: Pointer to the state table in use(for state grouping)
379 *****************************************************************************/
380 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
381 DWORD rep = StateTable[state].representative;
382 DWORD idx;
383 BYTE shift;
385 if(!rep || isStateDirty(context, rep)) return;
387 context->dirtyArray[context->numDirtyEntries++] = rep;
388 idx = rep >> 5;
389 shift = rep & 0x1f;
390 context->isStateDirty[idx] |= (1 << shift);
393 /*****************************************************************************
394 * AddContextToArray
396 * Adds a context to the context array. Helper function for CreateContext
398 * This method is not called in performance-critical code paths, only when a
399 * new render target or swapchain is created. Thus performance is not an issue
400 * here.
402 * Params:
403 * This: Device to add the context for
404 * hdc: device context
405 * glCtx: WGL context to add
406 * pbuffer: optional pbuffer used with this context
408 *****************************************************************************/
409 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
410 WineD3DContext **oldArray = This->contexts;
411 DWORD state;
413 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
414 if(This->contexts == NULL) {
415 ERR("Unable to grow the context array\n");
416 This->contexts = oldArray;
417 return NULL;
419 if(oldArray) {
420 memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
423 This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
424 if(This->contexts[This->numContexts] == NULL) {
425 ERR("Unable to allocate a new context\n");
426 HeapFree(GetProcessHeap(), 0, This->contexts);
427 This->contexts = oldArray;
428 return NULL;
431 This->contexts[This->numContexts]->hdc = hdc;
432 This->contexts[This->numContexts]->glCtx = glCtx;
433 This->contexts[This->numContexts]->pbuffer = pbuffer;
434 This->contexts[This->numContexts]->win_handle = win_handle;
435 HeapFree(GetProcessHeap(), 0, oldArray);
437 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
439 for(state = 0; state <= STATE_HIGHEST; state++) {
440 Context_MarkStateDirty(This->contexts[This->numContexts], state, This->StateTable);
443 This->numContexts++;
444 TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
445 return This->contexts[This->numContexts - 1];
448 /* This function takes care of WineD3D pixel format selection. */
449 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc,
450 const struct GlPixelFormatDesc *color_format_desc, const struct GlPixelFormatDesc *ds_format_desc,
451 BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
453 int iPixelFormat=0;
454 unsigned int matchtry;
455 short redBits, greenBits, blueBits, alphaBits, colorBits;
456 short depthBits=0, stencilBits=0;
458 struct match_type {
459 BOOL require_aux;
460 BOOL exact_alpha;
461 BOOL exact_color;
462 } matches[] = {
463 /* First, try without alpha match buffers. MacOS supports aux buffers only
464 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
465 * Then try without aux buffers - this is the most common cause for not
466 * finding a pixel format. Also some drivers(the open source ones)
467 * only offer 32 bit ARB pixel formats. First try without an exact alpha
468 * match, then try without an exact alpha and color match.
470 { TRUE, TRUE, TRUE },
471 { TRUE, FALSE, TRUE },
472 { FALSE, TRUE, TRUE },
473 { FALSE, FALSE, TRUE },
474 { TRUE, FALSE, FALSE },
475 { FALSE, FALSE, FALSE },
478 int i = 0;
479 int nCfgs = This->adapter->nCfgs;
481 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
482 debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format),
483 auxBuffers, numSamples, pbuffer, findCompatible);
485 if (!getColorBits(color_format_desc, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
487 ERR("Unable to get color bits for format %s (%#x)!\n",
488 debug_d3dformat(color_format_desc->format), color_format_desc->format);
489 return 0;
492 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
493 * You are able to add a depth + stencil surface at a later stage when you need it.
494 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
495 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
496 * context, need torecreate shaders, textures and other resources.
498 * The context manager already takes care of the state problem and for the other tasks code from Reset
499 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
500 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
501 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
502 * issue needs to be fixed. */
503 if (ds_format_desc->format != WINED3DFMT_D24S8)
505 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
506 ds_format_desc = getFormatDescEntry(WINED3DFMT_D24S8, &This->adapter->gl_info);
509 getDepthStencilBits(ds_format_desc, &depthBits, &stencilBits);
511 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
512 for(i=0; i<nCfgs; i++) {
513 BOOL exactDepthMatch = TRUE;
514 WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
516 /* For now only accept RGBA formats. Perhaps some day we will
517 * allow floating point formats for pbuffers. */
518 if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
519 continue;
521 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
522 if(!pbuffer && !(cfg->windowDrawable && cfg->doubleBuffer))
523 continue;
525 /* We like to have aux buffers in backbuffer mode */
526 if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
527 continue;
529 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
530 if(pbuffer && (!cfg->pbufferDrawable || cfg->doubleBuffer))
531 continue;
533 if(matches[matchtry].exact_color) {
534 if(cfg->redSize != redBits)
535 continue;
536 if(cfg->greenSize != greenBits)
537 continue;
538 if(cfg->blueSize != blueBits)
539 continue;
540 } else {
541 if(cfg->redSize < redBits)
542 continue;
543 if(cfg->greenSize < greenBits)
544 continue;
545 if(cfg->blueSize < blueBits)
546 continue;
548 if(matches[matchtry].exact_alpha) {
549 if(cfg->alphaSize != alphaBits)
550 continue;
551 } else {
552 if(cfg->alphaSize < alphaBits)
553 continue;
556 /* We try to locate a format which matches our requirements exactly. In case of
557 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
558 if(cfg->depthSize < depthBits)
559 continue;
560 else if(cfg->depthSize > depthBits)
561 exactDepthMatch = FALSE;
563 /* In all cases make sure the number of stencil bits matches our requirements
564 * even when we don't need stencil because it could affect performance EXCEPT
565 * on cards which don't offer depth formats without stencil like the i915 drivers
566 * on Linux. */
567 if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
568 continue;
570 /* Check multisampling support */
571 if(cfg->numSamples != numSamples)
572 continue;
574 /* When we have passed all the checks then we have found a format which matches our
575 * requirements. Note that we only check for a limit number of capabilities right now,
576 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
577 * can still differ in things like multisampling, stereo, SRGB and other flags.
580 /* Exit the loop as we have found a format :) */
581 if(exactDepthMatch) {
582 iPixelFormat = cfg->iPixelFormat;
583 break;
584 } else if(!iPixelFormat) {
585 /* In the end we might end up with a format which doesn't exactly match our depth
586 * requirements. Accept the first format we found because formats with higher iPixelFormat
587 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
588 iPixelFormat = cfg->iPixelFormat;
593 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
594 if(!iPixelFormat && !findCompatible) {
595 ERR("Can't find a suitable iPixelFormat\n");
596 return FALSE;
597 } else if(!iPixelFormat) {
598 PIXELFORMATDESCRIPTOR pfd;
600 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
601 /* PixelFormat selection */
602 ZeroMemory(&pfd, sizeof(pfd));
603 pfd.nSize = sizeof(pfd);
604 pfd.nVersion = 1;
605 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
606 pfd.iPixelType = PFD_TYPE_RGBA;
607 pfd.cAlphaBits = alphaBits;
608 pfd.cColorBits = colorBits;
609 pfd.cDepthBits = depthBits;
610 pfd.cStencilBits = stencilBits;
611 pfd.iLayerType = PFD_MAIN_PLANE;
613 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
614 if(!iPixelFormat) {
615 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
616 ERR("Can't find a suitable iPixelFormat\n");
617 return FALSE;
621 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
622 iPixelFormat, debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format));
623 return iPixelFormat;
626 /*****************************************************************************
627 * CreateContext
629 * Creates a new context for a window, or a pbuffer context.
631 * * Params:
632 * This: Device to activate the context for
633 * target: Surface this context will render to
634 * win_handle: handle to the window which we are drawing to
635 * create_pbuffer: tells whether to create a pbuffer or not
636 * pPresentParameters: contains the pixelformats to use for onscreen rendering
638 *****************************************************************************/
639 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
640 HDC oldDrawable, hdc;
641 HPBUFFERARB pbuffer = NULL;
642 HGLRC ctx = NULL, oldCtx;
643 WineD3DContext *ret = NULL;
644 unsigned int s;
646 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
648 if(create_pbuffer) {
649 HDC hdc_parent = GetDC(win_handle);
650 int iPixelFormat = 0;
652 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
653 const struct GlPixelFormatDesc *ds_format_desc = StencilSurface
654 ? ((IWineD3DSurfaceImpl *)StencilSurface)->resource.format_desc
655 : getFormatDescEntry(WINED3DFMT_UNKNOWN, &This->adapter->gl_info);
657 /* Try to find a pixel format with pbuffer support. */
658 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
659 ds_format_desc, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */,
660 FALSE /* findCompatible */);
661 if(!iPixelFormat) {
662 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
664 /* For some reason we weren't able to find a format, try to find something instead of crashing.
665 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
666 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
667 ds_format_desc, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */,
668 TRUE /* findCompatible */);
671 /* This shouldn't happen as ChoosePixelFormat always returns something */
672 if(!iPixelFormat) {
673 ERR("Unable to locate a pixel format for a pbuffer\n");
674 ReleaseDC(win_handle, hdc_parent);
675 goto out;
678 TRACE("Creating a pBuffer drawable for the new context\n");
679 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
680 if(!pbuffer) {
681 ERR("Cannot create a pbuffer\n");
682 ReleaseDC(win_handle, hdc_parent);
683 goto out;
686 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
687 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
688 if(!hdc) {
689 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
690 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
691 ReleaseDC(win_handle, hdc_parent);
692 goto out;
694 ReleaseDC(win_handle, hdc_parent);
695 } else {
696 PIXELFORMATDESCRIPTOR pfd;
697 int iPixelFormat;
698 int res;
699 const struct GlPixelFormatDesc *color_format_desc = target->resource.format_desc;
700 const struct GlPixelFormatDesc *ds_format_desc = getFormatDescEntry(WINED3DFMT_UNKNOWN,
701 &This->adapter->gl_info);
702 BOOL auxBuffers = FALSE;
703 int numSamples = 0;
705 hdc = GetDC(win_handle);
706 if(hdc == NULL) {
707 ERR("Cannot retrieve a device context!\n");
708 goto out;
711 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
712 if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
713 auxBuffers = TRUE;
715 if (color_format_desc->format == WINED3DFMT_X4R4G4B4)
716 color_format_desc = getFormatDescEntry(WINED3DFMT_A4R4G4B4, &This->adapter->gl_info);
717 else if (color_format_desc->format == WINED3DFMT_X8R8G8B8)
718 color_format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->adapter->gl_info);
721 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
722 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
723 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
724 * a format with 8bit alpha, so request A8R8G8B8. */
725 if (color_format_desc->format == WINED3DFMT_P8)
726 color_format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->adapter->gl_info);
728 /* Retrieve the depth stencil format from the present parameters.
729 * The choice of the proper format can give a nice performance boost
730 * in case of GPU limited programs. */
731 if(pPresentParms->EnableAutoDepthStencil) {
732 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
733 ds_format_desc = getFormatDescEntry(pPresentParms->AutoDepthStencilFormat, &This->adapter->gl_info);
736 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
737 if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
738 if(!GL_SUPPORT(ARB_MULTISAMPLE))
739 ERR("The program is requesting multisampling without support!\n");
740 else {
741 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
742 numSamples = pPresentParms->MultiSampleType;
746 /* Try to find a pixel format which matches our requirements */
747 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
748 auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
750 /* Try to locate a compatible format if we weren't able to find anything */
751 if(!iPixelFormat) {
752 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
753 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
754 auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
757 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
758 if(!iPixelFormat) {
759 ERR("Can't find a suitable iPixelFormat\n");
760 return FALSE;
763 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
764 res = SetPixelFormat(hdc, iPixelFormat, NULL);
765 if(!res) {
766 int oldPixelFormat = GetPixelFormat(hdc);
768 /* By default WGL doesn't allow pixel format adjustments but we need it here.
769 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
770 * set the pixel format multiple times. Only use it when it is really needed. */
772 if(oldPixelFormat == iPixelFormat) {
773 /* We don't have to do anything as the formats are the same :) */
774 } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
775 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
777 if(!res) {
778 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
779 return FALSE;
781 } else if(oldPixelFormat) {
782 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
783 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
784 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
785 } else {
786 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
787 return FALSE;
792 ctx = pwglCreateContext(hdc);
793 if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
795 if(!ctx) {
796 ERR("Failed to create a WGL context\n");
797 if(create_pbuffer) {
798 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
799 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
801 goto out;
803 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
804 if(!ret) {
805 ERR("Failed to add the newly created context to the context list\n");
806 pwglDeleteContext(ctx);
807 if(create_pbuffer) {
808 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
809 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
811 goto out;
813 ret->surface = (IWineD3DSurface *) target;
814 ret->isPBuffer = create_pbuffer;
815 ret->tid = GetCurrentThreadId();
816 if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
817 /* Create the dirty constants array and initialize them to dirty */
818 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
819 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
820 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
821 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
822 memset(ret->vshader_const_dirty, 1,
823 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
824 memset(ret->pshader_const_dirty, 1,
825 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
828 TRACE("Successfully created new context %p\n", ret);
830 list_init(&ret->fbo_list);
832 /* Set up the context defaults */
833 oldCtx = pwglGetCurrentContext();
834 oldDrawable = pwglGetCurrentDC();
835 if(oldCtx && oldDrawable) {
836 /* See comment in ActivateContext context switching */
837 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
839 if(pwglMakeCurrent(hdc, ctx) == FALSE) {
840 ERR("Cannot activate context to set up defaults\n");
841 goto out;
844 ENTER_GL();
846 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
848 TRACE("Setting up the screen\n");
849 /* Clear the screen */
850 glClearColor(1.0, 0.0, 0.0, 0.0);
851 checkGLcall("glClearColor");
852 glClearIndex(0);
853 glClearDepth(1);
854 glClearStencil(0xffff);
856 checkGLcall("glClear");
858 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
859 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
861 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
862 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
864 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
865 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
867 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
868 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
869 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
870 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
872 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
873 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
874 * and textures in DIB sections(due to the memory protection).
876 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
877 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
879 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
880 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
881 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
882 * GL_VERTEX_BLEND_ARB isn't enabled too
884 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
885 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
887 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
888 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
889 * the previous texture where to source the offset from is always unit - 1.
891 for(s = 1; s < GL_LIMITS(textures); s++) {
892 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
893 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
894 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
898 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
899 for(s = 0; s < GL_LIMITS(textures); s++) {
900 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
901 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
902 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
905 LEAVE_GL();
907 /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
908 * but enable it for the first context we create, and reenable it on the old context
910 if(oldDrawable && oldCtx) {
911 pwglMakeCurrent(oldDrawable, oldCtx);
912 } else {
913 last_device = This;
915 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
917 return ret;
919 out:
920 return NULL;
923 /*****************************************************************************
924 * RemoveContextFromArray
926 * Removes a context from the context manager. The opengl context is not
927 * destroyed or unset. context is not a valid pointer after that call.
929 * Similar to the former call this isn't a performance critical function. A
930 * helper function for DestroyContext.
932 * Params:
933 * This: Device to activate the context for
934 * context: Context to remove
936 *****************************************************************************/
937 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
938 WineD3DContext **new_array;
939 BOOL found = FALSE;
940 UINT i;
942 TRACE("Removing ctx %p\n", context);
944 for (i = 0; i < This->numContexts; ++i)
946 if (This->contexts[i] == context)
948 HeapFree(GetProcessHeap(), 0, context);
949 found = TRUE;
950 break;
954 if (!found)
956 ERR("Context %p doesn't exist in context array\n", context);
957 return;
960 while (i < This->numContexts - 1)
962 This->contexts[i] = This->contexts[i + 1];
963 ++i;
966 --This->numContexts;
967 if (!This->numContexts)
969 HeapFree(GetProcessHeap(), 0, This->contexts);
970 This->contexts = NULL;
971 return;
974 new_array = HeapReAlloc(GetProcessHeap(), 0, This->contexts, This->numContexts * sizeof(*This->contexts));
975 if (!new_array)
977 ERR("Failed to shrink context array. Oh well.\n");
978 return;
981 This->contexts = new_array;
984 /*****************************************************************************
985 * DestroyContext
987 * Destroys a wineD3DContext
989 * Params:
990 * This: Device to activate the context for
991 * context: Context to destroy
993 *****************************************************************************/
994 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
995 struct fbo_entry *entry, *entry2;
997 TRACE("Destroying ctx %p\n", context);
999 /* The correct GL context needs to be active to cleanup the GL resources below */
1000 if(pwglGetCurrentContext() != context->glCtx){
1001 pwglMakeCurrent(context->hdc, context->glCtx);
1002 last_device = NULL;
1005 ENTER_GL();
1007 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry) {
1008 context_destroy_fbo_entry(This, entry);
1010 if (context->src_fbo) {
1011 TRACE("Destroy src FBO %d\n", context->src_fbo);
1012 context_destroy_fbo(This, &context->src_fbo);
1014 if (context->dst_fbo) {
1015 TRACE("Destroy dst FBO %d\n", context->dst_fbo);
1016 context_destroy_fbo(This, &context->dst_fbo);
1019 LEAVE_GL();
1021 if (This->activeContext == context)
1023 This->activeContext = NULL;
1024 TRACE("Destroying the active context.\n");
1027 /* Cleanup the GL context */
1028 pwglMakeCurrent(NULL, NULL);
1029 if(context->isPBuffer) {
1030 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
1031 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
1032 } else ReleaseDC(context->win_handle, context->hdc);
1033 pwglDeleteContext(context->glCtx);
1035 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1036 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1037 RemoveContextFromArray(This, context);
1040 static inline void set_blit_dimension(UINT width, UINT height) {
1041 glMatrixMode(GL_PROJECTION);
1042 checkGLcall("glMatrixMode(GL_PROJECTION)");
1043 glLoadIdentity();
1044 checkGLcall("glLoadIdentity()");
1045 glOrtho(0, width, height, 0, 0.0, -1.0);
1046 checkGLcall("glOrtho");
1047 glViewport(0, 0, width, height);
1048 checkGLcall("glViewport");
1051 /*****************************************************************************
1052 * SetupForBlit
1054 * Sets up a context for DirectDraw blitting.
1055 * All texture units are disabled, texture unit 0 is set as current unit
1056 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1057 * color writing enabled for all channels
1058 * register combiners disabled, shaders disabled
1059 * world matrix is set to identity, texture matrix 0 too
1060 * projection matrix is setup for drawing screen coordinates
1062 * Params:
1063 * This: Device to activate the context for
1064 * context: Context to setup
1065 * width: render target width
1066 * height: render target height
1068 *****************************************************************************/
1069 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
1070 int i, sampler;
1071 const struct StateEntry *StateTable = This->StateTable;
1073 TRACE("Setting up context %p for blitting\n", context);
1074 if(context->last_was_blit) {
1075 if(context->blit_w != width || context->blit_h != height) {
1076 set_blit_dimension(width, height);
1077 context->blit_w = width; context->blit_h = height;
1078 /* No need to dirtify here, the states are still dirtified because they weren't
1079 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1080 * be set
1083 TRACE("Context is already set up for blitting, nothing to do\n");
1084 return;
1086 context->last_was_blit = TRUE;
1088 /* TODO: Use a display list */
1090 /* Disable shaders */
1091 This->shader_backend->shader_select((IWineD3DDevice *)This, FALSE, FALSE);
1092 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1093 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1095 /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1096 * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1097 * which can safely be called from here, we only lock once instead locking/unlocking
1098 * after each GL call.
1100 ENTER_GL();
1102 /* Disable all textures. The caller can then bind a texture it wants to blit
1103 * from
1105 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1106 * function texture unit. No need to care for higher samplers
1108 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
1109 sampler = This->rev_tex_unit_map[i];
1110 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1111 checkGLcall("glActiveTextureARB");
1113 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1114 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1115 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1117 glDisable(GL_TEXTURE_3D);
1118 checkGLcall("glDisable GL_TEXTURE_3D");
1119 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1120 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1121 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1123 glDisable(GL_TEXTURE_2D);
1124 checkGLcall("glDisable GL_TEXTURE_2D");
1126 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1127 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1129 if (sampler != -1) {
1130 if (sampler < MAX_TEXTURES) {
1131 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1133 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1136 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1137 checkGLcall("glActiveTextureARB");
1139 sampler = This->rev_tex_unit_map[0];
1141 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1142 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1143 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1145 glDisable(GL_TEXTURE_3D);
1146 checkGLcall("glDisable GL_TEXTURE_3D");
1147 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1148 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1149 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1151 glDisable(GL_TEXTURE_2D);
1152 checkGLcall("glDisable GL_TEXTURE_2D");
1154 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1156 glMatrixMode(GL_TEXTURE);
1157 checkGLcall("glMatrixMode(GL_TEXTURE)");
1158 glLoadIdentity();
1159 checkGLcall("glLoadIdentity()");
1161 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
1162 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1163 GL_TEXTURE_LOD_BIAS_EXT,
1164 0.0);
1165 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1168 if (sampler != -1) {
1169 if (sampler < MAX_TEXTURES) {
1170 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1171 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1173 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1176 /* Other misc states */
1177 glDisable(GL_ALPHA_TEST);
1178 checkGLcall("glDisable(GL_ALPHA_TEST)");
1179 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1180 glDisable(GL_LIGHTING);
1181 checkGLcall("glDisable GL_LIGHTING");
1182 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1183 glDisable(GL_DEPTH_TEST);
1184 checkGLcall("glDisable GL_DEPTH_TEST");
1185 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1186 glDisableWINE(GL_FOG);
1187 checkGLcall("glDisable GL_FOG");
1188 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1189 glDisable(GL_BLEND);
1190 checkGLcall("glDisable GL_BLEND");
1191 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1192 glDisable(GL_CULL_FACE);
1193 checkGLcall("glDisable GL_CULL_FACE");
1194 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1195 glDisable(GL_STENCIL_TEST);
1196 checkGLcall("glDisable GL_STENCIL_TEST");
1197 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1198 glDisable(GL_SCISSOR_TEST);
1199 checkGLcall("glDisable GL_SCISSOR_TEST");
1200 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1201 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
1202 glDisable(GL_POINT_SPRITE_ARB);
1203 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1204 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1206 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1207 checkGLcall("glColorMask");
1208 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1209 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
1210 glDisable(GL_COLOR_SUM_EXT);
1211 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1212 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1215 /* Setup transforms */
1216 glMatrixMode(GL_MODELVIEW);
1217 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1218 glLoadIdentity();
1219 checkGLcall("glLoadIdentity()");
1220 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1222 context->last_was_rhw = TRUE;
1223 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1225 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1226 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1227 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1228 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1229 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1230 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1231 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1232 LEAVE_GL();
1234 set_blit_dimension(width, height);
1235 context->blit_w = width; context->blit_h = height;
1236 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1237 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1240 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1243 /*****************************************************************************
1244 * findThreadContextForSwapChain
1246 * Searches a swapchain for all contexts and picks one for the thread tid.
1247 * If none can be found the swapchain is requested to create a new context
1249 *****************************************************************************/
1250 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
1251 unsigned int i;
1253 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1254 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1255 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1260 /* Create a new context for the thread */
1261 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
1264 /*****************************************************************************
1265 * FindContext
1267 * Finds a context for the current render target and thread
1269 * Parameters:
1270 * target: Render target to find the context for
1271 * tid: Thread to activate the context for
1273 * Returns: The needed context
1275 *****************************************************************************/
1276 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
1277 IWineD3DSwapChain *swapchain = NULL;
1278 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
1279 WineD3DContext *context = This->activeContext;
1280 BOOL oldRenderOffscreen = This->render_offscreen;
1281 const struct GlPixelFormatDesc *old = ((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->resource.format_desc;
1282 const struct GlPixelFormatDesc *new = ((IWineD3DSurfaceImpl *)target)->resource.format_desc;
1283 const struct StateEntry *StateTable = This->StateTable;
1285 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
1286 * the alpha blend state changes with different render target formats
1288 if (old->format != new->format)
1290 /* Disable blending when the alpha mask has changed and when a format doesn't support blending */
1291 if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
1292 || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
1294 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1298 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
1299 TRACE("Rendering onscreen\n");
1301 context = findThreadContextForSwapChain(swapchain, tid);
1303 This->render_offscreen = FALSE;
1304 /* The context != This->activeContext will catch a NOP context change. This can occur
1305 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
1306 * rendering. No context change is needed in that case
1309 if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
1310 if(This->pbufferContext && tid == This->pbufferContext->tid) {
1311 This->pbufferContext->tid = 0;
1314 IWineD3DSwapChain_Release(swapchain);
1316 if(oldRenderOffscreen) {
1317 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1318 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1319 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1320 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1321 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1324 } else {
1325 TRACE("Rendering offscreen\n");
1326 This->render_offscreen = TRUE;
1328 switch(wined3d_settings.offscreen_rendering_mode) {
1329 case ORM_FBO:
1330 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
1331 if(This->activeContext && tid == This->lastThread) {
1332 context = This->activeContext;
1333 } else {
1334 /* This may happen if the app jumps straight into offscreen rendering
1335 * Start using the context of the primary swapchain. tid == 0 is no problem
1336 * for findThreadContextForSwapChain.
1338 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1339 * is perfect to call.
1341 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1343 break;
1345 case ORM_PBUFFER:
1347 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
1348 if(This->pbufferContext == NULL ||
1349 This->pbufferWidth < targetimpl->currentDesc.Width ||
1350 This->pbufferHeight < targetimpl->currentDesc.Height) {
1351 if(This->pbufferContext) {
1352 DestroyContext(This, This->pbufferContext);
1355 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
1356 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
1358 This->pbufferContext = CreateContext(This, targetimpl,
1359 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
1360 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
1361 This->pbufferWidth = targetimpl->currentDesc.Width;
1362 This->pbufferHeight = targetimpl->currentDesc.Height;
1365 if(This->pbufferContext) {
1366 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
1367 FIXME("The PBuffr context is only supported for one thread for now!\n");
1369 This->pbufferContext->tid = tid;
1370 context = This->pbufferContext;
1371 break;
1372 } else {
1373 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
1374 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
1378 case ORM_BACKBUFFER:
1379 /* Stay with the currently active context for back buffer rendering */
1380 if(This->activeContext && tid == This->lastThread) {
1381 context = This->activeContext;
1382 } else {
1383 /* This may happen if the app jumps straight into offscreen rendering
1384 * Start using the context of the primary swapchain. tid == 0 is no problem
1385 * for findThreadContextForSwapChain.
1387 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1388 * is perfect to call.
1390 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1392 break;
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);
1404 /* When switching away from an offscreen render target, and we're not using FBOs,
1405 * we have to read the drawable into the texture. This is done via PreLoad(and
1406 * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1407 * PreLoad needs a GL context, and FindContext is called before the context is activated.
1408 * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1409 * is read. This leads to these possible situations:
1411 * 0) lastActiveRenderTarget == target && oldTid == newTid:
1412 * Nothing to do, we don't even reach this code in this case...
1414 * 1) lastActiveRenderTarget != target && oldTid == newTid:
1415 * The currently active context is OK for readback. Call PreLoad, and it
1416 * performs the read
1418 * 2) lastActiveRenderTarget == target && oldTid != newTid:
1419 * Nothing to do - the drawable is unchanged
1421 * 3) lastActiveRenderTarget != target && oldTid != newTid:
1422 * This is tricky. We have to get a context with the old drawable from somewhere
1423 * before we can switch to the new context. In this case, PreLoad calls
1424 * ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1425 * is case (2) then. The old drawable is activated for the new thread, and the
1426 * readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1427 * After that, the outer ActivateContext(which calls PreLoad) can activate the new
1428 * target for the new thread
1430 if (readTexture && This->lastActiveRenderTarget != target) {
1431 BOOL oldInDraw = This->isInDraw;
1433 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1434 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1435 * when using offscreen rendering with multithreading
1437 This->isInDraw = TRUE;
1439 /* Do that before switching the context:
1440 * Read the back buffer of the old drawable into the destination texture
1442 if(((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->glDescription.srgbTextureName) {
1443 surface_internal_preload(This->lastActiveRenderTarget, SRGB_BOTH);
1444 } else {
1445 surface_internal_preload(This->lastActiveRenderTarget, SRGB_RGB);
1448 /* Assume that the drawable will be modified by some other things now */
1449 IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
1451 This->isInDraw = oldInDraw;
1454 return context;
1457 static void apply_draw_buffer(IWineD3DDeviceImpl *This, IWineD3DSurface *target, BOOL blit)
1459 IWineD3DSwapChain *swapchain;
1461 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain)))
1463 IWineD3DSwapChain_Release((IUnknown *)swapchain);
1464 ENTER_GL();
1465 glDrawBuffer(surface_get_gl_buffer(target, swapchain));
1466 checkGLcall("glDrawBuffers()");
1467 LEAVE_GL();
1469 else
1471 ENTER_GL();
1472 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1474 if (!blit)
1476 if (GL_SUPPORT(ARB_DRAW_BUFFERS))
1478 GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), This->draw_buffers));
1479 checkGLcall("glDrawBuffers()");
1481 else
1483 glDrawBuffer(This->draw_buffers[0]);
1484 checkGLcall("glDrawBuffer()");
1486 } else {
1487 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
1488 checkGLcall("glDrawBuffer()");
1491 else
1493 glDrawBuffer(This->offscreenBuffer);
1494 checkGLcall("glDrawBuffer()");
1496 LEAVE_GL();
1500 /*****************************************************************************
1501 * ActivateContext
1503 * Finds a rendering context and drawable matching the device and render
1504 * target for the current thread, activates them and puts them into the
1505 * requested state.
1507 * Params:
1508 * This: Device to activate the context for
1509 * target: Requested render target
1510 * usage: Prepares the context for blitting, drawing or other actions
1512 *****************************************************************************/
1513 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
1514 DWORD tid = GetCurrentThreadId();
1515 DWORD i, dirtyState, idx;
1516 BYTE shift;
1517 WineD3DContext *context;
1518 const struct StateEntry *StateTable = This->StateTable;
1520 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
1521 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
1522 context = FindContext(This, target, tid);
1523 context->draw_buffer_dirty = TRUE;
1524 This->lastActiveRenderTarget = target;
1525 This->lastThread = tid;
1526 } else {
1527 /* Stick to the old context */
1528 context = This->activeContext;
1531 /* Activate the opengl context */
1532 if(last_device != This || context != This->activeContext) {
1533 BOOL ret;
1535 /* Prevent an unneeded context switch as those are expensive */
1536 if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1537 TRACE("Already using gl context %p\n", context->glCtx);
1539 else {
1540 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1542 ret = pwglMakeCurrent(context->hdc, context->glCtx);
1543 if(ret == FALSE) {
1544 ERR("Failed to activate the new context\n");
1545 } else if(!context->last_was_blit) {
1546 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1547 } else {
1548 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1551 if(This->activeContext->vshader_const_dirty) {
1552 memset(This->activeContext->vshader_const_dirty, 1,
1553 sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1555 if(This->activeContext->pshader_const_dirty) {
1556 memset(This->activeContext->pshader_const_dirty, 1,
1557 sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1559 This->activeContext = context;
1560 last_device = This;
1563 switch (usage) {
1564 case CTXUSAGE_CLEAR:
1565 case CTXUSAGE_DRAWPRIM:
1566 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1567 context_apply_fbo_state((IWineD3DDevice *)This);
1569 if (context->draw_buffer_dirty) {
1570 apply_draw_buffer(This, target, FALSE);
1571 context->draw_buffer_dirty = FALSE;
1573 break;
1575 case CTXUSAGE_BLIT:
1576 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1577 if (This->render_offscreen) {
1578 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
1579 context_bind_fbo((IWineD3DDevice *)This, GL_FRAMEBUFFER_EXT, &context->dst_fbo);
1580 context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, 0, target);
1582 ENTER_GL();
1583 GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0));
1584 checkGLcall("glFramebufferRenderbufferEXT");
1585 LEAVE_GL();
1586 } else {
1587 ENTER_GL();
1588 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
1589 checkGLcall("glFramebufferRenderbufferEXT");
1590 LEAVE_GL();
1592 context->draw_buffer_dirty = TRUE;
1594 if (context->draw_buffer_dirty) {
1595 apply_draw_buffer(This, target, TRUE);
1596 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1597 context->draw_buffer_dirty = FALSE;
1600 break;
1602 default:
1603 break;
1606 switch(usage) {
1607 case CTXUSAGE_RESOURCELOAD:
1608 /* This does not require any special states to be set up */
1609 break;
1611 case CTXUSAGE_CLEAR:
1612 if(context->last_was_blit) {
1613 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1616 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1617 * blending when clearing improves the clearing performance incredibly.
1619 ENTER_GL();
1620 glDisable(GL_BLEND);
1621 LEAVE_GL();
1622 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1624 ENTER_GL();
1625 glEnable(GL_SCISSOR_TEST);
1626 checkGLcall("glEnable GL_SCISSOR_TEST");
1627 LEAVE_GL();
1628 context->last_was_blit = FALSE;
1629 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1630 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1631 break;
1633 case CTXUSAGE_DRAWPRIM:
1634 /* This needs all dirty states applied */
1635 if(context->last_was_blit) {
1636 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1639 IWineD3DDeviceImpl_FindTexUnitMap(This);
1641 for(i=0; i < context->numDirtyEntries; i++) {
1642 dirtyState = context->dirtyArray[i];
1643 idx = dirtyState >> 5;
1644 shift = dirtyState & 0x1f;
1645 context->isStateDirty[idx] &= ~(1 << shift);
1646 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1648 context->numDirtyEntries = 0; /* This makes the whole list clean */
1649 context->last_was_blit = FALSE;
1650 break;
1652 case CTXUSAGE_BLIT:
1653 SetupForBlit(This, context,
1654 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1655 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1656 break;
1658 default:
1659 FIXME("Unexpected context usage requested\n");
1663 WineD3DContext *getActiveContext(void) {
1664 return last_device->activeContext;