2 * Copyright 2002 Lionel Ulmer
3 * Copyright 2002-2005 Jason Edmeades
4 * Copyright 2003-2004 Raphael Junqueira
5 * Copyright 2004 Christian Costa
6 * Copyright 2005 Oliver Stieber
7 * Copyright 2006-2008 Stefan Dösinger for CodeWeavers
8 * Copyright 2006-2008 Henri Verbeet
9 * Copyright 2007 Andrew Riedi
10 * Copyright 2009-2011 Henri Verbeet for CodeWeavers
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
32 #include "wined3d_private.h"
34 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
36 /* Define the default light parameters as specified by MSDN. */
37 const struct wined3d_light WINED3D_default_light =
39 WINED3DLIGHT_DIRECTIONAL, /* Type */
40 { 1.0f, 1.0f, 1.0f, 0.0f }, /* Diffuse r,g,b,a */
41 { 0.0f, 0.0f, 0.0f, 0.0f }, /* Specular r,g,b,a */
42 { 0.0f, 0.0f, 0.0f, 0.0f }, /* Ambient r,g,b,a, */
43 { 0.0f, 0.0f, 0.0f }, /* Position x,y,z */
44 { 0.0f, 0.0f, 1.0f }, /* Direction x,y,z */
47 0.0f, 0.0f, 0.0f, /* Attenuation 0,1,2 */
52 /**********************************************************
53 * Global variable / Constants follow
54 **********************************************************/
55 const float identity[] =
57 1.0f, 0.0f, 0.0f, 0.0f,
58 0.0f, 1.0f, 0.0f, 0.0f,
59 0.0f, 0.0f, 1.0f, 0.0f,
60 0.0f, 0.0f, 0.0f, 1.0f,
61 }; /* When needed for comparisons */
63 /* Note that except for WINED3DPT_POINTLIST and WINED3DPT_LINELIST these
64 * actually have the same values in GL and D3D. */
65 static GLenum gl_primitive_type_from_d3d(WINED3DPRIMITIVETYPE primitive_type)
67 switch(primitive_type)
69 case WINED3DPT_POINTLIST:
72 case WINED3DPT_LINELIST:
75 case WINED3DPT_LINESTRIP:
78 case WINED3DPT_TRIANGLELIST:
81 case WINED3DPT_TRIANGLESTRIP:
82 return GL_TRIANGLE_STRIP;
84 case WINED3DPT_TRIANGLEFAN:
85 return GL_TRIANGLE_FAN;
87 case WINED3DPT_LINELIST_ADJ:
88 return GL_LINES_ADJACENCY_ARB;
90 case WINED3DPT_LINESTRIP_ADJ:
91 return GL_LINE_STRIP_ADJACENCY_ARB;
93 case WINED3DPT_TRIANGLELIST_ADJ:
94 return GL_TRIANGLES_ADJACENCY_ARB;
96 case WINED3DPT_TRIANGLESTRIP_ADJ:
97 return GL_TRIANGLE_STRIP_ADJACENCY_ARB;
100 FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
105 static WINED3DPRIMITIVETYPE d3d_primitive_type_from_gl(GLenum primitive_type)
107 switch(primitive_type)
110 return WINED3DPT_POINTLIST;
113 return WINED3DPT_LINELIST;
116 return WINED3DPT_LINESTRIP;
119 return WINED3DPT_TRIANGLELIST;
121 case GL_TRIANGLE_STRIP:
122 return WINED3DPT_TRIANGLESTRIP;
124 case GL_TRIANGLE_FAN:
125 return WINED3DPT_TRIANGLEFAN;
127 case GL_LINES_ADJACENCY_ARB:
128 return WINED3DPT_LINELIST_ADJ;
130 case GL_LINE_STRIP_ADJACENCY_ARB:
131 return WINED3DPT_LINESTRIP_ADJ;
133 case GL_TRIANGLES_ADJACENCY_ARB:
134 return WINED3DPT_TRIANGLELIST_ADJ;
136 case GL_TRIANGLE_STRIP_ADJACENCY_ARB:
137 return WINED3DPT_TRIANGLESTRIP_ADJ;
140 FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
141 return WINED3DPT_UNDEFINED;
145 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
147 if ((usage == WINED3DDECLUSAGE_POSITION || usage == WINED3DDECLUSAGE_POSITIONT) && !usage_idx)
148 *regnum = WINED3D_FFP_POSITION;
149 else if (usage == WINED3DDECLUSAGE_BLENDWEIGHT && !usage_idx)
150 *regnum = WINED3D_FFP_BLENDWEIGHT;
151 else if (usage == WINED3DDECLUSAGE_BLENDINDICES && !usage_idx)
152 *regnum = WINED3D_FFP_BLENDINDICES;
153 else if (usage == WINED3DDECLUSAGE_NORMAL && !usage_idx)
154 *regnum = WINED3D_FFP_NORMAL;
155 else if (usage == WINED3DDECLUSAGE_PSIZE && !usage_idx)
156 *regnum = WINED3D_FFP_PSIZE;
157 else if (usage == WINED3DDECLUSAGE_COLOR && !usage_idx)
158 *regnum = WINED3D_FFP_DIFFUSE;
159 else if (usage == WINED3DDECLUSAGE_COLOR && usage_idx == 1)
160 *regnum = WINED3D_FFP_SPECULAR;
161 else if (usage == WINED3DDECLUSAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
162 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
165 FIXME("Unsupported input stream [usage=%s, usage_idx=%u]\n", debug_d3ddeclusage(usage), usage_idx);
173 /* Context activation is done by the caller. */
174 void device_stream_info_from_declaration(struct wined3d_device *device,
175 struct wined3d_stream_info *stream_info, BOOL *fixup)
177 const struct wined3d_state *state = &device->stateBlock->state;
178 /* We need to deal with frequency data! */
179 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
183 stream_info->use_map = 0;
184 stream_info->swizzle_map = 0;
186 /* Check for transformed vertices, disable vertex shader if present. */
187 stream_info->position_transformed = declaration->position_transformed;
188 use_vshader = state->vertex_shader && !declaration->position_transformed;
190 /* Translate the declaration into strided data. */
191 for (i = 0; i < declaration->element_count; ++i)
193 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
194 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
195 struct wined3d_buffer *buffer = stream->buffer;
196 struct wined3d_bo_address data;
201 TRACE("%p Element %p (%u of %u)\n", declaration->elements,
202 element, i + 1, declaration->element_count);
204 if (!buffer) continue;
206 data.buffer_object = 0;
209 stride = stream->stride;
210 if (state->user_stream)
212 TRACE("Stream %u is UP, %p\n", element->input_slot, buffer);
213 data.buffer_object = 0;
214 data.addr = (BYTE *)buffer;
218 TRACE("Stream %u isn't UP, %p\n", element->input_slot, buffer);
219 buffer_get_memory(buffer, &device->adapter->gl_info, &data);
221 /* Can't use vbo's if the base vertex index is negative. OpenGL doesn't accept negative offsets
222 * (or rather offsets bigger than the vbo, because the pointer is unsigned), so use system memory
223 * sources. In most sane cases the pointer - offset will still be > 0, otherwise it will wrap
224 * around to some big value. Hope that with the indices, the driver wraps it back internally. If
225 * not, drawStridedSlow is needed, including a vertex buffer path. */
226 if (state->load_base_vertex_index < 0)
228 WARN("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
229 state->load_base_vertex_index);
230 data.buffer_object = 0;
231 data.addr = buffer_get_sysmem(buffer, &device->adapter->gl_info);
232 if ((UINT_PTR)data.addr < -state->load_base_vertex_index * stride)
234 FIXME("System memory vertex data load offset is negative!\n");
240 if (data.buffer_object)
242 else if (*fixup && !use_vshader
243 && (element->usage == WINED3DDECLUSAGE_COLOR
244 || element->usage == WINED3DDECLUSAGE_POSITIONT))
246 static BOOL warned = FALSE;
249 /* This may be bad with the fixed function pipeline. */
250 FIXME("Missing vbo streams with unfixed colors or transformed position, expect problems\n");
256 data.addr += element->offset;
258 TRACE("offset %u input_slot %u usage_idx %d\n", element->offset, element->input_slot, element->usage_idx);
262 if (element->output_slot == ~0U)
264 /* TODO: Assuming vertexdeclarations are usually used with the
265 * same or a similar shader, it might be worth it to store the
266 * last used output slot and try that one first. */
267 stride_used = vshader_get_input(state->vertex_shader,
268 element->usage, element->usage_idx, &idx);
272 idx = element->output_slot;
278 if (!element->ffp_valid)
280 WARN("Skipping unsupported fixed function element of format %s and usage %s\n",
281 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
286 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
292 TRACE("Load %s array %u [usage %s, usage_idx %u, "
293 "input_slot %u, offset %u, stride %u, format %s, buffer_object %u]\n",
294 use_vshader ? "shader": "fixed function", idx,
295 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
296 element->offset, stride, debug_d3dformat(element->format->id), data.buffer_object);
298 data.addr += stream->offset;
300 stream_info->elements[idx].format = element->format;
301 stream_info->elements[idx].data = data;
302 stream_info->elements[idx].stride = stride;
303 stream_info->elements[idx].stream_idx = element->input_slot;
305 if (!device->adapter->gl_info.supported[ARB_VERTEX_ARRAY_BGRA]
306 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
308 stream_info->swizzle_map |= 1 << idx;
310 stream_info->use_map |= 1 << idx;
314 device->num_buffer_queries = 0;
315 if (!state->user_stream)
317 WORD map = stream_info->use_map;
319 /* PreLoad all the vertex buffers. */
320 for (i = 0; map; map >>= 1, ++i)
322 struct wined3d_stream_info_element *element;
323 struct wined3d_buffer *buffer;
325 if (!(map & 1)) continue;
327 element = &stream_info->elements[i];
328 buffer = state->streams[element->stream_idx].buffer;
329 wined3d_buffer_preload(buffer);
331 /* If the preload dropped the buffer object, update the stream info. */
332 if (buffer->buffer_object != element->data.buffer_object)
334 element->data.buffer_object = 0;
335 element->data.addr = buffer_get_sysmem(buffer, &device->adapter->gl_info)
336 + (ptrdiff_t)element->data.addr;
340 device->buffer_queries[device->num_buffer_queries++] = buffer->query;
345 static void stream_info_element_from_strided(const struct wined3d_gl_info *gl_info,
346 const struct WineDirect3DStridedData *strided, struct wined3d_stream_info_element *e)
348 e->data.addr = strided->lpData;
349 e->data.buffer_object = 0;
350 e->format = wined3d_get_format(gl_info, strided->format);
351 e->stride = strided->dwStride;
355 static void device_stream_info_from_strided(const struct wined3d_gl_info *gl_info,
356 const struct WineDirect3DVertexStridedData *strided, struct wined3d_stream_info *stream_info)
360 memset(stream_info, 0, sizeof(*stream_info));
362 if (strided->position.lpData)
363 stream_info_element_from_strided(gl_info, &strided->position, &stream_info->elements[WINED3D_FFP_POSITION]);
364 if (strided->normal.lpData)
365 stream_info_element_from_strided(gl_info, &strided->normal, &stream_info->elements[WINED3D_FFP_NORMAL]);
366 if (strided->diffuse.lpData)
367 stream_info_element_from_strided(gl_info, &strided->diffuse, &stream_info->elements[WINED3D_FFP_DIFFUSE]);
368 if (strided->specular.lpData)
369 stream_info_element_from_strided(gl_info, &strided->specular, &stream_info->elements[WINED3D_FFP_SPECULAR]);
371 for (i = 0; i < WINED3DDP_MAXTEXCOORD; ++i)
373 if (strided->texCoords[i].lpData)
374 stream_info_element_from_strided(gl_info, &strided->texCoords[i],
375 &stream_info->elements[WINED3D_FFP_TEXCOORD0 + i]);
378 stream_info->position_transformed = strided->position_transformed;
380 for (i = 0; i < sizeof(stream_info->elements) / sizeof(*stream_info->elements); ++i)
382 if (!stream_info->elements[i].format) continue;
384 if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
385 && stream_info->elements[i].format->id == WINED3DFMT_B8G8R8A8_UNORM)
387 stream_info->swizzle_map |= 1 << i;
389 stream_info->use_map |= 1 << i;
393 static void device_trace_strided_stream_info(const struct wined3d_stream_info *stream_info)
395 TRACE("Strided Data:\n");
396 TRACE_STRIDED(stream_info, WINED3D_FFP_POSITION);
397 TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDWEIGHT);
398 TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDINDICES);
399 TRACE_STRIDED(stream_info, WINED3D_FFP_NORMAL);
400 TRACE_STRIDED(stream_info, WINED3D_FFP_PSIZE);
401 TRACE_STRIDED(stream_info, WINED3D_FFP_DIFFUSE);
402 TRACE_STRIDED(stream_info, WINED3D_FFP_SPECULAR);
403 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD0);
404 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD1);
405 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD2);
406 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD3);
407 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD4);
408 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD5);
409 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD6);
410 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD7);
413 /* Context activation is done by the caller. */
414 void device_update_stream_info(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
416 struct wined3d_stream_info *stream_info = &device->strided_streams;
417 const struct wined3d_state *state = &device->stateBlock->state;
420 if (device->up_strided)
422 /* Note: this is a ddraw fixed-function code path. */
423 TRACE("=============================== Strided Input ================================\n");
424 device_stream_info_from_strided(gl_info, device->up_strided, stream_info);
425 if (TRACE_ON(d3d)) device_trace_strided_stream_info(stream_info);
429 TRACE("============================= Vertex Declaration =============================\n");
430 device_stream_info_from_declaration(device, stream_info, &fixup);
433 if (state->vertex_shader && !stream_info->position_transformed)
435 if (state->vertex_declaration->half_float_conv_needed && !fixup)
437 TRACE("Using drawStridedSlow with vertex shaders for FLOAT16 conversion.\n");
438 device->useDrawStridedSlow = TRUE;
442 device->useDrawStridedSlow = FALSE;
447 WORD slow_mask = (1 << WINED3D_FFP_PSIZE);
448 slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
449 & ((1 << WINED3D_FFP_DIFFUSE) | (1 << WINED3D_FFP_SPECULAR));
451 if ((stream_info->position_transformed || (stream_info->use_map & slow_mask)) && !fixup)
453 device->useDrawStridedSlow = TRUE;
457 device->useDrawStridedSlow = FALSE;
462 static void device_preload_texture(const struct wined3d_state *state, unsigned int idx)
464 struct wined3d_texture *texture;
465 enum WINED3DSRGB srgb;
467 if (!(texture = state->textures[idx])) return;
468 srgb = state->sampler_states[idx][WINED3DSAMP_SRGBTEXTURE] ? SRGB_SRGB : SRGB_RGB;
469 texture->texture_ops->texture_preload(texture, srgb);
472 void device_preload_textures(const struct wined3d_device *device)
474 const struct wined3d_state *state = &device->stateBlock->state;
479 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
481 if (state->vertex_shader->reg_maps.sampler_type[i])
482 device_preload_texture(state, MAX_FRAGMENT_SAMPLERS + i);
488 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
490 if (state->pixel_shader->reg_maps.sampler_type[i])
491 device_preload_texture(state, i);
496 WORD ffu_map = device->fixed_function_usage_map;
498 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
501 device_preload_texture(state, i);
506 BOOL device_context_add(struct wined3d_device *device, struct wined3d_context *context)
508 struct wined3d_context **new_array;
510 TRACE("Adding context %p.\n", context);
512 if (!device->contexts) new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_array));
513 else new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts,
514 sizeof(*new_array) * (device->context_count + 1));
518 ERR("Failed to grow the context array.\n");
522 new_array[device->context_count++] = context;
523 device->contexts = new_array;
527 void device_context_remove(struct wined3d_device *device, struct wined3d_context *context)
529 struct wined3d_context **new_array;
533 TRACE("Removing context %p.\n", context);
535 for (i = 0; i < device->context_count; ++i)
537 if (device->contexts[i] == context)
546 ERR("Context %p doesn't exist in context array.\n", context);
550 if (!--device->context_count)
552 HeapFree(GetProcessHeap(), 0, device->contexts);
553 device->contexts = NULL;
557 memmove(&device->contexts[i], &device->contexts[i + 1], (device->context_count - i) * sizeof(*device->contexts));
558 new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts, device->context_count * sizeof(*device->contexts));
561 ERR("Failed to shrink context array. Oh well.\n");
565 device->contexts = new_array;
568 /* Do not call while under the GL lock. */
569 void device_switch_onscreen_ds(struct wined3d_device *device,
570 struct wined3d_context *context, struct wined3d_surface *depth_stencil)
572 if (device->onscreen_depth_stencil)
574 surface_load_ds_location(device->onscreen_depth_stencil, context, SFLAG_DS_OFFSCREEN);
575 surface_modify_ds_location(device->onscreen_depth_stencil, SFLAG_DS_OFFSCREEN,
576 device->onscreen_depth_stencil->ds_current_size.cx,
577 device->onscreen_depth_stencil->ds_current_size.cy);
578 wined3d_surface_decref(device->onscreen_depth_stencil);
580 device->onscreen_depth_stencil = depth_stencil;
581 wined3d_surface_incref(device->onscreen_depth_stencil);
584 static BOOL is_full_clear(const struct wined3d_surface *target, const RECT *draw_rect, const RECT *clear_rect)
586 /* partial draw rect */
587 if (draw_rect->left || draw_rect->top
588 || draw_rect->right < target->resource.width
589 || draw_rect->bottom < target->resource.height)
592 /* partial clear rect */
593 if (clear_rect && (clear_rect->left > 0 || clear_rect->top > 0
594 || clear_rect->right < target->resource.width
595 || clear_rect->bottom < target->resource.height))
601 static void prepare_ds_clear(struct wined3d_surface *ds, struct wined3d_context *context,
602 DWORD location, const RECT *draw_rect, UINT rect_count, const RECT *clear_rect)
604 RECT current_rect, r;
606 if (ds->flags & location)
607 SetRect(¤t_rect, 0, 0,
608 ds->ds_current_size.cx,
609 ds->ds_current_size.cy);
611 SetRectEmpty(¤t_rect);
613 IntersectRect(&r, draw_rect, ¤t_rect);
614 if (EqualRect(&r, draw_rect))
616 /* current_rect ⊇ draw_rect, modify only. */
617 surface_modify_ds_location(ds, location, ds->ds_current_size.cx, ds->ds_current_size.cy);
621 if (EqualRect(&r, ¤t_rect))
623 /* draw_rect ⊇ current_rect, test if we're doing a full clear. */
627 /* Full clear, modify only. */
628 surface_modify_ds_location(ds, location, draw_rect->right, draw_rect->bottom);
632 IntersectRect(&r, draw_rect, clear_rect);
633 if (EqualRect(&r, draw_rect))
635 /* clear_rect ⊇ draw_rect, modify only. */
636 surface_modify_ds_location(ds, location, draw_rect->right, draw_rect->bottom);
642 surface_load_ds_location(ds, context, location);
643 surface_modify_ds_location(ds, location, ds->ds_current_size.cx, ds->ds_current_size.cy);
646 /* Do not call while under the GL lock. */
647 HRESULT device_clear_render_targets(struct wined3d_device *device, UINT rt_count, const struct wined3d_fb_state *fb,
648 UINT rect_count, const RECT *rects, const RECT *draw_rect, DWORD flags, const struct wined3d_color *color,
649 float depth, DWORD stencil)
651 const RECT *clear_rect = (rect_count > 0 && rects) ? (const RECT *)rects : NULL;
652 struct wined3d_surface *target = rt_count ? fb->render_targets[0] : NULL;
653 UINT drawable_width, drawable_height;
654 struct wined3d_context *context;
655 GLbitfield clear_mask = 0;
656 BOOL render_offscreen;
659 /* When we're clearing parts of the drawable, make sure that the target surface is well up to date in the
660 * drawable. After the clear we'll mark the drawable up to date, so we have to make sure that this is true
661 * for the cleared parts, and the untouched parts.
663 * If we're clearing the whole target there is no need to copy it into the drawable, it will be overwritten
664 * anyway. If we're not clearing the color buffer we don't have to copy either since we're not going to set
665 * the drawable up to date. We have to check all settings that limit the clear area though. Do not bother
666 * checking all this if the dest surface is in the drawable anyway. */
667 if (flags & WINED3DCLEAR_TARGET && !is_full_clear(target, draw_rect, clear_rect))
669 for (i = 0; i < rt_count; ++i)
671 struct wined3d_surface *rt = fb->render_targets[i];
673 surface_load_location(rt, rt->draw_binding, NULL);
677 context = context_acquire(device, target);
680 context_release(context);
681 WARN("Invalid context, skipping clear.\n");
687 render_offscreen = context->render_offscreen;
688 target->get_drawable_size(context, &drawable_width, &drawable_height);
692 render_offscreen = TRUE;
693 drawable_width = fb->depth_stencil->pow2Width;
694 drawable_height = fb->depth_stencil->pow2Height;
697 if (flags & WINED3DCLEAR_ZBUFFER)
699 DWORD location = render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
701 if (location == SFLAG_DS_ONSCREEN && fb->depth_stencil != device->onscreen_depth_stencil)
702 device_switch_onscreen_ds(device, context, fb->depth_stencil);
703 prepare_ds_clear(fb->depth_stencil, context, location, draw_rect, rect_count, clear_rect);
706 if (!context_apply_clear_state(context, device, rt_count, fb))
708 context_release(context);
709 WARN("Failed to apply clear state, skipping clear.\n");
715 /* Only set the values up once, as they are not changing. */
716 if (flags & WINED3DCLEAR_STENCIL)
718 if (context->gl_info->supported[EXT_STENCIL_TWO_SIDE])
720 glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
721 context_invalidate_state(context, STATE_RENDER(WINED3DRS_TWOSIDEDSTENCILMODE));
724 context_invalidate_state(context, STATE_RENDER(WINED3DRS_STENCILWRITEMASK));
725 glClearStencil(stencil);
726 checkGLcall("glClearStencil");
727 clear_mask = clear_mask | GL_STENCIL_BUFFER_BIT;
730 if (flags & WINED3DCLEAR_ZBUFFER)
732 surface_modify_location(fb->depth_stencil, fb->depth_stencil->draw_binding, TRUE);
734 glDepthMask(GL_TRUE);
735 context_invalidate_state(context, STATE_RENDER(WINED3DRS_ZWRITEENABLE));
737 checkGLcall("glClearDepth");
738 clear_mask = clear_mask | GL_DEPTH_BUFFER_BIT;
741 if (flags & WINED3DCLEAR_TARGET)
743 for (i = 0; i < rt_count; ++i)
745 struct wined3d_surface *rt = fb->render_targets[i];
748 surface_modify_location(rt, rt->draw_binding, TRUE);
751 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
752 context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE));
753 context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1));
754 context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2));
755 context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3));
756 glClearColor(color->r, color->g, color->b, color->a);
757 checkGLcall("glClearColor");
758 clear_mask = clear_mask | GL_COLOR_BUFFER_BIT;
763 if (render_offscreen)
765 glScissor(draw_rect->left, draw_rect->top,
766 draw_rect->right - draw_rect->left, draw_rect->bottom - draw_rect->top);
770 glScissor(draw_rect->left, drawable_height - draw_rect->bottom,
771 draw_rect->right - draw_rect->left, draw_rect->bottom - draw_rect->top);
773 checkGLcall("glScissor");
775 checkGLcall("glClear");
781 /* Now process each rect in turn. */
782 for (i = 0; i < rect_count; ++i)
784 /* Note that GL uses lower left, width/height. */
785 IntersectRect(¤t_rect, draw_rect, &clear_rect[i]);
787 TRACE("clear_rect[%u] %s, current_rect %s.\n", i,
788 wine_dbgstr_rect(&clear_rect[i]),
789 wine_dbgstr_rect(¤t_rect));
791 /* Tests show that rectangles where x1 > x2 or y1 > y2 are ignored silently.
792 * The rectangle is not cleared, no error is returned, but further rectangles are
793 * still cleared if they are valid. */
794 if (current_rect.left > current_rect.right || current_rect.top > current_rect.bottom)
796 TRACE("Rectangle with negative dimensions, ignoring.\n");
800 if (render_offscreen)
802 glScissor(current_rect.left, current_rect.top,
803 current_rect.right - current_rect.left, current_rect.bottom - current_rect.top);
807 glScissor(current_rect.left, drawable_height - current_rect.bottom,
808 current_rect.right - current_rect.left, current_rect.bottom - current_rect.top);
810 checkGLcall("glScissor");
813 checkGLcall("glClear");
819 if (wined3d_settings.strict_draw_ordering || (flags & WINED3DCLEAR_TARGET
820 && target->container.type == WINED3D_CONTAINER_SWAPCHAIN
821 && target->container.u.swapchain->front_buffer == target))
822 wglFlush(); /* Flush to ensure ordering across contexts. */
824 context_release(context);
829 ULONG CDECL wined3d_device_incref(struct wined3d_device *device)
831 ULONG refcount = InterlockedIncrement(&device->ref);
833 TRACE("%p increasing refcount to %u.\n", device, refcount);
838 ULONG CDECL wined3d_device_decref(struct wined3d_device *device)
840 ULONG refcount = InterlockedDecrement(&device->ref);
842 TRACE("%p decreasing refcount to %u.\n", device, refcount);
846 struct wined3d_stateblock *stateblock;
849 if (wined3d_stateblock_decref(device->updateStateBlock)
850 && device->updateStateBlock != device->stateBlock)
851 FIXME("Something's still holding the update stateblock.\n");
852 device->updateStateBlock = NULL;
854 stateblock = device->stateBlock;
855 device->stateBlock = NULL;
856 if (wined3d_stateblock_decref(stateblock))
857 FIXME("Something's still holding the stateblock.\n");
859 for (i = 0; i < sizeof(device->multistate_funcs) / sizeof(device->multistate_funcs[0]); ++i)
861 HeapFree(GetProcessHeap(), 0, device->multistate_funcs[i]);
862 device->multistate_funcs[i] = NULL;
865 if (!list_empty(&device->resources))
867 struct wined3d_resource *resource;
869 FIXME("Device released with resources still bound, acceptable but unexpected.\n");
871 LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
873 FIXME("Leftover resource %p with type %s (%#x).\n",
874 resource, debug_d3dresourcetype(resource->resourceType), resource->resourceType);
878 if (device->contexts)
879 ERR("Context array not freed!\n");
880 if (device->hardwareCursor)
881 DestroyCursor(device->hardwareCursor);
882 device->hardwareCursor = 0;
884 wined3d_decref(device->wined3d);
885 device->wined3d = NULL;
886 HeapFree(GetProcessHeap(), 0, device);
887 TRACE("Freed device %p.\n", device);
893 UINT CDECL wined3d_device_get_swapchain_count(const struct wined3d_device *device)
895 TRACE("device %p.\n", device);
897 return device->swapchain_count;
900 HRESULT CDECL wined3d_device_get_swapchain(const struct wined3d_device *device,
901 UINT swapchain_idx, struct wined3d_swapchain **swapchain)
903 TRACE("device %p, swapchain_idx %u, swapchain %p.\n",
904 device, swapchain_idx, swapchain);
906 if (swapchain_idx >= device->swapchain_count)
908 WARN("swapchain_idx %u >= swapchain_count %u.\n",
909 swapchain_idx, device->swapchain_count);
912 return WINED3DERR_INVALIDCALL;
915 *swapchain = device->swapchains[swapchain_idx];
916 wined3d_swapchain_incref(*swapchain);
917 TRACE("Returning %p.\n", *swapchain);
922 static void device_load_logo(struct wined3d_device *device, const char *filename)
927 HDC dcb = NULL, dcs = NULL;
928 WINEDDCOLORKEY colorkey;
930 hbm = LoadImageA(NULL, filename, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
933 GetObjectA(hbm, sizeof(BITMAP), &bm);
934 dcb = CreateCompatibleDC(NULL);
936 SelectObject(dcb, hbm);
940 /* Create a 32x32 white surface to indicate that wined3d is used, but the specified image
943 memset(&bm, 0, sizeof(bm));
948 hr = wined3d_surface_create(device, bm.bmWidth, bm.bmHeight, WINED3DFMT_B5G6R5_UNORM, 0, 0,
949 WINED3DPOOL_DEFAULT, WINED3DMULTISAMPLE_NONE, 0, SURFACE_OPENGL, WINED3D_SURFACE_MAPPABLE,
950 NULL, &wined3d_null_parent_ops, &device->logo_surface);
953 ERR("Wine logo requested, but failed to create surface, hr %#x.\n", hr);
959 if (FAILED(hr = wined3d_surface_getdc(device->logo_surface, &dcs)))
961 BitBlt(dcs, 0, 0, bm.bmWidth, bm.bmHeight, dcb, 0, 0, SRCCOPY);
962 wined3d_surface_releasedc(device->logo_surface, dcs);
964 colorkey.dwColorSpaceLowValue = 0;
965 colorkey.dwColorSpaceHighValue = 0;
966 wined3d_surface_set_color_key(device->logo_surface, WINEDDCKEY_SRCBLT, &colorkey);
970 const struct wined3d_color c = {1.0f, 1.0f, 1.0f, 1.0f};
971 /* Fill the surface with a white color to show that wined3d is there */
972 wined3d_device_color_fill(device, device->logo_surface, NULL, &c);
976 if (dcb) DeleteDC(dcb);
977 if (hbm) DeleteObject(hbm);
980 /* Context activation is done by the caller. */
981 static void create_dummy_textures(struct wined3d_device *device, struct wined3d_context *context)
983 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
984 unsigned int i, j, count;
985 /* Under DirectX you can sample even if no texture is bound, whereas
986 * OpenGL will only allow that when a valid texture is bound.
987 * We emulate this by creating dummy textures and binding them
988 * to each texture stage when the currently set D3D texture is NULL. */
991 if (gl_info->supported[APPLE_CLIENT_STORAGE])
993 /* The dummy texture does not have client storage backing */
994 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
995 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
998 count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
999 for (i = 0; i < count; ++i)
1001 DWORD color = 0x000000ff;
1003 /* Make appropriate texture active */
1004 context_active_texture(context, gl_info, i);
1006 glGenTextures(1, &device->dummy_texture_2d[i]);
1007 checkGLcall("glGenTextures");
1008 TRACE("Dummy 2D texture %u given name %u.\n", i, device->dummy_texture_2d[i]);
1010 glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1011 checkGLcall("glBindTexture");
1013 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1014 checkGLcall("glTexImage2D");
1016 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1018 glGenTextures(1, &device->dummy_texture_rect[i]);
1019 checkGLcall("glGenTextures");
1020 TRACE("Dummy rectangle texture %u given name %u.\n", i, device->dummy_texture_rect[i]);
1022 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1023 checkGLcall("glBindTexture");
1025 glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1026 checkGLcall("glTexImage2D");
1029 if (gl_info->supported[EXT_TEXTURE3D])
1031 glGenTextures(1, &device->dummy_texture_3d[i]);
1032 checkGLcall("glGenTextures");
1033 TRACE("Dummy 3D texture %u given name %u.\n", i, device->dummy_texture_3d[i]);
1035 glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1036 checkGLcall("glBindTexture");
1038 GL_EXTCALL(glTexImage3DEXT(GL_TEXTURE_3D, 0, GL_RGBA8, 1, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color));
1039 checkGLcall("glTexImage3D");
1042 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1044 glGenTextures(1, &device->dummy_texture_cube[i]);
1045 checkGLcall("glGenTextures");
1046 TRACE("Dummy cube texture %u given name %u.\n", i, device->dummy_texture_cube[i]);
1048 glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1049 checkGLcall("glBindTexture");
1051 for (j = GL_TEXTURE_CUBE_MAP_POSITIVE_X; j <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; ++j)
1053 glTexImage2D(j, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1054 checkGLcall("glTexImage2D");
1059 if (gl_info->supported[APPLE_CLIENT_STORAGE])
1061 /* Reenable because if supported it is enabled by default */
1062 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1063 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1069 /* Context activation is done by the caller. */
1070 static void destroy_dummy_textures(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
1072 unsigned int count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1075 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1077 glDeleteTextures(count, device->dummy_texture_cube);
1078 checkGLcall("glDeleteTextures(count, device->dummy_texture_cube)");
1081 if (gl_info->supported[EXT_TEXTURE3D])
1083 glDeleteTextures(count, device->dummy_texture_3d);
1084 checkGLcall("glDeleteTextures(count, device->dummy_texture_3d)");
1087 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1089 glDeleteTextures(count, device->dummy_texture_rect);
1090 checkGLcall("glDeleteTextures(count, device->dummy_texture_rect)");
1093 glDeleteTextures(count, device->dummy_texture_2d);
1094 checkGLcall("glDeleteTextures(count, device->dummy_texture_2d)");
1097 memset(device->dummy_texture_cube, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_cube));
1098 memset(device->dummy_texture_3d, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_3d));
1099 memset(device->dummy_texture_rect, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_rect));
1100 memset(device->dummy_texture_2d, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_2d));
1103 static LONG fullscreen_style(LONG style)
1105 /* Make sure the window is managed, otherwise we won't get keyboard input. */
1106 style |= WS_POPUP | WS_SYSMENU;
1107 style &= ~(WS_CAPTION | WS_THICKFRAME);
1112 static LONG fullscreen_exstyle(LONG exstyle)
1114 /* Filter out window decorations. */
1115 exstyle &= ~(WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);
1120 void CDECL wined3d_device_setup_fullscreen_window(struct wined3d_device *device, HWND window, UINT w, UINT h)
1122 BOOL filter_messages;
1123 LONG style, exstyle;
1125 TRACE("Setting up window %p for fullscreen mode.\n", window);
1127 if (device->style || device->exStyle)
1129 ERR("Changing the window style for window %p, but another style (%08x, %08x) is already stored.\n",
1130 window, device->style, device->exStyle);
1133 device->style = GetWindowLongW(window, GWL_STYLE);
1134 device->exStyle = GetWindowLongW(window, GWL_EXSTYLE);
1136 style = fullscreen_style(device->style);
1137 exstyle = fullscreen_exstyle(device->exStyle);
1139 TRACE("Old style was %08x, %08x, setting to %08x, %08x.\n",
1140 device->style, device->exStyle, style, exstyle);
1142 filter_messages = device->filter_messages;
1143 device->filter_messages = TRUE;
1145 SetWindowLongW(window, GWL_STYLE, style);
1146 SetWindowLongW(window, GWL_EXSTYLE, exstyle);
1147 SetWindowPos(window, HWND_TOP, 0, 0, w, h, SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOACTIVATE);
1149 device->filter_messages = filter_messages;
1152 void CDECL wined3d_device_restore_fullscreen_window(struct wined3d_device *device, HWND window)
1154 BOOL filter_messages;
1155 LONG style, exstyle;
1157 if (!device->style && !device->exStyle) return;
1159 TRACE("Restoring window style of window %p to %08x, %08x.\n",
1160 window, device->style, device->exStyle);
1162 style = GetWindowLongW(window, GWL_STYLE);
1163 exstyle = GetWindowLongW(window, GWL_EXSTYLE);
1165 filter_messages = device->filter_messages;
1166 device->filter_messages = TRUE;
1168 /* Only restore the style if the application didn't modify it during the
1169 * fullscreen phase. Some applications change it before calling Reset()
1170 * when switching between windowed and fullscreen modes (HL2), some
1171 * depend on the original style (Eve Online). */
1172 if (style == fullscreen_style(device->style) && exstyle == fullscreen_exstyle(device->exStyle))
1174 SetWindowLongW(window, GWL_STYLE, device->style);
1175 SetWindowLongW(window, GWL_EXSTYLE, device->exStyle);
1177 SetWindowPos(window, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
1179 device->filter_messages = filter_messages;
1181 /* Delete the old values. */
1183 device->exStyle = 0;
1186 HRESULT CDECL wined3d_device_acquire_focus_window(struct wined3d_device *device, HWND window)
1188 TRACE("device %p, window %p.\n", device, window);
1190 if (!wined3d_register_window(window, device))
1192 ERR("Failed to register window %p.\n", window);
1196 device->focus_window = window;
1197 SetWindowPos(window, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
1202 void CDECL wined3d_device_release_focus_window(struct wined3d_device *device)
1204 TRACE("device %p.\n", device);
1206 if (device->focus_window) wined3d_unregister_window(device->focus_window);
1207 device->focus_window = NULL;
1210 HRESULT CDECL wined3d_device_init_3d(struct wined3d_device *device,
1211 struct wined3d_swapchain_desc *swapchain_desc)
1213 static const struct wined3d_color black = {0.0f, 0.0f, 0.0f, 0.0f};
1214 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1215 struct wined3d_swapchain *swapchain = NULL;
1216 struct wined3d_context *context;
1221 TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
1223 if (device->d3d_initialized)
1224 return WINED3DERR_INVALIDCALL;
1225 if (!device->adapter->opengl)
1226 return WINED3DERR_INVALIDCALL;
1228 device->valid_rt_mask = 0;
1229 for (i = 0; i < gl_info->limits.buffers; ++i)
1230 device->valid_rt_mask |= (1 << i);
1231 device->fb.render_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1232 sizeof(*device->fb.render_targets) * gl_info->limits.buffers);
1234 /* Initialize the texture unit mapping to a 1:1 mapping */
1235 for (state = 0; state < MAX_COMBINED_SAMPLERS; ++state)
1237 if (state < gl_info->limits.fragment_samplers)
1239 device->texUnitMap[state] = state;
1240 device->rev_tex_unit_map[state] = state;
1244 device->texUnitMap[state] = WINED3D_UNMAPPED_STAGE;
1245 device->rev_tex_unit_map[state] = WINED3D_UNMAPPED_STAGE;
1249 /* Setup the implicit swapchain. This also initializes a context. */
1250 TRACE("Creating implicit swapchain\n");
1251 hr = device->device_parent->ops->create_swapchain(device->device_parent,
1252 swapchain_desc, &swapchain);
1255 WARN("Failed to create implicit swapchain\n");
1259 device->swapchain_count = 1;
1260 device->swapchains = HeapAlloc(GetProcessHeap(), 0, device->swapchain_count * sizeof(*device->swapchains));
1261 if (!device->swapchains)
1263 ERR("Out of memory!\n");
1266 device->swapchains[0] = swapchain;
1268 if (swapchain->back_buffers && swapchain->back_buffers[0])
1270 TRACE("Setting rendertarget to %p.\n", swapchain->back_buffers);
1271 device->fb.render_targets[0] = swapchain->back_buffers[0];
1275 TRACE("Setting rendertarget to %p.\n", swapchain->front_buffer);
1276 device->fb.render_targets[0] = swapchain->front_buffer;
1278 wined3d_surface_incref(device->fb.render_targets[0]);
1280 /* Depth Stencil support */
1281 device->fb.depth_stencil = device->auto_depth_stencil;
1282 if (device->fb.depth_stencil)
1283 wined3d_surface_incref(device->fb.depth_stencil);
1285 hr = device->shader_backend->shader_alloc_private(device);
1288 TRACE("Shader private data couldn't be allocated\n");
1291 hr = device->frag_pipe->alloc_private(device);
1294 TRACE("Fragment pipeline private data couldn't be allocated\n");
1297 hr = device->blitter->alloc_private(device);
1300 TRACE("Blitter private data couldn't be allocated\n");
1304 /* Set up some starting GL setup */
1306 /* Setup all the devices defaults */
1307 stateblock_init_default_state(device->stateBlock);
1309 context = context_acquire(device, swapchain->front_buffer);
1311 create_dummy_textures(device, context);
1315 /* Initialize the current view state */
1316 device->view_ident = 1;
1317 device->contexts[0]->last_was_rhw = 0;
1319 switch (wined3d_settings.offscreen_rendering_mode)
1322 device->offscreenBuffer = GL_COLOR_ATTACHMENT0;
1325 case ORM_BACKBUFFER:
1327 if (context_get_current()->aux_buffers > 0)
1329 TRACE("Using auxiliary buffer for offscreen rendering\n");
1330 device->offscreenBuffer = GL_AUX0;
1334 TRACE("Using back buffer for offscreen rendering\n");
1335 device->offscreenBuffer = GL_BACK;
1340 TRACE("All defaults now set up, leaving 3D init.\n");
1343 context_release(context);
1345 /* Clear the screen */
1346 wined3d_device_clear(device, 0, NULL, WINED3DCLEAR_TARGET
1347 | (swapchain_desc->enable_auto_depth_stencil ? WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL : 0),
1350 device->d3d_initialized = TRUE;
1352 if (wined3d_settings.logo)
1353 device_load_logo(device, wined3d_settings.logo);
1357 HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1358 HeapFree(GetProcessHeap(), 0, device->swapchains);
1359 device->swapchain_count = 0;
1361 wined3d_swapchain_decref(swapchain);
1362 if (device->blit_priv)
1363 device->blitter->free_private(device);
1364 if (device->fragment_priv)
1365 device->frag_pipe->free_private(device);
1366 if (device->shader_priv)
1367 device->shader_backend->shader_free_private(device);
1372 HRESULT CDECL wined3d_device_init_gdi(struct wined3d_device *device,
1373 struct wined3d_swapchain_desc *swapchain_desc)
1375 struct wined3d_swapchain *swapchain = NULL;
1378 TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
1380 /* Setup the implicit swapchain */
1381 TRACE("Creating implicit swapchain\n");
1382 hr = device->device_parent->ops->create_swapchain(device->device_parent,
1383 swapchain_desc, &swapchain);
1386 WARN("Failed to create implicit swapchain\n");
1390 device->swapchain_count = 1;
1391 device->swapchains = HeapAlloc(GetProcessHeap(), 0, device->swapchain_count * sizeof(*device->swapchains));
1392 if (!device->swapchains)
1394 ERR("Out of memory!\n");
1397 device->swapchains[0] = swapchain;
1401 wined3d_swapchain_decref(swapchain);
1405 HRESULT CDECL wined3d_device_uninit_3d(struct wined3d_device *device)
1407 struct wined3d_resource *resource, *cursor;
1408 const struct wined3d_gl_info *gl_info;
1409 struct wined3d_context *context;
1410 struct wined3d_surface *surface;
1413 TRACE("device %p.\n", device);
1415 if (!device->d3d_initialized)
1416 return WINED3DERR_INVALIDCALL;
1418 /* Force making the context current again, to verify it is still valid
1419 * (workaround for broken drivers) */
1420 context_set_current(NULL);
1421 /* I don't think that the interface guarantees that the device is destroyed from the same thread
1422 * it was created. Thus make sure a context is active for the glDelete* calls
1424 context = context_acquire(device, NULL);
1425 gl_info = context->gl_info;
1427 if (device->logo_surface)
1428 wined3d_surface_decref(device->logo_surface);
1430 /* Unload resources */
1431 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
1433 TRACE("Unloading resource %p.\n", resource);
1435 resource->resource_ops->resource_unload(resource);
1438 TRACE("Deleting high order patches\n");
1439 for(i = 0; i < PATCHMAP_SIZE; i++) {
1440 struct list *e1, *e2;
1441 struct WineD3DRectPatch *patch;
1442 LIST_FOR_EACH_SAFE(e1, e2, &device->patches[i])
1444 patch = LIST_ENTRY(e1, struct WineD3DRectPatch, entry);
1445 wined3d_device_delete_patch(device, patch->Handle);
1449 /* Delete the mouse cursor texture */
1450 if (device->cursorTexture)
1453 glDeleteTextures(1, &device->cursorTexture);
1455 device->cursorTexture = 0;
1458 /* Destroy the depth blt resources, they will be invalid after the reset. Also free shader
1459 * private data, it might contain opengl pointers
1461 if (device->depth_blt_texture)
1464 glDeleteTextures(1, &device->depth_blt_texture);
1466 device->depth_blt_texture = 0;
1469 /* Destroy the shader backend. Note that this has to happen after all shaders are destroyed. */
1470 device->blitter->free_private(device);
1471 device->frag_pipe->free_private(device);
1472 device->shader_backend->shader_free_private(device);
1474 /* Release the buffers (with sanity checks)*/
1475 if (device->onscreen_depth_stencil)
1477 surface = device->onscreen_depth_stencil;
1478 device->onscreen_depth_stencil = NULL;
1479 wined3d_surface_decref(surface);
1482 if (device->fb.depth_stencil)
1484 surface = device->fb.depth_stencil;
1486 TRACE("Releasing depth/stencil buffer %p.\n", surface);
1488 device->fb.depth_stencil = NULL;
1489 if (wined3d_surface_decref(surface)
1490 && surface != device->auto_depth_stencil)
1491 ERR("Something is still holding a reference to depth/stencil buffer %p.\n", surface);
1494 if (device->auto_depth_stencil)
1496 surface = device->auto_depth_stencil;
1497 device->auto_depth_stencil = NULL;
1498 if (wined3d_surface_decref(surface))
1499 FIXME("Something's still holding the auto depth stencil buffer (%p).\n", surface);
1502 for (i = 1; i < gl_info->limits.buffers; ++i)
1504 wined3d_device_set_render_target(device, i, NULL, FALSE);
1507 surface = device->fb.render_targets[0];
1508 TRACE("Setting rendertarget 0 to NULL\n");
1509 device->fb.render_targets[0] = NULL;
1510 TRACE("Releasing the render target at %p\n", surface);
1511 wined3d_surface_decref(surface);
1513 context_release(context);
1515 for (i = 0; i < device->swapchain_count; ++i)
1517 TRACE("Releasing the implicit swapchain %u.\n", i);
1518 if (wined3d_swapchain_decref(device->swapchains[i]))
1519 FIXME("Something's still holding the implicit swapchain.\n");
1522 HeapFree(GetProcessHeap(), 0, device->swapchains);
1523 device->swapchains = NULL;
1524 device->swapchain_count = 0;
1526 HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1527 device->fb.render_targets = NULL;
1529 device->d3d_initialized = FALSE;
1534 HRESULT CDECL wined3d_device_uninit_gdi(struct wined3d_device *device)
1538 for (i = 0; i < device->swapchain_count; ++i)
1540 TRACE("Releasing the implicit swapchain %u.\n", i);
1541 if (wined3d_swapchain_decref(device->swapchains[i]))
1542 FIXME("Something's still holding the implicit swapchain.\n");
1545 HeapFree(GetProcessHeap(), 0, device->swapchains);
1546 device->swapchains = NULL;
1547 device->swapchain_count = 0;
1551 /* Enables thread safety in the wined3d device and its resources. Called by DirectDraw
1552 * from SetCooperativeLevel if DDSCL_MULTITHREADED is specified, and by d3d8/9 from
1553 * CreateDevice if D3DCREATE_MULTITHREADED is passed.
1555 * There is no way to deactivate thread safety once it is enabled.
1557 void CDECL wined3d_device_set_multithreaded(struct wined3d_device *device)
1559 TRACE("device %p.\n", device);
1561 /* For now just store the flag (needed in case of ddraw). */
1562 device->create_parms.flags |= WINED3DCREATE_MULTITHREADED;
1565 HRESULT CDECL wined3d_device_set_display_mode(struct wined3d_device *device,
1566 UINT swapchain_idx, const struct wined3d_display_mode *mode)
1568 struct wined3d_adapter *adapter = device->adapter;
1569 const struct wined3d_format *format = wined3d_get_format(&adapter->gl_info, mode->format_id);
1574 TRACE("device %p, swapchain_idx %u, mode %p (%ux%u@%u %s).\n", device, swapchain_idx, mode,
1575 mode->width, mode->height, mode->refresh_rate, debug_d3dformat(mode->format_id));
1577 /* Resize the screen even without a window:
1578 * The app could have unset it with SetCooperativeLevel, but not called
1579 * RestoreDisplayMode first. Then the release will call RestoreDisplayMode,
1580 * but we don't have any hwnd
1583 memset(&devmode, 0, sizeof(devmode));
1584 devmode.dmSize = sizeof(devmode);
1585 devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1586 devmode.dmBitsPerPel = format->byte_count * CHAR_BIT;
1587 devmode.dmPelsWidth = mode->width;
1588 devmode.dmPelsHeight = mode->height;
1590 devmode.dmDisplayFrequency = mode->refresh_rate;
1591 if (mode->refresh_rate)
1592 devmode.dmFields |= DM_DISPLAYFREQUENCY;
1594 /* Only change the mode if necessary */
1595 if (adapter->screen_size.cx == mode->width && adapter->screen_size.cy == mode->height
1596 && adapter->screen_format == mode->format_id && !mode->refresh_rate)
1599 ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL);
1600 if (ret != DISP_CHANGE_SUCCESSFUL)
1602 if (devmode.dmDisplayFrequency)
1604 WARN("ChangeDisplaySettingsExW failed, trying without the refresh rate\n");
1605 devmode.dmFields &= ~DM_DISPLAYFREQUENCY;
1606 devmode.dmDisplayFrequency = 0;
1607 ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL) != DISP_CHANGE_SUCCESSFUL;
1609 if(ret != DISP_CHANGE_SUCCESSFUL) {
1610 return WINED3DERR_NOTAVAILABLE;
1614 /* Store the new values */
1615 adapter->screen_size.cx = mode->width;
1616 adapter->screen_size.cy = mode->height;
1617 adapter->screen_format = mode->format_id;
1619 /* And finally clip mouse to our screen */
1620 SetRect(&clip_rc, 0, 0, mode->width, mode->height);
1621 ClipCursor(&clip_rc);
1626 HRESULT CDECL wined3d_device_get_wined3d(const struct wined3d_device *device, struct wined3d **wined3d)
1628 TRACE("device %p, wined3d %p.\n", device, wined3d);
1630 *wined3d = device->wined3d;
1631 wined3d_incref(*wined3d);
1633 TRACE("Returning %p.\n", *wined3d);
1638 UINT CDECL wined3d_device_get_available_texture_mem(const struct wined3d_device *device)
1640 TRACE("device %p.\n", device);
1642 TRACE("Emulating %d MB, returning %d MB left.\n",
1643 device->adapter->TextureRam / (1024 * 1024),
1644 (device->adapter->TextureRam - device->adapter->UsedTextureRam) / (1024 * 1024));
1646 return device->adapter->TextureRam - device->adapter->UsedTextureRam;
1649 HRESULT CDECL wined3d_device_set_stream_source(struct wined3d_device *device, UINT stream_idx,
1650 struct wined3d_buffer *buffer, UINT offset, UINT stride)
1652 struct wined3d_stream_state *stream;
1653 struct wined3d_buffer *prev_buffer;
1655 TRACE("device %p, stream_idx %u, buffer %p, offset %u, stride %u.\n",
1656 device, stream_idx, buffer, offset, stride);
1658 if (stream_idx >= MAX_STREAMS)
1660 WARN("Stream index %u out of range.\n", stream_idx);
1661 return WINED3DERR_INVALIDCALL;
1663 else if (offset & 0x3)
1665 WARN("Offset %u is not 4 byte aligned.\n", offset);
1666 return WINED3DERR_INVALIDCALL;
1669 stream = &device->updateStateBlock->state.streams[stream_idx];
1670 prev_buffer = stream->buffer;
1672 device->updateStateBlock->changed.streamSource |= 1 << stream_idx;
1674 if (prev_buffer == buffer
1675 && stream->stride == stride
1676 && stream->offset == offset)
1678 TRACE("Application is setting the old values over, nothing to do.\n");
1682 stream->buffer = buffer;
1685 stream->stride = stride;
1686 stream->offset = offset;
1689 /* Handle recording of state blocks. */
1690 if (device->isRecordingState)
1692 TRACE("Recording... not performing anything.\n");
1694 wined3d_buffer_incref(buffer);
1696 wined3d_buffer_decref(prev_buffer);
1702 InterlockedIncrement(&buffer->bind_count);
1703 wined3d_buffer_incref(buffer);
1707 InterlockedDecrement(&prev_buffer->bind_count);
1708 wined3d_buffer_decref(prev_buffer);
1711 device_invalidate_state(device, STATE_STREAMSRC);
1716 HRESULT CDECL wined3d_device_get_stream_source(const struct wined3d_device *device,
1717 UINT stream_idx, struct wined3d_buffer **buffer, UINT *offset, UINT *stride)
1719 struct wined3d_stream_state *stream;
1721 TRACE("device %p, stream_idx %u, buffer %p, offset %p, stride %p.\n",
1722 device, stream_idx, buffer, offset, stride);
1724 if (stream_idx >= MAX_STREAMS)
1726 WARN("Stream index %u out of range.\n", stream_idx);
1727 return WINED3DERR_INVALIDCALL;
1730 stream = &device->stateBlock->state.streams[stream_idx];
1731 *buffer = stream->buffer;
1733 wined3d_buffer_incref(*buffer);
1735 *offset = stream->offset;
1736 *stride = stream->stride;
1741 HRESULT CDECL wined3d_device_set_stream_source_freq(struct wined3d_device *device, UINT stream_idx, UINT divider)
1743 struct wined3d_stream_state *stream;
1744 UINT old_flags, old_freq;
1746 TRACE("device %p, stream_idx %u, divider %#x.\n", device, stream_idx, divider);
1748 /* Verify input. At least in d3d9 this is invalid. */
1749 if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && (divider & WINED3DSTREAMSOURCE_INDEXEDDATA))
1751 WARN("INSTANCEDATA and INDEXEDDATA were set, returning D3DERR_INVALIDCALL.\n");
1752 return WINED3DERR_INVALIDCALL;
1754 if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && !stream_idx)
1756 WARN("INSTANCEDATA used on stream 0, returning D3DERR_INVALIDCALL.\n");
1757 return WINED3DERR_INVALIDCALL;
1761 WARN("Divider is 0, returning D3DERR_INVALIDCALL.\n");
1762 return WINED3DERR_INVALIDCALL;
1765 stream = &device->updateStateBlock->state.streams[stream_idx];
1766 old_flags = stream->flags;
1767 old_freq = stream->frequency;
1769 stream->flags = divider & (WINED3DSTREAMSOURCE_INSTANCEDATA | WINED3DSTREAMSOURCE_INDEXEDDATA);
1770 stream->frequency = divider & 0x7fffff;
1772 device->updateStateBlock->changed.streamFreq |= 1 << stream_idx;
1774 if (stream->frequency != old_freq || stream->flags != old_flags)
1775 device_invalidate_state(device, STATE_STREAMSRC);
1780 HRESULT CDECL wined3d_device_get_stream_source_freq(const struct wined3d_device *device,
1781 UINT stream_idx, UINT *divider)
1783 struct wined3d_stream_state *stream;
1785 TRACE("device %p, stream_idx %u, divider %p.\n", device, stream_idx, divider);
1787 stream = &device->updateStateBlock->state.streams[stream_idx];
1788 *divider = stream->flags | stream->frequency;
1790 TRACE("Returning %#x.\n", *divider);
1795 HRESULT CDECL wined3d_device_set_transform(struct wined3d_device *device,
1796 WINED3DTRANSFORMSTATETYPE d3dts, const struct wined3d_matrix *matrix)
1798 TRACE("device %p, state %s, matrix %p.\n",
1799 device, debug_d3dtstype(d3dts), matrix);
1801 /* Handle recording of state blocks. */
1802 if (device->isRecordingState)
1804 TRACE("Recording... not performing anything.\n");
1805 device->updateStateBlock->changed.transform[d3dts >> 5] |= 1 << (d3dts & 0x1f);
1806 device->updateStateBlock->state.transforms[d3dts] = *matrix;
1810 /* If the new matrix is the same as the current one,
1811 * we cut off any further processing. this seems to be a reasonable
1812 * optimization because as was noticed, some apps (warcraft3 for example)
1813 * tend towards setting the same matrix repeatedly for some reason.
1815 * From here on we assume that the new matrix is different, wherever it matters. */
1816 if (!memcmp(&device->stateBlock->state.transforms[d3dts].u.m[0][0], matrix, sizeof(*matrix)))
1818 TRACE("The application is setting the same matrix over again.\n");
1822 conv_mat(matrix, &device->stateBlock->state.transforms[d3dts].u.m[0][0]);
1824 /* ScreenCoord = ProjectionMat * ViewMat * WorldMat * ObjectCoord
1825 * where ViewMat = Camera space, WorldMat = world space.
1827 * In OpenGL, camera and world space is combined into GL_MODELVIEW
1828 * matrix. The Projection matrix stay projection matrix. */
1830 if (d3dts == WINED3DTS_VIEW)
1831 device->view_ident = !memcmp(matrix, identity, 16 * sizeof(float));
1833 if (d3dts < WINED3DTS_WORLDMATRIX(device->adapter->gl_info.limits.blends))
1834 device_invalidate_state(device, STATE_TRANSFORM(d3dts));
1840 HRESULT CDECL wined3d_device_get_transform(const struct wined3d_device *device,
1841 WINED3DTRANSFORMSTATETYPE state, struct wined3d_matrix *matrix)
1843 TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1845 *matrix = device->stateBlock->state.transforms[state];
1850 HRESULT CDECL wined3d_device_multiply_transform(struct wined3d_device *device,
1851 WINED3DTRANSFORMSTATETYPE state, const struct wined3d_matrix *matrix)
1853 const struct wined3d_matrix *mat = NULL;
1854 struct wined3d_matrix temp;
1856 TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1858 /* Note: Using 'updateStateBlock' rather than 'stateblock' in the code
1859 * below means it will be recorded in a state block change, but it
1860 * works regardless where it is recorded.
1861 * If this is found to be wrong, change to StateBlock. */
1862 if (state > HIGHEST_TRANSFORMSTATE)
1864 WARN("Unhandled transform state %#x.\n", state);
1868 mat = &device->updateStateBlock->state.transforms[state];
1869 multiply_matrix(&temp, mat, matrix);
1871 /* Apply change via set transform - will reapply to eg. lights this way. */
1872 return wined3d_device_set_transform(device, state, &temp);
1875 /* Note lights are real special cases. Although the device caps state only
1876 * e.g. 8 are supported, you can reference any indexes you want as long as
1877 * that number max are enabled at any one point in time. Therefore since the
1878 * indices can be anything, we need a hashmap of them. However, this causes
1879 * stateblock problems. When capturing the state block, I duplicate the
1880 * hashmap, but when recording, just build a chain pretty much of commands to
1882 HRESULT CDECL wined3d_device_set_light(struct wined3d_device *device,
1883 UINT light_idx, const struct wined3d_light *light)
1885 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
1886 struct wined3d_light_info *object = NULL;
1890 TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
1892 /* Check the parameter range. Need for speed most wanted sets junk lights
1893 * which confuse the GL driver. */
1895 return WINED3DERR_INVALIDCALL;
1897 switch (light->type)
1899 case WINED3DLIGHT_POINT:
1900 case WINED3DLIGHT_SPOT:
1901 case WINED3DLIGHT_PARALLELPOINT:
1902 case WINED3DLIGHT_GLSPOT:
1903 /* Incorrect attenuation values can cause the gl driver to crash.
1904 * Happens with Need for speed most wanted. */
1905 if (light->attenuation0 < 0.0f || light->attenuation1 < 0.0f || light->attenuation2 < 0.0f)
1907 WARN("Attenuation is negative, returning WINED3DERR_INVALIDCALL.\n");
1908 return WINED3DERR_INVALIDCALL;
1912 case WINED3DLIGHT_DIRECTIONAL:
1913 /* Ignores attenuation */
1917 WARN("Light type out of range, returning WINED3DERR_INVALIDCALL\n");
1918 return WINED3DERR_INVALIDCALL;
1921 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
1923 object = LIST_ENTRY(e, struct wined3d_light_info, entry);
1924 if (object->OriginalIndex == light_idx)
1931 TRACE("Adding new light\n");
1932 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1935 ERR("Out of memory error when allocating a light\n");
1936 return E_OUTOFMEMORY;
1938 list_add_head(&device->updateStateBlock->state.light_map[hash_idx], &object->entry);
1939 object->glIndex = -1;
1940 object->OriginalIndex = light_idx;
1943 /* Initialize the object. */
1944 TRACE("Light %d setting to type %d, Diffuse(%f,%f,%f,%f), Specular(%f,%f,%f,%f), Ambient(%f,%f,%f,%f)\n",
1945 light_idx, light->type,
1946 light->diffuse.r, light->diffuse.g, light->diffuse.b, light->diffuse.a,
1947 light->specular.r, light->specular.g, light->specular.b, light->specular.a,
1948 light->ambient.r, light->ambient.g, light->ambient.b, light->ambient.a);
1949 TRACE("... Pos(%f,%f,%f), Dir(%f,%f,%f)\n", light->position.x, light->position.y, light->position.z,
1950 light->direction.x, light->direction.y, light->direction.z);
1951 TRACE("... Range(%f), Falloff(%f), Theta(%f), Phi(%f)\n",
1952 light->range, light->falloff, light->theta, light->phi);
1954 /* Save away the information. */
1955 object->OriginalParms = *light;
1957 switch (light->type)
1959 case WINED3DLIGHT_POINT:
1961 object->lightPosn[0] = light->position.x;
1962 object->lightPosn[1] = light->position.y;
1963 object->lightPosn[2] = light->position.z;
1964 object->lightPosn[3] = 1.0f;
1965 object->cutoff = 180.0f;
1969 case WINED3DLIGHT_DIRECTIONAL:
1971 object->lightPosn[0] = -light->direction.x;
1972 object->lightPosn[1] = -light->direction.y;
1973 object->lightPosn[2] = -light->direction.z;
1974 object->lightPosn[3] = 0.0f;
1975 object->exponent = 0.0f;
1976 object->cutoff = 180.0f;
1979 case WINED3DLIGHT_SPOT:
1981 object->lightPosn[0] = light->position.x;
1982 object->lightPosn[1] = light->position.y;
1983 object->lightPosn[2] = light->position.z;
1984 object->lightPosn[3] = 1.0f;
1987 object->lightDirn[0] = light->direction.x;
1988 object->lightDirn[1] = light->direction.y;
1989 object->lightDirn[2] = light->direction.z;
1990 object->lightDirn[3] = 1.0f;
1992 /* opengl-ish and d3d-ish spot lights use too different models
1993 * for the light "intensity" as a function of the angle towards
1994 * the main light direction, so we only can approximate very
1995 * roughly. However, spot lights are rather rarely used in games
1996 * (if ever used at all). Furthermore if still used, probably
1997 * nobody pays attention to such details. */
1998 if (!light->falloff)
2000 /* Falloff = 0 is easy, because d3d's and opengl's spot light
2001 * equations have the falloff resp. exponent parameter as an
2002 * exponent, so the spot light lighting will always be 1.0 for
2003 * both of them, and we don't have to care for the rest of the
2004 * rather complex calculation. */
2005 object->exponent = 0.0f;
2009 rho = light->theta + (light->phi - light->theta) / (2 * light->falloff);
2012 object->exponent = -0.3f / logf(cosf(rho / 2));
2015 if (object->exponent > 128.0f)
2016 object->exponent = 128.0f;
2018 object->cutoff = (float)(light->phi * 90 / M_PI);
2023 FIXME("Unrecognized light type %#x.\n", light->type);
2026 /* Update the live definitions if the light is currently assigned a glIndex. */
2027 if (object->glIndex != -1 && !device->isRecordingState)
2028 device_invalidate_state(device, STATE_ACTIVELIGHT(object->glIndex));
2033 HRESULT CDECL wined3d_device_get_light(const struct wined3d_device *device,
2034 UINT light_idx, struct wined3d_light *light)
2036 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2037 struct wined3d_light_info *light_info = NULL;
2040 TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
2042 LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
2044 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2045 if (light_info->OriginalIndex == light_idx)
2052 TRACE("Light information requested but light not defined\n");
2053 return WINED3DERR_INVALIDCALL;
2056 *light = light_info->OriginalParms;
2060 HRESULT CDECL wined3d_device_set_light_enable(struct wined3d_device *device, UINT light_idx, BOOL enable)
2062 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2063 struct wined3d_light_info *light_info = NULL;
2066 TRACE("device %p, light_idx %u, enable %#x.\n", device, light_idx, enable);
2068 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2070 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2071 if (light_info->OriginalIndex == light_idx)
2075 TRACE("Found light %p.\n", light_info);
2077 /* Special case - enabling an undefined light creates one with a strict set of parameters. */
2080 TRACE("Light enabled requested but light not defined, so defining one!\n");
2081 wined3d_device_set_light(device, light_idx, &WINED3D_default_light);
2083 /* Search for it again! Should be fairly quick as near head of list. */
2084 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2086 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2087 if (light_info->OriginalIndex == light_idx)
2093 FIXME("Adding default lights has failed dismally\n");
2094 return WINED3DERR_INVALIDCALL;
2100 if (light_info->glIndex != -1)
2102 if (!device->isRecordingState)
2103 device_invalidate_state(device, STATE_ACTIVELIGHT(light_info->glIndex));
2105 device->updateStateBlock->state.lights[light_info->glIndex] = NULL;
2106 light_info->glIndex = -1;
2110 TRACE("Light already disabled, nothing to do\n");
2112 light_info->enabled = FALSE;
2116 light_info->enabled = TRUE;
2117 if (light_info->glIndex != -1)
2119 TRACE("Nothing to do as light was enabled\n");
2124 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2125 /* Find a free GL light. */
2126 for (i = 0; i < gl_info->limits.lights; ++i)
2128 if (!device->updateStateBlock->state.lights[i])
2130 device->updateStateBlock->state.lights[i] = light_info;
2131 light_info->glIndex = i;
2135 if (light_info->glIndex == -1)
2137 /* Our tests show that Windows returns D3D_OK in this situation, even with
2138 * D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE devices. This
2139 * is consistent among ddraw, d3d8 and d3d9. GetLightEnable returns TRUE
2140 * as well for those lights.
2142 * TODO: Test how this affects rendering. */
2143 WARN("Too many concurrently active lights\n");
2147 /* i == light_info->glIndex */
2148 if (!device->isRecordingState)
2149 device_invalidate_state(device, STATE_ACTIVELIGHT(i));
2156 HRESULT CDECL wined3d_device_get_light_enable(const struct wined3d_device *device, UINT light_idx, BOOL *enable)
2158 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2159 struct wined3d_light_info *light_info = NULL;
2162 TRACE("device %p, light_idx %u, enable %p.\n", device, light_idx, enable);
2164 LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
2166 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2167 if (light_info->OriginalIndex == light_idx)
2174 TRACE("Light enabled state requested but light not defined.\n");
2175 return WINED3DERR_INVALIDCALL;
2177 /* true is 128 according to SetLightEnable */
2178 *enable = light_info->enabled ? 128 : 0;
2182 HRESULT CDECL wined3d_device_set_clip_plane(struct wined3d_device *device, UINT plane_idx, const float *plane)
2184 TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2186 /* Validate plane_idx. */
2187 if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2189 TRACE("Application has requested clipplane this device doesn't support.\n");
2190 return WINED3DERR_INVALIDCALL;
2193 device->updateStateBlock->changed.clipplane |= 1 << plane_idx;
2195 if (device->updateStateBlock->state.clip_planes[plane_idx][0] == plane[0]
2196 && device->updateStateBlock->state.clip_planes[plane_idx][1] == plane[1]
2197 && device->updateStateBlock->state.clip_planes[plane_idx][2] == plane[2]
2198 && device->updateStateBlock->state.clip_planes[plane_idx][3] == plane[3])
2200 TRACE("Application is setting old values over, nothing to do.\n");
2204 device->updateStateBlock->state.clip_planes[plane_idx][0] = plane[0];
2205 device->updateStateBlock->state.clip_planes[plane_idx][1] = plane[1];
2206 device->updateStateBlock->state.clip_planes[plane_idx][2] = plane[2];
2207 device->updateStateBlock->state.clip_planes[plane_idx][3] = plane[3];
2209 /* Handle recording of state blocks. */
2210 if (device->isRecordingState)
2212 TRACE("Recording... not performing anything.\n");
2216 device_invalidate_state(device, STATE_CLIPPLANE(plane_idx));
2221 HRESULT CDECL wined3d_device_get_clip_plane(const struct wined3d_device *device, UINT plane_idx, float *plane)
2223 TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2225 /* Validate plane_idx. */
2226 if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2228 TRACE("Application has requested clipplane this device doesn't support.\n");
2229 return WINED3DERR_INVALIDCALL;
2232 plane[0] = (float)device->stateBlock->state.clip_planes[plane_idx][0];
2233 plane[1] = (float)device->stateBlock->state.clip_planes[plane_idx][1];
2234 plane[2] = (float)device->stateBlock->state.clip_planes[plane_idx][2];
2235 plane[3] = (float)device->stateBlock->state.clip_planes[plane_idx][3];
2240 HRESULT CDECL wined3d_device_set_clip_status(struct wined3d_device *device,
2241 const struct wined3d_clip_status *clip_status)
2243 FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2246 return WINED3DERR_INVALIDCALL;
2251 HRESULT CDECL wined3d_device_get_clip_status(const struct wined3d_device *device,
2252 struct wined3d_clip_status *clip_status)
2254 FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2257 return WINED3DERR_INVALIDCALL;
2262 HRESULT CDECL wined3d_device_set_material(struct wined3d_device *device, const struct wined3d_material *material)
2264 TRACE("device %p, material %p.\n", device, material);
2266 device->updateStateBlock->changed.material = TRUE;
2267 device->updateStateBlock->state.material = *material;
2269 /* Handle recording of state blocks */
2270 if (device->isRecordingState)
2272 TRACE("Recording... not performing anything.\n");
2276 device_invalidate_state(device, STATE_MATERIAL);
2281 HRESULT CDECL wined3d_device_get_material(const struct wined3d_device *device, struct wined3d_material *material)
2283 TRACE("device %p, material %p.\n", device, material);
2285 *material = device->updateStateBlock->state.material;
2287 TRACE("diffuse {%.8e, %.8e, %.8e, %.8e}\n",
2288 material->diffuse.r, material->diffuse.g,
2289 material->diffuse.b, material->diffuse.a);
2290 TRACE("ambient {%.8e, %.8e, %.8e, %.8e}\n",
2291 material->ambient.r, material->ambient.g,
2292 material->ambient.b, material->ambient.a);
2293 TRACE("specular {%.8e, %.8e, %.8e, %.8e}\n",
2294 material->specular.r, material->specular.g,
2295 material->specular.b, material->specular.a);
2296 TRACE("emissive {%.8e, %.8e, %.8e, %.8e}\n",
2297 material->emissive.r, material->emissive.g,
2298 material->emissive.b, material->emissive.a);
2299 TRACE("power %.8e.\n", material->power);
2304 HRESULT CDECL wined3d_device_set_index_buffer(struct wined3d_device *device,
2305 struct wined3d_buffer *buffer, enum wined3d_format_id format_id)
2307 struct wined3d_buffer *prev_buffer;
2309 TRACE("device %p, buffer %p, format %s.\n",
2310 device, buffer, debug_d3dformat(format_id));
2312 prev_buffer = device->updateStateBlock->state.index_buffer;
2314 device->updateStateBlock->changed.indices = TRUE;
2315 device->updateStateBlock->state.index_buffer = buffer;
2316 device->updateStateBlock->state.index_format = format_id;
2318 /* Handle recording of state blocks. */
2319 if (device->isRecordingState)
2321 TRACE("Recording... not performing anything.\n");
2323 wined3d_buffer_incref(buffer);
2325 wined3d_buffer_decref(prev_buffer);
2329 if (prev_buffer != buffer)
2331 device_invalidate_state(device, STATE_INDEXBUFFER);
2334 InterlockedIncrement(&buffer->bind_count);
2335 wined3d_buffer_incref(buffer);
2339 InterlockedDecrement(&prev_buffer->bind_count);
2340 wined3d_buffer_decref(prev_buffer);
2347 HRESULT CDECL wined3d_device_get_index_buffer(const struct wined3d_device *device, struct wined3d_buffer **buffer)
2349 TRACE("device %p, buffer %p.\n", device, buffer);
2351 *buffer = device->stateBlock->state.index_buffer;
2354 wined3d_buffer_incref(*buffer);
2356 TRACE("Returning %p.\n", *buffer);
2361 /* Method to offer d3d9 a simple way to set the base vertex index without messing with the index buffer */
2362 HRESULT CDECL wined3d_device_set_base_vertex_index(struct wined3d_device *device, INT base_index)
2364 TRACE("device %p, base_index %d.\n", device, base_index);
2366 if (device->updateStateBlock->state.base_vertex_index == base_index)
2368 TRACE("Application is setting the old value over, nothing to do\n");
2372 device->updateStateBlock->state.base_vertex_index = base_index;
2374 if (device->isRecordingState)
2376 TRACE("Recording... not performing anything\n");
2382 INT CDECL wined3d_device_get_base_vertex_index(const struct wined3d_device *device)
2384 TRACE("device %p.\n", device);
2386 return device->stateBlock->state.base_vertex_index;
2389 HRESULT CDECL wined3d_device_set_viewport(struct wined3d_device *device, const struct wined3d_viewport *viewport)
2391 TRACE("device %p, viewport %p.\n", device, viewport);
2392 TRACE("x %u, y %u, w %u, h %u, min_z %.8e, max_z %.8e.\n",
2393 viewport->x, viewport->y, viewport->width, viewport->height, viewport->min_z, viewport->max_z);
2395 device->updateStateBlock->changed.viewport = TRUE;
2396 device->updateStateBlock->state.viewport = *viewport;
2398 /* Handle recording of state blocks */
2399 if (device->isRecordingState)
2401 TRACE("Recording... not performing anything\n");
2405 device_invalidate_state(device, STATE_VIEWPORT);
2410 HRESULT CDECL wined3d_device_get_viewport(const struct wined3d_device *device, struct wined3d_viewport *viewport)
2412 TRACE("device %p, viewport %p.\n", device, viewport);
2414 *viewport = device->stateBlock->state.viewport;
2419 HRESULT CDECL wined3d_device_set_render_state(struct wined3d_device *device,
2420 WINED3DRENDERSTATETYPE state, DWORD value)
2422 DWORD old_value = device->stateBlock->state.render_states[state];
2424 TRACE("device %p, state %s (%#x), value %#x.\n", device, debug_d3drenderstate(state), state, value);
2426 device->updateStateBlock->changed.renderState[state >> 5] |= 1 << (state & 0x1f);
2427 device->updateStateBlock->state.render_states[state] = value;
2429 /* Handle recording of state blocks. */
2430 if (device->isRecordingState)
2432 TRACE("Recording... not performing anything.\n");
2436 /* Compared here and not before the assignment to allow proper stateblock recording. */
2437 if (value == old_value)
2438 TRACE("Application is setting the old value over, nothing to do.\n");
2440 device_invalidate_state(device, STATE_RENDER(state));
2445 HRESULT CDECL wined3d_device_get_render_state(const struct wined3d_device *device,
2446 WINED3DRENDERSTATETYPE state, DWORD *value)
2448 TRACE("device %p, state %s (%#x), value %p.\n", device, debug_d3drenderstate(state), state, value);
2450 *value = device->stateBlock->state.render_states[state];
2455 HRESULT CDECL wined3d_device_set_sampler_state(struct wined3d_device *device,
2456 UINT sampler_idx, WINED3DSAMPLERSTATETYPE state, DWORD value)
2460 TRACE("device %p, sampler_idx %u, state %s, value %#x.\n",
2461 device, sampler_idx, debug_d3dsamplerstate(state), value);
2463 if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2464 sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2466 if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2467 / sizeof(*device->stateBlock->state.sampler_states))
2469 WARN("Invalid sampler %u.\n", sampler_idx);
2470 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2473 old_value = device->stateBlock->state.sampler_states[sampler_idx][state];
2474 device->updateStateBlock->state.sampler_states[sampler_idx][state] = value;
2475 device->updateStateBlock->changed.samplerState[sampler_idx] |= 1 << state;
2477 /* Handle recording of state blocks. */
2478 if (device->isRecordingState)
2480 TRACE("Recording... not performing anything.\n");
2484 if (old_value == value)
2486 TRACE("Application is setting the old value over, nothing to do.\n");
2490 device_invalidate_state(device, STATE_SAMPLER(sampler_idx));
2495 HRESULT CDECL wined3d_device_get_sampler_state(const struct wined3d_device *device,
2496 UINT sampler_idx, WINED3DSAMPLERSTATETYPE state, DWORD *value)
2498 TRACE("device %p, sampler_idx %u, state %s, value %p.\n",
2499 device, sampler_idx, debug_d3dsamplerstate(state), value);
2501 if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2502 sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2504 if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2505 / sizeof(*device->stateBlock->state.sampler_states))
2507 WARN("Invalid sampler %u.\n", sampler_idx);
2508 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2511 *value = device->stateBlock->state.sampler_states[sampler_idx][state];
2512 TRACE("Returning %#x.\n", *value);
2517 HRESULT CDECL wined3d_device_set_scissor_rect(struct wined3d_device *device, const RECT *rect)
2519 TRACE("device %p, rect %s.\n", device, wine_dbgstr_rect(rect));
2521 device->updateStateBlock->changed.scissorRect = TRUE;
2522 if (EqualRect(&device->updateStateBlock->state.scissor_rect, rect))
2524 TRACE("App is setting the old scissor rectangle over, nothing to do.\n");
2527 CopyRect(&device->updateStateBlock->state.scissor_rect, rect);
2529 if (device->isRecordingState)
2531 TRACE("Recording... not performing anything.\n");
2535 device_invalidate_state(device, STATE_SCISSORRECT);
2540 HRESULT CDECL wined3d_device_get_scissor_rect(const struct wined3d_device *device, RECT *rect)
2542 TRACE("device %p, rect %p.\n", device, rect);
2544 *rect = device->updateStateBlock->state.scissor_rect;
2545 TRACE("Returning rect %s.\n", wine_dbgstr_rect(rect));
2550 HRESULT CDECL wined3d_device_set_vertex_declaration(struct wined3d_device *device,
2551 struct wined3d_vertex_declaration *declaration)
2553 struct wined3d_vertex_declaration *prev = device->updateStateBlock->state.vertex_declaration;
2555 TRACE("device %p, declaration %p.\n", device, declaration);
2558 wined3d_vertex_declaration_incref(declaration);
2560 wined3d_vertex_declaration_decref(prev);
2562 device->updateStateBlock->state.vertex_declaration = declaration;
2563 device->updateStateBlock->changed.vertexDecl = TRUE;
2565 if (device->isRecordingState)
2567 TRACE("Recording... not performing anything.\n");
2570 else if (declaration == prev)
2572 /* Checked after the assignment to allow proper stateblock recording. */
2573 TRACE("Application is setting the old declaration over, nothing to do.\n");
2577 device_invalidate_state(device, STATE_VDECL);
2581 HRESULT CDECL wined3d_device_get_vertex_declaration(const struct wined3d_device *device,
2582 struct wined3d_vertex_declaration **declaration)
2584 TRACE("device %p, declaration %p.\n", device, declaration);
2586 *declaration = device->stateBlock->state.vertex_declaration;
2588 wined3d_vertex_declaration_incref(*declaration);
2593 HRESULT CDECL wined3d_device_set_vertex_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2595 struct wined3d_shader *prev = device->updateStateBlock->state.vertex_shader;
2597 TRACE("device %p, shader %p.\n", device, shader);
2599 device->updateStateBlock->state.vertex_shader = shader;
2600 device->updateStateBlock->changed.vertexShader = TRUE;
2602 if (device->isRecordingState)
2605 wined3d_shader_incref(shader);
2607 wined3d_shader_decref(prev);
2608 TRACE("Recording... not performing anything.\n");
2614 TRACE("Application is setting the old shader over, nothing to do.\n");
2619 wined3d_shader_incref(shader);
2621 wined3d_shader_decref(prev);
2623 device_invalidate_state(device, STATE_VSHADER);
2628 struct wined3d_shader * CDECL wined3d_device_get_vertex_shader(const struct wined3d_device *device)
2630 struct wined3d_shader *shader;
2632 TRACE("device %p.\n", device);
2634 shader = device->stateBlock->state.vertex_shader;
2636 wined3d_shader_incref(shader);
2638 TRACE("Returning %p.\n", shader);
2642 HRESULT CDECL wined3d_device_set_vs_consts_b(struct wined3d_device *device,
2643 UINT start_register, const BOOL *constants, UINT bool_count)
2645 UINT count = min(bool_count, MAX_CONST_B - start_register);
2648 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2649 device, start_register, constants, bool_count);
2651 if (!constants || start_register >= MAX_CONST_B)
2652 return WINED3DERR_INVALIDCALL;
2654 memcpy(&device->updateStateBlock->state.vs_consts_b[start_register], constants, count * sizeof(BOOL));
2655 for (i = 0; i < count; ++i)
2656 TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
2658 for (i = start_register; i < count + start_register; ++i)
2659 device->updateStateBlock->changed.vertexShaderConstantsB |= (1 << i);
2661 if (!device->isRecordingState)
2662 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2667 HRESULT CDECL wined3d_device_get_vs_consts_b(const struct wined3d_device *device,
2668 UINT start_register, BOOL *constants, UINT bool_count)
2670 UINT count = min(bool_count, MAX_CONST_B - start_register);
2672 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2673 device, start_register, constants, bool_count);
2675 if (!constants || start_register >= MAX_CONST_B)
2676 return WINED3DERR_INVALIDCALL;
2678 memcpy(constants, &device->stateBlock->state.vs_consts_b[start_register], count * sizeof(BOOL));
2683 HRESULT CDECL wined3d_device_set_vs_consts_i(struct wined3d_device *device,
2684 UINT start_register, const int *constants, UINT vector4i_count)
2686 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2689 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2690 device, start_register, constants, vector4i_count);
2692 if (!constants || start_register >= MAX_CONST_I)
2693 return WINED3DERR_INVALIDCALL;
2695 memcpy(&device->updateStateBlock->state.vs_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
2696 for (i = 0; i < count; ++i)
2697 TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
2698 constants[i * 4], constants[i * 4 + 1],
2699 constants[i * 4 + 2], constants[i * 4 + 3]);
2701 for (i = start_register; i < count + start_register; ++i)
2702 device->updateStateBlock->changed.vertexShaderConstantsI |= (1 << i);
2704 if (!device->isRecordingState)
2705 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2710 HRESULT CDECL wined3d_device_get_vs_consts_i(const struct wined3d_device *device,
2711 UINT start_register, int *constants, UINT vector4i_count)
2713 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2715 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2716 device, start_register, constants, vector4i_count);
2718 if (!constants || start_register >= MAX_CONST_I)
2719 return WINED3DERR_INVALIDCALL;
2721 memcpy(constants, &device->stateBlock->state.vs_consts_i[start_register * 4], count * sizeof(int) * 4);
2725 HRESULT CDECL wined3d_device_set_vs_consts_f(struct wined3d_device *device,
2726 UINT start_register, const float *constants, UINT vector4f_count)
2730 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2731 device, start_register, constants, vector4f_count);
2733 /* Specifically test start_register > limit to catch MAX_UINT overflows
2734 * when adding start_register + vector4f_count. */
2736 || start_register + vector4f_count > device->d3d_vshader_constantF
2737 || start_register > device->d3d_vshader_constantF)
2738 return WINED3DERR_INVALIDCALL;
2740 memcpy(&device->updateStateBlock->state.vs_consts_f[start_register * 4],
2741 constants, vector4f_count * sizeof(float) * 4);
2744 for (i = 0; i < vector4f_count; ++i)
2745 TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
2746 constants[i * 4], constants[i * 4 + 1],
2747 constants[i * 4 + 2], constants[i * 4 + 3]);
2750 if (!device->isRecordingState)
2752 device->shader_backend->shader_update_float_vertex_constants(device, start_register, vector4f_count);
2753 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2756 memset(device->updateStateBlock->changed.vertexShaderConstantsF + start_register, 1,
2757 sizeof(*device->updateStateBlock->changed.vertexShaderConstantsF) * vector4f_count);
2762 HRESULT CDECL wined3d_device_get_vs_consts_f(const struct wined3d_device *device,
2763 UINT start_register, float *constants, UINT vector4f_count)
2765 int count = min(vector4f_count, device->d3d_vshader_constantF - start_register);
2767 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2768 device, start_register, constants, vector4f_count);
2770 if (!constants || count < 0)
2771 return WINED3DERR_INVALIDCALL;
2773 memcpy(constants, &device->stateBlock->state.vs_consts_f[start_register * 4], count * sizeof(float) * 4);
2778 static void device_invalidate_texture_stage(const struct wined3d_device *device, DWORD stage)
2782 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2784 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, i));
2788 static void device_map_stage(struct wined3d_device *device, DWORD stage, DWORD unit)
2790 DWORD i = device->rev_tex_unit_map[unit];
2791 DWORD j = device->texUnitMap[stage];
2793 device->texUnitMap[stage] = unit;
2794 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2795 device->texUnitMap[i] = WINED3D_UNMAPPED_STAGE;
2797 device->rev_tex_unit_map[unit] = stage;
2798 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2799 device->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2802 static void device_update_fixed_function_usage_map(struct wined3d_device *device)
2806 device->fixed_function_usage_map = 0;
2807 for (i = 0; i < MAX_TEXTURES; ++i)
2809 const struct wined3d_state *state = &device->stateBlock->state;
2810 WINED3DTEXTUREOP color_op = state->texture_states[i][WINED3DTSS_COLOROP];
2811 WINED3DTEXTUREOP alpha_op = state->texture_states[i][WINED3DTSS_ALPHAOP];
2812 DWORD color_arg1 = state->texture_states[i][WINED3DTSS_COLORARG1] & WINED3DTA_SELECTMASK;
2813 DWORD color_arg2 = state->texture_states[i][WINED3DTSS_COLORARG2] & WINED3DTA_SELECTMASK;
2814 DWORD color_arg3 = state->texture_states[i][WINED3DTSS_COLORARG0] & WINED3DTA_SELECTMASK;
2815 DWORD alpha_arg1 = state->texture_states[i][WINED3DTSS_ALPHAARG1] & WINED3DTA_SELECTMASK;
2816 DWORD alpha_arg2 = state->texture_states[i][WINED3DTSS_ALPHAARG2] & WINED3DTA_SELECTMASK;
2817 DWORD alpha_arg3 = state->texture_states[i][WINED3DTSS_ALPHAARG0] & WINED3DTA_SELECTMASK;
2819 if (color_op == WINED3DTOP_DISABLE) {
2820 /* Not used, and disable higher stages */
2824 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3DTOP_SELECTARG2)
2825 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3DTOP_SELECTARG1)
2826 || ((color_arg3 == WINED3DTA_TEXTURE)
2827 && (color_op == WINED3DTOP_MULTIPLYADD || color_op == WINED3DTOP_LERP))
2828 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3DTOP_SELECTARG2)
2829 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3DTOP_SELECTARG1)
2830 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2831 && (alpha_op == WINED3DTOP_MULTIPLYADD || alpha_op == WINED3DTOP_LERP)))
2832 device->fixed_function_usage_map |= (1 << i);
2834 if ((color_op == WINED3DTOP_BUMPENVMAP || color_op == WINED3DTOP_BUMPENVMAPLUMINANCE) && i < MAX_TEXTURES - 1)
2835 device->fixed_function_usage_map |= (1 << (i + 1));
2839 static void device_map_fixed_function_samplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2841 unsigned int i, tex;
2844 device_update_fixed_function_usage_map(device);
2845 ffu_map = device->fixed_function_usage_map;
2847 if (device->max_ffp_textures == gl_info->limits.texture_stages
2848 || device->stateBlock->state.lowest_disabled_stage <= device->max_ffp_textures)
2850 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2852 if (!(ffu_map & 1)) continue;
2854 if (device->texUnitMap[i] != i)
2856 device_map_stage(device, i, i);
2857 device_invalidate_state(device, STATE_SAMPLER(i));
2858 device_invalidate_texture_stage(device, i);
2864 /* Now work out the mapping */
2866 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2868 if (!(ffu_map & 1)) continue;
2870 if (device->texUnitMap[i] != tex)
2872 device_map_stage(device, i, tex);
2873 device_invalidate_state(device, STATE_SAMPLER(i));
2874 device_invalidate_texture_stage(device, i);
2881 static void device_map_psamplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2883 const enum wined3d_sampler_texture_type *sampler_type =
2884 device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2887 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2889 if (sampler_type[i] && device->texUnitMap[i] != i)
2891 device_map_stage(device, i, i);
2892 device_invalidate_state(device, STATE_SAMPLER(i));
2893 if (i < gl_info->limits.texture_stages)
2894 device_invalidate_texture_stage(device, i);
2899 static BOOL device_unit_free_for_vs(const struct wined3d_device *device,
2900 const enum wined3d_sampler_texture_type *pshader_sampler_tokens,
2901 const enum wined3d_sampler_texture_type *vshader_sampler_tokens, DWORD unit)
2903 DWORD current_mapping = device->rev_tex_unit_map[unit];
2905 /* Not currently used */
2906 if (current_mapping == WINED3D_UNMAPPED_STAGE) return TRUE;
2908 if (current_mapping < MAX_FRAGMENT_SAMPLERS) {
2909 /* Used by a fragment sampler */
2911 if (!pshader_sampler_tokens) {
2912 /* No pixel shader, check fixed function */
2913 return current_mapping >= MAX_TEXTURES || !(device->fixed_function_usage_map & (1 << current_mapping));
2916 /* Pixel shader, check the shader's sampler map */
2917 return !pshader_sampler_tokens[current_mapping];
2920 /* Used by a vertex sampler */
2921 return !vshader_sampler_tokens[current_mapping - MAX_FRAGMENT_SAMPLERS];
2924 static void device_map_vsamplers(struct wined3d_device *device, BOOL ps, const struct wined3d_gl_info *gl_info)
2926 const enum wined3d_sampler_texture_type *vshader_sampler_type =
2927 device->stateBlock->state.vertex_shader->reg_maps.sampler_type;
2928 const enum wined3d_sampler_texture_type *pshader_sampler_type = NULL;
2929 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2934 /* Note that we only care if a sampler is sampled or not, not the sampler's specific type.
2935 * Otherwise we'd need to call shader_update_samplers() here for 1.x pixelshaders. */
2936 pshader_sampler_type = device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2939 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
2940 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2941 if (vshader_sampler_type[i])
2943 if (device->texUnitMap[vsampler_idx] != WINED3D_UNMAPPED_STAGE)
2945 /* Already mapped somewhere */
2951 if (device_unit_free_for_vs(device, pshader_sampler_type, vshader_sampler_type, start))
2953 device_map_stage(device, vsampler_idx, start);
2954 device_invalidate_state(device, STATE_SAMPLER(vsampler_idx));
2966 void device_update_tex_unit_map(struct wined3d_device *device)
2968 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2969 const struct wined3d_state *state = &device->stateBlock->state;
2970 BOOL vs = use_vs(state);
2971 BOOL ps = use_ps(state);
2974 * -> Pixel shaders need a 1:1 map. In theory the shader input could be mapped too, but
2975 * that would be really messy and require shader recompilation
2976 * -> When the mapping of a stage is changed, sampler and ALL texture stage states have
2977 * to be reset. Because of that try to work with a 1:1 mapping as much as possible
2980 device_map_psamplers(device, gl_info);
2982 device_map_fixed_function_samplers(device, gl_info);
2985 device_map_vsamplers(device, ps, gl_info);
2988 HRESULT CDECL wined3d_device_set_pixel_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2990 struct wined3d_shader *prev = device->updateStateBlock->state.pixel_shader;
2992 TRACE("device %p, shader %p.\n", device, shader);
2994 device->updateStateBlock->state.pixel_shader = shader;
2995 device->updateStateBlock->changed.pixelShader = TRUE;
2997 if (device->isRecordingState)
3000 wined3d_shader_incref(shader);
3002 wined3d_shader_decref(prev);
3003 TRACE("Recording... not performing anything.\n");
3009 TRACE("Application is setting the old shader over, nothing to do.\n");
3014 wined3d_shader_incref(shader);
3016 wined3d_shader_decref(prev);
3018 device_invalidate_state(device, STATE_PIXELSHADER);
3023 struct wined3d_shader * CDECL wined3d_device_get_pixel_shader(const struct wined3d_device *device)
3025 struct wined3d_shader *shader;
3027 TRACE("device %p.\n", device);
3029 shader = device->stateBlock->state.pixel_shader;
3031 wined3d_shader_incref(shader);
3033 TRACE("Returning %p.\n", shader);
3037 HRESULT CDECL wined3d_device_set_ps_consts_b(struct wined3d_device *device,
3038 UINT start_register, const BOOL *constants, UINT bool_count)
3040 UINT count = min(bool_count, MAX_CONST_B - start_register);
3043 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
3044 device, start_register, constants, bool_count);
3046 if (!constants || start_register >= MAX_CONST_B)
3047 return WINED3DERR_INVALIDCALL;
3049 memcpy(&device->updateStateBlock->state.ps_consts_b[start_register], constants, count * sizeof(BOOL));
3050 for (i = 0; i < count; ++i)
3051 TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
3053 for (i = start_register; i < count + start_register; ++i)
3054 device->updateStateBlock->changed.pixelShaderConstantsB |= (1 << i);
3056 if (!device->isRecordingState)
3057 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3062 HRESULT CDECL wined3d_device_get_ps_consts_b(const struct wined3d_device *device,
3063 UINT start_register, BOOL *constants, UINT bool_count)
3065 UINT count = min(bool_count, MAX_CONST_B - start_register);
3067 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
3068 device, start_register, constants, bool_count);
3070 if (!constants || start_register >= MAX_CONST_B)
3071 return WINED3DERR_INVALIDCALL;
3073 memcpy(constants, &device->stateBlock->state.ps_consts_b[start_register], count * sizeof(BOOL));
3078 HRESULT CDECL wined3d_device_set_ps_consts_i(struct wined3d_device *device,
3079 UINT start_register, const int *constants, UINT vector4i_count)
3081 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
3084 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
3085 device, start_register, constants, vector4i_count);
3087 if (!constants || start_register >= MAX_CONST_I)
3088 return WINED3DERR_INVALIDCALL;
3090 memcpy(&device->updateStateBlock->state.ps_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
3091 for (i = 0; i < count; ++i)
3092 TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
3093 constants[i * 4], constants[i * 4 + 1],
3094 constants[i * 4 + 2], constants[i * 4 + 3]);
3096 for (i = start_register; i < count + start_register; ++i)
3097 device->updateStateBlock->changed.pixelShaderConstantsI |= (1 << i);
3099 if (!device->isRecordingState)
3100 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3105 HRESULT CDECL wined3d_device_get_ps_consts_i(const struct wined3d_device *device,
3106 UINT start_register, int *constants, UINT vector4i_count)
3108 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
3110 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
3111 device, start_register, constants, vector4i_count);
3113 if (!constants || start_register >= MAX_CONST_I)
3114 return WINED3DERR_INVALIDCALL;
3116 memcpy(constants, &device->stateBlock->state.ps_consts_i[start_register * 4], count * sizeof(int) * 4);
3121 HRESULT CDECL wined3d_device_set_ps_consts_f(struct wined3d_device *device,
3122 UINT start_register, const float *constants, UINT vector4f_count)
3126 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3127 device, start_register, constants, vector4f_count);
3129 /* Specifically test start_register > limit to catch MAX_UINT overflows
3130 * when adding start_register + vector4f_count. */
3132 || start_register + vector4f_count > device->d3d_pshader_constantF
3133 || start_register > device->d3d_pshader_constantF)
3134 return WINED3DERR_INVALIDCALL;
3136 memcpy(&device->updateStateBlock->state.ps_consts_f[start_register * 4],
3137 constants, vector4f_count * sizeof(float) * 4);
3140 for (i = 0; i < vector4f_count; ++i)
3141 TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
3142 constants[i * 4], constants[i * 4 + 1],
3143 constants[i * 4 + 2], constants[i * 4 + 3]);
3146 if (!device->isRecordingState)
3148 device->shader_backend->shader_update_float_pixel_constants(device, start_register, vector4f_count);
3149 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3152 memset(device->updateStateBlock->changed.pixelShaderConstantsF + start_register, 1,
3153 sizeof(*device->updateStateBlock->changed.pixelShaderConstantsF) * vector4f_count);
3158 HRESULT CDECL wined3d_device_get_ps_consts_f(const struct wined3d_device *device,
3159 UINT start_register, float *constants, UINT vector4f_count)
3161 int count = min(vector4f_count, device->d3d_pshader_constantF - start_register);
3163 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3164 device, start_register, constants, vector4f_count);
3166 if (!constants || count < 0)
3167 return WINED3DERR_INVALIDCALL;
3169 memcpy(constants, &device->stateBlock->state.ps_consts_f[start_register * 4], count * sizeof(float) * 4);
3174 /* Context activation is done by the caller. */
3175 /* Do not call while under the GL lock. */
3176 #define copy_and_next(dest, src, size) memcpy(dest, src, size); dest += (size)
3177 static HRESULT process_vertices_strided(const struct wined3d_device *device, DWORD dwDestIndex, DWORD dwCount,
3178 const struct wined3d_stream_info *stream_info, struct wined3d_buffer *dest, DWORD flags,
3181 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3182 char *dest_ptr, *dest_conv = NULL, *dest_conv_addr = NULL;
3183 struct wined3d_matrix mat, proj_mat, view_mat, world_mat;
3184 struct wined3d_viewport vp;
3189 if (stream_info->use_map & (1 << WINED3D_FFP_NORMAL))
3191 WARN(" lighting state not saved yet... Some strange stuff may happen !\n");
3194 if (!(stream_info->use_map & (1 << WINED3D_FFP_POSITION)))
3196 ERR("Source has no position mask\n");
3197 return WINED3DERR_INVALIDCALL;
3200 if (!dest->resource.allocatedMemory)
3201 buffer_get_sysmem(dest, gl_info);
3203 /* Get a pointer into the destination vbo(create one if none exists) and
3204 * write correct opengl data into it. It's cheap and allows us to run drawStridedFast
3206 if (!dest->buffer_object && gl_info->supported[ARB_VERTEX_BUFFER_OBJECT])
3208 dest->flags |= WINED3D_BUFFER_CREATEBO;
3209 wined3d_buffer_preload(dest);
3212 if (dest->buffer_object)
3214 unsigned char extrabytes = 0;
3215 /* If the destination vertex buffer has D3DFVF_XYZ position(non-rhw), native d3d writes RHW position, where the RHW
3216 * gets written into the 4 bytes after the Z position. In the case of a dest buffer that only has D3DFVF_XYZ data,
3217 * this may write 4 extra bytes beyond the area that should be written
3219 if(DestFVF == WINED3DFVF_XYZ) extrabytes = 4;
3220 dest_conv_addr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCount * get_flexible_vertex_size(DestFVF) + extrabytes);
3221 if(!dest_conv_addr) {
3222 ERR("Out of memory\n");
3223 /* Continue without storing converted vertices */
3225 dest_conv = dest_conv_addr;
3228 if (device->stateBlock->state.render_states[WINED3DRS_CLIPPING])
3230 static BOOL warned = FALSE;
3232 * The clipping code is not quite correct. Some things need
3233 * to be checked against IDirect3DDevice3 (!), d3d8 and d3d9,
3234 * so disable clipping for now.
3235 * (The graphics in Half-Life are broken, and my processvertices
3236 * test crashes with IDirect3DDevice3)
3242 FIXME("Clipping is broken and disabled for now\n");
3244 } else doClip = FALSE;
3245 dest_ptr = ((char *)buffer_get_sysmem(dest, gl_info)) + dwDestIndex * get_flexible_vertex_size(DestFVF);
3247 wined3d_device_get_transform(device, WINED3DTS_VIEW, &view_mat);
3248 wined3d_device_get_transform(device, WINED3DTS_PROJECTION, &proj_mat);
3249 wined3d_device_get_transform(device, WINED3DTS_WORLDMATRIX(0), &world_mat);
3251 TRACE("View mat:\n");
3252 TRACE("%f %f %f %f\n", view_mat.u.s._11, view_mat.u.s._12, view_mat.u.s._13, view_mat.u.s._14);
3253 TRACE("%f %f %f %f\n", view_mat.u.s._21, view_mat.u.s._22, view_mat.u.s._23, view_mat.u.s._24);
3254 TRACE("%f %f %f %f\n", view_mat.u.s._31, view_mat.u.s._32, view_mat.u.s._33, view_mat.u.s._34);
3255 TRACE("%f %f %f %f\n", view_mat.u.s._41, view_mat.u.s._42, view_mat.u.s._43, view_mat.u.s._44);
3257 TRACE("Proj mat:\n");
3258 TRACE("%f %f %f %f\n", proj_mat.u.s._11, proj_mat.u.s._12, proj_mat.u.s._13, proj_mat.u.s._14);
3259 TRACE("%f %f %f %f\n", proj_mat.u.s._21, proj_mat.u.s._22, proj_mat.u.s._23, proj_mat.u.s._24);
3260 TRACE("%f %f %f %f\n", proj_mat.u.s._31, proj_mat.u.s._32, proj_mat.u.s._33, proj_mat.u.s._34);
3261 TRACE("%f %f %f %f\n", proj_mat.u.s._41, proj_mat.u.s._42, proj_mat.u.s._43, proj_mat.u.s._44);
3263 TRACE("World mat:\n");
3264 TRACE("%f %f %f %f\n", world_mat.u.s._11, world_mat.u.s._12, world_mat.u.s._13, world_mat.u.s._14);
3265 TRACE("%f %f %f %f\n", world_mat.u.s._21, world_mat.u.s._22, world_mat.u.s._23, world_mat.u.s._24);
3266 TRACE("%f %f %f %f\n", world_mat.u.s._31, world_mat.u.s._32, world_mat.u.s._33, world_mat.u.s._34);
3267 TRACE("%f %f %f %f\n", world_mat.u.s._41, world_mat.u.s._42, world_mat.u.s._43, world_mat.u.s._44);
3269 /* Get the viewport */
3270 wined3d_device_get_viewport(device, &vp);
3271 TRACE("viewport x %u, y %u, width %u, height %u, min_z %.8e, max_z %.8e.\n",
3272 vp.x, vp.y, vp.width, vp.height, vp.min_z, vp.max_z);
3274 multiply_matrix(&mat,&view_mat,&world_mat);
3275 multiply_matrix(&mat,&proj_mat,&mat);
3277 numTextures = (DestFVF & WINED3DFVF_TEXCOUNT_MASK) >> WINED3DFVF_TEXCOUNT_SHIFT;
3279 for (i = 0; i < dwCount; i+= 1) {
3280 unsigned int tex_index;
3282 if ( ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZ ) ||
3283 ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW ) ) {
3284 /* The position first */
3285 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_POSITION];
3286 const float *p = (const float *)(element->data.addr + i * element->stride);
3288 TRACE("In: ( %06.2f %06.2f %06.2f )\n", p[0], p[1], p[2]);
3290 /* Multiplication with world, view and projection matrix */
3291 x = (p[0] * mat.u.s._11) + (p[1] * mat.u.s._21) + (p[2] * mat.u.s._31) + (1.0f * mat.u.s._41);
3292 y = (p[0] * mat.u.s._12) + (p[1] * mat.u.s._22) + (p[2] * mat.u.s._32) + (1.0f * mat.u.s._42);
3293 z = (p[0] * mat.u.s._13) + (p[1] * mat.u.s._23) + (p[2] * mat.u.s._33) + (1.0f * mat.u.s._43);
3294 rhw = (p[0] * mat.u.s._14) + (p[1] * mat.u.s._24) + (p[2] * mat.u.s._34) + (1.0f * mat.u.s._44);
3296 TRACE("x=%f y=%f z=%f rhw=%f\n", x, y, z, rhw);
3298 /* WARNING: The following things are taken from d3d7 and were not yet checked
3299 * against d3d8 or d3d9!
3302 /* Clipping conditions: From msdn
3304 * A vertex is clipped if it does not match the following requirements
3308 * 0 < rhw ( Not in d3d7, but tested in d3d7)
3310 * If clipping is on is determined by the D3DVOP_CLIP flag in D3D7, and
3311 * by the D3DRS_CLIPPING in D3D9(according to the msdn, not checked)
3316 ( (-rhw -eps < x) && (-rhw -eps < y) && ( -eps < z) &&
3317 (x <= rhw + eps) && (y <= rhw + eps ) && (z <= rhw + eps) &&
3320 /* "Normal" viewport transformation (not clipped)
3321 * 1) The values are divided by rhw
3322 * 2) The y axis is negative, so multiply it with -1
3323 * 3) Screen coordinates go from -(Width/2) to +(Width/2) and
3324 * -(Height/2) to +(Height/2). The z range is MinZ to MaxZ
3325 * 4) Multiply x with Width/2 and add Width/2
3326 * 5) The same for the height
3327 * 6) Add the viewpoint X and Y to the 2D coordinates and
3328 * The minimum Z value to z
3329 * 7) rhw = 1 / rhw Reciprocal of Homogeneous W....
3331 * Well, basically it's simply a linear transformation into viewport
3343 z *= vp.max_z - vp.min_z;
3345 x += vp.width / 2 + vp.x;
3346 y += vp.height / 2 + vp.y;
3351 /* That vertex got clipped
3352 * Contrary to OpenGL it is not dropped completely, it just
3353 * undergoes a different calculation.
3355 TRACE("Vertex got clipped\n");
3362 /* Msdn mentions that Direct3D9 keeps a list of clipped vertices
3363 * outside of the main vertex buffer memory. That needs some more
3368 TRACE("Writing (%f %f %f) %f\n", x, y, z, rhw);
3371 ( (float *) dest_ptr)[0] = x;
3372 ( (float *) dest_ptr)[1] = y;
3373 ( (float *) dest_ptr)[2] = z;
3374 ( (float *) dest_ptr)[3] = rhw; /* SIC, see ddraw test! */
3376 dest_ptr += 3 * sizeof(float);
3378 if((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW) {
3379 dest_ptr += sizeof(float);
3384 ( (float *) dest_conv)[0] = x * w;
3385 ( (float *) dest_conv)[1] = y * w;
3386 ( (float *) dest_conv)[2] = z * w;
3387 ( (float *) dest_conv)[3] = w;
3389 dest_conv += 3 * sizeof(float);
3391 if((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW) {
3392 dest_conv += sizeof(float);
3396 if (DestFVF & WINED3DFVF_PSIZE) {
3397 dest_ptr += sizeof(DWORD);
3398 if(dest_conv) dest_conv += sizeof(DWORD);
3400 if (DestFVF & WINED3DFVF_NORMAL)
3402 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_NORMAL];
3403 const float *normal = (const float *)(element->data.addr + i * element->stride);
3404 /* AFAIK this should go into the lighting information */
3405 FIXME("Didn't expect the destination to have a normal\n");
3406 copy_and_next(dest_ptr, normal, 3 * sizeof(float));
3408 copy_and_next(dest_conv, normal, 3 * sizeof(float));
3412 if (DestFVF & WINED3DFVF_DIFFUSE)
3414 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_DIFFUSE];
3415 const DWORD *color_d = (const DWORD *)(element->data.addr + i * element->stride);
3416 if (!(stream_info->use_map & (1 << WINED3D_FFP_DIFFUSE)))
3418 static BOOL warned = FALSE;
3421 ERR("No diffuse color in source, but destination has one\n");
3425 *( (DWORD *) dest_ptr) = 0xffffffff;
3426 dest_ptr += sizeof(DWORD);
3429 *( (DWORD *) dest_conv) = 0xffffffff;
3430 dest_conv += sizeof(DWORD);
3434 copy_and_next(dest_ptr, color_d, sizeof(DWORD));
3436 *( (DWORD *) dest_conv) = (*color_d & 0xff00ff00) ; /* Alpha + green */
3437 *( (DWORD *) dest_conv) |= (*color_d & 0x00ff0000) >> 16; /* Red */
3438 *( (DWORD *) dest_conv) |= (*color_d & 0xff0000ff) << 16; /* Blue */
3439 dest_conv += sizeof(DWORD);
3444 if (DestFVF & WINED3DFVF_SPECULAR)
3446 /* What's the color value in the feedback buffer? */
3447 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_SPECULAR];
3448 const DWORD *color_s = (const DWORD *)(element->data.addr + i * element->stride);
3449 if (!(stream_info->use_map & (1 << WINED3D_FFP_SPECULAR)))
3451 static BOOL warned = FALSE;
3454 ERR("No specular color in source, but destination has one\n");
3458 *( (DWORD *) dest_ptr) = 0xFF000000;
3459 dest_ptr += sizeof(DWORD);
3462 *( (DWORD *) dest_conv) = 0xFF000000;
3463 dest_conv += sizeof(DWORD);
3467 copy_and_next(dest_ptr, color_s, sizeof(DWORD));
3469 *( (DWORD *) dest_conv) = (*color_s & 0xff00ff00) ; /* Alpha + green */
3470 *( (DWORD *) dest_conv) |= (*color_s & 0x00ff0000) >> 16; /* Red */
3471 *( (DWORD *) dest_conv) |= (*color_s & 0xff0000ff) << 16; /* Blue */
3472 dest_conv += sizeof(DWORD);
3477 for (tex_index = 0; tex_index < numTextures; ++tex_index)
3479 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_TEXCOORD0 + tex_index];
3480 const float *tex_coord = (const float *)(element->data.addr + i * element->stride);
3481 if (!(stream_info->use_map & (1 << (WINED3D_FFP_TEXCOORD0 + tex_index))))
3483 ERR("No source texture, but destination requests one\n");
3484 dest_ptr+=GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float);
3485 if(dest_conv) dest_conv += GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float);
3488 copy_and_next(dest_ptr, tex_coord, GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float));
3490 copy_and_next(dest_conv, tex_coord, GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float));
3500 GL_EXTCALL(glBindBufferARB(GL_ARRAY_BUFFER_ARB, dest->buffer_object));
3501 checkGLcall("glBindBufferARB(GL_ARRAY_BUFFER_ARB)");
3502 GL_EXTCALL(glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, dwDestIndex * get_flexible_vertex_size(DestFVF),
3503 dwCount * get_flexible_vertex_size(DestFVF),
3505 checkGLcall("glBufferSubDataARB(GL_ARRAY_BUFFER_ARB)");
3509 HeapFree(GetProcessHeap(), 0, dest_conv_addr);
3514 #undef copy_and_next
3516 /* Do not call while under the GL lock. */
3517 HRESULT CDECL wined3d_device_process_vertices(struct wined3d_device *device,
3518 UINT src_start_idx, UINT dst_idx, UINT vertex_count, struct wined3d_buffer *dst_buffer,
3519 const struct wined3d_vertex_declaration *declaration, DWORD flags, DWORD dst_fvf)
3521 struct wined3d_state *state = &device->stateBlock->state;
3522 BOOL vbo = FALSE, streamWasUP = state->user_stream;
3523 struct wined3d_stream_info stream_info;
3524 const struct wined3d_gl_info *gl_info;
3525 struct wined3d_context *context;
3526 struct wined3d_shader *vs;
3529 TRACE("device %p, src_start_idx %u, dst_idx %u, vertex_count %u, "
3530 "dst_buffer %p, declaration %p, flags %#x, dst_fvf %#x.\n",
3531 device, src_start_idx, dst_idx, vertex_count,
3532 dst_buffer, declaration, flags, dst_fvf);
3535 FIXME("Output vertex declaration not implemented yet.\n");
3537 /* Need any context to write to the vbo. */
3538 context = context_acquire(device, NULL);
3539 gl_info = context->gl_info;
3541 /* ProcessVertices reads from vertex buffers, which have to be assigned.
3542 * DrawPrimitive and DrawPrimitiveUP control the streamIsUP flag, thus
3543 * restore it afterwards. */
3544 vs = state->vertex_shader;
3545 state->vertex_shader = NULL;
3546 state->user_stream = FALSE;
3547 device_stream_info_from_declaration(device, &stream_info, &vbo);
3548 state->user_stream = streamWasUP;
3549 state->vertex_shader = vs;
3551 if (vbo || src_start_idx)
3554 /* ProcessVertices can't convert FROM a vbo, and vertex buffers used to source into ProcessVertices are
3555 * unlikely to ever be used for drawing. Release vbos in those buffers and fix up the stream_info structure
3557 * Also get the start index in, but only loop over all elements if there's something to add at all.
3559 for (i = 0; i < (sizeof(stream_info.elements) / sizeof(*stream_info.elements)); ++i)
3561 struct wined3d_stream_info_element *e;
3563 if (!(stream_info.use_map & (1 << i))) continue;
3565 e = &stream_info.elements[i];
3566 if (e->data.buffer_object)
3568 struct wined3d_buffer *vb = state->streams[e->stream_idx].buffer;
3569 e->data.buffer_object = 0;
3570 e->data.addr = (BYTE *)((ULONG_PTR)e->data.addr + (ULONG_PTR)buffer_get_sysmem(vb, gl_info));
3572 GL_EXTCALL(glDeleteBuffersARB(1, &vb->buffer_object));
3573 vb->buffer_object = 0;
3577 e->data.addr += e->stride * src_start_idx;
3581 hr = process_vertices_strided(device, dst_idx, vertex_count,
3582 &stream_info, dst_buffer, flags, dst_fvf);
3584 context_release(context);
3589 HRESULT CDECL wined3d_device_set_texture_stage_state(struct wined3d_device *device,
3590 UINT stage, WINED3DTEXTURESTAGESTATETYPE state, DWORD value)
3592 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3595 TRACE("device %p, stage %u, state %s, value %#x.\n",
3596 device, stage, debug_d3dtexturestate(state), value);
3598 if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3600 WARN("Invalid state %#x passed.\n", state);
3604 if (stage >= gl_info->limits.texture_stages)
3606 WARN("Attempting to set stage %u which is higher than the max stage %u, ignoring.\n",
3607 stage, gl_info->limits.texture_stages - 1);
3611 old_value = device->updateStateBlock->state.texture_states[stage][state];
3612 device->updateStateBlock->changed.textureState[stage] |= 1 << state;
3613 device->updateStateBlock->state.texture_states[stage][state] = value;
3615 if (device->isRecordingState)
3617 TRACE("Recording... not performing anything.\n");
3621 /* Checked after the assignments to allow proper stateblock recording. */
3622 if (old_value == value)
3624 TRACE("Application is setting the old value over, nothing to do.\n");
3628 if (stage > device->stateBlock->state.lowest_disabled_stage
3629 && device->StateTable[STATE_TEXTURESTAGE(0, state)].representative
3630 == STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP))
3632 /* Colorop change above lowest disabled stage? That won't change
3633 * anything in the GL setup. Changes in other states are important on
3634 * disabled stages too. */
3638 if (state == WINED3DTSS_COLOROP)
3642 if (value == WINED3DTOP_DISABLE && old_value != WINED3DTOP_DISABLE)
3644 /* Previously enabled stage disabled now. Make sure to dirtify
3645 * all enabled stages above stage, they have to be disabled.
3647 * The current stage is dirtified below. */
3648 for (i = stage + 1; i < device->stateBlock->state.lowest_disabled_stage; ++i)
3650 TRACE("Additionally dirtifying stage %u.\n", i);
3651 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP));
3653 device->stateBlock->state.lowest_disabled_stage = stage;
3654 TRACE("New lowest disabled: %u.\n", stage);
3656 else if (value != WINED3DTOP_DISABLE && old_value == WINED3DTOP_DISABLE)
3658 /* Previously disabled stage enabled. Stages above it may need
3659 * enabling. Stage must be lowest_disabled_stage here, if it's
3660 * bigger success is returned above, and stages below the lowest
3661 * disabled stage can't be enabled (because they are enabled
3664 * Again stage stage doesn't need to be dirtified here, it is
3666 for (i = stage + 1; i < gl_info->limits.texture_stages; ++i)
3668 if (device->updateStateBlock->state.texture_states[i][WINED3DTSS_COLOROP] == WINED3DTOP_DISABLE)
3670 TRACE("Additionally dirtifying stage %u due to enable.\n", i);
3671 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP));
3673 device->stateBlock->state.lowest_disabled_stage = i;
3674 TRACE("New lowest disabled: %u.\n", i);
3678 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, state));
3683 HRESULT CDECL wined3d_device_get_texture_stage_state(const struct wined3d_device *device,
3684 UINT stage, WINED3DTEXTURESTAGESTATETYPE state, DWORD *value)
3686 TRACE("device %p, stage %u, state %s, value %p.\n",
3687 device, stage, debug_d3dtexturestate(state), value);
3689 if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3691 WARN("Invalid state %#x passed.\n", state);
3695 *value = device->updateStateBlock->state.texture_states[stage][state];
3696 TRACE("Returning %#x.\n", *value);
3701 HRESULT CDECL wined3d_device_set_texture(struct wined3d_device *device,
3702 UINT stage, struct wined3d_texture *texture)
3704 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3705 struct wined3d_texture *prev;
3707 TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3709 if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3710 stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3712 /* Windows accepts overflowing this array... we do not. */
3713 if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3715 WARN("Ignoring invalid stage %u.\n", stage);
3719 /* SetTexture isn't allowed on textures in WINED3DPOOL_SCRATCH */
3720 if (texture && texture->resource.pool == WINED3DPOOL_SCRATCH)
3722 WARN("Rejecting attempt to set scratch texture.\n");
3723 return WINED3DERR_INVALIDCALL;
3726 device->updateStateBlock->changed.textures |= 1 << stage;
3728 prev = device->updateStateBlock->state.textures[stage];
3729 TRACE("Previous texture %p.\n", prev);
3731 if (texture == prev)
3733 TRACE("App is setting the same texture again, nothing to do.\n");
3737 TRACE("Setting new texture to %p.\n", texture);
3738 device->updateStateBlock->state.textures[stage] = texture;
3740 if (device->isRecordingState)
3742 TRACE("Recording... not performing anything\n");
3744 if (texture) wined3d_texture_incref(texture);
3745 if (prev) wined3d_texture_decref(prev);
3752 LONG bind_count = InterlockedIncrement(&texture->bind_count);
3754 wined3d_texture_incref(texture);
3756 if (!prev || texture->target != prev->target)
3757 device_invalidate_state(device, STATE_PIXELSHADER);
3759 if (!prev && stage < gl_info->limits.texture_stages)
3761 /* The source arguments for color and alpha ops have different
3762 * meanings when a NULL texture is bound, so the COLOROP and
3763 * ALPHAOP have to be dirtified. */
3764 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3DTSS_COLOROP));
3765 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3DTSS_ALPHAOP));
3768 if (bind_count == 1)
3769 texture->sampler = stage;
3774 LONG bind_count = InterlockedDecrement(&prev->bind_count);
3776 wined3d_texture_decref(prev);
3778 if (!texture && stage < gl_info->limits.texture_stages)
3780 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3DTSS_COLOROP));
3781 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3DTSS_ALPHAOP));
3784 if (bind_count && prev->sampler == stage)
3788 /* Search for other stages the texture is bound to. Shouldn't
3789 * happen if applications bind textures to a single stage only. */
3790 TRACE("Searching for other stages the texture is bound to.\n");
3791 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
3793 if (device->updateStateBlock->state.textures[i] == prev)
3795 TRACE("Texture is also bound to stage %u.\n", i);
3803 device_invalidate_state(device, STATE_SAMPLER(stage));
3808 HRESULT CDECL wined3d_device_get_texture(const struct wined3d_device *device,
3809 UINT stage, struct wined3d_texture **texture)
3811 TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3813 if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3814 stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3816 if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3818 WARN("Ignoring invalid stage %u.\n", stage);
3819 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
3822 *texture = device->stateBlock->state.textures[stage];
3824 wined3d_texture_incref(*texture);
3826 TRACE("Returning %p.\n", *texture);
3831 HRESULT CDECL wined3d_device_get_back_buffer(const struct wined3d_device *device, UINT swapchain_idx,
3832 UINT backbuffer_idx, WINED3DBACKBUFFER_TYPE backbuffer_type, struct wined3d_surface **backbuffer)
3834 struct wined3d_swapchain *swapchain;
3837 TRACE("device %p, swapchain_idx %u, backbuffer_idx %u, backbuffer_type %#x, backbuffer %p.\n",
3838 device, swapchain_idx, backbuffer_idx, backbuffer_type, backbuffer);
3840 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
3843 WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
3847 hr = wined3d_swapchain_get_back_buffer(swapchain, backbuffer_idx, backbuffer_type, backbuffer);
3848 wined3d_swapchain_decref(swapchain);
3851 WARN("Failed to get backbuffer %u, hr %#x.\n", backbuffer_idx, hr);
3858 HRESULT CDECL wined3d_device_get_device_caps(const struct wined3d_device *device, WINED3DCAPS *caps)
3860 TRACE("device %p, caps %p.\n", device, caps);
3862 return wined3d_get_device_caps(device->wined3d, device->adapter->ordinal,
3863 device->create_parms.device_type, caps);
3866 HRESULT CDECL wined3d_device_get_display_mode(const struct wined3d_device *device,
3867 UINT swapchain_idx, struct wined3d_display_mode *mode)
3869 struct wined3d_swapchain *swapchain;
3872 TRACE("device %p, swapchain_idx %u, mode %p.\n", device, swapchain_idx, mode);
3876 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
3879 hr = wined3d_swapchain_get_display_mode(swapchain, mode);
3880 wined3d_swapchain_decref(swapchain);
3885 const struct wined3d_adapter *adapter = device->adapter;
3887 /* Don't read the real display mode, but return the stored mode
3888 * instead. X11 can't change the color depth, and some apps are
3889 * pretty angry if they SetDisplayMode from 24 to 16 bpp and find out
3890 * that GetDisplayMode still returns 24 bpp.
3892 * Also don't relay to the swapchain because with ddraw it's possible
3893 * that there isn't a swapchain at all. */
3894 mode->width = adapter->screen_size.cx;
3895 mode->height = adapter->screen_size.cy;
3896 mode->format_id = adapter->screen_format;
3897 mode->refresh_rate = 0;
3904 HRESULT CDECL wined3d_device_begin_stateblock(struct wined3d_device *device)
3906 struct wined3d_stateblock *stateblock;
3909 TRACE("device %p.\n", device);
3911 if (device->isRecordingState)
3912 return WINED3DERR_INVALIDCALL;
3914 hr = wined3d_stateblock_create(device, WINED3DSBT_RECORDED, &stateblock);
3918 wined3d_stateblock_decref(device->updateStateBlock);
3919 device->updateStateBlock = stateblock;
3920 device->isRecordingState = TRUE;
3922 TRACE("Recording stateblock %p.\n", stateblock);
3927 HRESULT CDECL wined3d_device_end_stateblock(struct wined3d_device *device,
3928 struct wined3d_stateblock **stateblock)
3930 struct wined3d_stateblock *object = device->updateStateBlock;
3932 TRACE("device %p, stateblock %p.\n", device, stateblock);
3934 if (!device->isRecordingState)
3936 WARN("Not recording.\n");
3938 return WINED3DERR_INVALIDCALL;
3941 stateblock_init_contained_states(object);
3943 *stateblock = object;
3944 device->isRecordingState = FALSE;
3945 device->updateStateBlock = device->stateBlock;
3946 wined3d_stateblock_incref(device->updateStateBlock);
3948 TRACE("Returning stateblock %p.\n", *stateblock);
3953 HRESULT CDECL wined3d_device_begin_scene(struct wined3d_device *device)
3955 /* At the moment we have no need for any functionality at the beginning
3957 TRACE("device %p.\n", device);
3959 if (device->inScene)
3961 WARN("Already in scene, returning WINED3DERR_INVALIDCALL.\n");
3962 return WINED3DERR_INVALIDCALL;
3964 device->inScene = TRUE;
3968 HRESULT CDECL wined3d_device_end_scene(struct wined3d_device *device)
3970 struct wined3d_context *context;
3972 TRACE("device %p.\n", device);
3974 if (!device->inScene)
3976 WARN("Not in scene, returning WINED3DERR_INVALIDCALL.\n");
3977 return WINED3DERR_INVALIDCALL;
3980 context = context_acquire(device, NULL);
3981 /* We only have to do this if we need to read the, swapbuffers performs a flush for us */
3983 /* No checkGLcall here to avoid locking the lock just for checking a call that hardly ever
3985 context_release(context);
3987 device->inScene = FALSE;
3991 HRESULT CDECL wined3d_device_present(const struct wined3d_device *device, const RECT *src_rect,
3992 const RECT *dst_rect, HWND dst_window_override, const RGNDATA *dirty_region)
3996 TRACE("device %p, src_rect %s, dst_rect %s, dst_window_override %p, dirty_region %p.\n",
3997 device, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect),
3998 dst_window_override, dirty_region);
4000 for (i = 0; i < device->swapchain_count; ++i)
4002 wined3d_swapchain_present(device->swapchains[i], src_rect,
4003 dst_rect, dst_window_override, dirty_region, 0);
4009 /* Do not call while under the GL lock. */
4010 HRESULT CDECL wined3d_device_clear(struct wined3d_device *device, DWORD rect_count,
4011 const RECT *rects, DWORD flags, const struct wined3d_color *color, float depth, DWORD stencil)
4015 TRACE("device %p, rect_count %u, rects %p, flags %#x, color {%.8e, %.8e, %.8e, %.8e}, depth %.8e, stencil %u.\n",
4016 device, rect_count, rects, flags, color->r, color->g, color->b, color->a, depth, stencil);
4018 if (flags & (WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL))
4020 struct wined3d_surface *ds = device->fb.depth_stencil;
4023 WARN("Clearing depth and/or stencil without a depth stencil buffer attached, returning WINED3DERR_INVALIDCALL\n");
4024 /* TODO: What about depth stencil buffers without stencil bits? */
4025 return WINED3DERR_INVALIDCALL;
4027 else if (flags & WINED3DCLEAR_TARGET)
4029 if (ds->resource.width < device->fb.render_targets[0]->resource.width
4030 || ds->resource.height < device->fb.render_targets[0]->resource.height)
4032 WARN("Silently ignoring depth and target clear with mismatching sizes\n");
4038 wined3d_get_draw_rect(&device->stateBlock->state, &draw_rect);
4040 return device_clear_render_targets(device, device->adapter->gl_info.limits.buffers,
4041 &device->fb, rect_count, rects,
4042 &draw_rect, flags, color, depth, stencil);
4045 void CDECL wined3d_device_set_primitive_type(struct wined3d_device *device,
4046 WINED3DPRIMITIVETYPE primitive_type)
4048 TRACE("device %p, primitive_type %s\n", device, debug_d3dprimitivetype(primitive_type));
4050 device->updateStateBlock->changed.primitive_type = TRUE;
4051 device->updateStateBlock->state.gl_primitive_type = gl_primitive_type_from_d3d(primitive_type);
4054 void CDECL wined3d_device_get_primitive_type(const struct wined3d_device *device,
4055 WINED3DPRIMITIVETYPE *primitive_type)
4057 TRACE("device %p, primitive_type %p\n", device, primitive_type);
4059 *primitive_type = d3d_primitive_type_from_gl(device->stateBlock->state.gl_primitive_type);
4061 TRACE("Returning %s\n", debug_d3dprimitivetype(*primitive_type));
4064 HRESULT CDECL wined3d_device_draw_primitive(struct wined3d_device *device, UINT start_vertex, UINT vertex_count)
4066 TRACE("device %p, start_vertex %u, vertex_count %u.\n", device, start_vertex, vertex_count);
4068 if (!device->stateBlock->state.vertex_declaration)
4070 WARN("Called without a valid vertex declaration set.\n");
4071 return WINED3DERR_INVALIDCALL;
4074 /* The index buffer is not needed here, but restore it, otherwise it is hell to keep track of */
4075 if (device->stateBlock->state.user_stream)
4077 device_invalidate_state(device, STATE_INDEXBUFFER);
4078 device->stateBlock->state.user_stream = FALSE;
4081 if (device->stateBlock->state.load_base_vertex_index)
4083 device->stateBlock->state.load_base_vertex_index = 0;
4084 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4087 /* Account for the loading offset due to index buffers. Instead of
4088 * reloading all sources correct it with the startvertex parameter. */
4089 drawPrimitive(device, vertex_count, start_vertex, 0, NULL);
4093 HRESULT CDECL wined3d_device_draw_indexed_primitive(struct wined3d_device *device, UINT start_idx, UINT index_count)
4095 struct wined3d_buffer *index_buffer;
4096 UINT index_size = 2;
4098 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4100 TRACE("device %p, start_idx %u, index_count %u.\n", device, start_idx, index_count);
4102 index_buffer = device->stateBlock->state.index_buffer;
4105 /* D3D9 returns D3DERR_INVALIDCALL when DrawIndexedPrimitive is called
4106 * without an index buffer set. (The first time at least...)
4107 * D3D8 simply dies, but I doubt it can do much harm to return
4108 * D3DERR_INVALIDCALL there as well. */
4109 WARN("Called without a valid index buffer set, returning WINED3DERR_INVALIDCALL.\n");
4110 return WINED3DERR_INVALIDCALL;
4113 if (!device->stateBlock->state.vertex_declaration)
4115 WARN("Called without a valid vertex declaration set.\n");
4116 return WINED3DERR_INVALIDCALL;
4119 if (device->stateBlock->state.user_stream)
4121 device_invalidate_state(device, STATE_INDEXBUFFER);
4122 device->stateBlock->state.user_stream = FALSE;
4124 vbo = index_buffer->buffer_object;
4126 if (device->stateBlock->state.index_format == WINED3DFMT_R16_UINT)
4131 if (!gl_info->supported[ARB_DRAW_ELEMENTS_BASE_VERTEX] &&
4132 device->stateBlock->state.load_base_vertex_index != device->stateBlock->state.base_vertex_index)
4134 device->stateBlock->state.load_base_vertex_index = device->stateBlock->state.base_vertex_index;
4135 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4138 drawPrimitive(device, index_count, start_idx, index_size,
4139 vbo ? NULL : index_buffer->resource.allocatedMemory);
4144 HRESULT CDECL wined3d_device_draw_primitive_up(struct wined3d_device *device, UINT vertex_count,
4145 const void *stream_data, UINT stream_stride)
4147 struct wined3d_stream_state *stream;
4148 struct wined3d_buffer *vb;
4150 TRACE("device %p, vertex count %u, stream_data %p, stream_stride %u.\n",
4151 device, vertex_count, stream_data, stream_stride);
4153 if (!device->stateBlock->state.vertex_declaration)
4155 WARN("Called without a valid vertex declaration set.\n");
4156 return WINED3DERR_INVALIDCALL;
4159 /* Note in the following, it's not this type, but that's the purpose of streamIsUP */
4160 stream = &device->stateBlock->state.streams[0];
4161 vb = stream->buffer;
4162 stream->buffer = (struct wined3d_buffer *)stream_data;
4164 wined3d_buffer_decref(vb);
4166 stream->stride = stream_stride;
4167 device->stateBlock->state.user_stream = TRUE;
4168 if (device->stateBlock->state.load_base_vertex_index)
4170 device->stateBlock->state.load_base_vertex_index = 0;
4171 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4174 /* TODO: Only mark dirty if drawing from a different UP address */
4175 device_invalidate_state(device, STATE_STREAMSRC);
4177 drawPrimitive(device, vertex_count, 0, 0, NULL);
4179 /* MSDN specifies stream zero settings must be set to NULL */
4180 stream->buffer = NULL;
4183 /* stream zero settings set to null at end, as per the msdn. No need to
4184 * mark dirty here, the app has to set the new stream sources or use UP
4189 HRESULT CDECL wined3d_device_draw_indexed_primitive_up(struct wined3d_device *device,
4190 UINT index_count, const void *index_data, enum wined3d_format_id index_data_format_id,
4191 const void *stream_data, UINT stream_stride)
4193 struct wined3d_stream_state *stream;
4194 struct wined3d_buffer *vb, *ib;
4197 TRACE("device %p, index_count %u, index_data %p, index_data_format %s, stream_data %p, stream_stride %u.\n",
4198 device, index_count, index_data, debug_d3dformat(index_data_format_id), stream_data, stream_stride);
4200 if (!device->stateBlock->state.vertex_declaration)
4202 WARN("(%p) : Called without a valid vertex declaration set\n", device);
4203 return WINED3DERR_INVALIDCALL;
4206 if (index_data_format_id == WINED3DFMT_R16_UINT)
4211 stream = &device->stateBlock->state.streams[0];
4212 vb = stream->buffer;
4213 stream->buffer = (struct wined3d_buffer *)stream_data;
4215 wined3d_buffer_decref(vb);
4217 stream->stride = stream_stride;
4218 device->stateBlock->state.user_stream = TRUE;
4220 /* Set to 0 as per msdn. Do it now due to the stream source loading during drawPrimitive */
4221 device->stateBlock->state.base_vertex_index = 0;
4222 if (device->stateBlock->state.load_base_vertex_index)
4224 device->stateBlock->state.load_base_vertex_index = 0;
4225 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4227 /* Invalidate the state until we have nicer tracking of the stream source pointers */
4228 device_invalidate_state(device, STATE_STREAMSRC);
4229 device_invalidate_state(device, STATE_INDEXBUFFER);
4231 drawPrimitive(device, index_count, 0, index_size, index_data);
4233 /* MSDN specifies stream zero settings and index buffer must be set to NULL */
4234 stream->buffer = NULL;
4236 ib = device->stateBlock->state.index_buffer;
4239 wined3d_buffer_decref(ib);
4240 device->stateBlock->state.index_buffer = NULL;
4242 /* No need to mark the stream source state dirty here. Either the app calls UP drawing again, or it has to call
4243 * SetStreamSource to specify a vertex buffer
4249 HRESULT CDECL wined3d_device_draw_primitive_strided(struct wined3d_device *device,
4250 UINT vertex_count, const WineDirect3DVertexStridedData *strided_data)
4252 /* Mark the state dirty until we have nicer tracking. It's fine to change
4253 * baseVertexIndex because that call is only called by ddraw which does
4254 * not need that value. */
4255 device_invalidate_state(device, STATE_VDECL);
4256 device_invalidate_state(device, STATE_STREAMSRC);
4257 device_invalidate_state(device, STATE_INDEXBUFFER);
4259 device->stateBlock->state.base_vertex_index = 0;
4260 device->up_strided = strided_data;
4261 drawPrimitive(device, vertex_count, 0, 0, NULL);
4262 device->up_strided = NULL;
4264 /* Invalidate the states again to make sure the values from the stateblock
4265 * are properly applied in the next regular draw. Note that the application-
4266 * provided strided data has ovwritten pretty much the entire vertex and
4267 * and index stream related states */
4268 device_invalidate_state(device, STATE_VDECL);
4269 device_invalidate_state(device, STATE_STREAMSRC);
4270 device_invalidate_state(device, STATE_INDEXBUFFER);
4274 HRESULT CDECL wined3d_device_draw_indexed_primitive_strided(struct wined3d_device *device,
4275 UINT index_count, const WineDirect3DVertexStridedData *strided_data,
4276 UINT vertex_count, const void *index_data, enum wined3d_format_id index_data_format_id)
4278 UINT index_size = index_data_format_id == WINED3DFMT_R32_UINT ? 4 : 2;
4280 /* Mark the state dirty until we have nicer tracking
4281 * its fine to change baseVertexIndex because that call is only called by ddraw which does not need
4284 device_invalidate_state(device, STATE_VDECL);
4285 device_invalidate_state(device, STATE_STREAMSRC);
4286 device_invalidate_state(device, STATE_INDEXBUFFER);
4288 device->stateBlock->state.user_stream = TRUE;
4289 device->stateBlock->state.base_vertex_index = 0;
4290 device->up_strided = strided_data;
4291 drawPrimitive(device, index_count, 0, index_size, index_data);
4292 device->up_strided = NULL;
4294 device_invalidate_state(device, STATE_VDECL);
4295 device_invalidate_state(device, STATE_STREAMSRC);
4296 device_invalidate_state(device, STATE_INDEXBUFFER);
4300 /* This is a helper function for UpdateTexture, there is no UpdateVolume method in D3D. */
4301 static HRESULT device_update_volume(struct wined3d_device *device,
4302 struct wined3d_volume *src_volume, struct wined3d_volume *dst_volume)
4304 struct wined3d_mapped_box src;
4305 struct wined3d_mapped_box dst;
4308 TRACE("device %p, src_volume %p, dst_volume %p.\n",
4309 device, src_volume, dst_volume);
4311 /* TODO: Implement direct loading into the gl volume instead of using
4312 * memcpy and dirtification to improve loading performance. */
4313 hr = wined3d_volume_map(src_volume, &src, NULL, WINED3DLOCK_READONLY);
4314 if (FAILED(hr)) return hr;
4315 hr = wined3d_volume_map(dst_volume, &dst, NULL, WINED3DLOCK_DISCARD);
4318 wined3d_volume_unmap(src_volume);
4322 memcpy(dst.data, src.data, dst_volume->resource.size);
4324 hr = wined3d_volume_unmap(dst_volume);
4326 wined3d_volume_unmap(src_volume);
4328 hr = wined3d_volume_unmap(src_volume);
4333 HRESULT CDECL wined3d_device_update_texture(struct wined3d_device *device,
4334 struct wined3d_texture *src_texture, struct wined3d_texture *dst_texture)
4336 unsigned int level_count, i;
4337 WINED3DRESOURCETYPE type;
4340 TRACE("device %p, src_texture %p, dst_texture %p.\n", device, src_texture, dst_texture);
4342 /* Verify that the source and destination textures are non-NULL. */
4343 if (!src_texture || !dst_texture)
4345 WARN("Source and destination textures must be non-NULL, returning WINED3DERR_INVALIDCALL.\n");
4346 return WINED3DERR_INVALIDCALL;
4349 if (src_texture == dst_texture)
4351 WARN("Source and destination are the same object, returning WINED3DERR_INVALIDCALL.\n");
4352 return WINED3DERR_INVALIDCALL;
4355 /* Verify that the source and destination textures are the same type. */
4356 type = src_texture->resource.resourceType;
4357 if (dst_texture->resource.resourceType != type)
4359 WARN("Source and destination have different types, returning WINED3DERR_INVALIDCALL.\n");
4360 return WINED3DERR_INVALIDCALL;
4363 /* Check that both textures have the identical numbers of levels. */
4364 level_count = wined3d_texture_get_level_count(src_texture);
4365 if (wined3d_texture_get_level_count(dst_texture) != level_count)
4367 WARN("Source and destination have different level counts, returning WINED3DERR_INVALIDCALL.\n");
4368 return WINED3DERR_INVALIDCALL;
4371 /* Make sure that the destination texture is loaded. */
4372 dst_texture->texture_ops->texture_preload(dst_texture, SRGB_RGB);
4374 /* Update every surface level of the texture. */
4377 case WINED3DRTYPE_TEXTURE:
4379 struct wined3d_surface *src_surface;
4380 struct wined3d_surface *dst_surface;
4382 for (i = 0; i < level_count; ++i)
4384 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4385 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4386 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4389 WARN("Failed to update surface, hr %#x.\n", hr);
4396 case WINED3DRTYPE_CUBETEXTURE:
4398 struct wined3d_surface *src_surface;
4399 struct wined3d_surface *dst_surface;
4401 for (i = 0; i < level_count * 6; ++i)
4403 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4404 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4405 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4408 WARN("Failed to update surface, hr %#x.\n", hr);
4415 case WINED3DRTYPE_VOLUMETEXTURE:
4417 for (i = 0; i < level_count; ++i)
4419 hr = device_update_volume(device,
4420 volume_from_resource(wined3d_texture_get_sub_resource(src_texture, i)),
4421 volume_from_resource(wined3d_texture_get_sub_resource(dst_texture, i)));
4424 WARN("Failed to update volume, hr %#x.\n", hr);
4432 FIXME("Unsupported texture type %#x.\n", type);
4433 return WINED3DERR_INVALIDCALL;
4439 HRESULT CDECL wined3d_device_get_front_buffer_data(const struct wined3d_device *device,
4440 UINT swapchain_idx, struct wined3d_surface *dst_surface)
4442 struct wined3d_swapchain *swapchain;
4445 TRACE("device %p, swapchain_idx %u, dst_surface %p.\n", device, swapchain_idx, dst_surface);
4447 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
4448 if (FAILED(hr)) return hr;
4450 hr = wined3d_swapchain_get_front_buffer_data(swapchain, dst_surface);
4451 wined3d_swapchain_decref(swapchain);
4456 HRESULT CDECL wined3d_device_validate_device(const struct wined3d_device *device, DWORD *num_passes)
4458 const struct wined3d_state *state = &device->stateBlock->state;
4459 struct wined3d_texture *texture;
4462 TRACE("device %p, num_passes %p.\n", device, num_passes);
4464 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
4466 if (state->sampler_states[i][WINED3DSAMP_MINFILTER] == WINED3DTEXF_NONE)
4468 WARN("Sampler state %u has minfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4469 return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4471 if (state->sampler_states[i][WINED3DSAMP_MAGFILTER] == WINED3DTEXF_NONE)
4473 WARN("Sampler state %u has magfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4474 return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4477 texture = state->textures[i];
4478 if (!texture || texture->resource.format->flags & WINED3DFMT_FLAG_FILTERING) continue;
4480 if (state->sampler_states[i][WINED3DSAMP_MAGFILTER] != WINED3DTEXF_POINT)
4482 WARN("Non-filterable texture and mag filter enabled on samper %u, returning E_FAIL\n", i);
4485 if (state->sampler_states[i][WINED3DSAMP_MINFILTER] != WINED3DTEXF_POINT)
4487 WARN("Non-filterable texture and min filter enabled on samper %u, returning E_FAIL\n", i);
4490 if (state->sampler_states[i][WINED3DSAMP_MIPFILTER] != WINED3DTEXF_NONE
4491 && state->sampler_states[i][WINED3DSAMP_MIPFILTER] != WINED3DTEXF_POINT)
4493 WARN("Non-filterable texture and mip filter enabled on samper %u, returning E_FAIL\n", i);
4498 if (state->render_states[WINED3DRS_ZENABLE] || state->render_states[WINED3DRS_ZWRITEENABLE] ||
4499 state->render_states[WINED3DRS_STENCILENABLE])
4501 struct wined3d_surface *ds = device->fb.depth_stencil;
4502 struct wined3d_surface *target = device->fb.render_targets[0];
4505 && (ds->resource.width < target->resource.width || ds->resource.height < target->resource.height))
4507 WARN("Depth stencil is smaller than the color buffer, returning D3DERR_CONFLICTINGRENDERSTATE\n");
4508 return WINED3DERR_CONFLICTINGRENDERSTATE;
4512 /* return a sensible default */
4515 TRACE("returning D3D_OK\n");
4519 HRESULT CDECL wined3d_device_set_software_vertex_processing(struct wined3d_device *device, BOOL software)
4523 TRACE("device %p, software %#x.\n", device, software);
4527 FIXME("device %p, software %#x stub!\n", device, software);
4531 device->softwareVertexProcessing = software;
4536 BOOL CDECL wined3d_device_get_software_vertex_processing(const struct wined3d_device *device)
4540 TRACE("device %p.\n", device);
4544 TRACE("device %p stub!\n", device);
4548 return device->softwareVertexProcessing;
4551 HRESULT CDECL wined3d_device_get_raster_status(const struct wined3d_device *device,
4552 UINT swapchain_idx, struct wined3d_raster_status *raster_status)
4554 struct wined3d_swapchain *swapchain;
4557 TRACE("device %p, swapchain_idx %u, raster_status %p.\n",
4558 device, swapchain_idx, raster_status);
4560 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
4563 WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
4567 hr = wined3d_swapchain_get_raster_status(swapchain, raster_status);
4568 wined3d_swapchain_decref(swapchain);
4571 WARN("Failed to get raster status, hr %#x.\n", hr);
4578 HRESULT CDECL wined3d_device_set_npatch_mode(struct wined3d_device *device, float segments)
4582 TRACE("device %p, segments %.8e.\n", device, segments);
4584 if (segments != 0.0f)
4588 FIXME("device %p, segments %.8e stub!\n", device, segments);
4596 float CDECL wined3d_device_get_npatch_mode(const struct wined3d_device *device)
4600 TRACE("device %p.\n", device);
4604 FIXME("device %p stub!\n", device);
4611 HRESULT CDECL wined3d_device_update_surface(struct wined3d_device *device,
4612 struct wined3d_surface *src_surface, const RECT *src_rect,
4613 struct wined3d_surface *dst_surface, const POINT *dst_point)
4615 TRACE("device %p, src_surface %p, src_rect %s, dst_surface %p, dst_point %s.\n",
4616 device, src_surface, wine_dbgstr_rect(src_rect),
4617 dst_surface, wine_dbgstr_point(dst_point));
4619 if (src_surface->resource.pool != WINED3DPOOL_SYSTEMMEM || dst_surface->resource.pool != WINED3DPOOL_DEFAULT)
4621 WARN("source %p must be SYSTEMMEM and dest %p must be DEFAULT, returning WINED3DERR_INVALIDCALL\n",
4622 src_surface, dst_surface);
4623 return WINED3DERR_INVALIDCALL;
4626 return surface_upload_from_surface(dst_surface, dst_point, src_surface, src_rect);
4629 HRESULT CDECL wined3d_device_draw_rect_patch(struct wined3d_device *device, UINT handle,
4630 const float *num_segs, const struct wined3d_rect_patch_info *rect_patch_info)
4632 struct WineD3DRectPatch *patch;
4633 GLenum old_primitive_type;
4638 TRACE("device %p, handle %#x, num_segs %p, rect_patch_info %p.\n",
4639 device, handle, num_segs, rect_patch_info);
4641 if (!(handle || rect_patch_info))
4643 /* TODO: Write a test for the return value, thus the FIXME */
4644 FIXME("Both handle and rect_patch_info are NULL.\n");
4645 return WINED3DERR_INVALIDCALL;
4650 i = PATCHMAP_HASHFUNC(handle);
4652 LIST_FOR_EACH(e, &device->patches[i])
4654 patch = LIST_ENTRY(e, struct WineD3DRectPatch, entry);
4655 if (patch->Handle == handle)
4664 TRACE("Patch does not exist. Creating a new one\n");
4665 patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4666 patch->Handle = handle;
4667 list_add_head(&device->patches[i], &patch->entry);
4669 TRACE("Found existing patch %p\n", patch);
4674 /* Since opengl does not load tesselated vertex attributes into numbered vertex
4675 * attributes we have to tesselate, read back, and draw. This needs a patch
4676 * management structure instance. Create one.
4678 * A possible improvement is to check if a vertex shader is used, and if not directly
4681 FIXME("Drawing an uncached patch. This is slow\n");
4682 patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4685 if (num_segs[0] != patch->numSegs[0] || num_segs[1] != patch->numSegs[1]
4686 || num_segs[2] != patch->numSegs[2] || num_segs[3] != patch->numSegs[3]
4687 || (rect_patch_info && memcmp(rect_patch_info, &patch->rect_patch_info, sizeof(*rect_patch_info))))
4690 TRACE("Tesselation density or patch info changed, retesselating\n");
4692 if (rect_patch_info)
4693 patch->rect_patch_info = *rect_patch_info;
4695 patch->numSegs[0] = num_segs[0];
4696 patch->numSegs[1] = num_segs[1];
4697 patch->numSegs[2] = num_segs[2];
4698 patch->numSegs[3] = num_segs[3];
4700 hr = tesselate_rectpatch(device, patch);
4703 WARN("Patch tesselation failed.\n");
4705 /* Do not release the handle to store the params of the patch */
4707 HeapFree(GetProcessHeap(), 0, patch);
4713 old_primitive_type = device->stateBlock->state.gl_primitive_type;
4714 device->stateBlock->state.gl_primitive_type = GL_TRIANGLES;
4715 wined3d_device_draw_primitive_strided(device, patch->numSegs[0] * patch->numSegs[1] * 2 * 3, &patch->strided);
4716 device->stateBlock->state.gl_primitive_type = old_primitive_type;
4718 /* Destroy uncached patches */
4721 HeapFree(GetProcessHeap(), 0, patch->mem);
4722 HeapFree(GetProcessHeap(), 0, patch);
4727 HRESULT CDECL wined3d_device_draw_tri_patch(struct wined3d_device *device, UINT handle,
4728 const float *segment_count, const struct wined3d_tri_patch_info *patch_info)
4730 FIXME("device %p, handle %#x, segment_count %p, patch_info %p stub!\n",
4731 device, handle, segment_count, patch_info);
4736 HRESULT CDECL wined3d_device_delete_patch(struct wined3d_device *device, UINT handle)
4738 struct WineD3DRectPatch *patch;
4742 TRACE("device %p, handle %#x.\n", device, handle);
4744 i = PATCHMAP_HASHFUNC(handle);
4745 LIST_FOR_EACH(e, &device->patches[i])
4747 patch = LIST_ENTRY(e, struct WineD3DRectPatch, entry);
4748 if (patch->Handle == handle)
4750 TRACE("Deleting patch %p\n", patch);
4751 list_remove(&patch->entry);
4752 HeapFree(GetProcessHeap(), 0, patch->mem);
4753 HeapFree(GetProcessHeap(), 0, patch);
4758 /* TODO: Write a test for the return value */
4759 FIXME("Attempt to destroy nonexistent patch\n");
4760 return WINED3DERR_INVALIDCALL;
4763 /* Do not call while under the GL lock. */
4764 HRESULT CDECL wined3d_device_color_fill(struct wined3d_device *device,
4765 struct wined3d_surface *surface, const RECT *rect, const struct wined3d_color *color)
4769 TRACE("device %p, surface %p, rect %s, color {%.8e, %.8e, %.8e, %.8e}.\n",
4770 device, surface, wine_dbgstr_rect(rect),
4771 color->r, color->g, color->b, color->a);
4773 if (surface->resource.pool != WINED3DPOOL_DEFAULT && surface->resource.pool != WINED3DPOOL_SYSTEMMEM)
4775 FIXME("call to colorfill with non WINED3DPOOL_DEFAULT or WINED3DPOOL_SYSTEMMEM surface\n");
4776 return WINED3DERR_INVALIDCALL;
4781 SetRect(&r, 0, 0, surface->resource.width, surface->resource.height);
4785 return surface_color_fill(surface, rect, color);
4788 /* Do not call while under the GL lock. */
4789 void CDECL wined3d_device_clear_rendertarget_view(struct wined3d_device *device,
4790 struct wined3d_rendertarget_view *rendertarget_view, const struct wined3d_color *color)
4792 struct wined3d_resource *resource;
4796 resource = rendertarget_view->resource;
4797 if (resource->resourceType != WINED3DRTYPE_SURFACE)
4799 FIXME("Only supported on surface resources\n");
4803 SetRect(&rect, 0, 0, resource->width, resource->height);
4804 hr = surface_color_fill(surface_from_resource(resource), &rect, color);
4805 if (FAILED(hr)) ERR("Color fill failed, hr %#x.\n", hr);
4808 HRESULT CDECL wined3d_device_get_render_target(const struct wined3d_device *device,
4809 UINT render_target_idx, struct wined3d_surface **render_target)
4811 TRACE("device %p, render_target_idx %u, render_target %p.\n",
4812 device, render_target_idx, render_target);
4814 if (render_target_idx >= device->adapter->gl_info.limits.buffers)
4816 WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
4817 return WINED3DERR_INVALIDCALL;
4820 *render_target = device->fb.render_targets[render_target_idx];
4821 TRACE("Returning render target %p.\n", *render_target);
4823 if (!*render_target)
4824 return WINED3DERR_NOTFOUND;
4826 wined3d_surface_incref(*render_target);
4831 HRESULT CDECL wined3d_device_get_depth_stencil(const struct wined3d_device *device,
4832 struct wined3d_surface **depth_stencil)
4834 TRACE("device %p, depth_stencil %p.\n", device, depth_stencil);
4836 *depth_stencil = device->fb.depth_stencil;
4837 TRACE("Returning depth/stencil surface %p.\n", *depth_stencil);
4839 if (!*depth_stencil)
4840 return WINED3DERR_NOTFOUND;
4842 wined3d_surface_incref(*depth_stencil);
4847 HRESULT CDECL wined3d_device_set_render_target(struct wined3d_device *device,
4848 UINT render_target_idx, struct wined3d_surface *render_target, BOOL set_viewport)
4850 struct wined3d_surface *prev;
4852 TRACE("device %p, render_target_idx %u, render_target %p, set_viewport %#x.\n",
4853 device, render_target_idx, render_target, set_viewport);
4855 if (render_target_idx >= device->adapter->gl_info.limits.buffers)
4857 WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
4858 return WINED3DERR_INVALIDCALL;
4861 prev = device->fb.render_targets[render_target_idx];
4862 if (render_target == prev)
4864 TRACE("Trying to do a NOP SetRenderTarget operation.\n");
4868 /* Render target 0 can't be set to NULL. */
4869 if (!render_target && !render_target_idx)
4871 WARN("Trying to set render target 0 to NULL.\n");
4872 return WINED3DERR_INVALIDCALL;
4875 if (render_target && !(render_target->resource.usage & WINED3DUSAGE_RENDERTARGET))
4877 FIXME("Surface %p doesn't have render target usage.\n", render_target);
4878 return WINED3DERR_INVALIDCALL;
4882 wined3d_surface_incref(render_target);
4883 device->fb.render_targets[render_target_idx] = render_target;
4884 /* Release after the assignment, to prevent device_resource_released()
4885 * from seeing the surface as still in use. */
4887 wined3d_surface_decref(prev);
4889 /* Render target 0 is special. */
4890 if (!render_target_idx && set_viewport)
4892 /* Set the viewport and scissor rectangles, if requested. Tests show
4893 * that stateblock recording is ignored, the change goes directly
4894 * into the primary stateblock. */
4895 device->stateBlock->state.viewport.height = device->fb.render_targets[0]->resource.height;
4896 device->stateBlock->state.viewport.width = device->fb.render_targets[0]->resource.width;
4897 device->stateBlock->state.viewport.x = 0;
4898 device->stateBlock->state.viewport.y = 0;
4899 device->stateBlock->state.viewport.max_z = 1.0f;
4900 device->stateBlock->state.viewport.min_z = 0.0f;
4901 device_invalidate_state(device, STATE_VIEWPORT);
4903 device->stateBlock->state.scissor_rect.top = 0;
4904 device->stateBlock->state.scissor_rect.left = 0;
4905 device->stateBlock->state.scissor_rect.right = device->stateBlock->state.viewport.width;
4906 device->stateBlock->state.scissor_rect.bottom = device->stateBlock->state.viewport.height;
4907 device_invalidate_state(device, STATE_SCISSORRECT);
4910 device_invalidate_state(device, STATE_FRAMEBUFFER);
4915 HRESULT CDECL wined3d_device_set_depth_stencil(struct wined3d_device *device, struct wined3d_surface *depth_stencil)
4917 struct wined3d_surface *prev = device->fb.depth_stencil;
4919 TRACE("device %p, depth_stencil %p, old depth_stencil %p.\n",
4920 device, depth_stencil, prev);
4922 if (prev == depth_stencil)
4924 TRACE("Trying to do a NOP SetRenderTarget operation.\n");
4930 if (device->swapchains[0]->desc.flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
4931 || prev->flags & SFLAG_DISCARD)
4933 surface_modify_ds_location(prev, SFLAG_DS_DISCARDED,
4934 prev->resource.width, prev->resource.height);
4935 if (prev == device->onscreen_depth_stencil)
4937 wined3d_surface_decref(device->onscreen_depth_stencil);
4938 device->onscreen_depth_stencil = NULL;
4943 device->fb.depth_stencil = depth_stencil;
4945 wined3d_surface_incref(depth_stencil);
4947 if (!prev != !depth_stencil)
4949 /* Swapping NULL / non NULL depth stencil affects the depth and tests */
4950 device_invalidate_state(device, STATE_RENDER(WINED3DRS_ZENABLE));
4951 device_invalidate_state(device, STATE_RENDER(WINED3DRS_STENCILENABLE));
4952 device_invalidate_state(device, STATE_RENDER(WINED3DRS_STENCILWRITEMASK));
4953 device_invalidate_state(device, STATE_RENDER(WINED3DRS_DEPTHBIAS));
4955 else if (prev && prev->resource.format->depth_size != depth_stencil->resource.format->depth_size)
4957 device_invalidate_state(device, STATE_RENDER(WINED3DRS_DEPTHBIAS));
4960 wined3d_surface_decref(prev);
4962 device_invalidate_state(device, STATE_FRAMEBUFFER);
4967 HRESULT CDECL wined3d_device_set_cursor_properties(struct wined3d_device *device,
4968 UINT x_hotspot, UINT y_hotspot, struct wined3d_surface *cursor_image)
4970 struct wined3d_mapped_rect mapped_rect;
4972 TRACE("device %p, x_hotspot %u, y_hotspot %u, cursor_image %p.\n",
4973 device, x_hotspot, y_hotspot, cursor_image);
4975 /* some basic validation checks */
4976 if (device->cursorTexture)
4978 struct wined3d_context *context = context_acquire(device, NULL);
4980 glDeleteTextures(1, &device->cursorTexture);
4982 context_release(context);
4983 device->cursorTexture = 0;
4988 struct wined3d_mapped_rect rect;
4990 /* MSDN: Cursor must be A8R8G8B8 */
4991 if (cursor_image->resource.format->id != WINED3DFMT_B8G8R8A8_UNORM)
4993 WARN("surface %p has an invalid format.\n", cursor_image);
4994 return WINED3DERR_INVALIDCALL;
4997 /* MSDN: Cursor must be smaller than the display mode */
4998 if (cursor_image->resource.width > device->adapter->screen_size.cx
4999 || cursor_image->resource.height > device->adapter->screen_size.cy)
5001 WARN("Surface %p dimensions are %ux%u, but screen dimensions are %ux%u.\n",
5002 cursor_image, cursor_image->resource.width, cursor_image->resource.height,
5003 device->adapter->screen_size.cx, device->adapter->screen_size.cy);
5004 return WINED3DERR_INVALIDCALL;
5007 /* TODO: MSDN: Cursor sizes must be a power of 2 */
5009 /* Do not store the surface's pointer because the application may
5010 * release it after setting the cursor image. Windows doesn't
5011 * addref the set surface, so we can't do this either without
5012 * creating circular refcount dependencies. Copy out the gl texture
5014 device->cursorWidth = cursor_image->resource.width;
5015 device->cursorHeight = cursor_image->resource.height;
5016 if (SUCCEEDED(wined3d_surface_map(cursor_image, &rect, NULL, WINED3DLOCK_READONLY)))
5018 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
5019 const struct wined3d_format *format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
5020 struct wined3d_context *context;
5021 char *mem, *bits = rect.data;
5022 GLint intfmt = format->glInternal;
5023 GLint gl_format = format->glFormat;
5024 GLint type = format->glType;
5025 INT height = device->cursorHeight;
5026 INT width = device->cursorWidth;
5027 INT bpp = format->byte_count;
5030 /* Reformat the texture memory (pitch and width can be
5032 mem = HeapAlloc(GetProcessHeap(), 0, width * height * bpp);
5033 for(i = 0; i < height; i++)
5034 memcpy(&mem[width * bpp * i], &bits[rect.row_pitch * i], width * bpp);
5035 wined3d_surface_unmap(cursor_image);
5037 context = context_acquire(device, NULL);
5041 if (gl_info->supported[APPLE_CLIENT_STORAGE])
5043 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
5044 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
5047 invalidate_active_texture(device, context);
5048 /* Create a new cursor texture */
5049 glGenTextures(1, &device->cursorTexture);
5050 checkGLcall("glGenTextures");
5051 context_bind_texture(context, GL_TEXTURE_2D, device->cursorTexture);
5052 /* Copy the bitmap memory into the cursor texture */
5053 glTexImage2D(GL_TEXTURE_2D, 0, intfmt, width, height, 0, gl_format, type, mem);
5054 checkGLcall("glTexImage2D");
5055 HeapFree(GetProcessHeap(), 0, mem);
5057 if (gl_info->supported[APPLE_CLIENT_STORAGE])
5059 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
5060 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
5065 context_release(context);
5069 FIXME("A cursor texture was not returned.\n");
5070 device->cursorTexture = 0;
5073 if (cursor_image->resource.width == 32 && cursor_image->resource.height == 32)
5075 /* Draw a hardware cursor */
5076 ICONINFO cursorInfo;
5078 /* Create and clear maskBits because it is not needed for
5079 * 32-bit cursors. 32x32 bits split into 32-bit chunks == 32
5081 DWORD *maskBits = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
5082 (cursor_image->resource.width * cursor_image->resource.height / 8));
5083 wined3d_surface_map(cursor_image, &mapped_rect, NULL,
5084 WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY);
5085 TRACE("width: %u height: %u.\n", cursor_image->resource.width, cursor_image->resource.height);
5087 cursorInfo.fIcon = FALSE;
5088 cursorInfo.xHotspot = x_hotspot;
5089 cursorInfo.yHotspot = y_hotspot;
5090 cursorInfo.hbmMask = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
5092 cursorInfo.hbmColor = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
5093 1, 32, mapped_rect.data);
5094 wined3d_surface_unmap(cursor_image);
5095 /* Create our cursor and clean up. */
5096 cursor = CreateIconIndirect(&cursorInfo);
5097 if (cursorInfo.hbmMask) DeleteObject(cursorInfo.hbmMask);
5098 if (cursorInfo.hbmColor) DeleteObject(cursorInfo.hbmColor);
5099 if (device->hardwareCursor) DestroyCursor(device->hardwareCursor);
5100 device->hardwareCursor = cursor;
5101 if (device->bCursorVisible) SetCursor( cursor );
5102 HeapFree(GetProcessHeap(), 0, maskBits);
5106 device->xHotSpot = x_hotspot;
5107 device->yHotSpot = y_hotspot;
5111 void CDECL wined3d_device_set_cursor_position(struct wined3d_device *device,
5112 int x_screen_space, int y_screen_space, DWORD flags)
5114 TRACE("device %p, x %d, y %d, flags %#x.\n",
5115 device, x_screen_space, y_screen_space, flags);
5117 device->xScreenSpace = x_screen_space;
5118 device->yScreenSpace = y_screen_space;
5120 if (device->hardwareCursor)
5124 GetCursorPos( &pt );
5125 if (x_screen_space == pt.x && y_screen_space == pt.y)
5127 SetCursorPos( x_screen_space, y_screen_space );
5129 /* Switch to the software cursor if position diverges from the hardware one. */
5130 GetCursorPos( &pt );
5131 if (x_screen_space != pt.x || y_screen_space != pt.y)
5133 if (device->bCursorVisible) SetCursor( NULL );
5134 DestroyCursor( device->hardwareCursor );
5135 device->hardwareCursor = 0;
5140 BOOL CDECL wined3d_device_show_cursor(struct wined3d_device *device, BOOL show)
5142 BOOL oldVisible = device->bCursorVisible;
5144 TRACE("device %p, show %#x.\n", device, show);
5147 * When ShowCursor is first called it should make the cursor appear at the OS's last
5148 * known cursor position.
5150 if (show && !oldVisible)
5154 device->xScreenSpace = pt.x;
5155 device->yScreenSpace = pt.y;
5158 if (device->hardwareCursor)
5160 device->bCursorVisible = show;
5162 SetCursor(device->hardwareCursor);
5168 if (device->cursorTexture)
5169 device->bCursorVisible = show;
5175 void CDECL wined3d_device_evict_managed_resources(struct wined3d_device *device)
5177 struct wined3d_resource *resource, *cursor;
5179 TRACE("device %p.\n", device);
5181 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5183 TRACE("Checking resource %p for eviction.\n", resource);
5185 if (resource->pool == WINED3DPOOL_MANAGED)
5187 TRACE("Evicting %p.\n", resource);
5188 resource->resource_ops->resource_unload(resource);
5192 /* Invalidate stream sources, the buffer(s) may have been evicted. */
5193 device_invalidate_state(device, STATE_STREAMSRC);
5196 static HRESULT updateSurfaceDesc(struct wined3d_surface *surface,
5197 const struct wined3d_swapchain_desc *swapchain_desc)
5199 struct wined3d_device *device = surface->resource.device;
5200 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
5202 /* Reallocate proper memory for the front and back buffer and adjust their sizes */
5203 if (surface->flags & SFLAG_DIBSECTION)
5205 DeleteDC(surface->hDC);
5206 DeleteObject(surface->dib.DIBsection);
5207 surface->dib.bitmap_data = NULL;
5208 surface->resource.allocatedMemory = NULL;
5209 surface->flags &= ~SFLAG_DIBSECTION;
5211 surface->resource.width = swapchain_desc->backbuffer_width;
5212 surface->resource.height = swapchain_desc->backbuffer_height;
5213 if (gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] || gl_info->supported[ARB_TEXTURE_RECTANGLE]
5214 || gl_info->supported[WINED3D_GL_NORMALIZED_TEXRECT])
5216 surface->pow2Width = swapchain_desc->backbuffer_width;
5217 surface->pow2Height = swapchain_desc->backbuffer_height;
5221 surface->pow2Width = surface->pow2Height = 1;
5222 while (surface->pow2Width < swapchain_desc->backbuffer_width)
5223 surface->pow2Width <<= 1;
5224 while (surface->pow2Height < swapchain_desc->backbuffer_height)
5225 surface->pow2Height <<= 1;
5228 if (!(surface->resource.usage & WINED3DUSAGE_DEPTHSTENCIL))
5229 surface->resource.format = wined3d_get_format(gl_info, swapchain_desc->backbuffer_format);
5230 surface->resource.multisample_type = swapchain_desc->multisample_type;
5231 surface->resource.multisample_quality = swapchain_desc->multisample_quality;
5233 if (device->d3d_initialized)
5234 surface->resource.resource_ops->resource_unload(&surface->resource);
5236 if (surface->pow2Width != swapchain_desc->backbuffer_width
5237 || surface->pow2Height != swapchain_desc->backbuffer_height)
5239 surface->flags |= SFLAG_NONPOW2;
5243 surface->flags &= ~SFLAG_NONPOW2;
5245 HeapFree(GetProcessHeap(), 0, surface->resource.heapMemory);
5246 surface->resource.allocatedMemory = NULL;
5247 surface->resource.heapMemory = NULL;
5248 surface->resource.size = wined3d_surface_get_pitch(surface) * surface->pow2Width;
5250 /* Put all surfaces into sysmem - the drawable might disappear if the backbuffer was rendered
5252 if (!surface_init_sysmem(surface))
5254 return E_OUTOFMEMORY;
5259 static BOOL is_display_mode_supported(const struct wined3d_device *device,
5260 const struct wined3d_swapchain_desc *swapchain_desc)
5262 struct wined3d_display_mode m;
5266 /* All Windowed modes are supported, as is leaving the current mode */
5267 if (swapchain_desc->windowed)
5269 if (!swapchain_desc->backbuffer_width)
5271 if (!swapchain_desc->backbuffer_height)
5274 count = wined3d_get_adapter_mode_count(device->wined3d, device->adapter->ordinal, WINED3DFMT_UNKNOWN);
5275 for (i = 0; i < count; ++i)
5277 memset(&m, 0, sizeof(m));
5278 hr = wined3d_enum_adapter_modes(device->wined3d, device->adapter->ordinal, WINED3DFMT_UNKNOWN, i, &m);
5280 ERR("Failed to enumerate adapter mode.\n");
5281 if (m.width == swapchain_desc->backbuffer_width && m.height == swapchain_desc->backbuffer_height)
5282 /* Mode found, it is supported. */
5285 /* Mode not found -> not supported */
5289 /* Do not call while under the GL lock. */
5290 static void delete_opengl_contexts(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
5292 struct wined3d_resource *resource, *cursor;
5293 const struct wined3d_gl_info *gl_info;
5294 struct wined3d_context *context;
5295 struct wined3d_shader *shader;
5297 context = context_acquire(device, NULL);
5298 gl_info = context->gl_info;
5300 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5302 TRACE("Unloading resource %p.\n", resource);
5304 resource->resource_ops->resource_unload(resource);
5307 LIST_FOR_EACH_ENTRY(shader, &device->shaders, struct wined3d_shader, shader_list_entry)
5309 device->shader_backend->shader_destroy(shader);
5313 if (device->depth_blt_texture)
5315 glDeleteTextures(1, &device->depth_blt_texture);
5316 device->depth_blt_texture = 0;
5318 if (device->cursorTexture)
5320 glDeleteTextures(1, &device->cursorTexture);
5321 device->cursorTexture = 0;
5325 device->blitter->free_private(device);
5326 device->frag_pipe->free_private(device);
5327 device->shader_backend->shader_free_private(device);
5328 destroy_dummy_textures(device, gl_info);
5330 context_release(context);
5332 while (device->context_count)
5334 swapchain_destroy_contexts(device->contexts[0]->swapchain);
5337 HeapFree(GetProcessHeap(), 0, swapchain->context);
5338 swapchain->context = NULL;
5341 /* Do not call while under the GL lock. */
5342 static HRESULT create_primary_opengl_context(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
5344 struct wined3d_context *context;
5345 struct wined3d_surface *target;
5348 /* Recreate the primary swapchain's context */
5349 swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(*swapchain->context));
5350 if (!swapchain->context)
5352 ERR("Failed to allocate memory for swapchain context array.\n");
5353 return E_OUTOFMEMORY;
5356 target = swapchain->back_buffers ? swapchain->back_buffers[0] : swapchain->front_buffer;
5357 if (!(context = context_create(swapchain, target, swapchain->ds_format)))
5359 WARN("Failed to create context.\n");
5360 HeapFree(GetProcessHeap(), 0, swapchain->context);
5364 swapchain->context[0] = context;
5365 swapchain->num_contexts = 1;
5366 create_dummy_textures(device, context);
5367 context_release(context);
5369 hr = device->shader_backend->shader_alloc_private(device);
5372 ERR("Failed to allocate shader private data, hr %#x.\n", hr);
5376 hr = device->frag_pipe->alloc_private(device);
5379 ERR("Failed to allocate fragment pipe private data, hr %#x.\n", hr);
5380 device->shader_backend->shader_free_private(device);
5384 hr = device->blitter->alloc_private(device);
5387 ERR("Failed to allocate blitter private data, hr %#x.\n", hr);
5388 device->frag_pipe->free_private(device);
5389 device->shader_backend->shader_free_private(device);
5396 context_acquire(device, NULL);
5397 destroy_dummy_textures(device, context->gl_info);
5398 context_release(context);
5399 context_destroy(device, context);
5400 HeapFree(GetProcessHeap(), 0, swapchain->context);
5401 swapchain->num_contexts = 0;
5405 /* Do not call while under the GL lock. */
5406 HRESULT CDECL wined3d_device_reset(struct wined3d_device *device,
5407 const struct wined3d_swapchain_desc *swapchain_desc,
5408 wined3d_device_reset_cb callback)
5410 struct wined3d_resource *resource, *cursor;
5411 struct wined3d_swapchain *swapchain;
5412 struct wined3d_display_mode mode;
5413 BOOL DisplayModeChanged = FALSE;
5414 BOOL update_desc = FALSE;
5418 TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
5420 wined3d_device_set_index_buffer(device, NULL, WINED3DFMT_UNKNOWN);
5421 for (i = 0; i < MAX_STREAMS; ++i)
5423 wined3d_device_set_stream_source(device, i, NULL, 0, 0);
5425 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
5427 wined3d_device_set_texture(device, i, NULL);
5429 if (device->onscreen_depth_stencil)
5431 wined3d_surface_decref(device->onscreen_depth_stencil);
5432 device->onscreen_depth_stencil = NULL;
5435 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5437 TRACE("Enumerating resource %p.\n", resource);
5438 if (FAILED(hr = callback(resource)))
5442 hr = wined3d_device_get_swapchain(device, 0, &swapchain);
5445 ERR("Failed to get the first implicit swapchain\n");
5449 if (!is_display_mode_supported(device, swapchain_desc))
5451 WARN("Rejecting reset() call because the requested display mode is not supported.\n");
5452 WARN("Requested mode: %ux%u.\n",
5453 swapchain_desc->backbuffer_width,
5454 swapchain_desc->backbuffer_height);
5455 wined3d_swapchain_decref(swapchain);
5456 return WINED3DERR_INVALIDCALL;
5459 /* Is it necessary to recreate the gl context? Actually every setting can be changed
5460 * on an existing gl context, so there's no real need for recreation.
5462 * TODO: Figure out how Reset influences resources in D3DPOOL_DEFAULT, D3DPOOL_SYSTEMMEMORY and D3DPOOL_MANAGED
5464 * TODO: Figure out what happens to explicit swapchains, or if we have more than one implicit swapchain
5466 TRACE("New params:\n");
5467 TRACE("backbuffer_width %u\n", swapchain_desc->backbuffer_width);
5468 TRACE("backbuffer_height %u\n", swapchain_desc->backbuffer_height);
5469 TRACE("backbuffer_format %s\n", debug_d3dformat(swapchain_desc->backbuffer_format));
5470 TRACE("backbuffer_count %u\n", swapchain_desc->backbuffer_count);
5471 TRACE("multisample_type %#x\n", swapchain_desc->multisample_type);
5472 TRACE("multisample_quality %u\n", swapchain_desc->multisample_quality);
5473 TRACE("swap_effect %#x\n", swapchain_desc->swap_effect);
5474 TRACE("device_window %p\n", swapchain_desc->device_window);
5475 TRACE("windowed %#x\n", swapchain_desc->windowed);
5476 TRACE("enable_auto_depth_stencil %#x\n", swapchain_desc->enable_auto_depth_stencil);
5477 TRACE("flags %#x\n", swapchain_desc->flags);
5478 TRACE("refresh_rate %u\n", swapchain_desc->refresh_rate);
5479 TRACE("swap_interval %u\n", swapchain_desc->swap_interval);
5481 /* No special treatment of these parameters. Just store them */
5482 swapchain->desc.swap_effect = swapchain_desc->swap_effect;
5483 swapchain->desc.flags = swapchain_desc->flags;
5484 swapchain->desc.swap_interval = swapchain_desc->swap_interval;
5485 swapchain->desc.refresh_rate = swapchain_desc->refresh_rate;
5487 /* What to do about these? */
5488 if (swapchain_desc->backbuffer_count
5489 && swapchain_desc->backbuffer_count != swapchain->desc.backbuffer_count)
5490 FIXME("Cannot change the back buffer count yet.\n");
5492 if (swapchain_desc->device_window
5493 && swapchain_desc->device_window != swapchain->desc.device_window)
5494 FIXME("Cannot change the device window yet.\n");
5496 if (swapchain_desc->enable_auto_depth_stencil && !device->auto_depth_stencil)
5500 TRACE("Creating the depth stencil buffer\n");
5502 hrc = device->device_parent->ops->create_depth_stencil(device->device_parent,
5503 swapchain_desc->backbuffer_width,
5504 swapchain_desc->backbuffer_height,
5505 swapchain_desc->auto_depth_stencil_format,
5506 swapchain_desc->multisample_type,
5507 swapchain_desc->multisample_quality,
5509 &device->auto_depth_stencil);
5512 ERR("Failed to create the depth stencil buffer.\n");
5513 wined3d_swapchain_decref(swapchain);
5514 return WINED3DERR_INVALIDCALL;
5518 if (device->onscreen_depth_stencil)
5520 wined3d_surface_decref(device->onscreen_depth_stencil);
5521 device->onscreen_depth_stencil = NULL;
5524 /* Reset the depth stencil */
5525 if (swapchain_desc->enable_auto_depth_stencil)
5526 wined3d_device_set_depth_stencil(device, device->auto_depth_stencil);
5528 wined3d_device_set_depth_stencil(device, NULL);
5530 TRACE("Resetting stateblock\n");
5531 wined3d_stateblock_decref(device->updateStateBlock);
5532 wined3d_stateblock_decref(device->stateBlock);
5534 if (swapchain_desc->windowed)
5536 mode.width = swapchain->orig_width;
5537 mode.height = swapchain->orig_height;
5538 mode.refresh_rate = 0;
5539 mode.format_id = swapchain->desc.backbuffer_format;
5543 mode.width = swapchain_desc->backbuffer_width;
5544 mode.height = swapchain_desc->backbuffer_height;
5545 mode.refresh_rate = swapchain_desc->refresh_rate;
5546 mode.format_id = swapchain_desc->backbuffer_format;
5549 /* Should Width == 800 && Height == 0 set 800x600? */
5550 if (swapchain_desc->backbuffer_width && swapchain_desc->backbuffer_height
5551 && (swapchain_desc->backbuffer_width != swapchain->desc.backbuffer_width
5552 || swapchain_desc->backbuffer_height != swapchain->desc.backbuffer_height))
5554 if (!swapchain_desc->windowed)
5555 DisplayModeChanged = TRUE;
5557 swapchain->desc.backbuffer_width = swapchain_desc->backbuffer_width;
5558 swapchain->desc.backbuffer_height = swapchain_desc->backbuffer_height;
5562 if (swapchain_desc->backbuffer_format != WINED3DFMT_UNKNOWN
5563 && swapchain_desc->backbuffer_format != swapchain->desc.backbuffer_format)
5565 swapchain->desc.backbuffer_format = swapchain_desc->backbuffer_format;
5569 if (swapchain_desc->multisample_type != swapchain->desc.multisample_type
5570 || swapchain_desc->multisample_quality != swapchain->desc.multisample_quality)
5572 swapchain->desc.multisample_type = swapchain_desc->multisample_type;
5573 swapchain->desc.multisample_quality = swapchain_desc->multisample_quality;
5581 hr = updateSurfaceDesc(swapchain->front_buffer, &swapchain->desc);
5584 wined3d_swapchain_decref(swapchain);
5588 for (i = 0; i < swapchain->desc.backbuffer_count; ++i)
5590 hr = updateSurfaceDesc(swapchain->back_buffers[i], &swapchain->desc);
5593 wined3d_swapchain_decref(swapchain);
5597 if (device->auto_depth_stencil)
5599 hr = updateSurfaceDesc(device->auto_depth_stencil, &swapchain->desc);
5602 wined3d_swapchain_decref(swapchain);
5608 if (device->d3d_initialized)
5609 delete_opengl_contexts(device, swapchain);
5611 if (!swapchain_desc->windowed != !swapchain->desc.windowed
5612 || DisplayModeChanged)
5614 wined3d_device_set_display_mode(device, 0, &mode);
5616 if (!swapchain_desc->windowed)
5618 if (swapchain->desc.windowed)
5620 HWND focus_window = device->create_parms.focus_window;
5622 focus_window = swapchain_desc->device_window;
5623 if (FAILED(hr = wined3d_device_acquire_focus_window(device, focus_window)))
5625 ERR("Failed to acquire focus window, hr %#x.\n", hr);
5626 wined3d_swapchain_decref(swapchain);
5630 /* switch from windowed to fs */
5631 wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5632 swapchain_desc->backbuffer_width,
5633 swapchain_desc->backbuffer_height);
5637 /* Fullscreen -> fullscreen mode change */
5638 MoveWindow(swapchain->device_window, 0, 0,
5639 swapchain_desc->backbuffer_width,
5640 swapchain_desc->backbuffer_height,
5644 else if (!swapchain->desc.windowed)
5646 /* Fullscreen -> windowed switch */
5647 wined3d_device_restore_fullscreen_window(device, swapchain->device_window);
5648 wined3d_device_release_focus_window(device);
5650 swapchain->desc.windowed = swapchain_desc->windowed;
5652 else if (!swapchain_desc->windowed)
5654 DWORD style = device->style;
5655 DWORD exStyle = device->exStyle;
5656 /* If we're in fullscreen, and the mode wasn't changed, we have to get the window back into
5657 * the right position. Some applications(Battlefield 2, Guild Wars) move it and then call
5658 * Reset to clear up their mess. Guild Wars also loses the device during that.
5661 device->exStyle = 0;
5662 wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5663 swapchain_desc->backbuffer_width,
5664 swapchain_desc->backbuffer_height);
5665 device->style = style;
5666 device->exStyle = exStyle;
5669 /* Note: No parent needed for initial internal stateblock */
5670 hr = wined3d_stateblock_create(device, WINED3DSBT_INIT, &device->stateBlock);
5672 ERR("Resetting the stateblock failed with error %#x.\n", hr);
5674 TRACE("Created stateblock %p.\n", device->stateBlock);
5675 device->updateStateBlock = device->stateBlock;
5676 wined3d_stateblock_incref(device->updateStateBlock);
5678 stateblock_init_default_state(device->stateBlock);
5680 swapchain_update_render_to_fbo(swapchain);
5681 swapchain_update_draw_bindings(swapchain);
5683 if (device->d3d_initialized)
5684 hr = create_primary_opengl_context(device, swapchain);
5685 wined3d_swapchain_decref(swapchain);
5687 /* All done. There is no need to reload resources or shaders, this will happen automatically on the
5693 HRESULT CDECL wined3d_device_set_dialog_box_mode(struct wined3d_device *device, BOOL enable_dialogs)
5695 TRACE("device %p, enable_dialogs %#x.\n", device, enable_dialogs);
5697 if (!enable_dialogs) FIXME("Dialogs cannot be disabled yet.\n");
5703 HRESULT CDECL wined3d_device_get_creation_parameters(const struct wined3d_device *device,
5704 struct wined3d_device_creation_parameters *parameters)
5706 TRACE("device %p, parameters %p.\n", device, parameters);
5708 *parameters = device->create_parms;
5712 void CDECL wined3d_device_set_gamma_ramp(const struct wined3d_device *device,
5713 UINT swapchain_idx, DWORD flags, const struct wined3d_gamma_ramp *ramp)
5715 struct wined3d_swapchain *swapchain;
5717 TRACE("device %p, swapchain_idx %u, flags %#x, ramp %p.\n",
5718 device, swapchain_idx, flags, ramp);
5720 if (SUCCEEDED(wined3d_device_get_swapchain(device, swapchain_idx, &swapchain)))
5722 wined3d_swapchain_set_gamma_ramp(swapchain, flags, ramp);
5723 wined3d_swapchain_decref(swapchain);
5727 void CDECL wined3d_device_get_gamma_ramp(const struct wined3d_device *device,
5728 UINT swapchain_idx, struct wined3d_gamma_ramp *ramp)
5730 struct wined3d_swapchain *swapchain;
5732 TRACE("device %p, swapchain_idx %u, ramp %p.\n",
5733 device, swapchain_idx, ramp);
5735 if (SUCCEEDED(wined3d_device_get_swapchain(device, swapchain_idx, &swapchain)))
5737 wined3d_swapchain_get_gamma_ramp(swapchain, ramp);
5738 wined3d_swapchain_decref(swapchain);
5742 void device_resource_add(struct wined3d_device *device, struct wined3d_resource *resource)
5744 TRACE("device %p, resource %p.\n", device, resource);
5746 list_add_head(&device->resources, &resource->resource_list_entry);
5749 static void device_resource_remove(struct wined3d_device *device, struct wined3d_resource *resource)
5751 TRACE("device %p, resource %p.\n", device, resource);
5753 list_remove(&resource->resource_list_entry);
5756 void device_resource_released(struct wined3d_device *device, struct wined3d_resource *resource)
5758 WINED3DRESOURCETYPE type = resource->resourceType;
5761 TRACE("device %p, resource %p, type %s.\n", device, resource, debug_d3dresourcetype(type));
5763 context_resource_released(device, resource, type);
5767 case WINED3DRTYPE_SURFACE:
5769 struct wined3d_surface *surface = surface_from_resource(resource);
5771 if (!device->d3d_initialized) break;
5773 for (i = 0; i < device->adapter->gl_info.limits.buffers; ++i)
5775 if (device->fb.render_targets[i] == surface)
5777 ERR("Surface %p is still in use as render target %u.\n", surface, i);
5778 device->fb.render_targets[i] = NULL;
5782 if (device->fb.depth_stencil == surface)
5784 ERR("Surface %p is still in use as depth/stencil buffer.\n", surface);
5785 device->fb.depth_stencil = NULL;
5790 case WINED3DRTYPE_TEXTURE:
5791 case WINED3DRTYPE_CUBETEXTURE:
5792 case WINED3DRTYPE_VOLUMETEXTURE:
5793 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
5795 struct wined3d_texture *texture = wined3d_texture_from_resource(resource);
5797 if (device->stateBlock && device->stateBlock->state.textures[i] == texture)
5799 ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
5800 texture, device->stateBlock, i);
5801 device->stateBlock->state.textures[i] = NULL;
5804 if (device->updateStateBlock != device->stateBlock
5805 && device->updateStateBlock->state.textures[i] == texture)
5807 ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
5808 texture, device->updateStateBlock, i);
5809 device->updateStateBlock->state.textures[i] = NULL;
5814 case WINED3DRTYPE_BUFFER:
5816 struct wined3d_buffer *buffer = buffer_from_resource(resource);
5818 for (i = 0; i < MAX_STREAMS; ++i)
5820 if (device->stateBlock && device->stateBlock->state.streams[i].buffer == buffer)
5822 ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
5823 buffer, device->stateBlock, i);
5824 device->stateBlock->state.streams[i].buffer = NULL;
5827 if (device->updateStateBlock != device->stateBlock
5828 && device->updateStateBlock->state.streams[i].buffer == buffer)
5830 ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
5831 buffer, device->updateStateBlock, i);
5832 device->updateStateBlock->state.streams[i].buffer = NULL;
5837 if (device->stateBlock && device->stateBlock->state.index_buffer == buffer)
5839 ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
5840 buffer, device->stateBlock);
5841 device->stateBlock->state.index_buffer = NULL;
5844 if (device->updateStateBlock != device->stateBlock
5845 && device->updateStateBlock->state.index_buffer == buffer)
5847 ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
5848 buffer, device->updateStateBlock);
5849 device->updateStateBlock->state.index_buffer = NULL;
5858 /* Remove the resource from the resourceStore */
5859 device_resource_remove(device, resource);
5861 TRACE("Resource released.\n");
5864 HRESULT CDECL wined3d_device_get_surface_from_dc(const struct wined3d_device *device,
5865 HDC dc, struct wined3d_surface **surface)
5867 struct wined3d_resource *resource;
5869 TRACE("device %p, dc %p, surface %p.\n", device, dc, surface);
5872 return WINED3DERR_INVALIDCALL;
5874 LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
5876 if (resource->resourceType == WINED3DRTYPE_SURFACE)
5878 struct wined3d_surface *s = surface_from_resource(resource);
5882 TRACE("Found surface %p for dc %p.\n", s, dc);
5889 return WINED3DERR_INVALIDCALL;
5892 HRESULT device_init(struct wined3d_device *device, struct wined3d *wined3d,
5893 UINT adapter_idx, WINED3DDEVTYPE device_type, HWND focus_window, DWORD flags,
5894 BYTE surface_alignment, struct wined3d_device_parent *device_parent)
5896 struct wined3d_adapter *adapter = &wined3d->adapters[adapter_idx];
5897 const struct fragment_pipeline *fragment_pipeline;
5898 struct wined3d_display_mode mode;
5899 struct shader_caps shader_caps;
5900 struct fragment_caps ffp_caps;
5905 device->wined3d = wined3d;
5906 wined3d_incref(device->wined3d);
5907 device->adapter = wined3d->adapter_count ? adapter : NULL;
5908 device->device_parent = device_parent;
5909 list_init(&device->resources);
5910 list_init(&device->shaders);
5911 device->surface_alignment = surface_alignment;
5913 /* Get the initial screen setup for ddraw. */
5914 hr = wined3d_get_adapter_display_mode(wined3d, adapter_idx, &mode);
5917 ERR("Failed to get the adapter's display mode, hr %#x.\n", hr);
5918 wined3d_decref(device->wined3d);
5921 adapter->screen_size.cx = mode.width;
5922 adapter->screen_size.cy = mode.height;
5923 adapter->screen_format = mode.format_id;
5925 /* Save the creation parameters. */
5926 device->create_parms.adapter_idx = adapter_idx;
5927 device->create_parms.device_type = device_type;
5928 device->create_parms.focus_window = focus_window;
5929 device->create_parms.flags = flags;
5931 for (i = 0; i < PATCHMAP_SIZE; ++i) list_init(&device->patches[i]);
5933 select_shader_mode(&adapter->gl_info, &device->ps_selected_mode, &device->vs_selected_mode);
5934 device->shader_backend = adapter->shader_backend;
5936 if (device->shader_backend)
5938 device->shader_backend->shader_get_caps(&adapter->gl_info, &shader_caps);
5939 device->vshader_version = shader_caps.VertexShaderVersion;
5940 device->pshader_version = shader_caps.PixelShaderVersion;
5941 device->d3d_vshader_constantF = shader_caps.MaxVertexShaderConst;
5942 device->d3d_pshader_constantF = shader_caps.MaxPixelShaderConst;
5943 device->vs_clipping = shader_caps.VSClipping;
5945 fragment_pipeline = adapter->fragment_pipe;
5946 device->frag_pipe = fragment_pipeline;
5947 if (fragment_pipeline)
5949 fragment_pipeline->get_caps(&adapter->gl_info, &ffp_caps);
5950 device->max_ffp_textures = ffp_caps.MaxSimultaneousTextures;
5952 hr = compile_state_table(device->StateTable, device->multistate_funcs, &adapter->gl_info,
5953 ffp_vertexstate_template, fragment_pipeline, misc_state_template);
5956 ERR("Failed to compile state table, hr %#x.\n", hr);
5957 wined3d_decref(device->wined3d);
5961 device->blitter = adapter->blitter;
5963 hr = wined3d_stateblock_create(device, WINED3DSBT_INIT, &device->stateBlock);
5966 WARN("Failed to create stateblock.\n");
5967 for (i = 0; i < sizeof(device->multistate_funcs) / sizeof(device->multistate_funcs[0]); ++i)
5969 HeapFree(GetProcessHeap(), 0, device->multistate_funcs[i]);
5971 wined3d_decref(device->wined3d);
5975 TRACE("Created stateblock %p.\n", device->stateBlock);
5976 device->updateStateBlock = device->stateBlock;
5977 wined3d_stateblock_incref(device->updateStateBlock);
5983 void device_invalidate_state(const struct wined3d_device *device, DWORD state)
5985 DWORD rep = device->StateTable[state].representative;
5986 struct wined3d_context *context;
5991 for (i = 0; i < device->context_count; ++i)
5993 context = device->contexts[i];
5994 if(isStateDirty(context, rep)) continue;
5996 context->dirtyArray[context->numDirtyEntries++] = rep;
5997 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
5998 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
5999 context->isStateDirty[idx] |= (1 << shift);
6003 void get_drawable_size_fbo(const struct wined3d_context *context, UINT *width, UINT *height)
6005 /* The drawable size of a fbo target is the opengl texture size, which is the power of two size. */
6006 *width = context->current_rt->pow2Width;
6007 *height = context->current_rt->pow2Height;
6010 void get_drawable_size_backbuffer(const struct wined3d_context *context, UINT *width, UINT *height)
6012 const struct wined3d_swapchain *swapchain = context->swapchain;
6013 /* The drawable size of a backbuffer / aux buffer offscreen target is the size of the
6014 * current context's drawable, which is the size of the back buffer of the swapchain
6015 * the active context belongs to. */
6016 *width = swapchain->desc.backbuffer_width;
6017 *height = swapchain->desc.backbuffer_height;
6020 LRESULT device_process_message(struct wined3d_device *device, HWND window, BOOL unicode,
6021 UINT message, WPARAM wparam, LPARAM lparam, WNDPROC proc)
6023 if (device->filter_messages)
6025 TRACE("Filtering message: window %p, message %#x, wparam %#lx, lparam %#lx.\n",
6026 window, message, wparam, lparam);
6028 return DefWindowProcW(window, message, wparam, lparam);
6030 return DefWindowProcA(window, message, wparam, lparam);
6033 if (message == WM_DESTROY)
6035 TRACE("unregister window %p.\n", window);
6036 wined3d_unregister_window(window);
6038 if (device->focus_window == window) device->focus_window = NULL;
6039 else ERR("Window %p is not the focus window for device %p.\n", window, device);
6041 else if (message == WM_DISPLAYCHANGE)
6043 device->device_parent->ops->mode_changed(device->device_parent);
6047 return CallWindowProcW(proc, window, message, wparam, lparam);
6049 return CallWindowProcA(proc, window, message, wparam, lparam);