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
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
;
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
)
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
;
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
);
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
);
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()");
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()");
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
);
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()");
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
;
188 status
= GL_EXTCALL(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT
));
189 if (status
== GL_FRAMEBUFFER_COMPLETE_EXT
)
191 TRACE("FBO complete\n");
193 IWineD3DSurfaceImpl
*attachment
;
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
];
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
;
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
;
233 static void context_destroy_fbo_entry(IWineD3DDeviceImpl
*This
, struct fbo_entry
*entry
)
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
)
260 entry
= context_create_fbo_entry(iface
);
261 list_add_head(&context
->fbo_list
, &entry
->entry
);
265 static void context_apply_fbo_entry(IWineD3DDevice
*iface
, struct fbo_entry
*entry
)
267 IWineD3DDeviceImpl
*This
= (IWineD3DDeviceImpl
*)iface
;
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
;
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
;
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
);
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
;
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
;
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
);
354 if (!destroyed
&& entry
->depth_stencil
== (IWineD3DSurface
*)resource
)
355 context_destroy_fbo_entry(This
, entry
);
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
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
;
385 if(!rep
|| isStateDirty(context
, rep
)) return;
387 context
->dirtyArray
[context
->numDirtyEntries
++] = rep
;
390 context
->isStateDirty
[idx
] |= (1 << shift
);
393 /*****************************************************************************
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
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
;
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
;
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
;
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
);
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
)
454 unsigned int matchtry
;
455 short redBits
, greenBits
, blueBits
, alphaBits
, colorBits
;
456 short depthBits
=0, stencilBits
=0;
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
},
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
);
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
)
521 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
522 if(!pbuffer
&& !(cfg
->windowDrawable
&& cfg
->doubleBuffer
))
525 /* We like to have aux buffers in backbuffer mode */
526 if(auxBuffers
&& !cfg
->auxBuffers
&& matches
[matchtry
].require_aux
)
529 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
530 if(pbuffer
&& (!cfg
->pbufferDrawable
|| cfg
->doubleBuffer
))
533 if(matches
[matchtry
].exact_color
) {
534 if(cfg
->redSize
!= redBits
)
536 if(cfg
->greenSize
!= greenBits
)
538 if(cfg
->blueSize
!= blueBits
)
541 if(cfg
->redSize
< redBits
)
543 if(cfg
->greenSize
< greenBits
)
545 if(cfg
->blueSize
< blueBits
)
548 if(matches
[matchtry
].exact_alpha
) {
549 if(cfg
->alphaSize
!= alphaBits
)
552 if(cfg
->alphaSize
< alphaBits
)
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
)
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
567 if(stencilBits
!= cfg
->stencilSize
&& !(This
->adapter
->brokenStencil
&& stencilBits
<= cfg
->stencilSize
))
570 /* Check multisampling support */
571 if(cfg
->numSamples
!= numSamples
)
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
;
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");
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
);
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
);
615 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
616 ERR("Can't find a suitable iPixelFormat\n");
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
));
626 /*****************************************************************************
629 * Creates a new context for a window, or a pbuffer context.
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
;
646 TRACE("(%p): Creating a %s context for render target %p\n", This
, create_pbuffer
? "offscreen" : "onscreen", target
);
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 */);
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 */
673 ERR("Unable to locate a pixel format for a pbuffer\n");
674 ReleaseDC(win_handle
, hdc_parent
);
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));
681 ERR("Cannot create a pbuffer\n");
682 ReleaseDC(win_handle
, hdc_parent
);
686 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
687 hdc
= GL_EXTCALL(wglGetPbufferDCARB(pbuffer
));
689 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer
);
690 GL_EXTCALL(wglDestroyPbufferARB(pbuffer
));
691 ReleaseDC(win_handle
, hdc_parent
);
694 ReleaseDC(win_handle
, hdc_parent
);
696 PIXELFORMATDESCRIPTOR pfd
;
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
;
705 hdc
= GetDC(win_handle
);
707 ERR("Cannot retrieve a device context!\n");
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
) {
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");
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 */
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 */
759 ERR("Can't find a suitable iPixelFormat\n");
763 DescribePixelFormat(hdc
, iPixelFormat
, sizeof(pfd
), &pfd
);
764 res
= SetPixelFormat(hdc
, iPixelFormat
, NULL
);
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
));
778 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc
, iPixelFormat
);
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
);
786 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc
, iPixelFormat
);
792 ctx
= pwglCreateContext(hdc
);
793 if(This
->numContexts
) pwglShareLists(This
->contexts
[0]->glCtx
, ctx
);
796 ERR("Failed to create a WGL context\n");
798 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer
, hdc
));
799 GL_EXTCALL(wglDestroyPbufferARB(pbuffer
));
803 ret
= AddContextToArray(This
, win_handle
, hdc
, ctx
, pbuffer
);
805 ERR("Failed to add the newly created context to the context list\n");
806 pwglDeleteContext(ctx
);
808 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer
, hdc
));
809 GL_EXTCALL(wglDestroyPbufferARB(pbuffer
));
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");
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");
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 for(s
= 0; s
< GL_LIMITS(point_sprite_units
); s
++) {
899 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB
+ s
));
900 glTexEnvi(GL_POINT_SPRITE_ARB
, GL_COORD_REPLACE_ARB
, GL_TRUE
);
901 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
905 /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
906 * but enable it for the first context we create, and reenable it on the old context
908 if(oldDrawable
&& oldCtx
) {
909 pwglMakeCurrent(oldDrawable
, oldCtx
);
913 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, TRUE
);
921 /*****************************************************************************
922 * RemoveContextFromArray
924 * Removes a context from the context manager. The opengl context is not
925 * destroyed or unset. context is not a valid pointer after that call.
927 * Similar to the former call this isn't a performance critical function. A
928 * helper function for DestroyContext.
931 * This: Device to activate the context for
932 * context: Context to remove
934 *****************************************************************************/
935 static void RemoveContextFromArray(IWineD3DDeviceImpl
*This
, WineD3DContext
*context
) {
936 WineD3DContext
**new_array
;
940 TRACE("Removing ctx %p\n", context
);
942 for (i
= 0; i
< This
->numContexts
; ++i
)
944 if (This
->contexts
[i
] == context
)
946 HeapFree(GetProcessHeap(), 0, context
);
954 ERR("Context %p doesn't exist in context array\n", context
);
958 while (i
< This
->numContexts
- 1)
960 This
->contexts
[i
] = This
->contexts
[i
+ 1];
965 if (!This
->numContexts
)
967 HeapFree(GetProcessHeap(), 0, This
->contexts
);
968 This
->contexts
= NULL
;
972 new_array
= HeapReAlloc(GetProcessHeap(), 0, This
->contexts
, This
->numContexts
* sizeof(*This
->contexts
));
975 ERR("Failed to shrink context array. Oh well.\n");
979 This
->contexts
= new_array
;
982 /*****************************************************************************
985 * Destroys a wineD3DContext
988 * This: Device to activate the context for
989 * context: Context to destroy
991 *****************************************************************************/
992 void DestroyContext(IWineD3DDeviceImpl
*This
, WineD3DContext
*context
) {
993 struct fbo_entry
*entry
, *entry2
;
995 TRACE("Destroying ctx %p\n", context
);
997 /* The correct GL context needs to be active to cleanup the GL resources below */
998 if(pwglGetCurrentContext() != context
->glCtx
){
999 pwglMakeCurrent(context
->hdc
, context
->glCtx
);
1005 LIST_FOR_EACH_ENTRY_SAFE(entry
, entry2
, &context
->fbo_list
, struct fbo_entry
, entry
) {
1006 context_destroy_fbo_entry(This
, entry
);
1008 if (context
->src_fbo
) {
1009 TRACE("Destroy src FBO %d\n", context
->src_fbo
);
1010 context_destroy_fbo(This
, &context
->src_fbo
);
1012 if (context
->dst_fbo
) {
1013 TRACE("Destroy dst FBO %d\n", context
->dst_fbo
);
1014 context_destroy_fbo(This
, &context
->dst_fbo
);
1019 if (This
->activeContext
== context
)
1021 This
->activeContext
= NULL
;
1022 TRACE("Destroying the active context.\n");
1025 /* Cleanup the GL context */
1026 pwglMakeCurrent(NULL
, NULL
);
1027 if(context
->isPBuffer
) {
1028 GL_EXTCALL(wglReleasePbufferDCARB(context
->pbuffer
, context
->hdc
));
1029 GL_EXTCALL(wglDestroyPbufferARB(context
->pbuffer
));
1030 } else ReleaseDC(context
->win_handle
, context
->hdc
);
1031 pwglDeleteContext(context
->glCtx
);
1033 HeapFree(GetProcessHeap(), 0, context
->vshader_const_dirty
);
1034 HeapFree(GetProcessHeap(), 0, context
->pshader_const_dirty
);
1035 RemoveContextFromArray(This
, context
);
1038 static inline void set_blit_dimension(UINT width
, UINT height
) {
1039 glMatrixMode(GL_PROJECTION
);
1040 checkGLcall("glMatrixMode(GL_PROJECTION)");
1042 checkGLcall("glLoadIdentity()");
1043 glOrtho(0, width
, height
, 0, 0.0, -1.0);
1044 checkGLcall("glOrtho");
1045 glViewport(0, 0, width
, height
);
1046 checkGLcall("glViewport");
1049 /*****************************************************************************
1052 * Sets up a context for DirectDraw blitting.
1053 * All texture units are disabled, texture unit 0 is set as current unit
1054 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1055 * color writing enabled for all channels
1056 * register combiners disabled, shaders disabled
1057 * world matrix is set to identity, texture matrix 0 too
1058 * projection matrix is setup for drawing screen coordinates
1061 * This: Device to activate the context for
1062 * context: Context to setup
1063 * width: render target width
1064 * height: render target height
1066 *****************************************************************************/
1067 static inline void SetupForBlit(IWineD3DDeviceImpl
*This
, WineD3DContext
*context
, UINT width
, UINT height
) {
1069 const struct StateEntry
*StateTable
= This
->StateTable
;
1071 TRACE("Setting up context %p for blitting\n", context
);
1072 if(context
->last_was_blit
) {
1073 if(context
->blit_w
!= width
|| context
->blit_h
!= height
) {
1074 set_blit_dimension(width
, height
);
1075 context
->blit_w
= width
; context
->blit_h
= height
;
1076 /* No need to dirtify here, the states are still dirtified because they weren't
1077 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1081 TRACE("Context is already set up for blitting, nothing to do\n");
1084 context
->last_was_blit
= TRUE
;
1086 /* TODO: Use a display list */
1088 /* Disable shaders */
1089 This
->shader_backend
->shader_select((IWineD3DDevice
*)This
, FALSE
, FALSE
);
1090 Context_MarkStateDirty(context
, STATE_VSHADER
, StateTable
);
1091 Context_MarkStateDirty(context
, STATE_PIXELSHADER
, StateTable
);
1093 /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1094 * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1095 * which can safely be called from here, we only lock once instead locking/unlocking
1096 * after each GL call.
1100 /* Disable all textures. The caller can then bind a texture it wants to blit
1103 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1104 * function texture unit. No need to care for higher samplers
1106 for(i
= GL_LIMITS(textures
) - 1; i
> 0 ; i
--) {
1107 sampler
= This
->rev_tex_unit_map
[i
];
1108 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB
+ i
));
1109 checkGLcall("glActiveTextureARB");
1111 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP
)) {
1112 glDisable(GL_TEXTURE_CUBE_MAP_ARB
);
1113 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1115 glDisable(GL_TEXTURE_3D
);
1116 checkGLcall("glDisable GL_TEXTURE_3D");
1117 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE
)) {
1118 glDisable(GL_TEXTURE_RECTANGLE_ARB
);
1119 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1121 glDisable(GL_TEXTURE_2D
);
1122 checkGLcall("glDisable GL_TEXTURE_2D");
1124 glTexEnvi(GL_TEXTURE_ENV
, GL_TEXTURE_ENV_MODE
, GL_REPLACE
);
1125 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1127 if (sampler
!= -1) {
1128 if (sampler
< MAX_TEXTURES
) {
1129 Context_MarkStateDirty(context
, STATE_TEXTURESTAGE(sampler
, WINED3DTSS_COLOROP
), StateTable
);
1131 Context_MarkStateDirty(context
, STATE_SAMPLER(sampler
), StateTable
);
1134 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB
));
1135 checkGLcall("glActiveTextureARB");
1137 sampler
= This
->rev_tex_unit_map
[0];
1139 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP
)) {
1140 glDisable(GL_TEXTURE_CUBE_MAP_ARB
);
1141 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1143 glDisable(GL_TEXTURE_3D
);
1144 checkGLcall("glDisable GL_TEXTURE_3D");
1145 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE
)) {
1146 glDisable(GL_TEXTURE_RECTANGLE_ARB
);
1147 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1149 glDisable(GL_TEXTURE_2D
);
1150 checkGLcall("glDisable GL_TEXTURE_2D");
1152 glTexEnvi(GL_TEXTURE_ENV
, GL_TEXTURE_ENV_MODE
, GL_REPLACE
);
1154 glMatrixMode(GL_TEXTURE
);
1155 checkGLcall("glMatrixMode(GL_TEXTURE)");
1157 checkGLcall("glLoadIdentity()");
1159 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS
)) {
1160 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT
,
1161 GL_TEXTURE_LOD_BIAS_EXT
,
1163 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1166 if (sampler
!= -1) {
1167 if (sampler
< MAX_TEXTURES
) {
1168 Context_MarkStateDirty(context
, STATE_TRANSFORM(WINED3DTS_TEXTURE0
+ sampler
), StateTable
);
1169 Context_MarkStateDirty(context
, STATE_TEXTURESTAGE(sampler
, WINED3DTSS_COLOROP
), StateTable
);
1171 Context_MarkStateDirty(context
, STATE_SAMPLER(sampler
), StateTable
);
1174 /* Other misc states */
1175 glDisable(GL_ALPHA_TEST
);
1176 checkGLcall("glDisable(GL_ALPHA_TEST)");
1177 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_ALPHATESTENABLE
), StateTable
);
1178 glDisable(GL_LIGHTING
);
1179 checkGLcall("glDisable GL_LIGHTING");
1180 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_LIGHTING
), StateTable
);
1181 glDisable(GL_DEPTH_TEST
);
1182 checkGLcall("glDisable GL_DEPTH_TEST");
1183 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_ZENABLE
), StateTable
);
1184 glDisableWINE(GL_FOG
);
1185 checkGLcall("glDisable GL_FOG");
1186 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_FOGENABLE
), StateTable
);
1187 glDisable(GL_BLEND
);
1188 checkGLcall("glDisable GL_BLEND");
1189 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE
), StateTable
);
1190 glDisable(GL_CULL_FACE
);
1191 checkGLcall("glDisable GL_CULL_FACE");
1192 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_CULLMODE
), StateTable
);
1193 glDisable(GL_STENCIL_TEST
);
1194 checkGLcall("glDisable GL_STENCIL_TEST");
1195 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_STENCILENABLE
), StateTable
);
1196 glDisable(GL_SCISSOR_TEST
);
1197 checkGLcall("glDisable GL_SCISSOR_TEST");
1198 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE
), StateTable
);
1199 if(GL_SUPPORT(ARB_POINT_SPRITE
)) {
1200 glDisable(GL_POINT_SPRITE_ARB
);
1201 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1202 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE
), StateTable
);
1204 glColorMask(GL_TRUE
, GL_TRUE
,GL_TRUE
,GL_TRUE
);
1205 checkGLcall("glColorMask");
1206 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_CLIPPING
), StateTable
);
1207 if (GL_SUPPORT(EXT_SECONDARY_COLOR
)) {
1208 glDisable(GL_COLOR_SUM_EXT
);
1209 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_SPECULARENABLE
), StateTable
);
1210 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1213 /* Setup transforms */
1214 glMatrixMode(GL_MODELVIEW
);
1215 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1217 checkGLcall("glLoadIdentity()");
1218 Context_MarkStateDirty(context
, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable
);
1220 context
->last_was_rhw
= TRUE
;
1221 Context_MarkStateDirty(context
, STATE_VDECL
, StateTable
); /* because of last_was_rhw = TRUE */
1223 glDisable(GL_CLIP_PLANE0
); checkGLcall("glDisable(clip plane 0)");
1224 glDisable(GL_CLIP_PLANE1
); checkGLcall("glDisable(clip plane 1)");
1225 glDisable(GL_CLIP_PLANE2
); checkGLcall("glDisable(clip plane 2)");
1226 glDisable(GL_CLIP_PLANE3
); checkGLcall("glDisable(clip plane 3)");
1227 glDisable(GL_CLIP_PLANE4
); checkGLcall("glDisable(clip plane 4)");
1228 glDisable(GL_CLIP_PLANE5
); checkGLcall("glDisable(clip plane 5)");
1229 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_CLIPPING
), StateTable
);
1232 set_blit_dimension(width
, height
);
1233 context
->blit_w
= width
; context
->blit_h
= height
;
1234 Context_MarkStateDirty(context
, STATE_VIEWPORT
, StateTable
);
1235 Context_MarkStateDirty(context
, STATE_TRANSFORM(WINED3DTS_PROJECTION
), StateTable
);
1238 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, FALSE
);
1241 /*****************************************************************************
1242 * findThreadContextForSwapChain
1244 * Searches a swapchain for all contexts and picks one for the thread tid.
1245 * If none can be found the swapchain is requested to create a new context
1247 *****************************************************************************/
1248 static WineD3DContext
*findThreadContextForSwapChain(IWineD3DSwapChain
*swapchain
, DWORD tid
) {
1251 for(i
= 0; i
< ((IWineD3DSwapChainImpl
*) swapchain
)->num_contexts
; i
++) {
1252 if(((IWineD3DSwapChainImpl
*) swapchain
)->context
[i
]->tid
== tid
) {
1253 return ((IWineD3DSwapChainImpl
*) swapchain
)->context
[i
];
1258 /* Create a new context for the thread */
1259 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain
);
1262 /*****************************************************************************
1265 * Finds a context for the current render target and thread
1268 * target: Render target to find the context for
1269 * tid: Thread to activate the context for
1271 * Returns: The needed context
1273 *****************************************************************************/
1274 static inline WineD3DContext
*FindContext(IWineD3DDeviceImpl
*This
, IWineD3DSurface
*target
, DWORD tid
) {
1275 IWineD3DSwapChain
*swapchain
= NULL
;
1276 BOOL readTexture
= wined3d_settings
.offscreen_rendering_mode
!= ORM_FBO
&& This
->render_offscreen
;
1277 WineD3DContext
*context
= This
->activeContext
;
1278 BOOL oldRenderOffscreen
= This
->render_offscreen
;
1279 const struct GlPixelFormatDesc
*old
= ((IWineD3DSurfaceImpl
*)This
->lastActiveRenderTarget
)->resource
.format_desc
;
1280 const struct GlPixelFormatDesc
*new = ((IWineD3DSurfaceImpl
*)target
)->resource
.format_desc
;
1281 const struct StateEntry
*StateTable
= This
->StateTable
;
1283 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
1284 * the alpha blend state changes with different render target formats
1286 if (old
->format
!= new->format
)
1288 /* Disable blending when the alpha mask has changed and when a format doesn't support blending */
1289 if ((old
->alpha_mask
&& !new->alpha_mask
) || (!old
->alpha_mask
&& new->alpha_mask
)
1290 || !(new->Flags
& WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING
))
1292 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE
), StateTable
);
1296 if (SUCCEEDED(IWineD3DSurface_GetContainer(target
, &IID_IWineD3DSwapChain
, (void **)&swapchain
))) {
1297 TRACE("Rendering onscreen\n");
1299 context
= findThreadContextForSwapChain(swapchain
, tid
);
1301 This
->render_offscreen
= FALSE
;
1302 /* The context != This->activeContext will catch a NOP context change. This can occur
1303 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
1304 * rendering. No context change is needed in that case
1307 if(wined3d_settings
.offscreen_rendering_mode
== ORM_PBUFFER
) {
1308 if(This
->pbufferContext
&& tid
== This
->pbufferContext
->tid
) {
1309 This
->pbufferContext
->tid
= 0;
1312 IWineD3DSwapChain_Release(swapchain
);
1314 if(oldRenderOffscreen
) {
1315 Context_MarkStateDirty(context
, WINED3DTS_PROJECTION
, StateTable
);
1316 Context_MarkStateDirty(context
, STATE_VDECL
, StateTable
);
1317 Context_MarkStateDirty(context
, STATE_VIEWPORT
, StateTable
);
1318 Context_MarkStateDirty(context
, STATE_SCISSORRECT
, StateTable
);
1319 Context_MarkStateDirty(context
, STATE_FRONTFACE
, StateTable
);
1323 TRACE("Rendering offscreen\n");
1324 This
->render_offscreen
= TRUE
;
1326 switch(wined3d_settings
.offscreen_rendering_mode
) {
1328 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
1329 if(This
->activeContext
&& tid
== This
->lastThread
) {
1330 context
= This
->activeContext
;
1332 /* This may happen if the app jumps straight into offscreen rendering
1333 * Start using the context of the primary swapchain. tid == 0 is no problem
1334 * for findThreadContextForSwapChain.
1336 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1337 * is perfect to call.
1339 context
= findThreadContextForSwapChain(This
->swapchains
[0], tid
);
1345 IWineD3DSurfaceImpl
*targetimpl
= (IWineD3DSurfaceImpl
*) target
;
1346 if(This
->pbufferContext
== NULL
||
1347 This
->pbufferWidth
< targetimpl
->currentDesc
.Width
||
1348 This
->pbufferHeight
< targetimpl
->currentDesc
.Height
) {
1349 if(This
->pbufferContext
) {
1350 DestroyContext(This
, This
->pbufferContext
);
1353 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
1354 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
1356 This
->pbufferContext
= CreateContext(This
, targetimpl
,
1357 ((IWineD3DSwapChainImpl
*) This
->swapchains
[0])->context
[0]->win_handle
,
1358 TRUE
/* pbuffer */, &((IWineD3DSwapChainImpl
*)This
->swapchains
[0])->presentParms
);
1359 This
->pbufferWidth
= targetimpl
->currentDesc
.Width
;
1360 This
->pbufferHeight
= targetimpl
->currentDesc
.Height
;
1363 if(This
->pbufferContext
) {
1364 if(This
->pbufferContext
->tid
!= 0 && This
->pbufferContext
->tid
!= tid
) {
1365 FIXME("The PBuffr context is only supported for one thread for now!\n");
1367 This
->pbufferContext
->tid
= tid
;
1368 context
= This
->pbufferContext
;
1371 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
1372 wined3d_settings
.offscreen_rendering_mode
= ORM_BACKBUFFER
;
1376 case ORM_BACKBUFFER
:
1377 /* Stay with the currently active context for back buffer rendering */
1378 if(This
->activeContext
&& tid
== This
->lastThread
) {
1379 context
= This
->activeContext
;
1381 /* This may happen if the app jumps straight into offscreen rendering
1382 * Start using the context of the primary swapchain. tid == 0 is no problem
1383 * for findThreadContextForSwapChain.
1385 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1386 * is perfect to call.
1388 context
= findThreadContextForSwapChain(This
->swapchains
[0], tid
);
1393 if(!oldRenderOffscreen
) {
1394 Context_MarkStateDirty(context
, WINED3DTS_PROJECTION
, StateTable
);
1395 Context_MarkStateDirty(context
, STATE_VDECL
, StateTable
);
1396 Context_MarkStateDirty(context
, STATE_VIEWPORT
, StateTable
);
1397 Context_MarkStateDirty(context
, STATE_SCISSORRECT
, StateTable
);
1398 Context_MarkStateDirty(context
, STATE_FRONTFACE
, StateTable
);
1402 /* When switching away from an offscreen render target, and we're not using FBOs,
1403 * we have to read the drawable into the texture. This is done via PreLoad(and
1404 * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1405 * PreLoad needs a GL context, and FindContext is called before the context is activated.
1406 * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1407 * is read. This leads to these possible situations:
1409 * 0) lastActiveRenderTarget == target && oldTid == newTid:
1410 * Nothing to do, we don't even reach this code in this case...
1412 * 1) lastActiveRenderTarget != target && oldTid == newTid:
1413 * The currently active context is OK for readback. Call PreLoad, and it
1416 * 2) lastActiveRenderTarget == target && oldTid != newTid:
1417 * Nothing to do - the drawable is unchanged
1419 * 3) lastActiveRenderTarget != target && oldTid != newTid:
1420 * This is tricky. We have to get a context with the old drawable from somewhere
1421 * before we can switch to the new context. In this case, PreLoad calls
1422 * ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1423 * is case (2) then. The old drawable is activated for the new thread, and the
1424 * readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1425 * After that, the outer ActivateContext(which calls PreLoad) can activate the new
1426 * target for the new thread
1428 if (readTexture
&& This
->lastActiveRenderTarget
!= target
) {
1429 BOOL oldInDraw
= This
->isInDraw
;
1431 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1432 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1433 * when using offscreen rendering with multithreading
1435 This
->isInDraw
= TRUE
;
1437 /* Do that before switching the context:
1438 * Read the back buffer of the old drawable into the destination texture
1440 if(((IWineD3DSurfaceImpl
*)This
->lastActiveRenderTarget
)->glDescription
.srgbTextureName
) {
1441 surface_internal_preload(This
->lastActiveRenderTarget
, SRGB_BOTH
);
1443 surface_internal_preload(This
->lastActiveRenderTarget
, SRGB_RGB
);
1446 /* Assume that the drawable will be modified by some other things now */
1447 IWineD3DSurface_ModifyLocation(This
->lastActiveRenderTarget
, SFLAG_INDRAWABLE
, FALSE
);
1449 This
->isInDraw
= oldInDraw
;
1455 static void apply_draw_buffer(IWineD3DDeviceImpl
*This
, IWineD3DSurface
*target
, BOOL blit
)
1457 IWineD3DSwapChain
*swapchain
;
1459 if (SUCCEEDED(IWineD3DSurface_GetContainer(target
, &IID_IWineD3DSwapChain
, (void **)&swapchain
)))
1461 IWineD3DSwapChain_Release((IUnknown
*)swapchain
);
1463 glDrawBuffer(surface_get_gl_buffer(target
, swapchain
));
1464 checkGLcall("glDrawBuffers()");
1470 if (wined3d_settings
.offscreen_rendering_mode
== ORM_FBO
)
1474 if (GL_SUPPORT(ARB_DRAW_BUFFERS
))
1476 GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers
), This
->draw_buffers
));
1477 checkGLcall("glDrawBuffers()");
1481 glDrawBuffer(This
->draw_buffers
[0]);
1482 checkGLcall("glDrawBuffer()");
1485 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT
);
1486 checkGLcall("glDrawBuffer()");
1491 glDrawBuffer(This
->offscreenBuffer
);
1492 checkGLcall("glDrawBuffer()");
1498 /*****************************************************************************
1501 * Finds a rendering context and drawable matching the device and render
1502 * target for the current thread, activates them and puts them into the
1506 * This: Device to activate the context for
1507 * target: Requested render target
1508 * usage: Prepares the context for blitting, drawing or other actions
1510 *****************************************************************************/
1511 void ActivateContext(IWineD3DDeviceImpl
*This
, IWineD3DSurface
*target
, ContextUsage usage
) {
1512 DWORD tid
= GetCurrentThreadId();
1513 DWORD i
, dirtyState
, idx
;
1515 WineD3DContext
*context
;
1516 const struct StateEntry
*StateTable
= This
->StateTable
;
1518 TRACE("(%p): Selecting context for render target %p, thread %d\n", This
, target
, tid
);
1519 if(This
->lastActiveRenderTarget
!= target
|| tid
!= This
->lastThread
) {
1520 context
= FindContext(This
, target
, tid
);
1521 context
->draw_buffer_dirty
= TRUE
;
1522 This
->lastActiveRenderTarget
= target
;
1523 This
->lastThread
= tid
;
1525 /* Stick to the old context */
1526 context
= This
->activeContext
;
1529 /* Activate the opengl context */
1530 if(last_device
!= This
|| context
!= This
->activeContext
) {
1533 /* Prevent an unneeded context switch as those are expensive */
1534 if(context
->glCtx
&& (context
->glCtx
== pwglGetCurrentContext())) {
1535 TRACE("Already using gl context %p\n", context
->glCtx
);
1538 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context
, context
->hdc
, context
->glCtx
);
1540 ret
= pwglMakeCurrent(context
->hdc
, context
->glCtx
);
1542 ERR("Failed to activate the new context\n");
1543 } else if(!context
->last_was_blit
) {
1544 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, TRUE
);
1546 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, FALSE
);
1549 if(This
->activeContext
->vshader_const_dirty
) {
1550 memset(This
->activeContext
->vshader_const_dirty
, 1,
1551 sizeof(*This
->activeContext
->vshader_const_dirty
) * GL_LIMITS(vshader_constantsF
));
1553 if(This
->activeContext
->pshader_const_dirty
) {
1554 memset(This
->activeContext
->pshader_const_dirty
, 1,
1555 sizeof(*This
->activeContext
->pshader_const_dirty
) * GL_LIMITS(pshader_constantsF
));
1557 This
->activeContext
= context
;
1562 case CTXUSAGE_CLEAR
:
1563 case CTXUSAGE_DRAWPRIM
:
1564 if (wined3d_settings
.offscreen_rendering_mode
== ORM_FBO
) {
1565 context_apply_fbo_state((IWineD3DDevice
*)This
);
1567 if (context
->draw_buffer_dirty
) {
1568 apply_draw_buffer(This
, target
, FALSE
);
1569 context
->draw_buffer_dirty
= FALSE
;
1574 if (wined3d_settings
.offscreen_rendering_mode
== ORM_FBO
) {
1575 if (This
->render_offscreen
) {
1576 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
1577 context_bind_fbo((IWineD3DDevice
*)This
, GL_FRAMEBUFFER_EXT
, &context
->dst_fbo
);
1578 context_attach_surface_fbo(This
, GL_FRAMEBUFFER_EXT
, 0, target
);
1581 GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT
, GL_DEPTH_ATTACHMENT_EXT
, GL_RENDERBUFFER_EXT
, 0));
1582 checkGLcall("glFramebufferRenderbufferEXT");
1586 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT
, 0));
1587 checkGLcall("glFramebufferRenderbufferEXT");
1590 context
->draw_buffer_dirty
= TRUE
;
1592 if (context
->draw_buffer_dirty
) {
1593 apply_draw_buffer(This
, target
, TRUE
);
1594 if (wined3d_settings
.offscreen_rendering_mode
!= ORM_FBO
) {
1595 context
->draw_buffer_dirty
= FALSE
;
1605 case CTXUSAGE_RESOURCELOAD
:
1606 /* This does not require any special states to be set up */
1609 case CTXUSAGE_CLEAR
:
1610 if(context
->last_was_blit
) {
1611 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, TRUE
);
1614 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1615 * blending when clearing improves the clearing performance incredibly.
1618 glDisable(GL_BLEND
);
1620 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE
), StateTable
);
1623 glEnable(GL_SCISSOR_TEST
);
1624 checkGLcall("glEnable GL_SCISSOR_TEST");
1626 context
->last_was_blit
= FALSE
;
1627 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE
), StateTable
);
1628 Context_MarkStateDirty(context
, STATE_SCISSORRECT
, StateTable
);
1631 case CTXUSAGE_DRAWPRIM
:
1632 /* This needs all dirty states applied */
1633 if(context
->last_was_blit
) {
1634 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, TRUE
);
1637 IWineD3DDeviceImpl_FindTexUnitMap(This
);
1639 for(i
=0; i
< context
->numDirtyEntries
; i
++) {
1640 dirtyState
= context
->dirtyArray
[i
];
1641 idx
= dirtyState
>> 5;
1642 shift
= dirtyState
& 0x1f;
1643 context
->isStateDirty
[idx
] &= ~(1 << shift
);
1644 StateTable
[dirtyState
].apply(dirtyState
, This
->stateBlock
, context
);
1646 context
->numDirtyEntries
= 0; /* This makes the whole list clean */
1647 context
->last_was_blit
= FALSE
;
1651 SetupForBlit(This
, context
,
1652 ((IWineD3DSurfaceImpl
*)target
)->currentDesc
.Width
,
1653 ((IWineD3DSurfaceImpl
*)target
)->currentDesc
.Height
);
1657 FIXME("Unexpected context usage requested\n");
1661 WineD3DContext
*getActiveContext(void) {
1662 return last_device
->activeContext
;