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
, update_magfilter
;
82 /* Update base texture states array */
83 if (SUCCEEDED(IWineD3DSurface_GetContainer(surface
, &IID_IWineD3DBaseTexture
, (void **)&texture_impl
)))
85 if (texture_impl
->baseTexture
.states
[WINED3DTEXSTA_MINFILTER
] != WINED3DTEXF_POINT
)
87 texture_impl
->baseTexture
.states
[WINED3DTEXSTA_MINFILTER
] = WINED3DTEXF_POINT
;
88 update_minfilter
= TRUE
;
91 if (texture_impl
->baseTexture
.states
[WINED3DTEXSTA_MAGFILTER
] != WINED3DTEXF_POINT
)
93 texture_impl
->baseTexture
.states
[WINED3DTEXSTA_MAGFILTER
] = WINED3DTEXF_POINT
;
94 update_magfilter
= TRUE
;
97 if (texture_impl
->baseTexture
.bindCount
)
99 WARN("Render targets should not be bound to a sampler\n");
100 IWineD3DDeviceImpl_MarkStateDirty(This
, STATE_SAMPLER(texture_impl
->baseTexture
.sampler
));
103 IWineD3DBaseTexture_Release((IWineD3DBaseTexture
*)texture_impl
);
106 if (update_minfilter
|| update_magfilter
|| force_preload
)
108 GLenum target
, bind_target
;
111 target
= surface_impl
->glDescription
.target
;
112 if (target
== GL_TEXTURE_2D
)
114 bind_target
= GL_TEXTURE_2D
;
115 glGetIntegerv(GL_TEXTURE_BINDING_2D
, &old_binding
);
116 } else if (target
== GL_TEXTURE_RECTANGLE_ARB
) {
117 bind_target
= GL_TEXTURE_RECTANGLE_ARB
;
118 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB
, &old_binding
);
120 bind_target
= GL_TEXTURE_CUBE_MAP_ARB
;
121 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB
, &old_binding
);
124 IWineD3DSurface_PreLoad(surface
);
126 glBindTexture(bind_target
, surface_impl
->glDescription
.textureName
);
127 if (update_minfilter
) glTexParameteri(bind_target
, GL_TEXTURE_MIN_FILTER
, GL_NEAREST
);
128 if (update_magfilter
) glTexParameteri(bind_target
, GL_TEXTURE_MAG_FILTER
, GL_NEAREST
);
129 glBindTexture(bind_target
, old_binding
);
132 checkGLcall("apply_attachment_filter_states()");
135 /* TODO: Handle stencil attachments */
136 void context_attach_depth_stencil_fbo(IWineD3DDeviceImpl
*This
, GLenum fbo_target
, IWineD3DSurface
*depth_stencil
, BOOL use_render_buffer
)
138 IWineD3DSurfaceImpl
*depth_stencil_impl
= (IWineD3DSurfaceImpl
*)depth_stencil
;
140 TRACE("Attach depth stencil %p\n", depth_stencil
);
144 if (use_render_buffer
&& depth_stencil_impl
->current_renderbuffer
)
146 GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target
, GL_DEPTH_ATTACHMENT_EXT
, GL_RENDERBUFFER_EXT
, depth_stencil_impl
->current_renderbuffer
->id
));
147 checkGLcall("glFramebufferRenderbufferEXT()");
149 context_apply_attachment_filter_states((IWineD3DDevice
*)This
, depth_stencil
, TRUE
);
151 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target
, GL_DEPTH_ATTACHMENT_EXT
, depth_stencil_impl
->glDescription
.target
,
152 depth_stencil_impl
->glDescription
.textureName
, depth_stencil_impl
->glDescription
.level
));
153 checkGLcall("glFramebufferTexture2DEXT()");
156 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target
, GL_DEPTH_ATTACHMENT_EXT
, GL_TEXTURE_2D
, 0, 0));
157 checkGLcall("glFramebufferTexture2DEXT()");
161 void context_attach_surface_fbo(IWineD3DDeviceImpl
*This
, GLenum fbo_target
, DWORD idx
, IWineD3DSurface
*surface
)
163 const IWineD3DSurfaceImpl
*surface_impl
= (IWineD3DSurfaceImpl
*)surface
;
165 TRACE("Attach surface %p to %u\n", surface
, idx
);
169 context_apply_attachment_filter_states((IWineD3DDevice
*)This
, surface
, TRUE
);
171 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target
, GL_COLOR_ATTACHMENT0_EXT
+ idx
, surface_impl
->glDescription
.target
,
172 surface_impl
->glDescription
.textureName
, surface_impl
->glDescription
.level
));
173 checkGLcall("glFramebufferTexture2DEXT()");
175 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target
, GL_COLOR_ATTACHMENT0_EXT
+ idx
, GL_TEXTURE_2D
, 0, 0));
176 checkGLcall("glFramebufferTexture2DEXT()");
180 static void context_check_fbo_status(IWineD3DDevice
*iface
)
182 IWineD3DDeviceImpl
*This
= (IWineD3DDeviceImpl
*)iface
;
185 status
= GL_EXTCALL(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT
));
186 if (status
== GL_FRAMEBUFFER_COMPLETE_EXT
)
188 TRACE("FBO complete\n");
190 IWineD3DSurfaceImpl
*attachment
;
192 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status
), status
);
194 /* Dump the FBO attachments */
195 for (i
= 0; i
< GL_LIMITS(buffers
); ++i
)
197 attachment
= (IWineD3DSurfaceImpl
*)This
->activeContext
->current_fbo
->render_targets
[i
];
200 FIXME("\tColor attachment %d: (%p) %s %ux%u\n", i
, attachment
, debug_d3dformat(attachment
->resource
.format
),
201 attachment
->pow2Width
, attachment
->pow2Height
);
204 attachment
= (IWineD3DSurfaceImpl
*)This
->activeContext
->current_fbo
->depth_stencil
;
207 FIXME("\tDepth attachment: (%p) %s %ux%u\n", attachment
, debug_d3dformat(attachment
->resource
.format
),
208 attachment
->pow2Width
, attachment
->pow2Height
);
213 static struct fbo_entry
*context_create_fbo_entry(IWineD3DDevice
*iface
)
215 IWineD3DDeviceImpl
*This
= (IWineD3DDeviceImpl
*)iface
;
216 struct fbo_entry
*entry
;
218 entry
= HeapAlloc(GetProcessHeap(), 0, sizeof(*entry
));
219 entry
->render_targets
= HeapAlloc(GetProcessHeap(), 0, GL_LIMITS(buffers
) * sizeof(*entry
->render_targets
));
220 memcpy(entry
->render_targets
, This
->render_targets
, GL_LIMITS(buffers
) * sizeof(*entry
->render_targets
));
221 entry
->depth_stencil
= This
->stencilBufferTarget
;
222 entry
->attached
= FALSE
;
228 void context_destroy_fbo_entry(IWineD3DDeviceImpl
*This
, struct fbo_entry
*entry
)
232 TRACE("Destroy FBO %d\n", entry
->id
);
233 context_destroy_fbo(This
, &entry
->id
);
235 list_remove(&entry
->entry
);
236 HeapFree(GetProcessHeap(), 0, entry
->render_targets
);
237 HeapFree(GetProcessHeap(), 0, entry
);
241 static struct fbo_entry
*context_find_fbo_entry(IWineD3DDevice
*iface
, WineD3DContext
*context
)
243 IWineD3DDeviceImpl
*This
= (IWineD3DDeviceImpl
*)iface
;
244 struct fbo_entry
*entry
;
246 LIST_FOR_EACH_ENTRY(entry
, &context
->fbo_list
, struct fbo_entry
, entry
)
248 if (!memcmp(entry
->render_targets
, This
->render_targets
, GL_LIMITS(buffers
) * sizeof(*entry
->render_targets
))
249 && entry
->depth_stencil
== This
->stencilBufferTarget
)
255 entry
= context_create_fbo_entry(iface
);
256 list_add_head(&context
->fbo_list
, &entry
->entry
);
260 static void context_apply_fbo_entry(IWineD3DDevice
*iface
, struct fbo_entry
*entry
)
262 IWineD3DDeviceImpl
*This
= (IWineD3DDeviceImpl
*)iface
;
265 context_bind_fbo(iface
, GL_FRAMEBUFFER_EXT
, &entry
->id
);
267 if (!entry
->attached
)
269 /* Apply render targets */
270 for (i
= 0; i
< GL_LIMITS(buffers
); ++i
)
272 IWineD3DSurface
*render_target
= This
->render_targets
[i
];
273 context_attach_surface_fbo(This
, GL_FRAMEBUFFER_EXT
, i
, render_target
);
276 /* Apply depth targets */
277 if (This
->stencilBufferTarget
) {
278 unsigned int w
= ((IWineD3DSurfaceImpl
*)This
->render_targets
[0])->pow2Width
;
279 unsigned int h
= ((IWineD3DSurfaceImpl
*)This
->render_targets
[0])->pow2Height
;
281 surface_set_compatible_renderbuffer(This
->stencilBufferTarget
, w
, h
);
283 context_attach_depth_stencil_fbo(This
, GL_FRAMEBUFFER_EXT
, This
->stencilBufferTarget
, TRUE
);
285 entry
->attached
= TRUE
;
287 for (i
= 0; i
< GL_LIMITS(buffers
); ++i
)
289 if (This
->render_targets
[i
])
290 context_apply_attachment_filter_states(iface
, This
->render_targets
[i
], FALSE
);
292 if (This
->stencilBufferTarget
)
293 context_apply_attachment_filter_states(iface
, This
->stencilBufferTarget
, FALSE
);
296 for (i
= 0; i
< GL_LIMITS(buffers
); ++i
)
298 if (This
->render_targets
[i
])
299 This
->draw_buffers
[i
] = GL_COLOR_ATTACHMENT0_EXT
+ i
;
301 This
->draw_buffers
[i
] = GL_NONE
;
305 static void context_apply_fbo_state(IWineD3DDevice
*iface
)
307 IWineD3DDeviceImpl
*This
= (IWineD3DDeviceImpl
*)iface
;
308 WineD3DContext
*context
= This
->activeContext
;
310 if (This
->render_offscreen
)
312 context
->current_fbo
= context_find_fbo_entry(iface
, context
);
313 context_apply_fbo_entry(iface
, context
->current_fbo
);
315 context
->current_fbo
= NULL
;
316 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT
, 0));
319 context_check_fbo_status(iface
);
322 /*****************************************************************************
323 * Context_MarkStateDirty
325 * Marks a state in a context dirty. Only one context, opposed to
326 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
330 * context: Context to mark the state dirty in
331 * state: State to mark dirty
332 * StateTable: Pointer to the state table in use(for state grouping)
334 *****************************************************************************/
335 static void Context_MarkStateDirty(WineD3DContext
*context
, DWORD state
, const struct StateEntry
*StateTable
) {
336 DWORD rep
= StateTable
[state
].representative
;
340 if(!rep
|| isStateDirty(context
, rep
)) return;
342 context
->dirtyArray
[context
->numDirtyEntries
++] = rep
;
345 context
->isStateDirty
[idx
] |= (1 << shift
);
348 /*****************************************************************************
351 * Adds a context to the context array. Helper function for CreateContext
353 * This method is not called in performance-critical code paths, only when a
354 * new render target or swapchain is created. Thus performance is not an issue
358 * This: Device to add the context for
359 * hdc: device context
360 * glCtx: WGL context to add
361 * pbuffer: optional pbuffer used with this context
363 *****************************************************************************/
364 static WineD3DContext
*AddContextToArray(IWineD3DDeviceImpl
*This
, HWND win_handle
, HDC hdc
, HGLRC glCtx
, HPBUFFERARB pbuffer
) {
365 WineD3DContext
**oldArray
= This
->contexts
;
368 This
->contexts
= HeapAlloc(GetProcessHeap(), 0, sizeof(*This
->contexts
) * (This
->numContexts
+ 1));
369 if(This
->contexts
== NULL
) {
370 ERR("Unable to grow the context array\n");
371 This
->contexts
= oldArray
;
375 memcpy(This
->contexts
, oldArray
, sizeof(*This
->contexts
) * This
->numContexts
);
378 This
->contexts
[This
->numContexts
] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(WineD3DContext
));
379 if(This
->contexts
[This
->numContexts
] == NULL
) {
380 ERR("Unable to allocate a new context\n");
381 HeapFree(GetProcessHeap(), 0, This
->contexts
);
382 This
->contexts
= oldArray
;
386 This
->contexts
[This
->numContexts
]->hdc
= hdc
;
387 This
->contexts
[This
->numContexts
]->glCtx
= glCtx
;
388 This
->contexts
[This
->numContexts
]->pbuffer
= pbuffer
;
389 This
->contexts
[This
->numContexts
]->win_handle
= win_handle
;
390 HeapFree(GetProcessHeap(), 0, oldArray
);
392 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
394 for(state
= 0; state
<= STATE_HIGHEST
; state
++) {
395 Context_MarkStateDirty(This
->contexts
[This
->numContexts
], state
, This
->StateTable
);
399 TRACE("Created context %p\n", This
->contexts
[This
->numContexts
- 1]);
400 return This
->contexts
[This
->numContexts
- 1];
403 /* This function takes care of WineD3D pixel format selection. */
404 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl
*This
, HDC hdc
, WINED3DFORMAT ColorFormat
, WINED3DFORMAT DepthStencilFormat
, BOOL auxBuffers
, int numSamples
, BOOL pbuffer
, BOOL findCompatible
)
406 int iPixelFormat
=0, matchtry
;
407 short redBits
, greenBits
, blueBits
, alphaBits
, colorBits
;
408 short depthBits
=0, stencilBits
=0;
415 /* First, try without alpha match buffers. MacOS supports aux buffers only
416 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
417 * Then try without aux buffers - this is the most common cause for not
418 * finding a pixel format. Also some drivers(the open source ones)
419 * only offer 32 bit ARB pixel formats. First try without an exact alpha
420 * match, then try without an exact alpha and color match.
422 { TRUE
, TRUE
, TRUE
},
423 { TRUE
, FALSE
, TRUE
},
424 { FALSE
, TRUE
, TRUE
},
425 { FALSE
, FALSE
, TRUE
},
426 { TRUE
, FALSE
, FALSE
},
427 { FALSE
, FALSE
, FALSE
},
431 int nCfgs
= This
->adapter
->nCfgs
;
432 WineD3D_PixelFormat
*cfgs
= This
->adapter
->cfgs
;
434 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
435 debug_d3dformat(ColorFormat
), debug_d3dformat(DepthStencilFormat
), auxBuffers
, numSamples
, pbuffer
, findCompatible
);
437 if(!getColorBits(ColorFormat
, &redBits
, &greenBits
, &blueBits
, &alphaBits
, &colorBits
)) {
438 ERR("Unable to get color bits for format %s (%#x)!\n", debug_d3dformat(ColorFormat
), ColorFormat
);
442 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
443 * You are able to add a depth + stencil surface at a later stage when you need it.
444 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
445 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
446 * context, need torecreate shaders, textures and other resources.
448 * The context manager already takes care of the state problem and for the other tasks code from Reset
449 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
450 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
451 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
452 * issue needs to be fixed. */
453 if(DepthStencilFormat
!= WINED3DFMT_D24S8
)
454 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
456 DepthStencilFormat
= WINED3DFMT_D24S8
;
458 if(DepthStencilFormat
) {
459 getDepthStencilBits(DepthStencilFormat
, &depthBits
, &stencilBits
);
462 for(matchtry
= 0; matchtry
< (sizeof(matches
) / sizeof(matches
[0])) && !iPixelFormat
; matchtry
++) {
463 for(i
=0; i
<nCfgs
; i
++) {
464 BOOL exactDepthMatch
= TRUE
;
465 cfgs
= &This
->adapter
->cfgs
[i
];
467 /* For now only accept RGBA formats. Perhaps some day we will
468 * allow floating point formats for pbuffers. */
469 if(cfgs
->iPixelType
!= WGL_TYPE_RGBA_ARB
)
472 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
473 if(!pbuffer
&& !(cfgs
->windowDrawable
&& cfgs
->doubleBuffer
))
476 /* We like to have aux buffers in backbuffer mode */
477 if(auxBuffers
&& !cfgs
->auxBuffers
&& matches
[matchtry
].require_aux
)
480 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
481 if(pbuffer
&& (!cfgs
->pbufferDrawable
|| cfgs
->doubleBuffer
))
484 if(matches
[matchtry
].exact_color
) {
485 if(cfgs
->redSize
!= redBits
)
487 if(cfgs
->greenSize
!= greenBits
)
489 if(cfgs
->blueSize
!= blueBits
)
492 if(cfgs
->redSize
< redBits
)
494 if(cfgs
->greenSize
< greenBits
)
496 if(cfgs
->blueSize
< blueBits
)
499 if(matches
[matchtry
].exact_alpha
) {
500 if(cfgs
->alphaSize
!= alphaBits
)
503 if(cfgs
->alphaSize
< alphaBits
)
507 /* We try to locate a format which matches our requirements exactly. In case of
508 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
509 if(cfgs
->depthSize
< depthBits
)
511 else if(cfgs
->depthSize
> depthBits
)
512 exactDepthMatch
= FALSE
;
514 /* In all cases make sure the number of stencil bits matches our requirements
515 * even when we don't need stencil because it could affect performance EXCEPT
516 * on cards which don't offer depth formats without stencil like the i915 drivers
518 if(stencilBits
!= cfgs
->stencilSize
&& !(This
->adapter
->brokenStencil
&& stencilBits
<= cfgs
->stencilSize
))
521 /* Check multisampling support */
522 if(cfgs
->numSamples
!= numSamples
)
525 /* When we have passed all the checks then we have found a format which matches our
526 * requirements. Note that we only check for a limit number of capabilities right now,
527 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
528 * can still differ in things like multisampling, stereo, SRGB and other flags.
531 /* Exit the loop as we have found a format :) */
532 if(exactDepthMatch
) {
533 iPixelFormat
= cfgs
->iPixelFormat
;
535 } else if(!iPixelFormat
) {
536 /* In the end we might end up with a format which doesn't exactly match our depth
537 * requirements. Accept the first format we found because formats with higher iPixelFormat
538 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
539 iPixelFormat
= cfgs
->iPixelFormat
;
544 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
545 if(!iPixelFormat
&& !findCompatible
) {
546 ERR("Can't find a suitable iPixelFormat\n");
548 } else if(!iPixelFormat
) {
549 PIXELFORMATDESCRIPTOR pfd
;
551 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
552 /* PixelFormat selection */
553 ZeroMemory(&pfd
, sizeof(pfd
));
554 pfd
.nSize
= sizeof(pfd
);
556 pfd
.dwFlags
= PFD_SUPPORT_OPENGL
| PFD_DOUBLEBUFFER
| PFD_DRAW_TO_WINDOW
;/*PFD_GENERIC_ACCELERATED*/
557 pfd
.iPixelType
= PFD_TYPE_RGBA
;
558 pfd
.cAlphaBits
= alphaBits
;
559 pfd
.cColorBits
= colorBits
;
560 pfd
.cDepthBits
= depthBits
;
561 pfd
.cStencilBits
= stencilBits
;
562 pfd
.iLayerType
= PFD_MAIN_PLANE
;
564 iPixelFormat
= ChoosePixelFormat(hdc
, &pfd
);
566 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
567 ERR("Can't find a suitable iPixelFormat\n");
572 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n", iPixelFormat
, debug_d3dformat(ColorFormat
), debug_d3dformat(DepthStencilFormat
));
576 /*****************************************************************************
579 * Creates a new context for a window, or a pbuffer context.
582 * This: Device to activate the context for
583 * target: Surface this context will render to
584 * win_handle: handle to the window which we are drawing to
585 * create_pbuffer: tells whether to create a pbuffer or not
586 * pPresentParameters: contains the pixelformats to use for onscreen rendering
588 *****************************************************************************/
589 WineD3DContext
*CreateContext(IWineD3DDeviceImpl
*This
, IWineD3DSurfaceImpl
*target
, HWND win_handle
, BOOL create_pbuffer
, const WINED3DPRESENT_PARAMETERS
*pPresentParms
) {
590 HDC oldDrawable
, hdc
;
591 HPBUFFERARB pbuffer
= NULL
;
592 HGLRC ctx
= NULL
, oldCtx
;
593 WineD3DContext
*ret
= NULL
;
596 TRACE("(%p): Creating a %s context for render target %p\n", This
, create_pbuffer
? "offscreen" : "onscreen", target
);
599 HDC hdc_parent
= GetDC(win_handle
);
600 int iPixelFormat
= 0;
602 IWineD3DSurface
*StencilSurface
= This
->stencilBufferTarget
;
603 WINED3DFORMAT StencilBufferFormat
= (NULL
!= StencilSurface
) ? ((IWineD3DSurfaceImpl
*) StencilSurface
)->resource
.format
: 0;
605 /* Try to find a pixel format with pbuffer support. */
606 iPixelFormat
= WineD3D_ChoosePixelFormat(This
, hdc_parent
, target
->resource
.format
, StencilBufferFormat
, FALSE
/* auxBuffers */, 0 /* numSamples */, TRUE
/* PBUFFER */, FALSE
/* findCompatible */);
608 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
610 /* For some reason we weren't able to find a format, try to find something instead of crashing.
611 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
612 iPixelFormat
= WineD3D_ChoosePixelFormat(This
, hdc_parent
, target
->resource
.format
, StencilBufferFormat
, FALSE
/* auxBuffer */, 0 /* numSamples */, TRUE
/* PBUFFER */, TRUE
/* findCompatible */);
615 /* This shouldn't happen as ChoosePixelFormat always returns something */
617 ERR("Unable to locate a pixel format for a pbuffer\n");
618 ReleaseDC(win_handle
, hdc_parent
);
622 TRACE("Creating a pBuffer drawable for the new context\n");
623 pbuffer
= GL_EXTCALL(wglCreatePbufferARB(hdc_parent
, iPixelFormat
, target
->currentDesc
.Width
, target
->currentDesc
.Height
, 0));
625 ERR("Cannot create a pbuffer\n");
626 ReleaseDC(win_handle
, hdc_parent
);
630 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
631 hdc
= GL_EXTCALL(wglGetPbufferDCARB(pbuffer
));
633 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer
);
634 GL_EXTCALL(wglDestroyPbufferARB(pbuffer
));
635 ReleaseDC(win_handle
, hdc_parent
);
638 ReleaseDC(win_handle
, hdc_parent
);
640 PIXELFORMATDESCRIPTOR pfd
;
643 WINED3DFORMAT ColorFormat
= target
->resource
.format
;
644 WINED3DFORMAT DepthStencilFormat
= 0;
645 BOOL auxBuffers
= FALSE
;
648 hdc
= GetDC(win_handle
);
650 ERR("Cannot retrieve a device context!\n");
654 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
655 if(wined3d_settings
.offscreen_rendering_mode
== ORM_BACKBUFFER
) {
658 if(target
->resource
.format
== WINED3DFMT_X4R4G4B4
)
659 ColorFormat
= WINED3DFMT_A4R4G4B4
;
660 else if(target
->resource
.format
== WINED3DFMT_X8R8G8B8
)
661 ColorFormat
= WINED3DFMT_A8R8G8B8
;
664 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
665 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
666 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
667 * a format with 8bit alpha, so request A8R8G8B8. */
668 if(ColorFormat
== WINED3DFMT_P8
)
669 ColorFormat
= WINED3DFMT_A8R8G8B8
;
671 /* Retrieve the depth stencil format from the present parameters.
672 * The choice of the proper format can give a nice performance boost
673 * in case of GPU limited programs. */
674 if(pPresentParms
->EnableAutoDepthStencil
) {
675 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms
->AutoDepthStencilFormat
));
676 DepthStencilFormat
= pPresentParms
->AutoDepthStencilFormat
;
679 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
680 if(pPresentParms
->MultiSampleType
&& (pPresentParms
->SwapEffect
== WINED3DSWAPEFFECT_DISCARD
)) {
681 if(!GL_SUPPORT(ARB_MULTISAMPLE
))
682 ERR("The program is requesting multisampling without support!\n");
684 ERR("Requesting MultiSampleType=%d\n", pPresentParms
->MultiSampleType
);
685 numSamples
= pPresentParms
->MultiSampleType
;
689 /* Try to find a pixel format which matches our requirements */
690 iPixelFormat
= WineD3D_ChoosePixelFormat(This
, hdc
, ColorFormat
, DepthStencilFormat
, auxBuffers
, numSamples
, FALSE
/* PBUFFER */, FALSE
/* findCompatible */);
692 /* Try to locate a compatible format if we weren't able to find anything */
694 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
695 iPixelFormat
= WineD3D_ChoosePixelFormat(This
, hdc
, ColorFormat
, DepthStencilFormat
, auxBuffers
, 0 /* numSamples */, FALSE
/* PBUFFER */, TRUE
/* findCompatible */ );
698 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
700 ERR("Can't find a suitable iPixelFormat\n");
704 DescribePixelFormat(hdc
, iPixelFormat
, sizeof(pfd
), &pfd
);
705 res
= SetPixelFormat(hdc
, iPixelFormat
, NULL
);
707 int oldPixelFormat
= GetPixelFormat(hdc
);
709 /* By default WGL doesn't allow pixel format adjustments but we need it here.
710 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
711 * set the pixel format multiple times. Only use it when it is really needed. */
713 if(oldPixelFormat
== iPixelFormat
) {
714 /* We don't have to do anything as the formats are the same :) */
715 } else if(oldPixelFormat
&& GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH
)) {
716 res
= GL_EXTCALL(wglSetPixelFormatWINE(hdc
, iPixelFormat
, NULL
));
719 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc
, iPixelFormat
);
722 } else if(oldPixelFormat
) {
723 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
724 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
725 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc
, oldPixelFormat
);
727 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc
, iPixelFormat
);
733 ctx
= pwglCreateContext(hdc
);
734 if(This
->numContexts
) pwglShareLists(This
->contexts
[0]->glCtx
, ctx
);
737 ERR("Failed to create a WGL context\n");
739 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer
, hdc
));
740 GL_EXTCALL(wglDestroyPbufferARB(pbuffer
));
744 ret
= AddContextToArray(This
, win_handle
, hdc
, ctx
, pbuffer
);
746 ERR("Failed to add the newly created context to the context list\n");
747 pwglDeleteContext(ctx
);
749 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer
, hdc
));
750 GL_EXTCALL(wglDestroyPbufferARB(pbuffer
));
754 ret
->surface
= (IWineD3DSurface
*) target
;
755 ret
->isPBuffer
= create_pbuffer
;
756 ret
->tid
= GetCurrentThreadId();
757 if(This
->shader_backend
->shader_dirtifyable_constants((IWineD3DDevice
*) This
)) {
758 /* Create the dirty constants array and initialize them to dirty */
759 ret
->vshader_const_dirty
= HeapAlloc(GetProcessHeap(), 0,
760 sizeof(*ret
->vshader_const_dirty
) * GL_LIMITS(vshader_constantsF
));
761 ret
->pshader_const_dirty
= HeapAlloc(GetProcessHeap(), 0,
762 sizeof(*ret
->pshader_const_dirty
) * GL_LIMITS(pshader_constantsF
));
763 memset(ret
->vshader_const_dirty
, 1,
764 sizeof(*ret
->vshader_const_dirty
) * GL_LIMITS(vshader_constantsF
));
765 memset(ret
->pshader_const_dirty
, 1,
766 sizeof(*ret
->pshader_const_dirty
) * GL_LIMITS(pshader_constantsF
));
769 TRACE("Successfully created new context %p\n", ret
);
771 list_init(&ret
->fbo_list
);
773 /* Set up the context defaults */
774 oldCtx
= pwglGetCurrentContext();
775 oldDrawable
= pwglGetCurrentDC();
776 if(oldCtx
&& oldDrawable
) {
777 /* See comment in ActivateContext context switching */
778 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, FALSE
);
780 if(pwglMakeCurrent(hdc
, ctx
) == FALSE
) {
781 ERR("Cannot activate context to set up defaults\n");
787 glGetIntegerv(GL_AUX_BUFFERS
, &ret
->aux_buffers
);
789 TRACE("Setting up the screen\n");
790 /* Clear the screen */
791 glClearColor(1.0, 0.0, 0.0, 0.0);
792 checkGLcall("glClearColor");
795 glClearStencil(0xffff);
797 checkGLcall("glClear");
799 glColor3f(1.0, 1.0, 1.0);
800 checkGLcall("glColor3f");
802 glEnable(GL_LIGHTING
);
803 checkGLcall("glEnable");
805 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER
, GL_TRUE
);
806 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
808 glTexEnvf(GL_TEXTURE_ENV
, GL_TEXTURE_ENV_MODE
, GL_COMBINE_EXT
);
809 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
811 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL
, GL_SEPARATE_SPECULAR_COLOR
);
812 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
814 glPixelStorei(GL_PACK_ALIGNMENT
, This
->surface_alignment
);
815 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
816 glPixelStorei(GL_UNPACK_ALIGNMENT
, This
->surface_alignment
);
817 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
819 if(GL_SUPPORT(APPLE_CLIENT_STORAGE
)) {
820 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
821 * and textures in DIB sections(due to the memory protection).
823 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE
, GL_TRUE
);
824 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
826 if(GL_SUPPORT(ARB_VERTEX_BLEND
)) {
827 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
828 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
829 * GL_VERTEX_BLEND_ARB isn't enabled too
831 glEnable(GL_WEIGHT_SUM_UNITY_ARB
);
832 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
834 if(GL_SUPPORT(NV_TEXTURE_SHADER2
)) {
835 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
836 * the previous texture where to source the offset from is always unit - 1.
838 for(s
= 1; s
< GL_LIMITS(textures
); s
++) {
839 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB
+ s
));
840 glTexEnvi(GL_TEXTURE_SHADER_NV
, GL_PREVIOUS_TEXTURE_INPUT_NV
, GL_TEXTURE0_ARB
+ s
- 1);
841 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
845 if(GL_SUPPORT(ARB_POINT_SPRITE
)) {
846 for(s
= 0; s
< GL_LIMITS(textures
); s
++) {
847 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB
+ s
));
848 glTexEnvi(GL_POINT_SPRITE_ARB
, GL_COORD_REPLACE_ARB
, GL_TRUE
);
849 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
854 /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
855 * but enable it for the first context we create, and reenable it on the old context
857 if(oldDrawable
&& oldCtx
) {
858 pwglMakeCurrent(oldDrawable
, oldCtx
);
862 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, TRUE
);
870 /*****************************************************************************
871 * RemoveContextFromArray
873 * Removes a context from the context manager. The opengl context is not
874 * destroyed or unset. context is not a valid pointer after that call.
876 * Similar to the former call this isn't a performance critical function. A
877 * helper function for DestroyContext.
880 * This: Device to activate the context for
881 * context: Context to remove
883 *****************************************************************************/
884 static void RemoveContextFromArray(IWineD3DDeviceImpl
*This
, WineD3DContext
*context
) {
886 WineD3DContext
**oldArray
= This
->contexts
;
888 TRACE("Removing ctx %p\n", context
);
892 if(This
->numContexts
) {
893 This
->contexts
= HeapAlloc(GetProcessHeap(), 0, sizeof(*This
->contexts
) * This
->numContexts
);
894 if(!This
->contexts
) {
895 ERR("Cannot allocate a new context array, PANIC!!!\n");
898 /* Note that we decreased numContexts a few lines up, so use '<=' instead of '<' */
899 for(s
= 0; s
<= This
->numContexts
; s
++) {
900 if(oldArray
[s
] == context
) continue;
901 This
->contexts
[t
] = oldArray
[s
];
905 This
->contexts
= NULL
;
908 HeapFree(GetProcessHeap(), 0, context
);
909 HeapFree(GetProcessHeap(), 0, oldArray
);
912 /*****************************************************************************
915 * Destroys a wineD3DContext
918 * This: Device to activate the context for
919 * context: Context to destroy
921 *****************************************************************************/
922 void DestroyContext(IWineD3DDeviceImpl
*This
, WineD3DContext
*context
) {
923 struct fbo_entry
*entry
, *entry2
;
925 TRACE("Destroying ctx %p\n", context
);
927 /* The correct GL context needs to be active to cleanup the GL resources below */
928 if(pwglGetCurrentContext() != context
->glCtx
){
929 pwglMakeCurrent(context
->hdc
, context
->glCtx
);
935 LIST_FOR_EACH_ENTRY_SAFE(entry
, entry2
, &context
->fbo_list
, struct fbo_entry
, entry
) {
936 context_destroy_fbo_entry(This
, entry
);
938 if (context
->src_fbo
) {
939 TRACE("Destroy src FBO %d\n", context
->src_fbo
);
940 context_destroy_fbo(This
, &context
->src_fbo
);
942 if (context
->dst_fbo
) {
943 TRACE("Destroy dst FBO %d\n", context
->dst_fbo
);
944 context_destroy_fbo(This
, &context
->dst_fbo
);
949 /* Cleanup the GL context */
950 pwglMakeCurrent(NULL
, NULL
);
951 if(context
->isPBuffer
) {
952 GL_EXTCALL(wglReleasePbufferDCARB(context
->pbuffer
, context
->hdc
));
953 GL_EXTCALL(wglDestroyPbufferARB(context
->pbuffer
));
954 } else ReleaseDC(context
->win_handle
, context
->hdc
);
955 pwglDeleteContext(context
->glCtx
);
957 HeapFree(GetProcessHeap(), 0, context
->vshader_const_dirty
);
958 HeapFree(GetProcessHeap(), 0, context
->pshader_const_dirty
);
959 RemoveContextFromArray(This
, context
);
962 static inline void set_blit_dimension(UINT width
, UINT height
) {
963 glMatrixMode(GL_PROJECTION
);
964 checkGLcall("glMatrixMode(GL_PROJECTION)");
966 checkGLcall("glLoadIdentity()");
967 glOrtho(0, width
, height
, 0, 0.0, -1.0);
968 checkGLcall("glOrtho");
969 glViewport(0, 0, width
, height
);
970 checkGLcall("glViewport");
973 /*****************************************************************************
976 * Sets up a context for DirectDraw blitting.
977 * All texture units are disabled, texture unit 0 is set as current unit
978 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
979 * color writing enabled for all channels
980 * register combiners disabled, shaders disabled
981 * world matrix is set to identity, texture matrix 0 too
982 * projection matrix is setup for drawing screen coordinates
985 * This: Device to activate the context for
986 * context: Context to setup
987 * width: render target width
988 * height: render target height
990 *****************************************************************************/
991 static inline void SetupForBlit(IWineD3DDeviceImpl
*This
, WineD3DContext
*context
, UINT width
, UINT height
) {
993 const struct StateEntry
*StateTable
= This
->StateTable
;
995 TRACE("Setting up context %p for blitting\n", context
);
996 if(context
->last_was_blit
) {
997 if(context
->blit_w
!= width
|| context
->blit_h
!= height
) {
998 set_blit_dimension(width
, height
);
999 context
->blit_w
= width
; context
->blit_h
= height
;
1000 /* No need to dirtify here, the states are still dirtified because they weren't
1001 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1005 TRACE("Context is already set up for blitting, nothing to do\n");
1008 context
->last_was_blit
= TRUE
;
1010 /* TODO: Use a display list */
1012 /* Disable shaders */
1013 This
->shader_backend
->shader_cleanup((IWineD3DDevice
*) This
);
1014 Context_MarkStateDirty(context
, STATE_VSHADER
, StateTable
);
1015 Context_MarkStateDirty(context
, STATE_PIXELSHADER
, StateTable
);
1017 /* Disable all textures. The caller can then bind a texture it wants to blit
1020 if (GL_SUPPORT(ARB_MULTITEXTURE
)) {
1021 /* The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1022 * function texture unit. No need to care for higher samplers
1024 for(i
= GL_LIMITS(textures
) - 1; i
> 0 ; i
--) {
1025 sampler
= This
->rev_tex_unit_map
[i
];
1026 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB
+ i
));
1027 checkGLcall("glActiveTextureARB");
1029 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP
)) {
1030 glDisable(GL_TEXTURE_CUBE_MAP_ARB
);
1031 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1033 glDisable(GL_TEXTURE_3D
);
1034 checkGLcall("glDisable GL_TEXTURE_3D");
1035 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE
)) {
1036 glDisable(GL_TEXTURE_RECTANGLE_ARB
);
1037 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1039 glDisable(GL_TEXTURE_2D
);
1040 checkGLcall("glDisable GL_TEXTURE_2D");
1042 glTexEnvi(GL_TEXTURE_ENV
, GL_TEXTURE_ENV_MODE
, GL_REPLACE
);
1043 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1045 if (sampler
!= -1) {
1046 if (sampler
< MAX_TEXTURES
) {
1047 Context_MarkStateDirty(context
, STATE_TEXTURESTAGE(sampler
, WINED3DTSS_COLOROP
), StateTable
);
1049 Context_MarkStateDirty(context
, STATE_SAMPLER(sampler
), StateTable
);
1052 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB
));
1053 checkGLcall("glActiveTextureARB");
1056 sampler
= This
->rev_tex_unit_map
[0];
1058 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP
)) {
1059 glDisable(GL_TEXTURE_CUBE_MAP_ARB
);
1060 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1062 glDisable(GL_TEXTURE_3D
);
1063 checkGLcall("glDisable GL_TEXTURE_3D");
1064 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE
)) {
1065 glDisable(GL_TEXTURE_RECTANGLE_ARB
);
1066 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1068 glDisable(GL_TEXTURE_2D
);
1069 checkGLcall("glDisable GL_TEXTURE_2D");
1071 glTexEnvi(GL_TEXTURE_ENV
, GL_TEXTURE_ENV_MODE
, GL_REPLACE
);
1073 glMatrixMode(GL_TEXTURE
);
1074 checkGLcall("glMatrixMode(GL_TEXTURE)");
1076 checkGLcall("glLoadIdentity()");
1078 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS
)) {
1079 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT
,
1080 GL_TEXTURE_LOD_BIAS_EXT
,
1082 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1085 if (sampler
!= -1) {
1086 if (sampler
< MAX_TEXTURES
) {
1087 Context_MarkStateDirty(context
, STATE_TRANSFORM(WINED3DTS_TEXTURE0
+ sampler
), StateTable
);
1088 Context_MarkStateDirty(context
, STATE_TEXTURESTAGE(sampler
, WINED3DTSS_COLOROP
), StateTable
);
1090 Context_MarkStateDirty(context
, STATE_SAMPLER(sampler
), StateTable
);
1093 /* Other misc states */
1094 glDisable(GL_ALPHA_TEST
);
1095 checkGLcall("glDisable(GL_ALPHA_TEST)");
1096 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_ALPHATESTENABLE
), StateTable
);
1097 glDisable(GL_LIGHTING
);
1098 checkGLcall("glDisable GL_LIGHTING");
1099 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_LIGHTING
), StateTable
);
1100 glDisable(GL_DEPTH_TEST
);
1101 checkGLcall("glDisable GL_DEPTH_TEST");
1102 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_ZENABLE
), StateTable
);
1104 checkGLcall("glDisable GL_FOG");
1105 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_FOGENABLE
), StateTable
);
1106 glDisable(GL_BLEND
);
1107 checkGLcall("glDisable GL_BLEND");
1108 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE
), StateTable
);
1109 glDisable(GL_CULL_FACE
);
1110 checkGLcall("glDisable GL_CULL_FACE");
1111 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_CULLMODE
), StateTable
);
1112 glDisable(GL_STENCIL_TEST
);
1113 checkGLcall("glDisable GL_STENCIL_TEST");
1114 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_STENCILENABLE
), StateTable
);
1115 glDisable(GL_SCISSOR_TEST
);
1116 checkGLcall("glDisable GL_SCISSOR_TEST");
1117 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE
), StateTable
);
1118 if(GL_SUPPORT(ARB_POINT_SPRITE
)) {
1119 glDisable(GL_POINT_SPRITE_ARB
);
1120 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1121 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE
), StateTable
);
1123 glColorMask(GL_TRUE
, GL_TRUE
,GL_TRUE
,GL_TRUE
);
1124 checkGLcall("glColorMask");
1125 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_CLIPPING
), StateTable
);
1126 if (GL_SUPPORT(EXT_SECONDARY_COLOR
)) {
1127 glDisable(GL_COLOR_SUM_EXT
);
1128 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_SPECULARENABLE
), StateTable
);
1129 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1132 /* Setup transforms */
1133 glMatrixMode(GL_MODELVIEW
);
1134 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1136 checkGLcall("glLoadIdentity()");
1137 Context_MarkStateDirty(context
, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable
);
1139 context
->last_was_rhw
= TRUE
;
1140 Context_MarkStateDirty(context
, STATE_VDECL
, StateTable
); /* because of last_was_rhw = TRUE */
1142 glDisable(GL_CLIP_PLANE0
); checkGLcall("glDisable(clip plane 0)");
1143 glDisable(GL_CLIP_PLANE1
); checkGLcall("glDisable(clip plane 1)");
1144 glDisable(GL_CLIP_PLANE2
); checkGLcall("glDisable(clip plane 2)");
1145 glDisable(GL_CLIP_PLANE3
); checkGLcall("glDisable(clip plane 3)");
1146 glDisable(GL_CLIP_PLANE4
); checkGLcall("glDisable(clip plane 4)");
1147 glDisable(GL_CLIP_PLANE5
); checkGLcall("glDisable(clip plane 5)");
1148 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_CLIPPING
), StateTable
);
1150 set_blit_dimension(width
, height
);
1151 context
->blit_w
= width
; context
->blit_h
= height
;
1152 Context_MarkStateDirty(context
, STATE_VIEWPORT
, StateTable
);
1153 Context_MarkStateDirty(context
, STATE_TRANSFORM(WINED3DTS_PROJECTION
), StateTable
);
1156 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, FALSE
);
1159 /*****************************************************************************
1160 * findThreadContextForSwapChain
1162 * Searches a swapchain for all contexts and picks one for the thread tid.
1163 * If none can be found the swapchain is requested to create a new context
1165 *****************************************************************************/
1166 static WineD3DContext
*findThreadContextForSwapChain(IWineD3DSwapChain
*swapchain
, DWORD tid
) {
1169 for(i
= 0; i
< ((IWineD3DSwapChainImpl
*) swapchain
)->num_contexts
; i
++) {
1170 if(((IWineD3DSwapChainImpl
*) swapchain
)->context
[i
]->tid
== tid
) {
1171 return ((IWineD3DSwapChainImpl
*) swapchain
)->context
[i
];
1176 /* Create a new context for the thread */
1177 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain
);
1180 /*****************************************************************************
1183 * Finds a context for the current render target and thread
1186 * target: Render target to find the context for
1187 * tid: Thread to activate the context for
1189 * Returns: The needed context
1191 *****************************************************************************/
1192 static inline WineD3DContext
*FindContext(IWineD3DDeviceImpl
*This
, IWineD3DSurface
*target
, DWORD tid
) {
1193 IWineD3DSwapChain
*swapchain
= NULL
;
1195 BOOL readTexture
= wined3d_settings
.offscreen_rendering_mode
!= ORM_FBO
&& This
->render_offscreen
;
1196 WineD3DContext
*context
= This
->activeContext
;
1197 BOOL oldRenderOffscreen
= This
->render_offscreen
;
1198 const WINED3DFORMAT oldFmt
= ((IWineD3DSurfaceImpl
*) This
->lastActiveRenderTarget
)->resource
.format
;
1199 const WINED3DFORMAT newFmt
= ((IWineD3DSurfaceImpl
*) target
)->resource
.format
;
1200 const struct StateEntry
*StateTable
= This
->StateTable
;
1202 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
1203 * the alpha blend state changes with different render target formats
1205 if(oldFmt
!= newFmt
) {
1206 const GlPixelFormatDesc
*glDesc
;
1207 const StaticPixelFormatDesc
*old
= getFormatDescEntry(oldFmt
, NULL
, NULL
);
1208 const StaticPixelFormatDesc
*new = getFormatDescEntry(newFmt
, &GLINFO_LOCATION
, &glDesc
);
1210 /* Disable blending when the alphaMask has changed and when a format doesn't support blending */
1211 if((old
->alphaMask
&& !new->alphaMask
) || (!old
->alphaMask
&& new->alphaMask
) || !(glDesc
->Flags
& WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING
)) {
1212 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE
), StateTable
);
1216 hr
= IWineD3DSurface_GetContainer(target
, &IID_IWineD3DSwapChain
, (void **) &swapchain
);
1217 if(hr
== WINED3D_OK
&& swapchain
) {
1218 TRACE("Rendering onscreen\n");
1220 context
= findThreadContextForSwapChain(swapchain
, tid
);
1222 This
->render_offscreen
= FALSE
;
1223 /* The context != This->activeContext will catch a NOP context change. This can occur
1224 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
1225 * rendering. No context change is needed in that case
1228 if(wined3d_settings
.offscreen_rendering_mode
== ORM_PBUFFER
) {
1229 if(This
->pbufferContext
&& tid
== This
->pbufferContext
->tid
) {
1230 This
->pbufferContext
->tid
= 0;
1233 IWineD3DSwapChain_Release(swapchain
);
1235 if(oldRenderOffscreen
) {
1236 Context_MarkStateDirty(context
, WINED3DTS_PROJECTION
, StateTable
);
1237 Context_MarkStateDirty(context
, STATE_VDECL
, StateTable
);
1238 Context_MarkStateDirty(context
, STATE_VIEWPORT
, StateTable
);
1239 Context_MarkStateDirty(context
, STATE_SCISSORRECT
, StateTable
);
1240 Context_MarkStateDirty(context
, STATE_FRONTFACE
, StateTable
);
1244 TRACE("Rendering offscreen\n");
1245 This
->render_offscreen
= TRUE
;
1247 switch(wined3d_settings
.offscreen_rendering_mode
) {
1249 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
1250 if(This
->activeContext
&& tid
== This
->lastThread
) {
1251 context
= This
->activeContext
;
1253 /* This may happen if the app jumps straight into offscreen rendering
1254 * Start using the context of the primary swapchain. tid == 0 is no problem
1255 * for findThreadContextForSwapChain.
1257 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1258 * is perfect to call.
1260 context
= findThreadContextForSwapChain(This
->swapchains
[0], tid
);
1266 IWineD3DSurfaceImpl
*targetimpl
= (IWineD3DSurfaceImpl
*) target
;
1267 if(This
->pbufferContext
== NULL
||
1268 This
->pbufferWidth
< targetimpl
->currentDesc
.Width
||
1269 This
->pbufferHeight
< targetimpl
->currentDesc
.Height
) {
1270 if(This
->pbufferContext
) {
1271 DestroyContext(This
, This
->pbufferContext
);
1274 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
1275 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
1277 This
->pbufferContext
= CreateContext(This
, targetimpl
,
1278 ((IWineD3DSwapChainImpl
*) This
->swapchains
[0])->context
[0]->win_handle
,
1279 TRUE
/* pbuffer */, &((IWineD3DSwapChainImpl
*)This
->swapchains
[0])->presentParms
);
1280 This
->pbufferWidth
= targetimpl
->currentDesc
.Width
;
1281 This
->pbufferHeight
= targetimpl
->currentDesc
.Height
;
1284 if(This
->pbufferContext
) {
1285 if(This
->pbufferContext
->tid
!= 0 && This
->pbufferContext
->tid
!= tid
) {
1286 FIXME("The PBuffr context is only supported for one thread for now!\n");
1288 This
->pbufferContext
->tid
= tid
;
1289 context
= This
->pbufferContext
;
1292 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
1293 wined3d_settings
.offscreen_rendering_mode
= ORM_BACKBUFFER
;
1297 case ORM_BACKBUFFER
:
1298 /* Stay with the currently active context for back buffer rendering */
1299 if(This
->activeContext
&& tid
== This
->lastThread
) {
1300 context
= This
->activeContext
;
1302 /* This may happen if the app jumps straight into offscreen rendering
1303 * Start using the context of the primary swapchain. tid == 0 is no problem
1304 * for findThreadContextForSwapChain.
1306 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1307 * is perfect to call.
1309 context
= findThreadContextForSwapChain(This
->swapchains
[0], tid
);
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 /* When switching away from an offscreen render target, and we're not using FBOs,
1324 * we have to read the drawable into the texture. This is done via PreLoad(and
1325 * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1326 * PreLoad needs a GL context, and FindContext is called before the context is activated.
1327 * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1328 * is read. This leads to these possible situations:
1330 * 0) lastActiveRenderTarget == target && oldTid == newTid:
1331 * Nothing to do, we don't even reach this code in this case...
1333 * 1) lastActiveRenderTarget != target && oldTid == newTid:
1334 * The currently active context is OK for readback. Call PreLoad, and it
1337 * 2) lastActiveRenderTarget == target && oldTid != newTid:
1338 * Nothing to do - the drawable is unchanged
1340 * 3) lastActiveRenderTarget != target && oldTid != newTid:
1341 * This is tricky. We have to get a context with the old drawable from somewhere
1342 * before we can switch to the new context. In this case, PreLoad calls
1343 * ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1344 * is case (2) then. The old drawable is activated for the new thread, and the
1345 * readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1346 * After that, the outer ActivateContext(which calls PreLoad) can activate the new
1347 * target for the new thread
1349 if (readTexture
&& This
->lastActiveRenderTarget
!= target
) {
1350 BOOL oldInDraw
= This
->isInDraw
;
1352 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1353 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1354 * when using offscreen rendering with multithreading
1356 This
->isInDraw
= TRUE
;
1358 /* Do that before switching the context:
1359 * Read the back buffer of the old drawable into the destination texture
1361 IWineD3DSurface_PreLoad(This
->lastActiveRenderTarget
);
1363 /* Assume that the drawable will be modified by some other things now */
1364 IWineD3DSurface_ModifyLocation(This
->lastActiveRenderTarget
, SFLAG_INDRAWABLE
, FALSE
);
1366 This
->isInDraw
= oldInDraw
;
1372 static void apply_draw_buffer(IWineD3DDeviceImpl
*This
, IWineD3DSurface
*target
, BOOL blit
)
1375 IWineD3DSwapChain
*swapchain
;
1377 hr
= IWineD3DSurface_GetContainer(target
, &IID_IWineD3DSwapChain
, (void **)&swapchain
);
1380 IWineD3DSwapChain_Release((IUnknown
*)swapchain
);
1381 glDrawBuffer(surface_get_gl_buffer(target
, swapchain
));
1382 checkGLcall("glDrawBuffers()");
1386 if (wined3d_settings
.offscreen_rendering_mode
== ORM_FBO
)
1390 if (GL_SUPPORT(ARB_DRAW_BUFFERS
))
1392 GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers
), This
->draw_buffers
));
1393 checkGLcall("glDrawBuffers()");
1397 glDrawBuffer(This
->draw_buffers
[0]);
1398 checkGLcall("glDrawBuffer()");
1401 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT
);
1402 checkGLcall("glDrawBuffer()");
1407 glDrawBuffer(This
->offscreenBuffer
);
1408 checkGLcall("glDrawBuffer()");
1413 /*****************************************************************************
1416 * Finds a rendering context and drawable matching the device and render
1417 * target for the current thread, activates them and puts them into the
1421 * This: Device to activate the context for
1422 * target: Requested render target
1423 * usage: Prepares the context for blitting, drawing or other actions
1425 *****************************************************************************/
1426 void ActivateContext(IWineD3DDeviceImpl
*This
, IWineD3DSurface
*target
, ContextUsage usage
) {
1427 DWORD tid
= GetCurrentThreadId();
1429 DWORD dirtyState
, idx
;
1431 WineD3DContext
*context
;
1432 const struct StateEntry
*StateTable
= This
->StateTable
;
1434 TRACE("(%p): Selecting context for render target %p, thread %d\n", This
, target
, tid
);
1435 if(This
->lastActiveRenderTarget
!= target
|| tid
!= This
->lastThread
) {
1436 context
= FindContext(This
, target
, tid
);
1437 context
->draw_buffer_dirty
= TRUE
;
1438 This
->lastActiveRenderTarget
= target
;
1439 This
->lastThread
= tid
;
1441 /* Stick to the old context */
1442 context
= This
->activeContext
;
1445 /* Activate the opengl context */
1446 if(last_device
!= This
|| context
!= This
->activeContext
) {
1449 /* Prevent an unneeded context switch as those are expensive */
1450 if(context
->glCtx
&& (context
->glCtx
== pwglGetCurrentContext())) {
1451 TRACE("Already using gl context %p\n", context
->glCtx
);
1454 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context
, context
->hdc
, context
->glCtx
);
1456 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, FALSE
);
1457 ret
= pwglMakeCurrent(context
->hdc
, context
->glCtx
);
1459 ERR("Failed to activate the new context\n");
1460 } else if(!context
->last_was_blit
) {
1461 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, TRUE
);
1464 if(This
->activeContext
->vshader_const_dirty
) {
1465 memset(This
->activeContext
->vshader_const_dirty
, 1,
1466 sizeof(*This
->activeContext
->vshader_const_dirty
) * GL_LIMITS(vshader_constantsF
));
1468 if(This
->activeContext
->pshader_const_dirty
) {
1469 memset(This
->activeContext
->pshader_const_dirty
, 1,
1470 sizeof(*This
->activeContext
->pshader_const_dirty
) * GL_LIMITS(pshader_constantsF
));
1472 This
->activeContext
= context
;
1476 /* We only need ENTER_GL for the gl calls made below and for the helper functions which make GL calls */
1480 case CTXUSAGE_CLEAR
:
1481 case CTXUSAGE_DRAWPRIM
:
1482 if (wined3d_settings
.offscreen_rendering_mode
== ORM_FBO
) {
1483 context_apply_fbo_state((IWineD3DDevice
*)This
);
1485 if (context
->draw_buffer_dirty
) {
1486 apply_draw_buffer(This
, target
, FALSE
);
1487 context
->draw_buffer_dirty
= FALSE
;
1492 if (wined3d_settings
.offscreen_rendering_mode
== ORM_FBO
) {
1493 if (This
->render_offscreen
) {
1494 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
1495 context_bind_fbo((IWineD3DDevice
*)This
, GL_FRAMEBUFFER_EXT
, &context
->dst_fbo
);
1496 context_attach_surface_fbo(This
, GL_FRAMEBUFFER_EXT
, 0, target
);
1497 GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT
, GL_DEPTH_ATTACHMENT_EXT
, GL_RENDERBUFFER_EXT
, 0));
1498 checkGLcall("glFramebufferRenderbufferEXT");
1500 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT
, 0));
1501 checkGLcall("glFramebufferRenderbufferEXT");
1503 context
->draw_buffer_dirty
= TRUE
;
1505 if (context
->draw_buffer_dirty
) {
1506 apply_draw_buffer(This
, target
, TRUE
);
1507 if (wined3d_settings
.offscreen_rendering_mode
!= ORM_FBO
) {
1508 context
->draw_buffer_dirty
= FALSE
;
1518 case CTXUSAGE_RESOURCELOAD
:
1519 /* This does not require any special states to be set up */
1522 case CTXUSAGE_CLEAR
:
1523 if(context
->last_was_blit
) {
1524 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, TRUE
);
1527 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1528 * blending when clearing improves the clearing performance incredibly.
1530 glDisable(GL_BLEND
);
1531 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE
), StateTable
);
1533 glEnable(GL_SCISSOR_TEST
);
1534 checkGLcall("glEnable GL_SCISSOR_TEST");
1535 context
->last_was_blit
= FALSE
;
1536 Context_MarkStateDirty(context
, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE
), StateTable
);
1537 Context_MarkStateDirty(context
, STATE_SCISSORRECT
, StateTable
);
1540 case CTXUSAGE_DRAWPRIM
:
1541 /* This needs all dirty states applied */
1542 if(context
->last_was_blit
) {
1543 This
->frag_pipe
->enable_extension((IWineD3DDevice
*) This
, TRUE
);
1546 IWineD3DDeviceImpl_FindTexUnitMap(This
);
1548 for(i
=0; i
< context
->numDirtyEntries
; i
++) {
1549 dirtyState
= context
->dirtyArray
[i
];
1550 idx
= dirtyState
>> 5;
1551 shift
= dirtyState
& 0x1f;
1552 context
->isStateDirty
[idx
] &= ~(1 << shift
);
1553 StateTable
[dirtyState
].apply(dirtyState
, This
->stateBlock
, context
);
1555 context
->numDirtyEntries
= 0; /* This makes the whole list clean */
1556 context
->last_was_blit
= FALSE
;
1560 SetupForBlit(This
, context
,
1561 ((IWineD3DSurfaceImpl
*)target
)->currentDesc
.Width
,
1562 ((IWineD3DSurfaceImpl
*)target
)->currentDesc
.Height
);
1566 FIXME("Unexpected context usage requested\n");