wined3d: Get rid of the WINED3DRENDERSTATETYPE typedef.
[wine/multimedia.git] / dlls / wined3d / device.c
blob00670e594a2abd50224043faf9d6e0dd5fc21045
1 /*
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
27 #include "config.h"
28 #include <stdio.h>
29 #ifdef HAVE_FLOAT_H
30 # include <float.h>
31 #endif
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 WINED3D_LIGHT_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 */
45 0.0f, /* Range */
46 0.0f, /* Falloff */
47 0.0f, 0.0f, 0.0f, /* Attenuation 0,1,2 */
48 0.0f, /* Theta */
49 0.0f /* Phi */
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(enum wined3d_primitive_type primitive_type)
67 switch(primitive_type)
69 case WINED3D_PT_POINTLIST:
70 return GL_POINTS;
72 case WINED3D_PT_LINELIST:
73 return GL_LINES;
75 case WINED3D_PT_LINESTRIP:
76 return GL_LINE_STRIP;
78 case WINED3D_PT_TRIANGLELIST:
79 return GL_TRIANGLES;
81 case WINED3D_PT_TRIANGLESTRIP:
82 return GL_TRIANGLE_STRIP;
84 case WINED3D_PT_TRIANGLEFAN:
85 return GL_TRIANGLE_FAN;
87 case WINED3D_PT_LINELIST_ADJ:
88 return GL_LINES_ADJACENCY_ARB;
90 case WINED3D_PT_LINESTRIP_ADJ:
91 return GL_LINE_STRIP_ADJACENCY_ARB;
93 case WINED3D_PT_TRIANGLELIST_ADJ:
94 return GL_TRIANGLES_ADJACENCY_ARB;
96 case WINED3D_PT_TRIANGLESTRIP_ADJ:
97 return GL_TRIANGLE_STRIP_ADJACENCY_ARB;
99 default:
100 FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
101 return GL_NONE;
105 static enum wined3d_primitive_type d3d_primitive_type_from_gl(GLenum primitive_type)
107 switch(primitive_type)
109 case GL_POINTS:
110 return WINED3D_PT_POINTLIST;
112 case GL_LINES:
113 return WINED3D_PT_LINELIST;
115 case GL_LINE_STRIP:
116 return WINED3D_PT_LINESTRIP;
118 case GL_TRIANGLES:
119 return WINED3D_PT_TRIANGLELIST;
121 case GL_TRIANGLE_STRIP:
122 return WINED3D_PT_TRIANGLESTRIP;
124 case GL_TRIANGLE_FAN:
125 return WINED3D_PT_TRIANGLEFAN;
127 case GL_LINES_ADJACENCY_ARB:
128 return WINED3D_PT_LINELIST_ADJ;
130 case GL_LINE_STRIP_ADJACENCY_ARB:
131 return WINED3D_PT_LINESTRIP_ADJ;
133 case GL_TRIANGLES_ADJACENCY_ARB:
134 return WINED3D_PT_TRIANGLELIST_ADJ;
136 case GL_TRIANGLE_STRIP_ADJACENCY_ARB:
137 return WINED3D_PT_TRIANGLESTRIP_ADJ;
139 default:
140 FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
141 return WINED3D_PT_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;
163 else
165 FIXME("Unsupported input stream [usage=%s, usage_idx=%u]\n", debug_d3ddeclusage(usage), usage_idx);
166 *regnum = ~0U;
167 return FALSE;
170 return TRUE;
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;
180 BOOL use_vshader;
181 unsigned int i;
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;
197 BOOL stride_used;
198 unsigned int idx;
199 DWORD stride;
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;
207 data.addr = NULL;
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;
216 else
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");
238 if (fixup)
240 if (data.buffer_object)
241 *fixup = TRUE;
242 else if (*fixup && !use_vshader
243 && (element->usage == WINED3DDECLUSAGE_COLOR
244 || element->usage == WINED3DDECLUSAGE_POSITIONT))
246 static BOOL warned = FALSE;
247 if (!warned)
249 /* This may be bad with the fixed function pipeline. */
250 FIXME("Missing vbo streams with unfixed colors or transformed position, expect problems\n");
251 warned = TRUE;
256 data.addr += element->offset;
258 TRACE("offset %u input_slot %u usage_idx %d\n", element->offset, element->input_slot, element->usage_idx);
260 if (use_vshader)
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);
270 else
272 idx = element->output_slot;
273 stride_used = TRUE;
276 else
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));
282 stride_used = FALSE;
284 else
286 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
290 if (stride_used)
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;
339 if (buffer->query)
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 wined3d_strided_element *strided, struct wined3d_stream_info_element *e)
348 e->data.addr = strided->data;
349 e->data.buffer_object = 0;
350 e->format = wined3d_get_format(gl_info, strided->format);
351 e->stride = strided->stride;
352 e->stream_idx = 0;
355 static void device_stream_info_from_strided(const struct wined3d_gl_info *gl_info,
356 const struct wined3d_strided_data *strided, struct wined3d_stream_info *stream_info)
358 unsigned int i;
360 memset(stream_info, 0, sizeof(*stream_info));
362 if (strided->position.data)
363 stream_info_element_from_strided(gl_info, &strided->position, &stream_info->elements[WINED3D_FFP_POSITION]);
364 if (strided->normal.data)
365 stream_info_element_from_strided(gl_info, &strided->normal, &stream_info->elements[WINED3D_FFP_NORMAL]);
366 if (strided->diffuse.data)
367 stream_info_element_from_strided(gl_info, &strided->diffuse, &stream_info->elements[WINED3D_FFP_DIFFUSE]);
368 if (strided->specular.data)
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->tex_coords[i].data)
374 stream_info_element_from_strided(gl_info, &strided->tex_coords[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;
418 BOOL fixup = FALSE;
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);
427 else
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;
440 else
442 device->useDrawStridedSlow = FALSE;
445 else
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;
455 else
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;
475 unsigned int i;
477 if (use_vs(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);
486 if (use_ps(state))
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);
494 else
496 WORD ffu_map = device->fixed_function_usage_map;
498 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
500 if (ffu_map & 1)
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));
516 if (!new_array)
518 ERR("Failed to grow the context array.\n");
519 return FALSE;
522 new_array[device->context_count++] = context;
523 device->contexts = new_array;
524 return TRUE;
527 void device_context_remove(struct wined3d_device *device, struct wined3d_context *context)
529 struct wined3d_context **new_array;
530 BOOL found = FALSE;
531 UINT i;
533 TRACE("Removing context %p.\n", context);
535 for (i = 0; i < device->context_count; ++i)
537 if (device->contexts[i] == context)
539 found = TRUE;
540 break;
544 if (!found)
546 ERR("Context %p doesn't exist in context array.\n", context);
547 return;
550 if (!--device->context_count)
552 HeapFree(GetProcessHeap(), 0, device->contexts);
553 device->contexts = NULL;
554 return;
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));
559 if (!new_array)
561 ERR("Failed to shrink context array. Oh well.\n");
562 return;
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)
590 return FALSE;
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))
596 return FALSE;
598 return TRUE;
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(&current_rect, 0, 0,
608 ds->ds_current_size.cx,
609 ds->ds_current_size.cy);
610 else
611 SetRectEmpty(&current_rect);
613 IntersectRect(&r, draw_rect, &current_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);
618 return;
621 if (EqualRect(&r, &current_rect))
623 /* draw_rect ⊇ current_rect, test if we're doing a full clear. */
625 if (!clear_rect)
627 /* Full clear, modify only. */
628 surface_modify_ds_location(ds, location, draw_rect->right, draw_rect->bottom);
629 return;
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);
637 return;
641 /* Full load. */
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;
657 unsigned int i;
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];
672 if (rt)
673 surface_load_location(rt, rt->draw_binding, NULL);
677 context = context_acquire(device, target);
678 if (!context->valid)
680 context_release(context);
681 WARN("Invalid context, skipping clear.\n");
682 return WINED3D_OK;
685 if (target)
687 render_offscreen = context->render_offscreen;
688 target->get_drawable_size(context, &drawable_width, &drawable_height);
690 else
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");
710 return WINED3D_OK;
713 ENTER_GL();
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(WINED3D_RS_TWOSIDEDSTENCILMODE));
723 glStencilMask(~0U);
724 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_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(WINED3D_RS_ZWRITEENABLE));
736 glClearDepth(depth);
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];
747 if (rt)
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(WINED3D_RS_COLORWRITEENABLE));
753 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
754 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
755 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
756 glClearColor(color->r, color->g, color->b, color->a);
757 checkGLcall("glClearColor");
758 clear_mask = clear_mask | GL_COLOR_BUFFER_BIT;
761 if (!clear_rect)
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);
768 else
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");
774 glClear(clear_mask);
775 checkGLcall("glClear");
777 else
779 RECT current_rect;
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(&current_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(&current_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");
797 continue;
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);
805 else
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");
812 glClear(clear_mask);
813 checkGLcall("glClear");
817 LEAVE_GL();
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);
826 return WINED3D_OK;
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);
835 return 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);
844 if (!refcount)
846 struct wined3d_stateblock *stateblock;
847 UINT i;
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);
890 return refcount;
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);
910 *swapchain = NULL;
912 return WINED3DERR_INVALIDCALL;
915 *swapchain = device->swapchains[swapchain_idx];
916 wined3d_swapchain_incref(*swapchain);
917 TRACE("Returning %p.\n", *swapchain);
919 return WINED3D_OK;
922 static void device_load_logo(struct wined3d_device *device, const char *filename)
924 struct wined3d_color_key color_key;
925 HBITMAP hbm;
926 BITMAP bm;
927 HRESULT hr;
928 HDC dcb = NULL, dcs = NULL;
930 hbm = LoadImageA(NULL, filename, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
931 if(hbm)
933 GetObjectA(hbm, sizeof(BITMAP), &bm);
934 dcb = CreateCompatibleDC(NULL);
935 if(!dcb) goto out;
936 SelectObject(dcb, hbm);
938 else
940 /* Create a 32x32 white surface to indicate that wined3d is used, but the specified image
941 * couldn't be loaded
943 memset(&bm, 0, sizeof(bm));
944 bm.bmWidth = 32;
945 bm.bmHeight = 32;
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);
951 if (FAILED(hr))
953 ERR("Wine logo requested, but failed to create surface, hr %#x.\n", hr);
954 goto out;
957 if (dcb)
959 if (FAILED(hr = wined3d_surface_getdc(device->logo_surface, &dcs)))
960 goto out;
961 BitBlt(dcs, 0, 0, bm.bmWidth, bm.bmHeight, dcb, 0, 0, SRCCOPY);
962 wined3d_surface_releasedc(device->logo_surface, dcs);
964 color_key.color_space_low_value = 0;
965 color_key.color_space_high_value = 0;
966 wined3d_surface_set_color_key(device->logo_surface, WINEDDCKEY_SRCBLT, &color_key);
968 else
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);
975 out:
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. */
989 ENTER_GL();
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)");
1066 LEAVE_GL();
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);
1074 ENTER_GL();
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)");
1095 LEAVE_GL();
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);
1109 return style;
1112 static LONG fullscreen_exstyle(LONG exstyle)
1114 /* Filter out window decorations. */
1115 exstyle &= ~(WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);
1117 return exstyle;
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. */
1182 device->style = 0;
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);
1193 return E_FAIL;
1196 device->focus_window = window;
1197 SetWindowPos(window, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
1199 return WINED3D_OK;
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;
1217 HRESULT hr;
1218 DWORD state;
1219 unsigned int i;
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;
1242 else
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);
1253 if (FAILED(hr))
1255 WARN("Failed to create implicit swapchain\n");
1256 goto err_out;
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");
1264 goto err_out;
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];
1273 else
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);
1286 if (FAILED(hr))
1288 TRACE("Shader private data couldn't be allocated\n");
1289 goto err_out;
1291 hr = device->frag_pipe->alloc_private(device);
1292 if (FAILED(hr))
1294 TRACE("Fragment pipeline private data couldn't be allocated\n");
1295 goto err_out;
1297 hr = device->blitter->alloc_private(device);
1298 if (FAILED(hr))
1300 TRACE("Blitter private data couldn't be allocated\n");
1301 goto err_out;
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);
1313 ENTER_GL();
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)
1321 case ORM_FBO:
1322 device->offscreenBuffer = GL_COLOR_ATTACHMENT0;
1323 break;
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;
1332 else
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");
1341 LEAVE_GL();
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),
1348 &black, 1.0f, 0);
1350 device->d3d_initialized = TRUE;
1352 if (wined3d_settings.logo)
1353 device_load_logo(device, wined3d_settings.logo);
1354 return WINED3D_OK;
1356 err_out:
1357 HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1358 HeapFree(GetProcessHeap(), 0, device->swapchains);
1359 device->swapchain_count = 0;
1360 if (swapchain)
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);
1369 return hr;
1372 HRESULT CDECL wined3d_device_init_gdi(struct wined3d_device *device,
1373 struct wined3d_swapchain_desc *swapchain_desc)
1375 struct wined3d_swapchain *swapchain = NULL;
1376 HRESULT hr;
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);
1384 if (FAILED(hr))
1386 WARN("Failed to create implicit swapchain\n");
1387 goto err_out;
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");
1395 goto err_out;
1397 device->swapchains[0] = swapchain;
1398 return WINED3D_OK;
1400 err_out:
1401 wined3d_swapchain_decref(swapchain);
1402 return hr;
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;
1411 UINT i;
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 stateblock_unbind_resources(device->stateBlock);
1432 /* Unload resources */
1433 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
1435 TRACE("Unloading resource %p.\n", resource);
1437 resource->resource_ops->resource_unload(resource);
1440 TRACE("Deleting high order patches\n");
1441 for(i = 0; i < PATCHMAP_SIZE; i++) {
1442 struct list *e1, *e2;
1443 struct WineD3DRectPatch *patch;
1444 LIST_FOR_EACH_SAFE(e1, e2, &device->patches[i])
1446 patch = LIST_ENTRY(e1, struct WineD3DRectPatch, entry);
1447 wined3d_device_delete_patch(device, patch->Handle);
1451 /* Delete the mouse cursor texture */
1452 if (device->cursorTexture)
1454 ENTER_GL();
1455 glDeleteTextures(1, &device->cursorTexture);
1456 LEAVE_GL();
1457 device->cursorTexture = 0;
1460 /* Destroy the depth blt resources, they will be invalid after the reset. Also free shader
1461 * private data, it might contain opengl pointers
1463 if (device->depth_blt_texture)
1465 ENTER_GL();
1466 glDeleteTextures(1, &device->depth_blt_texture);
1467 LEAVE_GL();
1468 device->depth_blt_texture = 0;
1471 /* Destroy the shader backend. Note that this has to happen after all shaders are destroyed. */
1472 device->blitter->free_private(device);
1473 device->frag_pipe->free_private(device);
1474 device->shader_backend->shader_free_private(device);
1476 /* Release the buffers (with sanity checks)*/
1477 if (device->onscreen_depth_stencil)
1479 surface = device->onscreen_depth_stencil;
1480 device->onscreen_depth_stencil = NULL;
1481 wined3d_surface_decref(surface);
1484 if (device->fb.depth_stencil)
1486 surface = device->fb.depth_stencil;
1488 TRACE("Releasing depth/stencil buffer %p.\n", surface);
1490 device->fb.depth_stencil = NULL;
1491 if (wined3d_surface_decref(surface)
1492 && surface != device->auto_depth_stencil)
1493 ERR("Something is still holding a reference to depth/stencil buffer %p.\n", surface);
1496 if (device->auto_depth_stencil)
1498 surface = device->auto_depth_stencil;
1499 device->auto_depth_stencil = NULL;
1500 if (wined3d_surface_decref(surface))
1501 FIXME("Something's still holding the auto depth stencil buffer (%p).\n", surface);
1504 for (i = 1; i < gl_info->limits.buffers; ++i)
1506 wined3d_device_set_render_target(device, i, NULL, FALSE);
1509 surface = device->fb.render_targets[0];
1510 TRACE("Setting rendertarget 0 to NULL\n");
1511 device->fb.render_targets[0] = NULL;
1512 TRACE("Releasing the render target at %p\n", surface);
1513 wined3d_surface_decref(surface);
1515 context_release(context);
1517 for (i = 0; i < device->swapchain_count; ++i)
1519 TRACE("Releasing the implicit swapchain %u.\n", i);
1520 if (wined3d_swapchain_decref(device->swapchains[i]))
1521 FIXME("Something's still holding the implicit swapchain.\n");
1524 HeapFree(GetProcessHeap(), 0, device->swapchains);
1525 device->swapchains = NULL;
1526 device->swapchain_count = 0;
1528 HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1529 device->fb.render_targets = NULL;
1531 device->d3d_initialized = FALSE;
1533 return WINED3D_OK;
1536 HRESULT CDECL wined3d_device_uninit_gdi(struct wined3d_device *device)
1538 unsigned int i;
1540 for (i = 0; i < device->swapchain_count; ++i)
1542 TRACE("Releasing the implicit swapchain %u.\n", i);
1543 if (wined3d_swapchain_decref(device->swapchains[i]))
1544 FIXME("Something's still holding the implicit swapchain.\n");
1547 HeapFree(GetProcessHeap(), 0, device->swapchains);
1548 device->swapchains = NULL;
1549 device->swapchain_count = 0;
1550 return WINED3D_OK;
1553 /* Enables thread safety in the wined3d device and its resources. Called by DirectDraw
1554 * from SetCooperativeLevel if DDSCL_MULTITHREADED is specified, and by d3d8/9 from
1555 * CreateDevice if D3DCREATE_MULTITHREADED is passed.
1557 * There is no way to deactivate thread safety once it is enabled.
1559 void CDECL wined3d_device_set_multithreaded(struct wined3d_device *device)
1561 TRACE("device %p.\n", device);
1563 /* For now just store the flag (needed in case of ddraw). */
1564 device->create_parms.flags |= WINED3DCREATE_MULTITHREADED;
1567 HRESULT CDECL wined3d_device_set_display_mode(struct wined3d_device *device,
1568 UINT swapchain_idx, const struct wined3d_display_mode *mode)
1570 struct wined3d_adapter *adapter = device->adapter;
1571 const struct wined3d_format *format = wined3d_get_format(&adapter->gl_info, mode->format_id);
1572 DEVMODEW devmode;
1573 LONG ret;
1574 RECT clip_rc;
1576 TRACE("device %p, swapchain_idx %u, mode %p (%ux%u@%u %s).\n", device, swapchain_idx, mode,
1577 mode->width, mode->height, mode->refresh_rate, debug_d3dformat(mode->format_id));
1579 /* Resize the screen even without a window:
1580 * The app could have unset it with SetCooperativeLevel, but not called
1581 * RestoreDisplayMode first. Then the release will call RestoreDisplayMode,
1582 * but we don't have any hwnd
1585 memset(&devmode, 0, sizeof(devmode));
1586 devmode.dmSize = sizeof(devmode);
1587 devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1588 devmode.dmBitsPerPel = format->byte_count * CHAR_BIT;
1589 devmode.dmPelsWidth = mode->width;
1590 devmode.dmPelsHeight = mode->height;
1592 devmode.dmDisplayFrequency = mode->refresh_rate;
1593 if (mode->refresh_rate)
1594 devmode.dmFields |= DM_DISPLAYFREQUENCY;
1596 /* Only change the mode if necessary */
1597 if (adapter->screen_size.cx == mode->width && adapter->screen_size.cy == mode->height
1598 && adapter->screen_format == mode->format_id && !mode->refresh_rate)
1599 return WINED3D_OK;
1601 ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL);
1602 if (ret != DISP_CHANGE_SUCCESSFUL)
1604 if (devmode.dmDisplayFrequency)
1606 WARN("ChangeDisplaySettingsExW failed, trying without the refresh rate\n");
1607 devmode.dmFields &= ~DM_DISPLAYFREQUENCY;
1608 devmode.dmDisplayFrequency = 0;
1609 ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL) != DISP_CHANGE_SUCCESSFUL;
1611 if(ret != DISP_CHANGE_SUCCESSFUL) {
1612 return WINED3DERR_NOTAVAILABLE;
1616 /* Store the new values */
1617 adapter->screen_size.cx = mode->width;
1618 adapter->screen_size.cy = mode->height;
1619 adapter->screen_format = mode->format_id;
1621 /* And finally clip mouse to our screen */
1622 SetRect(&clip_rc, 0, 0, mode->width, mode->height);
1623 ClipCursor(&clip_rc);
1625 return WINED3D_OK;
1628 HRESULT CDECL wined3d_device_get_wined3d(const struct wined3d_device *device, struct wined3d **wined3d)
1630 TRACE("device %p, wined3d %p.\n", device, wined3d);
1632 *wined3d = device->wined3d;
1633 wined3d_incref(*wined3d);
1635 TRACE("Returning %p.\n", *wined3d);
1637 return WINED3D_OK;
1640 UINT CDECL wined3d_device_get_available_texture_mem(const struct wined3d_device *device)
1642 TRACE("device %p.\n", device);
1644 TRACE("Emulating %d MB, returning %d MB left.\n",
1645 device->adapter->TextureRam / (1024 * 1024),
1646 (device->adapter->TextureRam - device->adapter->UsedTextureRam) / (1024 * 1024));
1648 return device->adapter->TextureRam - device->adapter->UsedTextureRam;
1651 HRESULT CDECL wined3d_device_set_stream_source(struct wined3d_device *device, UINT stream_idx,
1652 struct wined3d_buffer *buffer, UINT offset, UINT stride)
1654 struct wined3d_stream_state *stream;
1655 struct wined3d_buffer *prev_buffer;
1657 TRACE("device %p, stream_idx %u, buffer %p, offset %u, stride %u.\n",
1658 device, stream_idx, buffer, offset, stride);
1660 if (stream_idx >= MAX_STREAMS)
1662 WARN("Stream index %u out of range.\n", stream_idx);
1663 return WINED3DERR_INVALIDCALL;
1665 else if (offset & 0x3)
1667 WARN("Offset %u is not 4 byte aligned.\n", offset);
1668 return WINED3DERR_INVALIDCALL;
1671 stream = &device->updateStateBlock->state.streams[stream_idx];
1672 prev_buffer = stream->buffer;
1674 device->updateStateBlock->changed.streamSource |= 1 << stream_idx;
1676 if (prev_buffer == buffer
1677 && stream->stride == stride
1678 && stream->offset == offset)
1680 TRACE("Application is setting the old values over, nothing to do.\n");
1681 return WINED3D_OK;
1684 stream->buffer = buffer;
1685 if (buffer)
1687 stream->stride = stride;
1688 stream->offset = offset;
1691 /* Handle recording of state blocks. */
1692 if (device->isRecordingState)
1694 TRACE("Recording... not performing anything.\n");
1695 if (buffer)
1696 wined3d_buffer_incref(buffer);
1697 if (prev_buffer)
1698 wined3d_buffer_decref(prev_buffer);
1699 return WINED3D_OK;
1702 if (buffer)
1704 InterlockedIncrement(&buffer->bind_count);
1705 wined3d_buffer_incref(buffer);
1707 if (prev_buffer)
1709 InterlockedDecrement(&prev_buffer->bind_count);
1710 wined3d_buffer_decref(prev_buffer);
1713 device_invalidate_state(device, STATE_STREAMSRC);
1715 return WINED3D_OK;
1718 HRESULT CDECL wined3d_device_get_stream_source(const struct wined3d_device *device,
1719 UINT stream_idx, struct wined3d_buffer **buffer, UINT *offset, UINT *stride)
1721 struct wined3d_stream_state *stream;
1723 TRACE("device %p, stream_idx %u, buffer %p, offset %p, stride %p.\n",
1724 device, stream_idx, buffer, offset, stride);
1726 if (stream_idx >= MAX_STREAMS)
1728 WARN("Stream index %u out of range.\n", stream_idx);
1729 return WINED3DERR_INVALIDCALL;
1732 stream = &device->stateBlock->state.streams[stream_idx];
1733 *buffer = stream->buffer;
1734 if (*buffer)
1735 wined3d_buffer_incref(*buffer);
1736 if (offset)
1737 *offset = stream->offset;
1738 *stride = stream->stride;
1740 return WINED3D_OK;
1743 HRESULT CDECL wined3d_device_set_stream_source_freq(struct wined3d_device *device, UINT stream_idx, UINT divider)
1745 struct wined3d_stream_state *stream;
1746 UINT old_flags, old_freq;
1748 TRACE("device %p, stream_idx %u, divider %#x.\n", device, stream_idx, divider);
1750 /* Verify input. At least in d3d9 this is invalid. */
1751 if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && (divider & WINED3DSTREAMSOURCE_INDEXEDDATA))
1753 WARN("INSTANCEDATA and INDEXEDDATA were set, returning D3DERR_INVALIDCALL.\n");
1754 return WINED3DERR_INVALIDCALL;
1756 if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && !stream_idx)
1758 WARN("INSTANCEDATA used on stream 0, returning D3DERR_INVALIDCALL.\n");
1759 return WINED3DERR_INVALIDCALL;
1761 if (!divider)
1763 WARN("Divider is 0, returning D3DERR_INVALIDCALL.\n");
1764 return WINED3DERR_INVALIDCALL;
1767 stream = &device->updateStateBlock->state.streams[stream_idx];
1768 old_flags = stream->flags;
1769 old_freq = stream->frequency;
1771 stream->flags = divider & (WINED3DSTREAMSOURCE_INSTANCEDATA | WINED3DSTREAMSOURCE_INDEXEDDATA);
1772 stream->frequency = divider & 0x7fffff;
1774 device->updateStateBlock->changed.streamFreq |= 1 << stream_idx;
1776 if (stream->frequency != old_freq || stream->flags != old_flags)
1777 device_invalidate_state(device, STATE_STREAMSRC);
1779 return WINED3D_OK;
1782 HRESULT CDECL wined3d_device_get_stream_source_freq(const struct wined3d_device *device,
1783 UINT stream_idx, UINT *divider)
1785 struct wined3d_stream_state *stream;
1787 TRACE("device %p, stream_idx %u, divider %p.\n", device, stream_idx, divider);
1789 stream = &device->updateStateBlock->state.streams[stream_idx];
1790 *divider = stream->flags | stream->frequency;
1792 TRACE("Returning %#x.\n", *divider);
1794 return WINED3D_OK;
1797 HRESULT CDECL wined3d_device_set_transform(struct wined3d_device *device,
1798 WINED3DTRANSFORMSTATETYPE d3dts, const struct wined3d_matrix *matrix)
1800 TRACE("device %p, state %s, matrix %p.\n",
1801 device, debug_d3dtstype(d3dts), matrix);
1803 /* Handle recording of state blocks. */
1804 if (device->isRecordingState)
1806 TRACE("Recording... not performing anything.\n");
1807 device->updateStateBlock->changed.transform[d3dts >> 5] |= 1 << (d3dts & 0x1f);
1808 device->updateStateBlock->state.transforms[d3dts] = *matrix;
1809 return WINED3D_OK;
1812 /* If the new matrix is the same as the current one,
1813 * we cut off any further processing. this seems to be a reasonable
1814 * optimization because as was noticed, some apps (warcraft3 for example)
1815 * tend towards setting the same matrix repeatedly for some reason.
1817 * From here on we assume that the new matrix is different, wherever it matters. */
1818 if (!memcmp(&device->stateBlock->state.transforms[d3dts].u.m[0][0], matrix, sizeof(*matrix)))
1820 TRACE("The application is setting the same matrix over again.\n");
1821 return WINED3D_OK;
1824 conv_mat(matrix, &device->stateBlock->state.transforms[d3dts].u.m[0][0]);
1826 /* ScreenCoord = ProjectionMat * ViewMat * WorldMat * ObjectCoord
1827 * where ViewMat = Camera space, WorldMat = world space.
1829 * In OpenGL, camera and world space is combined into GL_MODELVIEW
1830 * matrix. The Projection matrix stay projection matrix. */
1832 if (d3dts == WINED3DTS_VIEW)
1833 device->view_ident = !memcmp(matrix, identity, 16 * sizeof(float));
1835 if (d3dts < WINED3DTS_WORLDMATRIX(device->adapter->gl_info.limits.blends))
1836 device_invalidate_state(device, STATE_TRANSFORM(d3dts));
1838 return WINED3D_OK;
1842 HRESULT CDECL wined3d_device_get_transform(const struct wined3d_device *device,
1843 WINED3DTRANSFORMSTATETYPE state, struct wined3d_matrix *matrix)
1845 TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1847 *matrix = device->stateBlock->state.transforms[state];
1849 return WINED3D_OK;
1852 HRESULT CDECL wined3d_device_multiply_transform(struct wined3d_device *device,
1853 WINED3DTRANSFORMSTATETYPE state, const struct wined3d_matrix *matrix)
1855 const struct wined3d_matrix *mat = NULL;
1856 struct wined3d_matrix temp;
1858 TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1860 /* Note: Using 'updateStateBlock' rather than 'stateblock' in the code
1861 * below means it will be recorded in a state block change, but it
1862 * works regardless where it is recorded.
1863 * If this is found to be wrong, change to StateBlock. */
1864 if (state > HIGHEST_TRANSFORMSTATE)
1866 WARN("Unhandled transform state %#x.\n", state);
1867 return WINED3D_OK;
1870 mat = &device->updateStateBlock->state.transforms[state];
1871 multiply_matrix(&temp, mat, matrix);
1873 /* Apply change via set transform - will reapply to eg. lights this way. */
1874 return wined3d_device_set_transform(device, state, &temp);
1877 /* Note lights are real special cases. Although the device caps state only
1878 * e.g. 8 are supported, you can reference any indexes you want as long as
1879 * that number max are enabled at any one point in time. Therefore since the
1880 * indices can be anything, we need a hashmap of them. However, this causes
1881 * stateblock problems. When capturing the state block, I duplicate the
1882 * hashmap, but when recording, just build a chain pretty much of commands to
1883 * be replayed. */
1884 HRESULT CDECL wined3d_device_set_light(struct wined3d_device *device,
1885 UINT light_idx, const struct wined3d_light *light)
1887 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
1888 struct wined3d_light_info *object = NULL;
1889 struct list *e;
1890 float rho;
1892 TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
1894 /* Check the parameter range. Need for speed most wanted sets junk lights
1895 * which confuse the GL driver. */
1896 if (!light)
1897 return WINED3DERR_INVALIDCALL;
1899 switch (light->type)
1901 case WINED3D_LIGHT_POINT:
1902 case WINED3D_LIGHT_SPOT:
1903 case WINED3D_LIGHT_PARALLELPOINT:
1904 case WINED3D_LIGHT_GLSPOT:
1905 /* Incorrect attenuation values can cause the gl driver to crash.
1906 * Happens with Need for speed most wanted. */
1907 if (light->attenuation0 < 0.0f || light->attenuation1 < 0.0f || light->attenuation2 < 0.0f)
1909 WARN("Attenuation is negative, returning WINED3DERR_INVALIDCALL.\n");
1910 return WINED3DERR_INVALIDCALL;
1912 break;
1914 case WINED3D_LIGHT_DIRECTIONAL:
1915 /* Ignores attenuation */
1916 break;
1918 default:
1919 WARN("Light type out of range, returning WINED3DERR_INVALIDCALL\n");
1920 return WINED3DERR_INVALIDCALL;
1923 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
1925 object = LIST_ENTRY(e, struct wined3d_light_info, entry);
1926 if (object->OriginalIndex == light_idx)
1927 break;
1928 object = NULL;
1931 if (!object)
1933 TRACE("Adding new light\n");
1934 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1935 if (!object)
1937 ERR("Out of memory error when allocating a light\n");
1938 return E_OUTOFMEMORY;
1940 list_add_head(&device->updateStateBlock->state.light_map[hash_idx], &object->entry);
1941 object->glIndex = -1;
1942 object->OriginalIndex = light_idx;
1945 /* Initialize the object. */
1946 TRACE("Light %d setting to type %d, Diffuse(%f,%f,%f,%f), Specular(%f,%f,%f,%f), Ambient(%f,%f,%f,%f)\n",
1947 light_idx, light->type,
1948 light->diffuse.r, light->diffuse.g, light->diffuse.b, light->diffuse.a,
1949 light->specular.r, light->specular.g, light->specular.b, light->specular.a,
1950 light->ambient.r, light->ambient.g, light->ambient.b, light->ambient.a);
1951 TRACE("... Pos(%f,%f,%f), Dir(%f,%f,%f)\n", light->position.x, light->position.y, light->position.z,
1952 light->direction.x, light->direction.y, light->direction.z);
1953 TRACE("... Range(%f), Falloff(%f), Theta(%f), Phi(%f)\n",
1954 light->range, light->falloff, light->theta, light->phi);
1956 /* Save away the information. */
1957 object->OriginalParms = *light;
1959 switch (light->type)
1961 case WINED3D_LIGHT_POINT:
1962 /* Position */
1963 object->lightPosn[0] = light->position.x;
1964 object->lightPosn[1] = light->position.y;
1965 object->lightPosn[2] = light->position.z;
1966 object->lightPosn[3] = 1.0f;
1967 object->cutoff = 180.0f;
1968 /* FIXME: Range */
1969 break;
1971 case WINED3D_LIGHT_DIRECTIONAL:
1972 /* Direction */
1973 object->lightPosn[0] = -light->direction.x;
1974 object->lightPosn[1] = -light->direction.y;
1975 object->lightPosn[2] = -light->direction.z;
1976 object->lightPosn[3] = 0.0f;
1977 object->exponent = 0.0f;
1978 object->cutoff = 180.0f;
1979 break;
1981 case WINED3D_LIGHT_SPOT:
1982 /* Position */
1983 object->lightPosn[0] = light->position.x;
1984 object->lightPosn[1] = light->position.y;
1985 object->lightPosn[2] = light->position.z;
1986 object->lightPosn[3] = 1.0f;
1988 /* Direction */
1989 object->lightDirn[0] = light->direction.x;
1990 object->lightDirn[1] = light->direction.y;
1991 object->lightDirn[2] = light->direction.z;
1992 object->lightDirn[3] = 1.0f;
1994 /* opengl-ish and d3d-ish spot lights use too different models
1995 * for the light "intensity" as a function of the angle towards
1996 * the main light direction, so we only can approximate very
1997 * roughly. However, spot lights are rather rarely used in games
1998 * (if ever used at all). Furthermore if still used, probably
1999 * nobody pays attention to such details. */
2000 if (!light->falloff)
2002 /* Falloff = 0 is easy, because d3d's and opengl's spot light
2003 * equations have the falloff resp. exponent parameter as an
2004 * exponent, so the spot light lighting will always be 1.0 for
2005 * both of them, and we don't have to care for the rest of the
2006 * rather complex calculation. */
2007 object->exponent = 0.0f;
2009 else
2011 rho = light->theta + (light->phi - light->theta) / (2 * light->falloff);
2012 if (rho < 0.0001f)
2013 rho = 0.0001f;
2014 object->exponent = -0.3f / logf(cosf(rho / 2));
2017 if (object->exponent > 128.0f)
2018 object->exponent = 128.0f;
2020 object->cutoff = (float)(light->phi * 90 / M_PI);
2021 /* FIXME: Range */
2022 break;
2024 default:
2025 FIXME("Unrecognized light type %#x.\n", light->type);
2028 /* Update the live definitions if the light is currently assigned a glIndex. */
2029 if (object->glIndex != -1 && !device->isRecordingState)
2030 device_invalidate_state(device, STATE_ACTIVELIGHT(object->glIndex));
2032 return WINED3D_OK;
2035 HRESULT CDECL wined3d_device_get_light(const struct wined3d_device *device,
2036 UINT light_idx, struct wined3d_light *light)
2038 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2039 struct wined3d_light_info *light_info = NULL;
2040 struct list *e;
2042 TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
2044 LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
2046 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2047 if (light_info->OriginalIndex == light_idx)
2048 break;
2049 light_info = NULL;
2052 if (!light_info)
2054 TRACE("Light information requested but light not defined\n");
2055 return WINED3DERR_INVALIDCALL;
2058 *light = light_info->OriginalParms;
2059 return WINED3D_OK;
2062 HRESULT CDECL wined3d_device_set_light_enable(struct wined3d_device *device, UINT light_idx, BOOL enable)
2064 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2065 struct wined3d_light_info *light_info = NULL;
2066 struct list *e;
2068 TRACE("device %p, light_idx %u, enable %#x.\n", device, light_idx, enable);
2070 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2072 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2073 if (light_info->OriginalIndex == light_idx)
2074 break;
2075 light_info = NULL;
2077 TRACE("Found light %p.\n", light_info);
2079 /* Special case - enabling an undefined light creates one with a strict set of parameters. */
2080 if (!light_info)
2082 TRACE("Light enabled requested but light not defined, so defining one!\n");
2083 wined3d_device_set_light(device, light_idx, &WINED3D_default_light);
2085 /* Search for it again! Should be fairly quick as near head of list. */
2086 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2088 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2089 if (light_info->OriginalIndex == light_idx)
2090 break;
2091 light_info = NULL;
2093 if (!light_info)
2095 FIXME("Adding default lights has failed dismally\n");
2096 return WINED3DERR_INVALIDCALL;
2100 if (!enable)
2102 if (light_info->glIndex != -1)
2104 if (!device->isRecordingState)
2105 device_invalidate_state(device, STATE_ACTIVELIGHT(light_info->glIndex));
2107 device->updateStateBlock->state.lights[light_info->glIndex] = NULL;
2108 light_info->glIndex = -1;
2110 else
2112 TRACE("Light already disabled, nothing to do\n");
2114 light_info->enabled = FALSE;
2116 else
2118 light_info->enabled = TRUE;
2119 if (light_info->glIndex != -1)
2121 TRACE("Nothing to do as light was enabled\n");
2123 else
2125 unsigned int i;
2126 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2127 /* Find a free GL light. */
2128 for (i = 0; i < gl_info->limits.lights; ++i)
2130 if (!device->updateStateBlock->state.lights[i])
2132 device->updateStateBlock->state.lights[i] = light_info;
2133 light_info->glIndex = i;
2134 break;
2137 if (light_info->glIndex == -1)
2139 /* Our tests show that Windows returns D3D_OK in this situation, even with
2140 * D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE devices. This
2141 * is consistent among ddraw, d3d8 and d3d9. GetLightEnable returns TRUE
2142 * as well for those lights.
2144 * TODO: Test how this affects rendering. */
2145 WARN("Too many concurrently active lights\n");
2146 return WINED3D_OK;
2149 /* i == light_info->glIndex */
2150 if (!device->isRecordingState)
2151 device_invalidate_state(device, STATE_ACTIVELIGHT(i));
2155 return WINED3D_OK;
2158 HRESULT CDECL wined3d_device_get_light_enable(const struct wined3d_device *device, UINT light_idx, BOOL *enable)
2160 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2161 struct wined3d_light_info *light_info = NULL;
2162 struct list *e;
2164 TRACE("device %p, light_idx %u, enable %p.\n", device, light_idx, enable);
2166 LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
2168 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2169 if (light_info->OriginalIndex == light_idx)
2170 break;
2171 light_info = NULL;
2174 if (!light_info)
2176 TRACE("Light enabled state requested but light not defined.\n");
2177 return WINED3DERR_INVALIDCALL;
2179 /* true is 128 according to SetLightEnable */
2180 *enable = light_info->enabled ? 128 : 0;
2181 return WINED3D_OK;
2184 HRESULT CDECL wined3d_device_set_clip_plane(struct wined3d_device *device, UINT plane_idx, const float *plane)
2186 TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2188 /* Validate plane_idx. */
2189 if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2191 TRACE("Application has requested clipplane this device doesn't support.\n");
2192 return WINED3DERR_INVALIDCALL;
2195 device->updateStateBlock->changed.clipplane |= 1 << plane_idx;
2197 if (device->updateStateBlock->state.clip_planes[plane_idx][0] == plane[0]
2198 && device->updateStateBlock->state.clip_planes[plane_idx][1] == plane[1]
2199 && device->updateStateBlock->state.clip_planes[plane_idx][2] == plane[2]
2200 && device->updateStateBlock->state.clip_planes[plane_idx][3] == plane[3])
2202 TRACE("Application is setting old values over, nothing to do.\n");
2203 return WINED3D_OK;
2206 device->updateStateBlock->state.clip_planes[plane_idx][0] = plane[0];
2207 device->updateStateBlock->state.clip_planes[plane_idx][1] = plane[1];
2208 device->updateStateBlock->state.clip_planes[plane_idx][2] = plane[2];
2209 device->updateStateBlock->state.clip_planes[plane_idx][3] = plane[3];
2211 /* Handle recording of state blocks. */
2212 if (device->isRecordingState)
2214 TRACE("Recording... not performing anything.\n");
2215 return WINED3D_OK;
2218 device_invalidate_state(device, STATE_CLIPPLANE(plane_idx));
2220 return WINED3D_OK;
2223 HRESULT CDECL wined3d_device_get_clip_plane(const struct wined3d_device *device, UINT plane_idx, float *plane)
2225 TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2227 /* Validate plane_idx. */
2228 if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2230 TRACE("Application has requested clipplane this device doesn't support.\n");
2231 return WINED3DERR_INVALIDCALL;
2234 plane[0] = (float)device->stateBlock->state.clip_planes[plane_idx][0];
2235 plane[1] = (float)device->stateBlock->state.clip_planes[plane_idx][1];
2236 plane[2] = (float)device->stateBlock->state.clip_planes[plane_idx][2];
2237 plane[3] = (float)device->stateBlock->state.clip_planes[plane_idx][3];
2239 return WINED3D_OK;
2242 HRESULT CDECL wined3d_device_set_clip_status(struct wined3d_device *device,
2243 const struct wined3d_clip_status *clip_status)
2245 FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2247 if (!clip_status)
2248 return WINED3DERR_INVALIDCALL;
2250 return WINED3D_OK;
2253 HRESULT CDECL wined3d_device_get_clip_status(const struct wined3d_device *device,
2254 struct wined3d_clip_status *clip_status)
2256 FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2258 if (!clip_status)
2259 return WINED3DERR_INVALIDCALL;
2261 return WINED3D_OK;
2264 HRESULT CDECL wined3d_device_set_material(struct wined3d_device *device, const struct wined3d_material *material)
2266 TRACE("device %p, material %p.\n", device, material);
2268 device->updateStateBlock->changed.material = TRUE;
2269 device->updateStateBlock->state.material = *material;
2271 /* Handle recording of state blocks */
2272 if (device->isRecordingState)
2274 TRACE("Recording... not performing anything.\n");
2275 return WINED3D_OK;
2278 device_invalidate_state(device, STATE_MATERIAL);
2280 return WINED3D_OK;
2283 HRESULT CDECL wined3d_device_get_material(const struct wined3d_device *device, struct wined3d_material *material)
2285 TRACE("device %p, material %p.\n", device, material);
2287 *material = device->updateStateBlock->state.material;
2289 TRACE("diffuse {%.8e, %.8e, %.8e, %.8e}\n",
2290 material->diffuse.r, material->diffuse.g,
2291 material->diffuse.b, material->diffuse.a);
2292 TRACE("ambient {%.8e, %.8e, %.8e, %.8e}\n",
2293 material->ambient.r, material->ambient.g,
2294 material->ambient.b, material->ambient.a);
2295 TRACE("specular {%.8e, %.8e, %.8e, %.8e}\n",
2296 material->specular.r, material->specular.g,
2297 material->specular.b, material->specular.a);
2298 TRACE("emissive {%.8e, %.8e, %.8e, %.8e}\n",
2299 material->emissive.r, material->emissive.g,
2300 material->emissive.b, material->emissive.a);
2301 TRACE("power %.8e.\n", material->power);
2303 return WINED3D_OK;
2306 HRESULT CDECL wined3d_device_set_index_buffer(struct wined3d_device *device,
2307 struct wined3d_buffer *buffer, enum wined3d_format_id format_id)
2309 struct wined3d_buffer *prev_buffer;
2311 TRACE("device %p, buffer %p, format %s.\n",
2312 device, buffer, debug_d3dformat(format_id));
2314 prev_buffer = device->updateStateBlock->state.index_buffer;
2316 device->updateStateBlock->changed.indices = TRUE;
2317 device->updateStateBlock->state.index_buffer = buffer;
2318 device->updateStateBlock->state.index_format = format_id;
2320 /* Handle recording of state blocks. */
2321 if (device->isRecordingState)
2323 TRACE("Recording... not performing anything.\n");
2324 if (buffer)
2325 wined3d_buffer_incref(buffer);
2326 if (prev_buffer)
2327 wined3d_buffer_decref(prev_buffer);
2328 return WINED3D_OK;
2331 if (prev_buffer != buffer)
2333 device_invalidate_state(device, STATE_INDEXBUFFER);
2334 if (buffer)
2336 InterlockedIncrement(&buffer->bind_count);
2337 wined3d_buffer_incref(buffer);
2339 if (prev_buffer)
2341 InterlockedDecrement(&prev_buffer->bind_count);
2342 wined3d_buffer_decref(prev_buffer);
2346 return WINED3D_OK;
2349 HRESULT CDECL wined3d_device_get_index_buffer(const struct wined3d_device *device, struct wined3d_buffer **buffer)
2351 TRACE("device %p, buffer %p.\n", device, buffer);
2353 *buffer = device->stateBlock->state.index_buffer;
2355 if (*buffer)
2356 wined3d_buffer_incref(*buffer);
2358 TRACE("Returning %p.\n", *buffer);
2360 return WINED3D_OK;
2363 /* Method to offer d3d9 a simple way to set the base vertex index without messing with the index buffer */
2364 HRESULT CDECL wined3d_device_set_base_vertex_index(struct wined3d_device *device, INT base_index)
2366 TRACE("device %p, base_index %d.\n", device, base_index);
2368 if (device->updateStateBlock->state.base_vertex_index == base_index)
2370 TRACE("Application is setting the old value over, nothing to do\n");
2371 return WINED3D_OK;
2374 device->updateStateBlock->state.base_vertex_index = base_index;
2376 if (device->isRecordingState)
2378 TRACE("Recording... not performing anything\n");
2379 return WINED3D_OK;
2381 return WINED3D_OK;
2384 INT CDECL wined3d_device_get_base_vertex_index(const struct wined3d_device *device)
2386 TRACE("device %p.\n", device);
2388 return device->stateBlock->state.base_vertex_index;
2391 HRESULT CDECL wined3d_device_set_viewport(struct wined3d_device *device, const struct wined3d_viewport *viewport)
2393 TRACE("device %p, viewport %p.\n", device, viewport);
2394 TRACE("x %u, y %u, w %u, h %u, min_z %.8e, max_z %.8e.\n",
2395 viewport->x, viewport->y, viewport->width, viewport->height, viewport->min_z, viewport->max_z);
2397 device->updateStateBlock->changed.viewport = TRUE;
2398 device->updateStateBlock->state.viewport = *viewport;
2400 /* Handle recording of state blocks */
2401 if (device->isRecordingState)
2403 TRACE("Recording... not performing anything\n");
2404 return WINED3D_OK;
2407 device_invalidate_state(device, STATE_VIEWPORT);
2409 return WINED3D_OK;
2412 HRESULT CDECL wined3d_device_get_viewport(const struct wined3d_device *device, struct wined3d_viewport *viewport)
2414 TRACE("device %p, viewport %p.\n", device, viewport);
2416 *viewport = device->stateBlock->state.viewport;
2418 return WINED3D_OK;
2421 HRESULT CDECL wined3d_device_set_render_state(struct wined3d_device *device,
2422 enum wined3d_render_state state, DWORD value)
2424 DWORD old_value = device->stateBlock->state.render_states[state];
2426 TRACE("device %p, state %s (%#x), value %#x.\n", device, debug_d3drenderstate(state), state, value);
2428 device->updateStateBlock->changed.renderState[state >> 5] |= 1 << (state & 0x1f);
2429 device->updateStateBlock->state.render_states[state] = value;
2431 /* Handle recording of state blocks. */
2432 if (device->isRecordingState)
2434 TRACE("Recording... not performing anything.\n");
2435 return WINED3D_OK;
2438 /* Compared here and not before the assignment to allow proper stateblock recording. */
2439 if (value == old_value)
2440 TRACE("Application is setting the old value over, nothing to do.\n");
2441 else
2442 device_invalidate_state(device, STATE_RENDER(state));
2444 return WINED3D_OK;
2447 HRESULT CDECL wined3d_device_get_render_state(const struct wined3d_device *device,
2448 enum wined3d_render_state state, DWORD *value)
2450 TRACE("device %p, state %s (%#x), value %p.\n", device, debug_d3drenderstate(state), state, value);
2452 *value = device->stateBlock->state.render_states[state];
2454 return WINED3D_OK;
2457 HRESULT CDECL wined3d_device_set_sampler_state(struct wined3d_device *device,
2458 UINT sampler_idx, WINED3DSAMPLERSTATETYPE state, DWORD value)
2460 DWORD old_value;
2462 TRACE("device %p, sampler_idx %u, state %s, value %#x.\n",
2463 device, sampler_idx, debug_d3dsamplerstate(state), value);
2465 if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2466 sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2468 if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2469 / sizeof(*device->stateBlock->state.sampler_states))
2471 WARN("Invalid sampler %u.\n", sampler_idx);
2472 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2475 old_value = device->stateBlock->state.sampler_states[sampler_idx][state];
2476 device->updateStateBlock->state.sampler_states[sampler_idx][state] = value;
2477 device->updateStateBlock->changed.samplerState[sampler_idx] |= 1 << state;
2479 /* Handle recording of state blocks. */
2480 if (device->isRecordingState)
2482 TRACE("Recording... not performing anything.\n");
2483 return WINED3D_OK;
2486 if (old_value == value)
2488 TRACE("Application is setting the old value over, nothing to do.\n");
2489 return WINED3D_OK;
2492 device_invalidate_state(device, STATE_SAMPLER(sampler_idx));
2494 return WINED3D_OK;
2497 HRESULT CDECL wined3d_device_get_sampler_state(const struct wined3d_device *device,
2498 UINT sampler_idx, WINED3DSAMPLERSTATETYPE state, DWORD *value)
2500 TRACE("device %p, sampler_idx %u, state %s, value %p.\n",
2501 device, sampler_idx, debug_d3dsamplerstate(state), value);
2503 if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2504 sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2506 if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2507 / sizeof(*device->stateBlock->state.sampler_states))
2509 WARN("Invalid sampler %u.\n", sampler_idx);
2510 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2513 *value = device->stateBlock->state.sampler_states[sampler_idx][state];
2514 TRACE("Returning %#x.\n", *value);
2516 return WINED3D_OK;
2519 HRESULT CDECL wined3d_device_set_scissor_rect(struct wined3d_device *device, const RECT *rect)
2521 TRACE("device %p, rect %s.\n", device, wine_dbgstr_rect(rect));
2523 device->updateStateBlock->changed.scissorRect = TRUE;
2524 if (EqualRect(&device->updateStateBlock->state.scissor_rect, rect))
2526 TRACE("App is setting the old scissor rectangle over, nothing to do.\n");
2527 return WINED3D_OK;
2529 CopyRect(&device->updateStateBlock->state.scissor_rect, rect);
2531 if (device->isRecordingState)
2533 TRACE("Recording... not performing anything.\n");
2534 return WINED3D_OK;
2537 device_invalidate_state(device, STATE_SCISSORRECT);
2539 return WINED3D_OK;
2542 HRESULT CDECL wined3d_device_get_scissor_rect(const struct wined3d_device *device, RECT *rect)
2544 TRACE("device %p, rect %p.\n", device, rect);
2546 *rect = device->updateStateBlock->state.scissor_rect;
2547 TRACE("Returning rect %s.\n", wine_dbgstr_rect(rect));
2549 return WINED3D_OK;
2552 HRESULT CDECL wined3d_device_set_vertex_declaration(struct wined3d_device *device,
2553 struct wined3d_vertex_declaration *declaration)
2555 struct wined3d_vertex_declaration *prev = device->updateStateBlock->state.vertex_declaration;
2557 TRACE("device %p, declaration %p.\n", device, declaration);
2559 if (declaration)
2560 wined3d_vertex_declaration_incref(declaration);
2561 if (prev)
2562 wined3d_vertex_declaration_decref(prev);
2564 device->updateStateBlock->state.vertex_declaration = declaration;
2565 device->updateStateBlock->changed.vertexDecl = TRUE;
2567 if (device->isRecordingState)
2569 TRACE("Recording... not performing anything.\n");
2570 return WINED3D_OK;
2572 else if (declaration == prev)
2574 /* Checked after the assignment to allow proper stateblock recording. */
2575 TRACE("Application is setting the old declaration over, nothing to do.\n");
2576 return WINED3D_OK;
2579 device_invalidate_state(device, STATE_VDECL);
2580 return WINED3D_OK;
2583 HRESULT CDECL wined3d_device_get_vertex_declaration(const struct wined3d_device *device,
2584 struct wined3d_vertex_declaration **declaration)
2586 TRACE("device %p, declaration %p.\n", device, declaration);
2588 *declaration = device->stateBlock->state.vertex_declaration;
2589 if (*declaration)
2590 wined3d_vertex_declaration_incref(*declaration);
2592 return WINED3D_OK;
2595 HRESULT CDECL wined3d_device_set_vertex_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2597 struct wined3d_shader *prev = device->updateStateBlock->state.vertex_shader;
2599 TRACE("device %p, shader %p.\n", device, shader);
2601 device->updateStateBlock->state.vertex_shader = shader;
2602 device->updateStateBlock->changed.vertexShader = TRUE;
2604 if (device->isRecordingState)
2606 if (shader)
2607 wined3d_shader_incref(shader);
2608 if (prev)
2609 wined3d_shader_decref(prev);
2610 TRACE("Recording... not performing anything.\n");
2611 return WINED3D_OK;
2614 if (shader == prev)
2616 TRACE("Application is setting the old shader over, nothing to do.\n");
2617 return WINED3D_OK;
2620 if (shader)
2621 wined3d_shader_incref(shader);
2622 if (prev)
2623 wined3d_shader_decref(prev);
2625 device_invalidate_state(device, STATE_VSHADER);
2627 return WINED3D_OK;
2630 struct wined3d_shader * CDECL wined3d_device_get_vertex_shader(const struct wined3d_device *device)
2632 struct wined3d_shader *shader;
2634 TRACE("device %p.\n", device);
2636 shader = device->stateBlock->state.vertex_shader;
2637 if (shader)
2638 wined3d_shader_incref(shader);
2640 TRACE("Returning %p.\n", shader);
2641 return shader;
2644 HRESULT CDECL wined3d_device_set_vs_consts_b(struct wined3d_device *device,
2645 UINT start_register, const BOOL *constants, UINT bool_count)
2647 UINT count = min(bool_count, MAX_CONST_B - start_register);
2648 UINT i;
2650 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2651 device, start_register, constants, bool_count);
2653 if (!constants || start_register >= MAX_CONST_B)
2654 return WINED3DERR_INVALIDCALL;
2656 memcpy(&device->updateStateBlock->state.vs_consts_b[start_register], constants, count * sizeof(BOOL));
2657 for (i = 0; i < count; ++i)
2658 TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
2660 for (i = start_register; i < count + start_register; ++i)
2661 device->updateStateBlock->changed.vertexShaderConstantsB |= (1 << i);
2663 if (!device->isRecordingState)
2664 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2666 return WINED3D_OK;
2669 HRESULT CDECL wined3d_device_get_vs_consts_b(const struct wined3d_device *device,
2670 UINT start_register, BOOL *constants, UINT bool_count)
2672 UINT count = min(bool_count, MAX_CONST_B - start_register);
2674 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2675 device, start_register, constants, bool_count);
2677 if (!constants || start_register >= MAX_CONST_B)
2678 return WINED3DERR_INVALIDCALL;
2680 memcpy(constants, &device->stateBlock->state.vs_consts_b[start_register], count * sizeof(BOOL));
2682 return WINED3D_OK;
2685 HRESULT CDECL wined3d_device_set_vs_consts_i(struct wined3d_device *device,
2686 UINT start_register, const int *constants, UINT vector4i_count)
2688 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2689 UINT i;
2691 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2692 device, start_register, constants, vector4i_count);
2694 if (!constants || start_register >= MAX_CONST_I)
2695 return WINED3DERR_INVALIDCALL;
2697 memcpy(&device->updateStateBlock->state.vs_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
2698 for (i = 0; i < count; ++i)
2699 TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
2700 constants[i * 4], constants[i * 4 + 1],
2701 constants[i * 4 + 2], constants[i * 4 + 3]);
2703 for (i = start_register; i < count + start_register; ++i)
2704 device->updateStateBlock->changed.vertexShaderConstantsI |= (1 << i);
2706 if (!device->isRecordingState)
2707 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2709 return WINED3D_OK;
2712 HRESULT CDECL wined3d_device_get_vs_consts_i(const struct wined3d_device *device,
2713 UINT start_register, int *constants, UINT vector4i_count)
2715 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2717 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2718 device, start_register, constants, vector4i_count);
2720 if (!constants || start_register >= MAX_CONST_I)
2721 return WINED3DERR_INVALIDCALL;
2723 memcpy(constants, &device->stateBlock->state.vs_consts_i[start_register * 4], count * sizeof(int) * 4);
2724 return WINED3D_OK;
2727 HRESULT CDECL wined3d_device_set_vs_consts_f(struct wined3d_device *device,
2728 UINT start_register, const float *constants, UINT vector4f_count)
2730 UINT i;
2732 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2733 device, start_register, constants, vector4f_count);
2735 /* Specifically test start_register > limit to catch MAX_UINT overflows
2736 * when adding start_register + vector4f_count. */
2737 if (!constants
2738 || start_register + vector4f_count > device->d3d_vshader_constantF
2739 || start_register > device->d3d_vshader_constantF)
2740 return WINED3DERR_INVALIDCALL;
2742 memcpy(&device->updateStateBlock->state.vs_consts_f[start_register * 4],
2743 constants, vector4f_count * sizeof(float) * 4);
2744 if (TRACE_ON(d3d))
2746 for (i = 0; i < vector4f_count; ++i)
2747 TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
2748 constants[i * 4], constants[i * 4 + 1],
2749 constants[i * 4 + 2], constants[i * 4 + 3]);
2752 if (!device->isRecordingState)
2754 device->shader_backend->shader_update_float_vertex_constants(device, start_register, vector4f_count);
2755 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2758 memset(device->updateStateBlock->changed.vertexShaderConstantsF + start_register, 1,
2759 sizeof(*device->updateStateBlock->changed.vertexShaderConstantsF) * vector4f_count);
2761 return WINED3D_OK;
2764 HRESULT CDECL wined3d_device_get_vs_consts_f(const struct wined3d_device *device,
2765 UINT start_register, float *constants, UINT vector4f_count)
2767 int count = min(vector4f_count, device->d3d_vshader_constantF - start_register);
2769 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2770 device, start_register, constants, vector4f_count);
2772 if (!constants || count < 0)
2773 return WINED3DERR_INVALIDCALL;
2775 memcpy(constants, &device->stateBlock->state.vs_consts_f[start_register * 4], count * sizeof(float) * 4);
2777 return WINED3D_OK;
2780 static void device_invalidate_texture_stage(const struct wined3d_device *device, DWORD stage)
2782 DWORD i;
2784 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2786 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, i));
2790 static void device_map_stage(struct wined3d_device *device, DWORD stage, DWORD unit)
2792 DWORD i = device->rev_tex_unit_map[unit];
2793 DWORD j = device->texUnitMap[stage];
2795 device->texUnitMap[stage] = unit;
2796 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2797 device->texUnitMap[i] = WINED3D_UNMAPPED_STAGE;
2799 device->rev_tex_unit_map[unit] = stage;
2800 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2801 device->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2804 static void device_update_fixed_function_usage_map(struct wined3d_device *device)
2806 UINT i;
2808 device->fixed_function_usage_map = 0;
2809 for (i = 0; i < MAX_TEXTURES; ++i)
2811 const struct wined3d_state *state = &device->stateBlock->state;
2812 WINED3DTEXTUREOP color_op = state->texture_states[i][WINED3DTSS_COLOROP];
2813 WINED3DTEXTUREOP alpha_op = state->texture_states[i][WINED3DTSS_ALPHAOP];
2814 DWORD color_arg1 = state->texture_states[i][WINED3DTSS_COLORARG1] & WINED3DTA_SELECTMASK;
2815 DWORD color_arg2 = state->texture_states[i][WINED3DTSS_COLORARG2] & WINED3DTA_SELECTMASK;
2816 DWORD color_arg3 = state->texture_states[i][WINED3DTSS_COLORARG0] & WINED3DTA_SELECTMASK;
2817 DWORD alpha_arg1 = state->texture_states[i][WINED3DTSS_ALPHAARG1] & WINED3DTA_SELECTMASK;
2818 DWORD alpha_arg2 = state->texture_states[i][WINED3DTSS_ALPHAARG2] & WINED3DTA_SELECTMASK;
2819 DWORD alpha_arg3 = state->texture_states[i][WINED3DTSS_ALPHAARG0] & WINED3DTA_SELECTMASK;
2821 if (color_op == WINED3DTOP_DISABLE) {
2822 /* Not used, and disable higher stages */
2823 break;
2826 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3DTOP_SELECTARG2)
2827 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3DTOP_SELECTARG1)
2828 || ((color_arg3 == WINED3DTA_TEXTURE)
2829 && (color_op == WINED3DTOP_MULTIPLYADD || color_op == WINED3DTOP_LERP))
2830 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3DTOP_SELECTARG2)
2831 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3DTOP_SELECTARG1)
2832 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2833 && (alpha_op == WINED3DTOP_MULTIPLYADD || alpha_op == WINED3DTOP_LERP)))
2834 device->fixed_function_usage_map |= (1 << i);
2836 if ((color_op == WINED3DTOP_BUMPENVMAP || color_op == WINED3DTOP_BUMPENVMAPLUMINANCE) && i < MAX_TEXTURES - 1)
2837 device->fixed_function_usage_map |= (1 << (i + 1));
2841 static void device_map_fixed_function_samplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2843 unsigned int i, tex;
2844 WORD ffu_map;
2846 device_update_fixed_function_usage_map(device);
2847 ffu_map = device->fixed_function_usage_map;
2849 if (device->max_ffp_textures == gl_info->limits.texture_stages
2850 || device->stateBlock->state.lowest_disabled_stage <= device->max_ffp_textures)
2852 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2854 if (!(ffu_map & 1)) continue;
2856 if (device->texUnitMap[i] != i)
2858 device_map_stage(device, i, i);
2859 device_invalidate_state(device, STATE_SAMPLER(i));
2860 device_invalidate_texture_stage(device, i);
2863 return;
2866 /* Now work out the mapping */
2867 tex = 0;
2868 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2870 if (!(ffu_map & 1)) continue;
2872 if (device->texUnitMap[i] != tex)
2874 device_map_stage(device, i, tex);
2875 device_invalidate_state(device, STATE_SAMPLER(i));
2876 device_invalidate_texture_stage(device, i);
2879 ++tex;
2883 static void device_map_psamplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2885 const enum wined3d_sampler_texture_type *sampler_type =
2886 device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2887 unsigned int i;
2889 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2891 if (sampler_type[i] && device->texUnitMap[i] != i)
2893 device_map_stage(device, i, i);
2894 device_invalidate_state(device, STATE_SAMPLER(i));
2895 if (i < gl_info->limits.texture_stages)
2896 device_invalidate_texture_stage(device, i);
2901 static BOOL device_unit_free_for_vs(const struct wined3d_device *device,
2902 const enum wined3d_sampler_texture_type *pshader_sampler_tokens,
2903 const enum wined3d_sampler_texture_type *vshader_sampler_tokens, DWORD unit)
2905 DWORD current_mapping = device->rev_tex_unit_map[unit];
2907 /* Not currently used */
2908 if (current_mapping == WINED3D_UNMAPPED_STAGE) return TRUE;
2910 if (current_mapping < MAX_FRAGMENT_SAMPLERS) {
2911 /* Used by a fragment sampler */
2913 if (!pshader_sampler_tokens) {
2914 /* No pixel shader, check fixed function */
2915 return current_mapping >= MAX_TEXTURES || !(device->fixed_function_usage_map & (1 << current_mapping));
2918 /* Pixel shader, check the shader's sampler map */
2919 return !pshader_sampler_tokens[current_mapping];
2922 /* Used by a vertex sampler */
2923 return !vshader_sampler_tokens[current_mapping - MAX_FRAGMENT_SAMPLERS];
2926 static void device_map_vsamplers(struct wined3d_device *device, BOOL ps, const struct wined3d_gl_info *gl_info)
2928 const enum wined3d_sampler_texture_type *vshader_sampler_type =
2929 device->stateBlock->state.vertex_shader->reg_maps.sampler_type;
2930 const enum wined3d_sampler_texture_type *pshader_sampler_type = NULL;
2931 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2932 int i;
2934 if (ps)
2936 /* Note that we only care if a sampler is sampled or not, not the sampler's specific type.
2937 * Otherwise we'd need to call shader_update_samplers() here for 1.x pixelshaders. */
2938 pshader_sampler_type = device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2941 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
2942 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2943 if (vshader_sampler_type[i])
2945 if (device->texUnitMap[vsampler_idx] != WINED3D_UNMAPPED_STAGE)
2947 /* Already mapped somewhere */
2948 continue;
2951 while (start >= 0)
2953 if (device_unit_free_for_vs(device, pshader_sampler_type, vshader_sampler_type, start))
2955 device_map_stage(device, vsampler_idx, start);
2956 device_invalidate_state(device, STATE_SAMPLER(vsampler_idx));
2958 --start;
2959 break;
2962 --start;
2968 void device_update_tex_unit_map(struct wined3d_device *device)
2970 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2971 const struct wined3d_state *state = &device->stateBlock->state;
2972 BOOL vs = use_vs(state);
2973 BOOL ps = use_ps(state);
2975 * Rules are:
2976 * -> Pixel shaders need a 1:1 map. In theory the shader input could be mapped too, but
2977 * that would be really messy and require shader recompilation
2978 * -> When the mapping of a stage is changed, sampler and ALL texture stage states have
2979 * to be reset. Because of that try to work with a 1:1 mapping as much as possible
2981 if (ps)
2982 device_map_psamplers(device, gl_info);
2983 else
2984 device_map_fixed_function_samplers(device, gl_info);
2986 if (vs)
2987 device_map_vsamplers(device, ps, gl_info);
2990 HRESULT CDECL wined3d_device_set_pixel_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2992 struct wined3d_shader *prev = device->updateStateBlock->state.pixel_shader;
2994 TRACE("device %p, shader %p.\n", device, shader);
2996 device->updateStateBlock->state.pixel_shader = shader;
2997 device->updateStateBlock->changed.pixelShader = TRUE;
2999 if (device->isRecordingState)
3001 if (shader)
3002 wined3d_shader_incref(shader);
3003 if (prev)
3004 wined3d_shader_decref(prev);
3005 TRACE("Recording... not performing anything.\n");
3006 return WINED3D_OK;
3009 if (shader == prev)
3011 TRACE("Application is setting the old shader over, nothing to do.\n");
3012 return WINED3D_OK;
3015 if (shader)
3016 wined3d_shader_incref(shader);
3017 if (prev)
3018 wined3d_shader_decref(prev);
3020 device_invalidate_state(device, STATE_PIXELSHADER);
3022 return WINED3D_OK;
3025 struct wined3d_shader * CDECL wined3d_device_get_pixel_shader(const struct wined3d_device *device)
3027 struct wined3d_shader *shader;
3029 TRACE("device %p.\n", device);
3031 shader = device->stateBlock->state.pixel_shader;
3032 if (shader)
3033 wined3d_shader_incref(shader);
3035 TRACE("Returning %p.\n", shader);
3036 return shader;
3039 HRESULT CDECL wined3d_device_set_ps_consts_b(struct wined3d_device *device,
3040 UINT start_register, const BOOL *constants, UINT bool_count)
3042 UINT count = min(bool_count, MAX_CONST_B - start_register);
3043 UINT i;
3045 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
3046 device, start_register, constants, bool_count);
3048 if (!constants || start_register >= MAX_CONST_B)
3049 return WINED3DERR_INVALIDCALL;
3051 memcpy(&device->updateStateBlock->state.ps_consts_b[start_register], constants, count * sizeof(BOOL));
3052 for (i = 0; i < count; ++i)
3053 TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
3055 for (i = start_register; i < count + start_register; ++i)
3056 device->updateStateBlock->changed.pixelShaderConstantsB |= (1 << i);
3058 if (!device->isRecordingState)
3059 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3061 return WINED3D_OK;
3064 HRESULT CDECL wined3d_device_get_ps_consts_b(const struct wined3d_device *device,
3065 UINT start_register, BOOL *constants, UINT bool_count)
3067 UINT count = min(bool_count, MAX_CONST_B - start_register);
3069 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
3070 device, start_register, constants, bool_count);
3072 if (!constants || start_register >= MAX_CONST_B)
3073 return WINED3DERR_INVALIDCALL;
3075 memcpy(constants, &device->stateBlock->state.ps_consts_b[start_register], count * sizeof(BOOL));
3077 return WINED3D_OK;
3080 HRESULT CDECL wined3d_device_set_ps_consts_i(struct wined3d_device *device,
3081 UINT start_register, const int *constants, UINT vector4i_count)
3083 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
3084 UINT i;
3086 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
3087 device, start_register, constants, vector4i_count);
3089 if (!constants || start_register >= MAX_CONST_I)
3090 return WINED3DERR_INVALIDCALL;
3092 memcpy(&device->updateStateBlock->state.ps_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
3093 for (i = 0; i < count; ++i)
3094 TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
3095 constants[i * 4], constants[i * 4 + 1],
3096 constants[i * 4 + 2], constants[i * 4 + 3]);
3098 for (i = start_register; i < count + start_register; ++i)
3099 device->updateStateBlock->changed.pixelShaderConstantsI |= (1 << i);
3101 if (!device->isRecordingState)
3102 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3104 return WINED3D_OK;
3107 HRESULT CDECL wined3d_device_get_ps_consts_i(const struct wined3d_device *device,
3108 UINT start_register, int *constants, UINT vector4i_count)
3110 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
3112 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
3113 device, start_register, constants, vector4i_count);
3115 if (!constants || start_register >= MAX_CONST_I)
3116 return WINED3DERR_INVALIDCALL;
3118 memcpy(constants, &device->stateBlock->state.ps_consts_i[start_register * 4], count * sizeof(int) * 4);
3120 return WINED3D_OK;
3123 HRESULT CDECL wined3d_device_set_ps_consts_f(struct wined3d_device *device,
3124 UINT start_register, const float *constants, UINT vector4f_count)
3126 UINT i;
3128 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3129 device, start_register, constants, vector4f_count);
3131 /* Specifically test start_register > limit to catch MAX_UINT overflows
3132 * when adding start_register + vector4f_count. */
3133 if (!constants
3134 || start_register + vector4f_count > device->d3d_pshader_constantF
3135 || start_register > device->d3d_pshader_constantF)
3136 return WINED3DERR_INVALIDCALL;
3138 memcpy(&device->updateStateBlock->state.ps_consts_f[start_register * 4],
3139 constants, vector4f_count * sizeof(float) * 4);
3140 if (TRACE_ON(d3d))
3142 for (i = 0; i < vector4f_count; ++i)
3143 TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
3144 constants[i * 4], constants[i * 4 + 1],
3145 constants[i * 4 + 2], constants[i * 4 + 3]);
3148 if (!device->isRecordingState)
3150 device->shader_backend->shader_update_float_pixel_constants(device, start_register, vector4f_count);
3151 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3154 memset(device->updateStateBlock->changed.pixelShaderConstantsF + start_register, 1,
3155 sizeof(*device->updateStateBlock->changed.pixelShaderConstantsF) * vector4f_count);
3157 return WINED3D_OK;
3160 HRESULT CDECL wined3d_device_get_ps_consts_f(const struct wined3d_device *device,
3161 UINT start_register, float *constants, UINT vector4f_count)
3163 int count = min(vector4f_count, device->d3d_pshader_constantF - start_register);
3165 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3166 device, start_register, constants, vector4f_count);
3168 if (!constants || count < 0)
3169 return WINED3DERR_INVALIDCALL;
3171 memcpy(constants, &device->stateBlock->state.ps_consts_f[start_register * 4], count * sizeof(float) * 4);
3173 return WINED3D_OK;
3176 /* Context activation is done by the caller. */
3177 /* Do not call while under the GL lock. */
3178 #define copy_and_next(dest, src, size) memcpy(dest, src, size); dest += (size)
3179 static HRESULT process_vertices_strided(const struct wined3d_device *device, DWORD dwDestIndex, DWORD dwCount,
3180 const struct wined3d_stream_info *stream_info, struct wined3d_buffer *dest, DWORD flags,
3181 DWORD DestFVF)
3183 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3184 char *dest_ptr, *dest_conv = NULL, *dest_conv_addr = NULL;
3185 struct wined3d_matrix mat, proj_mat, view_mat, world_mat;
3186 struct wined3d_viewport vp;
3187 unsigned int i;
3188 BOOL doClip;
3189 DWORD numTextures;
3191 if (stream_info->use_map & (1 << WINED3D_FFP_NORMAL))
3193 WARN(" lighting state not saved yet... Some strange stuff may happen !\n");
3196 if (!(stream_info->use_map & (1 << WINED3D_FFP_POSITION)))
3198 ERR("Source has no position mask\n");
3199 return WINED3DERR_INVALIDCALL;
3202 if (!dest->resource.allocatedMemory)
3203 buffer_get_sysmem(dest, gl_info);
3205 /* Get a pointer into the destination vbo(create one if none exists) and
3206 * write correct opengl data into it. It's cheap and allows us to run drawStridedFast
3208 if (!dest->buffer_object && gl_info->supported[ARB_VERTEX_BUFFER_OBJECT])
3210 dest->flags |= WINED3D_BUFFER_CREATEBO;
3211 wined3d_buffer_preload(dest);
3214 if (dest->buffer_object)
3216 unsigned char extrabytes = 0;
3217 /* If the destination vertex buffer has D3DFVF_XYZ position(non-rhw), native d3d writes RHW position, where the RHW
3218 * gets written into the 4 bytes after the Z position. In the case of a dest buffer that only has D3DFVF_XYZ data,
3219 * this may write 4 extra bytes beyond the area that should be written
3221 if(DestFVF == WINED3DFVF_XYZ) extrabytes = 4;
3222 dest_conv_addr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCount * get_flexible_vertex_size(DestFVF) + extrabytes);
3223 if(!dest_conv_addr) {
3224 ERR("Out of memory\n");
3225 /* Continue without storing converted vertices */
3227 dest_conv = dest_conv_addr;
3230 if (device->stateBlock->state.render_states[WINED3D_RS_CLIPPING])
3232 static BOOL warned = FALSE;
3234 * The clipping code is not quite correct. Some things need
3235 * to be checked against IDirect3DDevice3 (!), d3d8 and d3d9,
3236 * so disable clipping for now.
3237 * (The graphics in Half-Life are broken, and my processvertices
3238 * test crashes with IDirect3DDevice3)
3239 doClip = TRUE;
3241 doClip = FALSE;
3242 if(!warned) {
3243 warned = TRUE;
3244 FIXME("Clipping is broken and disabled for now\n");
3246 } else doClip = FALSE;
3247 dest_ptr = ((char *)buffer_get_sysmem(dest, gl_info)) + dwDestIndex * get_flexible_vertex_size(DestFVF);
3249 wined3d_device_get_transform(device, WINED3DTS_VIEW, &view_mat);
3250 wined3d_device_get_transform(device, WINED3DTS_PROJECTION, &proj_mat);
3251 wined3d_device_get_transform(device, WINED3DTS_WORLDMATRIX(0), &world_mat);
3253 TRACE("View mat:\n");
3254 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);
3255 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);
3256 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);
3257 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);
3259 TRACE("Proj mat:\n");
3260 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);
3261 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);
3262 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);
3263 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);
3265 TRACE("World mat:\n");
3266 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);
3267 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);
3268 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);
3269 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);
3271 /* Get the viewport */
3272 wined3d_device_get_viewport(device, &vp);
3273 TRACE("viewport x %u, y %u, width %u, height %u, min_z %.8e, max_z %.8e.\n",
3274 vp.x, vp.y, vp.width, vp.height, vp.min_z, vp.max_z);
3276 multiply_matrix(&mat,&view_mat,&world_mat);
3277 multiply_matrix(&mat,&proj_mat,&mat);
3279 numTextures = (DestFVF & WINED3DFVF_TEXCOUNT_MASK) >> WINED3DFVF_TEXCOUNT_SHIFT;
3281 for (i = 0; i < dwCount; i+= 1) {
3282 unsigned int tex_index;
3284 if ( ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZ ) ||
3285 ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW ) ) {
3286 /* The position first */
3287 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_POSITION];
3288 const float *p = (const float *)(element->data.addr + i * element->stride);
3289 float x, y, z, rhw;
3290 TRACE("In: ( %06.2f %06.2f %06.2f )\n", p[0], p[1], p[2]);
3292 /* Multiplication with world, view and projection matrix */
3293 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);
3294 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);
3295 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);
3296 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);
3298 TRACE("x=%f y=%f z=%f rhw=%f\n", x, y, z, rhw);
3300 /* WARNING: The following things are taken from d3d7 and were not yet checked
3301 * against d3d8 or d3d9!
3304 /* Clipping conditions: From msdn
3306 * A vertex is clipped if it does not match the following requirements
3307 * -rhw < x <= rhw
3308 * -rhw < y <= rhw
3309 * 0 < z <= rhw
3310 * 0 < rhw ( Not in d3d7, but tested in d3d7)
3312 * If clipping is on is determined by the D3DVOP_CLIP flag in D3D7, and
3313 * by the D3DRS_CLIPPING in D3D9(according to the msdn, not checked)
3317 if( !doClip ||
3318 ( (-rhw -eps < x) && (-rhw -eps < y) && ( -eps < z) &&
3319 (x <= rhw + eps) && (y <= rhw + eps ) && (z <= rhw + eps) &&
3320 ( rhw > eps ) ) ) {
3322 /* "Normal" viewport transformation (not clipped)
3323 * 1) The values are divided by rhw
3324 * 2) The y axis is negative, so multiply it with -1
3325 * 3) Screen coordinates go from -(Width/2) to +(Width/2) and
3326 * -(Height/2) to +(Height/2). The z range is MinZ to MaxZ
3327 * 4) Multiply x with Width/2 and add Width/2
3328 * 5) The same for the height
3329 * 6) Add the viewpoint X and Y to the 2D coordinates and
3330 * The minimum Z value to z
3331 * 7) rhw = 1 / rhw Reciprocal of Homogeneous W....
3333 * Well, basically it's simply a linear transformation into viewport
3334 * coordinates
3337 x /= rhw;
3338 y /= rhw;
3339 z /= rhw;
3341 y *= -1;
3343 x *= vp.width / 2;
3344 y *= vp.height / 2;
3345 z *= vp.max_z - vp.min_z;
3347 x += vp.width / 2 + vp.x;
3348 y += vp.height / 2 + vp.y;
3349 z += vp.min_z;
3351 rhw = 1 / rhw;
3352 } else {
3353 /* That vertex got clipped
3354 * Contrary to OpenGL it is not dropped completely, it just
3355 * undergoes a different calculation.
3357 TRACE("Vertex got clipped\n");
3358 x += rhw;
3359 y += rhw;
3361 x /= 2;
3362 y /= 2;
3364 /* Msdn mentions that Direct3D9 keeps a list of clipped vertices
3365 * outside of the main vertex buffer memory. That needs some more
3366 * investigation...
3370 TRACE("Writing (%f %f %f) %f\n", x, y, z, rhw);
3373 ( (float *) dest_ptr)[0] = x;
3374 ( (float *) dest_ptr)[1] = y;
3375 ( (float *) dest_ptr)[2] = z;
3376 ( (float *) dest_ptr)[3] = rhw; /* SIC, see ddraw test! */
3378 dest_ptr += 3 * sizeof(float);
3380 if((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW) {
3381 dest_ptr += sizeof(float);
3384 if(dest_conv) {
3385 float w = 1 / rhw;
3386 ( (float *) dest_conv)[0] = x * w;
3387 ( (float *) dest_conv)[1] = y * w;
3388 ( (float *) dest_conv)[2] = z * w;
3389 ( (float *) dest_conv)[3] = w;
3391 dest_conv += 3 * sizeof(float);
3393 if((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW) {
3394 dest_conv += sizeof(float);
3398 if (DestFVF & WINED3DFVF_PSIZE) {
3399 dest_ptr += sizeof(DWORD);
3400 if(dest_conv) dest_conv += sizeof(DWORD);
3402 if (DestFVF & WINED3DFVF_NORMAL)
3404 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_NORMAL];
3405 const float *normal = (const float *)(element->data.addr + i * element->stride);
3406 /* AFAIK this should go into the lighting information */
3407 FIXME("Didn't expect the destination to have a normal\n");
3408 copy_and_next(dest_ptr, normal, 3 * sizeof(float));
3409 if(dest_conv) {
3410 copy_and_next(dest_conv, normal, 3 * sizeof(float));
3414 if (DestFVF & WINED3DFVF_DIFFUSE)
3416 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_DIFFUSE];
3417 const DWORD *color_d = (const DWORD *)(element->data.addr + i * element->stride);
3418 if (!(stream_info->use_map & (1 << WINED3D_FFP_DIFFUSE)))
3420 static BOOL warned = FALSE;
3422 if(!warned) {
3423 ERR("No diffuse color in source, but destination has one\n");
3424 warned = TRUE;
3427 *( (DWORD *) dest_ptr) = 0xffffffff;
3428 dest_ptr += sizeof(DWORD);
3430 if(dest_conv) {
3431 *( (DWORD *) dest_conv) = 0xffffffff;
3432 dest_conv += sizeof(DWORD);
3435 else {
3436 copy_and_next(dest_ptr, color_d, sizeof(DWORD));
3437 if(dest_conv) {
3438 *( (DWORD *) dest_conv) = (*color_d & 0xff00ff00) ; /* Alpha + green */
3439 *( (DWORD *) dest_conv) |= (*color_d & 0x00ff0000) >> 16; /* Red */
3440 *( (DWORD *) dest_conv) |= (*color_d & 0xff0000ff) << 16; /* Blue */
3441 dest_conv += sizeof(DWORD);
3446 if (DestFVF & WINED3DFVF_SPECULAR)
3448 /* What's the color value in the feedback buffer? */
3449 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_SPECULAR];
3450 const DWORD *color_s = (const DWORD *)(element->data.addr + i * element->stride);
3451 if (!(stream_info->use_map & (1 << WINED3D_FFP_SPECULAR)))
3453 static BOOL warned = FALSE;
3455 if(!warned) {
3456 ERR("No specular color in source, but destination has one\n");
3457 warned = TRUE;
3460 *( (DWORD *) dest_ptr) = 0xFF000000;
3461 dest_ptr += sizeof(DWORD);
3463 if(dest_conv) {
3464 *( (DWORD *) dest_conv) = 0xFF000000;
3465 dest_conv += sizeof(DWORD);
3468 else {
3469 copy_and_next(dest_ptr, color_s, sizeof(DWORD));
3470 if(dest_conv) {
3471 *( (DWORD *) dest_conv) = (*color_s & 0xff00ff00) ; /* Alpha + green */
3472 *( (DWORD *) dest_conv) |= (*color_s & 0x00ff0000) >> 16; /* Red */
3473 *( (DWORD *) dest_conv) |= (*color_s & 0xff0000ff) << 16; /* Blue */
3474 dest_conv += sizeof(DWORD);
3479 for (tex_index = 0; tex_index < numTextures; ++tex_index)
3481 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_TEXCOORD0 + tex_index];
3482 const float *tex_coord = (const float *)(element->data.addr + i * element->stride);
3483 if (!(stream_info->use_map & (1 << (WINED3D_FFP_TEXCOORD0 + tex_index))))
3485 ERR("No source texture, but destination requests one\n");
3486 dest_ptr+=GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float);
3487 if(dest_conv) dest_conv += GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float);
3489 else {
3490 copy_and_next(dest_ptr, tex_coord, GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float));
3491 if(dest_conv) {
3492 copy_and_next(dest_conv, tex_coord, GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float));
3498 if (dest_conv)
3500 ENTER_GL();
3502 GL_EXTCALL(glBindBufferARB(GL_ARRAY_BUFFER_ARB, dest->buffer_object));
3503 checkGLcall("glBindBufferARB(GL_ARRAY_BUFFER_ARB)");
3504 GL_EXTCALL(glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, dwDestIndex * get_flexible_vertex_size(DestFVF),
3505 dwCount * get_flexible_vertex_size(DestFVF),
3506 dest_conv_addr));
3507 checkGLcall("glBufferSubDataARB(GL_ARRAY_BUFFER_ARB)");
3509 LEAVE_GL();
3511 HeapFree(GetProcessHeap(), 0, dest_conv_addr);
3514 return WINED3D_OK;
3516 #undef copy_and_next
3518 /* Do not call while under the GL lock. */
3519 HRESULT CDECL wined3d_device_process_vertices(struct wined3d_device *device,
3520 UINT src_start_idx, UINT dst_idx, UINT vertex_count, struct wined3d_buffer *dst_buffer,
3521 const struct wined3d_vertex_declaration *declaration, DWORD flags, DWORD dst_fvf)
3523 struct wined3d_state *state = &device->stateBlock->state;
3524 BOOL vbo = FALSE, streamWasUP = state->user_stream;
3525 struct wined3d_stream_info stream_info;
3526 const struct wined3d_gl_info *gl_info;
3527 struct wined3d_context *context;
3528 struct wined3d_shader *vs;
3529 HRESULT hr;
3531 TRACE("device %p, src_start_idx %u, dst_idx %u, vertex_count %u, "
3532 "dst_buffer %p, declaration %p, flags %#x, dst_fvf %#x.\n",
3533 device, src_start_idx, dst_idx, vertex_count,
3534 dst_buffer, declaration, flags, dst_fvf);
3536 if (declaration)
3537 FIXME("Output vertex declaration not implemented yet.\n");
3539 /* Need any context to write to the vbo. */
3540 context = context_acquire(device, NULL);
3541 gl_info = context->gl_info;
3543 /* ProcessVertices reads from vertex buffers, which have to be assigned.
3544 * DrawPrimitive and DrawPrimitiveUP control the streamIsUP flag, thus
3545 * restore it afterwards. */
3546 vs = state->vertex_shader;
3547 state->vertex_shader = NULL;
3548 state->user_stream = FALSE;
3549 device_stream_info_from_declaration(device, &stream_info, &vbo);
3550 state->user_stream = streamWasUP;
3551 state->vertex_shader = vs;
3553 if (vbo || src_start_idx)
3555 unsigned int i;
3556 /* ProcessVertices can't convert FROM a vbo, and vertex buffers used to source into ProcessVertices are
3557 * unlikely to ever be used for drawing. Release vbos in those buffers and fix up the stream_info structure
3559 * Also get the start index in, but only loop over all elements if there's something to add at all.
3561 for (i = 0; i < (sizeof(stream_info.elements) / sizeof(*stream_info.elements)); ++i)
3563 struct wined3d_stream_info_element *e;
3565 if (!(stream_info.use_map & (1 << i))) continue;
3567 e = &stream_info.elements[i];
3568 if (e->data.buffer_object)
3570 struct wined3d_buffer *vb = state->streams[e->stream_idx].buffer;
3571 e->data.buffer_object = 0;
3572 e->data.addr = (BYTE *)((ULONG_PTR)e->data.addr + (ULONG_PTR)buffer_get_sysmem(vb, gl_info));
3573 ENTER_GL();
3574 GL_EXTCALL(glDeleteBuffersARB(1, &vb->buffer_object));
3575 vb->buffer_object = 0;
3576 LEAVE_GL();
3578 if (e->data.addr)
3579 e->data.addr += e->stride * src_start_idx;
3583 hr = process_vertices_strided(device, dst_idx, vertex_count,
3584 &stream_info, dst_buffer, flags, dst_fvf);
3586 context_release(context);
3588 return hr;
3591 HRESULT CDECL wined3d_device_set_texture_stage_state(struct wined3d_device *device,
3592 UINT stage, WINED3DTEXTURESTAGESTATETYPE state, DWORD value)
3594 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3595 DWORD old_value;
3597 TRACE("device %p, stage %u, state %s, value %#x.\n",
3598 device, stage, debug_d3dtexturestate(state), value);
3600 if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3602 WARN("Invalid state %#x passed.\n", state);
3603 return WINED3D_OK;
3606 if (stage >= gl_info->limits.texture_stages)
3608 WARN("Attempting to set stage %u which is higher than the max stage %u, ignoring.\n",
3609 stage, gl_info->limits.texture_stages - 1);
3610 return WINED3D_OK;
3613 old_value = device->updateStateBlock->state.texture_states[stage][state];
3614 device->updateStateBlock->changed.textureState[stage] |= 1 << state;
3615 device->updateStateBlock->state.texture_states[stage][state] = value;
3617 if (device->isRecordingState)
3619 TRACE("Recording... not performing anything.\n");
3620 return WINED3D_OK;
3623 /* Checked after the assignments to allow proper stateblock recording. */
3624 if (old_value == value)
3626 TRACE("Application is setting the old value over, nothing to do.\n");
3627 return WINED3D_OK;
3630 if (stage > device->stateBlock->state.lowest_disabled_stage
3631 && device->StateTable[STATE_TEXTURESTAGE(0, state)].representative
3632 == STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP))
3634 /* Colorop change above lowest disabled stage? That won't change
3635 * anything in the GL setup. Changes in other states are important on
3636 * disabled stages too. */
3637 return WINED3D_OK;
3640 if (state == WINED3DTSS_COLOROP)
3642 unsigned int i;
3644 if (value == WINED3DTOP_DISABLE && old_value != WINED3DTOP_DISABLE)
3646 /* Previously enabled stage disabled now. Make sure to dirtify
3647 * all enabled stages above stage, they have to be disabled.
3649 * The current stage is dirtified below. */
3650 for (i = stage + 1; i < device->stateBlock->state.lowest_disabled_stage; ++i)
3652 TRACE("Additionally dirtifying stage %u.\n", i);
3653 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP));
3655 device->stateBlock->state.lowest_disabled_stage = stage;
3656 TRACE("New lowest disabled: %u.\n", stage);
3658 else if (value != WINED3DTOP_DISABLE && old_value == WINED3DTOP_DISABLE)
3660 /* Previously disabled stage enabled. Stages above it may need
3661 * enabling. Stage must be lowest_disabled_stage here, if it's
3662 * bigger success is returned above, and stages below the lowest
3663 * disabled stage can't be enabled (because they are enabled
3664 * already).
3666 * Again stage stage doesn't need to be dirtified here, it is
3667 * handled below. */
3668 for (i = stage + 1; i < gl_info->limits.texture_stages; ++i)
3670 if (device->updateStateBlock->state.texture_states[i][WINED3DTSS_COLOROP] == WINED3DTOP_DISABLE)
3671 break;
3672 TRACE("Additionally dirtifying stage %u due to enable.\n", i);
3673 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP));
3675 device->stateBlock->state.lowest_disabled_stage = i;
3676 TRACE("New lowest disabled: %u.\n", i);
3680 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, state));
3682 return WINED3D_OK;
3685 HRESULT CDECL wined3d_device_get_texture_stage_state(const struct wined3d_device *device,
3686 UINT stage, WINED3DTEXTURESTAGESTATETYPE state, DWORD *value)
3688 TRACE("device %p, stage %u, state %s, value %p.\n",
3689 device, stage, debug_d3dtexturestate(state), value);
3691 if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3693 WARN("Invalid state %#x passed.\n", state);
3694 return WINED3D_OK;
3697 *value = device->updateStateBlock->state.texture_states[stage][state];
3698 TRACE("Returning %#x.\n", *value);
3700 return WINED3D_OK;
3703 HRESULT CDECL wined3d_device_set_texture(struct wined3d_device *device,
3704 UINT stage, struct wined3d_texture *texture)
3706 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3707 struct wined3d_texture *prev;
3709 TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3711 if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3712 stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3714 /* Windows accepts overflowing this array... we do not. */
3715 if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3717 WARN("Ignoring invalid stage %u.\n", stage);
3718 return WINED3D_OK;
3721 /* SetTexture isn't allowed on textures in WINED3DPOOL_SCRATCH */
3722 if (texture && texture->resource.pool == WINED3DPOOL_SCRATCH)
3724 WARN("Rejecting attempt to set scratch texture.\n");
3725 return WINED3DERR_INVALIDCALL;
3728 device->updateStateBlock->changed.textures |= 1 << stage;
3730 prev = device->updateStateBlock->state.textures[stage];
3731 TRACE("Previous texture %p.\n", prev);
3733 if (texture == prev)
3735 TRACE("App is setting the same texture again, nothing to do.\n");
3736 return WINED3D_OK;
3739 TRACE("Setting new texture to %p.\n", texture);
3740 device->updateStateBlock->state.textures[stage] = texture;
3742 if (device->isRecordingState)
3744 TRACE("Recording... not performing anything\n");
3746 if (texture) wined3d_texture_incref(texture);
3747 if (prev) wined3d_texture_decref(prev);
3749 return WINED3D_OK;
3752 if (texture)
3754 LONG bind_count = InterlockedIncrement(&texture->bind_count);
3756 wined3d_texture_incref(texture);
3758 if (!prev || texture->target != prev->target)
3759 device_invalidate_state(device, STATE_PIXELSHADER);
3761 if (!prev && stage < gl_info->limits.texture_stages)
3763 /* The source arguments for color and alpha ops have different
3764 * meanings when a NULL texture is bound, so the COLOROP and
3765 * ALPHAOP have to be dirtified. */
3766 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3DTSS_COLOROP));
3767 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3DTSS_ALPHAOP));
3770 if (bind_count == 1)
3771 texture->sampler = stage;
3774 if (prev)
3776 LONG bind_count = InterlockedDecrement(&prev->bind_count);
3778 wined3d_texture_decref(prev);
3780 if (!texture && stage < gl_info->limits.texture_stages)
3782 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3DTSS_COLOROP));
3783 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3DTSS_ALPHAOP));
3786 if (bind_count && prev->sampler == stage)
3788 unsigned int i;
3790 /* Search for other stages the texture is bound to. Shouldn't
3791 * happen if applications bind textures to a single stage only. */
3792 TRACE("Searching for other stages the texture is bound to.\n");
3793 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
3795 if (device->updateStateBlock->state.textures[i] == prev)
3797 TRACE("Texture is also bound to stage %u.\n", i);
3798 prev->sampler = i;
3799 break;
3805 device_invalidate_state(device, STATE_SAMPLER(stage));
3807 return WINED3D_OK;
3810 HRESULT CDECL wined3d_device_get_texture(const struct wined3d_device *device,
3811 UINT stage, struct wined3d_texture **texture)
3813 TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3815 if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3816 stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3818 if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3820 WARN("Ignoring invalid stage %u.\n", stage);
3821 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
3824 *texture = device->stateBlock->state.textures[stage];
3825 if (*texture)
3826 wined3d_texture_incref(*texture);
3828 TRACE("Returning %p.\n", *texture);
3830 return WINED3D_OK;
3833 HRESULT CDECL wined3d_device_get_back_buffer(const struct wined3d_device *device, UINT swapchain_idx,
3834 UINT backbuffer_idx, WINED3DBACKBUFFER_TYPE backbuffer_type, struct wined3d_surface **backbuffer)
3836 struct wined3d_swapchain *swapchain;
3837 HRESULT hr;
3839 TRACE("device %p, swapchain_idx %u, backbuffer_idx %u, backbuffer_type %#x, backbuffer %p.\n",
3840 device, swapchain_idx, backbuffer_idx, backbuffer_type, backbuffer);
3842 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
3843 if (FAILED(hr))
3845 WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
3846 return hr;
3849 hr = wined3d_swapchain_get_back_buffer(swapchain, backbuffer_idx, backbuffer_type, backbuffer);
3850 wined3d_swapchain_decref(swapchain);
3851 if (FAILED(hr))
3853 WARN("Failed to get backbuffer %u, hr %#x.\n", backbuffer_idx, hr);
3854 return hr;
3857 return WINED3D_OK;
3860 HRESULT CDECL wined3d_device_get_device_caps(const struct wined3d_device *device, WINED3DCAPS *caps)
3862 TRACE("device %p, caps %p.\n", device, caps);
3864 return wined3d_get_device_caps(device->wined3d, device->adapter->ordinal,
3865 device->create_parms.device_type, caps);
3868 HRESULT CDECL wined3d_device_get_display_mode(const struct wined3d_device *device,
3869 UINT swapchain_idx, struct wined3d_display_mode *mode)
3871 struct wined3d_swapchain *swapchain;
3872 HRESULT hr;
3874 TRACE("device %p, swapchain_idx %u, mode %p.\n", device, swapchain_idx, mode);
3876 if (swapchain_idx)
3878 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
3879 if (SUCCEEDED(hr))
3881 hr = wined3d_swapchain_get_display_mode(swapchain, mode);
3882 wined3d_swapchain_decref(swapchain);
3885 else
3887 const struct wined3d_adapter *adapter = device->adapter;
3889 /* Don't read the real display mode, but return the stored mode
3890 * instead. X11 can't change the color depth, and some apps are
3891 * pretty angry if they SetDisplayMode from 24 to 16 bpp and find out
3892 * that GetDisplayMode still returns 24 bpp.
3894 * Also don't relay to the swapchain because with ddraw it's possible
3895 * that there isn't a swapchain at all. */
3896 mode->width = adapter->screen_size.cx;
3897 mode->height = adapter->screen_size.cy;
3898 mode->format_id = adapter->screen_format;
3899 mode->refresh_rate = 0;
3900 hr = WINED3D_OK;
3903 return hr;
3906 HRESULT CDECL wined3d_device_begin_stateblock(struct wined3d_device *device)
3908 struct wined3d_stateblock *stateblock;
3909 HRESULT hr;
3911 TRACE("device %p.\n", device);
3913 if (device->isRecordingState)
3914 return WINED3DERR_INVALIDCALL;
3916 hr = wined3d_stateblock_create(device, WINED3DSBT_RECORDED, &stateblock);
3917 if (FAILED(hr))
3918 return hr;
3920 wined3d_stateblock_decref(device->updateStateBlock);
3921 device->updateStateBlock = stateblock;
3922 device->isRecordingState = TRUE;
3924 TRACE("Recording stateblock %p.\n", stateblock);
3926 return WINED3D_OK;
3929 HRESULT CDECL wined3d_device_end_stateblock(struct wined3d_device *device,
3930 struct wined3d_stateblock **stateblock)
3932 struct wined3d_stateblock *object = device->updateStateBlock;
3934 TRACE("device %p, stateblock %p.\n", device, stateblock);
3936 if (!device->isRecordingState)
3938 WARN("Not recording.\n");
3939 *stateblock = NULL;
3940 return WINED3DERR_INVALIDCALL;
3943 stateblock_init_contained_states(object);
3945 *stateblock = object;
3946 device->isRecordingState = FALSE;
3947 device->updateStateBlock = device->stateBlock;
3948 wined3d_stateblock_incref(device->updateStateBlock);
3950 TRACE("Returning stateblock %p.\n", *stateblock);
3952 return WINED3D_OK;
3955 HRESULT CDECL wined3d_device_begin_scene(struct wined3d_device *device)
3957 /* At the moment we have no need for any functionality at the beginning
3958 * of a scene. */
3959 TRACE("device %p.\n", device);
3961 if (device->inScene)
3963 WARN("Already in scene, returning WINED3DERR_INVALIDCALL.\n");
3964 return WINED3DERR_INVALIDCALL;
3966 device->inScene = TRUE;
3967 return WINED3D_OK;
3970 HRESULT CDECL wined3d_device_end_scene(struct wined3d_device *device)
3972 struct wined3d_context *context;
3974 TRACE("device %p.\n", device);
3976 if (!device->inScene)
3978 WARN("Not in scene, returning WINED3DERR_INVALIDCALL.\n");
3979 return WINED3DERR_INVALIDCALL;
3982 context = context_acquire(device, NULL);
3983 /* We only have to do this if we need to read the, swapbuffers performs a flush for us */
3984 wglFlush();
3985 /* No checkGLcall here to avoid locking the lock just for checking a call that hardly ever
3986 * fails. */
3987 context_release(context);
3989 device->inScene = FALSE;
3990 return WINED3D_OK;
3993 HRESULT CDECL wined3d_device_present(const struct wined3d_device *device, const RECT *src_rect,
3994 const RECT *dst_rect, HWND dst_window_override, const RGNDATA *dirty_region)
3996 UINT i;
3998 TRACE("device %p, src_rect %s, dst_rect %s, dst_window_override %p, dirty_region %p.\n",
3999 device, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect),
4000 dst_window_override, dirty_region);
4002 for (i = 0; i < device->swapchain_count; ++i)
4004 wined3d_swapchain_present(device->swapchains[i], src_rect,
4005 dst_rect, dst_window_override, dirty_region, 0);
4008 return WINED3D_OK;
4011 /* Do not call while under the GL lock. */
4012 HRESULT CDECL wined3d_device_clear(struct wined3d_device *device, DWORD rect_count,
4013 const RECT *rects, DWORD flags, const struct wined3d_color *color, float depth, DWORD stencil)
4015 RECT draw_rect;
4017 TRACE("device %p, rect_count %u, rects %p, flags %#x, color {%.8e, %.8e, %.8e, %.8e}, depth %.8e, stencil %u.\n",
4018 device, rect_count, rects, flags, color->r, color->g, color->b, color->a, depth, stencil);
4020 if (flags & (WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL))
4022 struct wined3d_surface *ds = device->fb.depth_stencil;
4023 if (!ds)
4025 WARN("Clearing depth and/or stencil without a depth stencil buffer attached, returning WINED3DERR_INVALIDCALL\n");
4026 /* TODO: What about depth stencil buffers without stencil bits? */
4027 return WINED3DERR_INVALIDCALL;
4029 else if (flags & WINED3DCLEAR_TARGET)
4031 if (ds->resource.width < device->fb.render_targets[0]->resource.width
4032 || ds->resource.height < device->fb.render_targets[0]->resource.height)
4034 WARN("Silently ignoring depth and target clear with mismatching sizes\n");
4035 return WINED3D_OK;
4040 wined3d_get_draw_rect(&device->stateBlock->state, &draw_rect);
4042 return device_clear_render_targets(device, device->adapter->gl_info.limits.buffers,
4043 &device->fb, rect_count, rects,
4044 &draw_rect, flags, color, depth, stencil);
4047 void CDECL wined3d_device_set_primitive_type(struct wined3d_device *device,
4048 enum wined3d_primitive_type primitive_type)
4050 TRACE("device %p, primitive_type %s\n", device, debug_d3dprimitivetype(primitive_type));
4052 device->updateStateBlock->changed.primitive_type = TRUE;
4053 device->updateStateBlock->state.gl_primitive_type = gl_primitive_type_from_d3d(primitive_type);
4056 void CDECL wined3d_device_get_primitive_type(const struct wined3d_device *device,
4057 enum wined3d_primitive_type *primitive_type)
4059 TRACE("device %p, primitive_type %p\n", device, primitive_type);
4061 *primitive_type = d3d_primitive_type_from_gl(device->stateBlock->state.gl_primitive_type);
4063 TRACE("Returning %s\n", debug_d3dprimitivetype(*primitive_type));
4066 HRESULT CDECL wined3d_device_draw_primitive(struct wined3d_device *device, UINT start_vertex, UINT vertex_count)
4068 TRACE("device %p, start_vertex %u, vertex_count %u.\n", device, start_vertex, vertex_count);
4070 if (!device->stateBlock->state.vertex_declaration)
4072 WARN("Called without a valid vertex declaration set.\n");
4073 return WINED3DERR_INVALIDCALL;
4076 /* The index buffer is not needed here, but restore it, otherwise it is hell to keep track of */
4077 if (device->stateBlock->state.user_stream)
4079 device_invalidate_state(device, STATE_INDEXBUFFER);
4080 device->stateBlock->state.user_stream = FALSE;
4083 if (device->stateBlock->state.load_base_vertex_index)
4085 device->stateBlock->state.load_base_vertex_index = 0;
4086 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4089 /* Account for the loading offset due to index buffers. Instead of
4090 * reloading all sources correct it with the startvertex parameter. */
4091 drawPrimitive(device, vertex_count, start_vertex, 0, NULL);
4092 return WINED3D_OK;
4095 HRESULT CDECL wined3d_device_draw_indexed_primitive(struct wined3d_device *device, UINT start_idx, UINT index_count)
4097 struct wined3d_buffer *index_buffer;
4098 UINT index_size = 2;
4099 GLuint vbo;
4100 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4102 TRACE("device %p, start_idx %u, index_count %u.\n", device, start_idx, index_count);
4104 index_buffer = device->stateBlock->state.index_buffer;
4105 if (!index_buffer)
4107 /* D3D9 returns D3DERR_INVALIDCALL when DrawIndexedPrimitive is called
4108 * without an index buffer set. (The first time at least...)
4109 * D3D8 simply dies, but I doubt it can do much harm to return
4110 * D3DERR_INVALIDCALL there as well. */
4111 WARN("Called without a valid index buffer set, returning WINED3DERR_INVALIDCALL.\n");
4112 return WINED3DERR_INVALIDCALL;
4115 if (!device->stateBlock->state.vertex_declaration)
4117 WARN("Called without a valid vertex declaration set.\n");
4118 return WINED3DERR_INVALIDCALL;
4121 if (device->stateBlock->state.user_stream)
4123 device_invalidate_state(device, STATE_INDEXBUFFER);
4124 device->stateBlock->state.user_stream = FALSE;
4126 vbo = index_buffer->buffer_object;
4128 if (device->stateBlock->state.index_format == WINED3DFMT_R16_UINT)
4129 index_size = 2;
4130 else
4131 index_size = 4;
4133 if (!gl_info->supported[ARB_DRAW_ELEMENTS_BASE_VERTEX] &&
4134 device->stateBlock->state.load_base_vertex_index != device->stateBlock->state.base_vertex_index)
4136 device->stateBlock->state.load_base_vertex_index = device->stateBlock->state.base_vertex_index;
4137 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4140 drawPrimitive(device, index_count, start_idx, index_size,
4141 vbo ? NULL : index_buffer->resource.allocatedMemory);
4143 return WINED3D_OK;
4146 HRESULT CDECL wined3d_device_draw_primitive_up(struct wined3d_device *device, UINT vertex_count,
4147 const void *stream_data, UINT stream_stride)
4149 struct wined3d_stream_state *stream;
4150 struct wined3d_buffer *vb;
4152 TRACE("device %p, vertex count %u, stream_data %p, stream_stride %u.\n",
4153 device, vertex_count, stream_data, stream_stride);
4155 if (!device->stateBlock->state.vertex_declaration)
4157 WARN("Called without a valid vertex declaration set.\n");
4158 return WINED3DERR_INVALIDCALL;
4161 /* Note in the following, it's not this type, but that's the purpose of streamIsUP */
4162 stream = &device->stateBlock->state.streams[0];
4163 vb = stream->buffer;
4164 stream->buffer = (struct wined3d_buffer *)stream_data;
4165 if (vb)
4166 wined3d_buffer_decref(vb);
4167 stream->offset = 0;
4168 stream->stride = stream_stride;
4169 device->stateBlock->state.user_stream = TRUE;
4170 if (device->stateBlock->state.load_base_vertex_index)
4172 device->stateBlock->state.load_base_vertex_index = 0;
4173 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4176 /* TODO: Only mark dirty if drawing from a different UP address */
4177 device_invalidate_state(device, STATE_STREAMSRC);
4179 drawPrimitive(device, vertex_count, 0, 0, NULL);
4181 /* MSDN specifies stream zero settings must be set to NULL */
4182 stream->buffer = NULL;
4183 stream->stride = 0;
4185 /* stream zero settings set to null at end, as per the msdn. No need to
4186 * mark dirty here, the app has to set the new stream sources or use UP
4187 * drawing again. */
4188 return WINED3D_OK;
4191 HRESULT CDECL wined3d_device_draw_indexed_primitive_up(struct wined3d_device *device,
4192 UINT index_count, const void *index_data, enum wined3d_format_id index_data_format_id,
4193 const void *stream_data, UINT stream_stride)
4195 struct wined3d_stream_state *stream;
4196 struct wined3d_buffer *vb, *ib;
4197 UINT index_size;
4199 TRACE("device %p, index_count %u, index_data %p, index_data_format %s, stream_data %p, stream_stride %u.\n",
4200 device, index_count, index_data, debug_d3dformat(index_data_format_id), stream_data, stream_stride);
4202 if (!device->stateBlock->state.vertex_declaration)
4204 WARN("(%p) : Called without a valid vertex declaration set\n", device);
4205 return WINED3DERR_INVALIDCALL;
4208 if (index_data_format_id == WINED3DFMT_R16_UINT)
4209 index_size = 2;
4210 else
4211 index_size = 4;
4213 stream = &device->stateBlock->state.streams[0];
4214 vb = stream->buffer;
4215 stream->buffer = (struct wined3d_buffer *)stream_data;
4216 if (vb)
4217 wined3d_buffer_decref(vb);
4218 stream->offset = 0;
4219 stream->stride = stream_stride;
4220 device->stateBlock->state.user_stream = TRUE;
4222 /* Set to 0 as per msdn. Do it now due to the stream source loading during drawPrimitive */
4223 device->stateBlock->state.base_vertex_index = 0;
4224 if (device->stateBlock->state.load_base_vertex_index)
4226 device->stateBlock->state.load_base_vertex_index = 0;
4227 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4229 /* Invalidate the state until we have nicer tracking of the stream source pointers */
4230 device_invalidate_state(device, STATE_STREAMSRC);
4231 device_invalidate_state(device, STATE_INDEXBUFFER);
4233 drawPrimitive(device, index_count, 0, index_size, index_data);
4235 /* MSDN specifies stream zero settings and index buffer must be set to NULL */
4236 stream->buffer = NULL;
4237 stream->stride = 0;
4238 ib = device->stateBlock->state.index_buffer;
4239 if (ib)
4241 wined3d_buffer_decref(ib);
4242 device->stateBlock->state.index_buffer = NULL;
4244 /* No need to mark the stream source state dirty here. Either the app calls UP drawing again, or it has to call
4245 * SetStreamSource to specify a vertex buffer
4248 return WINED3D_OK;
4251 HRESULT CDECL wined3d_device_draw_primitive_strided(struct wined3d_device *device,
4252 UINT vertex_count, const struct wined3d_strided_data *strided_data)
4254 /* Mark the state dirty until we have nicer tracking. It's fine to change
4255 * baseVertexIndex because that call is only called by ddraw which does
4256 * not need that value. */
4257 device_invalidate_state(device, STATE_VDECL);
4258 device_invalidate_state(device, STATE_STREAMSRC);
4259 device_invalidate_state(device, STATE_INDEXBUFFER);
4261 device->stateBlock->state.base_vertex_index = 0;
4262 device->up_strided = strided_data;
4263 drawPrimitive(device, vertex_count, 0, 0, NULL);
4264 device->up_strided = NULL;
4266 /* Invalidate the states again to make sure the values from the stateblock
4267 * are properly applied in the next regular draw. Note that the application-
4268 * provided strided data has ovwritten pretty much the entire vertex and
4269 * and index stream related states */
4270 device_invalidate_state(device, STATE_VDECL);
4271 device_invalidate_state(device, STATE_STREAMSRC);
4272 device_invalidate_state(device, STATE_INDEXBUFFER);
4273 return WINED3D_OK;
4276 HRESULT CDECL wined3d_device_draw_indexed_primitive_strided(struct wined3d_device *device,
4277 UINT index_count, const struct wined3d_strided_data *strided_data,
4278 UINT vertex_count, const void *index_data, enum wined3d_format_id index_data_format_id)
4280 UINT index_size = index_data_format_id == WINED3DFMT_R32_UINT ? 4 : 2;
4282 /* Mark the state dirty until we have nicer tracking
4283 * its fine to change baseVertexIndex because that call is only called by ddraw which does not need
4284 * that value.
4286 device_invalidate_state(device, STATE_VDECL);
4287 device_invalidate_state(device, STATE_STREAMSRC);
4288 device_invalidate_state(device, STATE_INDEXBUFFER);
4290 device->stateBlock->state.user_stream = TRUE;
4291 device->stateBlock->state.base_vertex_index = 0;
4292 device->up_strided = strided_data;
4293 drawPrimitive(device, index_count, 0, index_size, index_data);
4294 device->up_strided = NULL;
4296 device_invalidate_state(device, STATE_VDECL);
4297 device_invalidate_state(device, STATE_STREAMSRC);
4298 device_invalidate_state(device, STATE_INDEXBUFFER);
4299 return WINED3D_OK;
4302 /* This is a helper function for UpdateTexture, there is no UpdateVolume method in D3D. */
4303 static HRESULT device_update_volume(struct wined3d_device *device,
4304 struct wined3d_volume *src_volume, struct wined3d_volume *dst_volume)
4306 struct wined3d_mapped_box src;
4307 struct wined3d_mapped_box dst;
4308 HRESULT hr;
4310 TRACE("device %p, src_volume %p, dst_volume %p.\n",
4311 device, src_volume, dst_volume);
4313 /* TODO: Implement direct loading into the gl volume instead of using
4314 * memcpy and dirtification to improve loading performance. */
4315 hr = wined3d_volume_map(src_volume, &src, NULL, WINED3DLOCK_READONLY);
4316 if (FAILED(hr)) return hr;
4317 hr = wined3d_volume_map(dst_volume, &dst, NULL, WINED3DLOCK_DISCARD);
4318 if (FAILED(hr))
4320 wined3d_volume_unmap(src_volume);
4321 return hr;
4324 memcpy(dst.data, src.data, dst_volume->resource.size);
4326 hr = wined3d_volume_unmap(dst_volume);
4327 if (FAILED(hr))
4328 wined3d_volume_unmap(src_volume);
4329 else
4330 hr = wined3d_volume_unmap(src_volume);
4332 return hr;
4335 HRESULT CDECL wined3d_device_update_texture(struct wined3d_device *device,
4336 struct wined3d_texture *src_texture, struct wined3d_texture *dst_texture)
4338 unsigned int level_count, i;
4339 WINED3DRESOURCETYPE type;
4340 HRESULT hr;
4342 TRACE("device %p, src_texture %p, dst_texture %p.\n", device, src_texture, dst_texture);
4344 /* Verify that the source and destination textures are non-NULL. */
4345 if (!src_texture || !dst_texture)
4347 WARN("Source and destination textures must be non-NULL, returning WINED3DERR_INVALIDCALL.\n");
4348 return WINED3DERR_INVALIDCALL;
4351 if (src_texture == dst_texture)
4353 WARN("Source and destination are the same object, returning WINED3DERR_INVALIDCALL.\n");
4354 return WINED3DERR_INVALIDCALL;
4357 /* Verify that the source and destination textures are the same type. */
4358 type = src_texture->resource.resourceType;
4359 if (dst_texture->resource.resourceType != type)
4361 WARN("Source and destination have different types, returning WINED3DERR_INVALIDCALL.\n");
4362 return WINED3DERR_INVALIDCALL;
4365 /* Check that both textures have the identical numbers of levels. */
4366 level_count = wined3d_texture_get_level_count(src_texture);
4367 if (wined3d_texture_get_level_count(dst_texture) != level_count)
4369 WARN("Source and destination have different level counts, returning WINED3DERR_INVALIDCALL.\n");
4370 return WINED3DERR_INVALIDCALL;
4373 /* Make sure that the destination texture is loaded. */
4374 dst_texture->texture_ops->texture_preload(dst_texture, SRGB_RGB);
4376 /* Update every surface level of the texture. */
4377 switch (type)
4379 case WINED3DRTYPE_TEXTURE:
4381 struct wined3d_surface *src_surface;
4382 struct wined3d_surface *dst_surface;
4384 for (i = 0; i < level_count; ++i)
4386 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4387 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4388 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4389 if (FAILED(hr))
4391 WARN("Failed to update surface, hr %#x.\n", hr);
4392 return hr;
4395 break;
4398 case WINED3DRTYPE_CUBETEXTURE:
4400 struct wined3d_surface *src_surface;
4401 struct wined3d_surface *dst_surface;
4403 for (i = 0; i < level_count * 6; ++i)
4405 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4406 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4407 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4408 if (FAILED(hr))
4410 WARN("Failed to update surface, hr %#x.\n", hr);
4411 return hr;
4414 break;
4417 case WINED3DRTYPE_VOLUMETEXTURE:
4419 for (i = 0; i < level_count; ++i)
4421 hr = device_update_volume(device,
4422 volume_from_resource(wined3d_texture_get_sub_resource(src_texture, i)),
4423 volume_from_resource(wined3d_texture_get_sub_resource(dst_texture, i)));
4424 if (FAILED(hr))
4426 WARN("Failed to update volume, hr %#x.\n", hr);
4427 return hr;
4430 break;
4433 default:
4434 FIXME("Unsupported texture type %#x.\n", type);
4435 return WINED3DERR_INVALIDCALL;
4438 return WINED3D_OK;
4441 HRESULT CDECL wined3d_device_get_front_buffer_data(const struct wined3d_device *device,
4442 UINT swapchain_idx, struct wined3d_surface *dst_surface)
4444 struct wined3d_swapchain *swapchain;
4445 HRESULT hr;
4447 TRACE("device %p, swapchain_idx %u, dst_surface %p.\n", device, swapchain_idx, dst_surface);
4449 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
4450 if (FAILED(hr)) return hr;
4452 hr = wined3d_swapchain_get_front_buffer_data(swapchain, dst_surface);
4453 wined3d_swapchain_decref(swapchain);
4455 return hr;
4458 HRESULT CDECL wined3d_device_validate_device(const struct wined3d_device *device, DWORD *num_passes)
4460 const struct wined3d_state *state = &device->stateBlock->state;
4461 struct wined3d_texture *texture;
4462 DWORD i;
4464 TRACE("device %p, num_passes %p.\n", device, num_passes);
4466 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
4468 if (state->sampler_states[i][WINED3DSAMP_MINFILTER] == WINED3DTEXF_NONE)
4470 WARN("Sampler state %u has minfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4471 return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4473 if (state->sampler_states[i][WINED3DSAMP_MAGFILTER] == WINED3DTEXF_NONE)
4475 WARN("Sampler state %u has magfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4476 return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4479 texture = state->textures[i];
4480 if (!texture || texture->resource.format->flags & WINED3DFMT_FLAG_FILTERING) continue;
4482 if (state->sampler_states[i][WINED3DSAMP_MAGFILTER] != WINED3DTEXF_POINT)
4484 WARN("Non-filterable texture and mag filter enabled on samper %u, returning E_FAIL\n", i);
4485 return E_FAIL;
4487 if (state->sampler_states[i][WINED3DSAMP_MINFILTER] != WINED3DTEXF_POINT)
4489 WARN("Non-filterable texture and min filter enabled on samper %u, returning E_FAIL\n", i);
4490 return E_FAIL;
4492 if (state->sampler_states[i][WINED3DSAMP_MIPFILTER] != WINED3DTEXF_NONE
4493 && state->sampler_states[i][WINED3DSAMP_MIPFILTER] != WINED3DTEXF_POINT)
4495 WARN("Non-filterable texture and mip filter enabled on samper %u, returning E_FAIL\n", i);
4496 return E_FAIL;
4500 if (state->render_states[WINED3D_RS_ZENABLE] || state->render_states[WINED3D_RS_ZWRITEENABLE]
4501 || state->render_states[WINED3D_RS_STENCILENABLE])
4503 struct wined3d_surface *ds = device->fb.depth_stencil;
4504 struct wined3d_surface *target = device->fb.render_targets[0];
4506 if(ds && target
4507 && (ds->resource.width < target->resource.width || ds->resource.height < target->resource.height))
4509 WARN("Depth stencil is smaller than the color buffer, returning D3DERR_CONFLICTINGRENDERSTATE\n");
4510 return WINED3DERR_CONFLICTINGRENDERSTATE;
4514 /* return a sensible default */
4515 *num_passes = 1;
4517 TRACE("returning D3D_OK\n");
4518 return WINED3D_OK;
4521 HRESULT CDECL wined3d_device_set_software_vertex_processing(struct wined3d_device *device, BOOL software)
4523 static BOOL warned;
4525 TRACE("device %p, software %#x.\n", device, software);
4527 if (!warned)
4529 FIXME("device %p, software %#x stub!\n", device, software);
4530 warned = TRUE;
4533 device->softwareVertexProcessing = software;
4535 return WINED3D_OK;
4538 BOOL CDECL wined3d_device_get_software_vertex_processing(const struct wined3d_device *device)
4540 static BOOL warned;
4542 TRACE("device %p.\n", device);
4544 if (!warned)
4546 TRACE("device %p stub!\n", device);
4547 warned = TRUE;
4550 return device->softwareVertexProcessing;
4553 HRESULT CDECL wined3d_device_get_raster_status(const struct wined3d_device *device,
4554 UINT swapchain_idx, struct wined3d_raster_status *raster_status)
4556 struct wined3d_swapchain *swapchain;
4557 HRESULT hr;
4559 TRACE("device %p, swapchain_idx %u, raster_status %p.\n",
4560 device, swapchain_idx, raster_status);
4562 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
4563 if (FAILED(hr))
4565 WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
4566 return hr;
4569 hr = wined3d_swapchain_get_raster_status(swapchain, raster_status);
4570 wined3d_swapchain_decref(swapchain);
4571 if (FAILED(hr))
4573 WARN("Failed to get raster status, hr %#x.\n", hr);
4574 return hr;
4577 return WINED3D_OK;
4580 HRESULT CDECL wined3d_device_set_npatch_mode(struct wined3d_device *device, float segments)
4582 static BOOL warned;
4584 TRACE("device %p, segments %.8e.\n", device, segments);
4586 if (segments != 0.0f)
4588 if (!warned)
4590 FIXME("device %p, segments %.8e stub!\n", device, segments);
4591 warned = TRUE;
4595 return WINED3D_OK;
4598 float CDECL wined3d_device_get_npatch_mode(const struct wined3d_device *device)
4600 static BOOL warned;
4602 TRACE("device %p.\n", device);
4604 if (!warned)
4606 FIXME("device %p stub!\n", device);
4607 warned = TRUE;
4610 return 0.0f;
4613 HRESULT CDECL wined3d_device_update_surface(struct wined3d_device *device,
4614 struct wined3d_surface *src_surface, const RECT *src_rect,
4615 struct wined3d_surface *dst_surface, const POINT *dst_point)
4617 TRACE("device %p, src_surface %p, src_rect %s, dst_surface %p, dst_point %s.\n",
4618 device, src_surface, wine_dbgstr_rect(src_rect),
4619 dst_surface, wine_dbgstr_point(dst_point));
4621 if (src_surface->resource.pool != WINED3DPOOL_SYSTEMMEM || dst_surface->resource.pool != WINED3DPOOL_DEFAULT)
4623 WARN("source %p must be SYSTEMMEM and dest %p must be DEFAULT, returning WINED3DERR_INVALIDCALL\n",
4624 src_surface, dst_surface);
4625 return WINED3DERR_INVALIDCALL;
4628 return surface_upload_from_surface(dst_surface, dst_point, src_surface, src_rect);
4631 HRESULT CDECL wined3d_device_draw_rect_patch(struct wined3d_device *device, UINT handle,
4632 const float *num_segs, const struct wined3d_rect_patch_info *rect_patch_info)
4634 struct WineD3DRectPatch *patch;
4635 GLenum old_primitive_type;
4636 unsigned int i;
4637 struct list *e;
4638 BOOL found;
4640 TRACE("device %p, handle %#x, num_segs %p, rect_patch_info %p.\n",
4641 device, handle, num_segs, rect_patch_info);
4643 if (!(handle || rect_patch_info))
4645 /* TODO: Write a test for the return value, thus the FIXME */
4646 FIXME("Both handle and rect_patch_info are NULL.\n");
4647 return WINED3DERR_INVALIDCALL;
4650 if (handle)
4652 i = PATCHMAP_HASHFUNC(handle);
4653 found = FALSE;
4654 LIST_FOR_EACH(e, &device->patches[i])
4656 patch = LIST_ENTRY(e, struct WineD3DRectPatch, entry);
4657 if (patch->Handle == handle)
4659 found = TRUE;
4660 break;
4664 if (!found)
4666 TRACE("Patch does not exist. Creating a new one\n");
4667 patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4668 patch->Handle = handle;
4669 list_add_head(&device->patches[i], &patch->entry);
4670 } else {
4671 TRACE("Found existing patch %p\n", patch);
4674 else
4676 /* Since opengl does not load tesselated vertex attributes into numbered vertex
4677 * attributes we have to tesselate, read back, and draw. This needs a patch
4678 * management structure instance. Create one.
4680 * A possible improvement is to check if a vertex shader is used, and if not directly
4681 * draw the patch.
4683 FIXME("Drawing an uncached patch. This is slow\n");
4684 patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4687 if (num_segs[0] != patch->numSegs[0] || num_segs[1] != patch->numSegs[1]
4688 || num_segs[2] != patch->numSegs[2] || num_segs[3] != patch->numSegs[3]
4689 || (rect_patch_info && memcmp(rect_patch_info, &patch->rect_patch_info, sizeof(*rect_patch_info))))
4691 HRESULT hr;
4692 TRACE("Tesselation density or patch info changed, retesselating\n");
4694 if (rect_patch_info)
4695 patch->rect_patch_info = *rect_patch_info;
4697 patch->numSegs[0] = num_segs[0];
4698 patch->numSegs[1] = num_segs[1];
4699 patch->numSegs[2] = num_segs[2];
4700 patch->numSegs[3] = num_segs[3];
4702 hr = tesselate_rectpatch(device, patch);
4703 if (FAILED(hr))
4705 WARN("Patch tesselation failed.\n");
4707 /* Do not release the handle to store the params of the patch */
4708 if (!handle)
4709 HeapFree(GetProcessHeap(), 0, patch);
4711 return hr;
4715 old_primitive_type = device->stateBlock->state.gl_primitive_type;
4716 device->stateBlock->state.gl_primitive_type = GL_TRIANGLES;
4717 wined3d_device_draw_primitive_strided(device, patch->numSegs[0] * patch->numSegs[1] * 2 * 3, &patch->strided);
4718 device->stateBlock->state.gl_primitive_type = old_primitive_type;
4720 /* Destroy uncached patches */
4721 if (!handle)
4723 HeapFree(GetProcessHeap(), 0, patch->mem);
4724 HeapFree(GetProcessHeap(), 0, patch);
4726 return WINED3D_OK;
4729 HRESULT CDECL wined3d_device_draw_tri_patch(struct wined3d_device *device, UINT handle,
4730 const float *segment_count, const struct wined3d_tri_patch_info *patch_info)
4732 FIXME("device %p, handle %#x, segment_count %p, patch_info %p stub!\n",
4733 device, handle, segment_count, patch_info);
4735 return WINED3D_OK;
4738 HRESULT CDECL wined3d_device_delete_patch(struct wined3d_device *device, UINT handle)
4740 struct WineD3DRectPatch *patch;
4741 struct list *e;
4742 int i;
4744 TRACE("device %p, handle %#x.\n", device, handle);
4746 i = PATCHMAP_HASHFUNC(handle);
4747 LIST_FOR_EACH(e, &device->patches[i])
4749 patch = LIST_ENTRY(e, struct WineD3DRectPatch, entry);
4750 if (patch->Handle == handle)
4752 TRACE("Deleting patch %p\n", patch);
4753 list_remove(&patch->entry);
4754 HeapFree(GetProcessHeap(), 0, patch->mem);
4755 HeapFree(GetProcessHeap(), 0, patch);
4756 return WINED3D_OK;
4760 /* TODO: Write a test for the return value */
4761 FIXME("Attempt to destroy nonexistent patch\n");
4762 return WINED3DERR_INVALIDCALL;
4765 /* Do not call while under the GL lock. */
4766 HRESULT CDECL wined3d_device_color_fill(struct wined3d_device *device,
4767 struct wined3d_surface *surface, const RECT *rect, const struct wined3d_color *color)
4769 RECT r;
4771 TRACE("device %p, surface %p, rect %s, color {%.8e, %.8e, %.8e, %.8e}.\n",
4772 device, surface, wine_dbgstr_rect(rect),
4773 color->r, color->g, color->b, color->a);
4775 if (surface->resource.pool != WINED3DPOOL_DEFAULT && surface->resource.pool != WINED3DPOOL_SYSTEMMEM)
4777 FIXME("call to colorfill with non WINED3DPOOL_DEFAULT or WINED3DPOOL_SYSTEMMEM surface\n");
4778 return WINED3DERR_INVALIDCALL;
4781 if (!rect)
4783 SetRect(&r, 0, 0, surface->resource.width, surface->resource.height);
4784 rect = &r;
4787 return surface_color_fill(surface, rect, color);
4790 /* Do not call while under the GL lock. */
4791 void CDECL wined3d_device_clear_rendertarget_view(struct wined3d_device *device,
4792 struct wined3d_rendertarget_view *rendertarget_view, const struct wined3d_color *color)
4794 struct wined3d_resource *resource;
4795 HRESULT hr;
4796 RECT rect;
4798 resource = rendertarget_view->resource;
4799 if (resource->resourceType != WINED3DRTYPE_SURFACE)
4801 FIXME("Only supported on surface resources\n");
4802 return;
4805 SetRect(&rect, 0, 0, resource->width, resource->height);
4806 hr = surface_color_fill(surface_from_resource(resource), &rect, color);
4807 if (FAILED(hr)) ERR("Color fill failed, hr %#x.\n", hr);
4810 HRESULT CDECL wined3d_device_get_render_target(const struct wined3d_device *device,
4811 UINT render_target_idx, struct wined3d_surface **render_target)
4813 TRACE("device %p, render_target_idx %u, render_target %p.\n",
4814 device, render_target_idx, render_target);
4816 if (render_target_idx >= device->adapter->gl_info.limits.buffers)
4818 WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
4819 return WINED3DERR_INVALIDCALL;
4822 *render_target = device->fb.render_targets[render_target_idx];
4823 TRACE("Returning render target %p.\n", *render_target);
4825 if (!*render_target)
4826 return WINED3DERR_NOTFOUND;
4828 wined3d_surface_incref(*render_target);
4830 return WINED3D_OK;
4833 HRESULT CDECL wined3d_device_get_depth_stencil(const struct wined3d_device *device,
4834 struct wined3d_surface **depth_stencil)
4836 TRACE("device %p, depth_stencil %p.\n", device, depth_stencil);
4838 *depth_stencil = device->fb.depth_stencil;
4839 TRACE("Returning depth/stencil surface %p.\n", *depth_stencil);
4841 if (!*depth_stencil)
4842 return WINED3DERR_NOTFOUND;
4844 wined3d_surface_incref(*depth_stencil);
4846 return WINED3D_OK;
4849 HRESULT CDECL wined3d_device_set_render_target(struct wined3d_device *device,
4850 UINT render_target_idx, struct wined3d_surface *render_target, BOOL set_viewport)
4852 struct wined3d_surface *prev;
4854 TRACE("device %p, render_target_idx %u, render_target %p, set_viewport %#x.\n",
4855 device, render_target_idx, render_target, set_viewport);
4857 if (render_target_idx >= device->adapter->gl_info.limits.buffers)
4859 WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
4860 return WINED3DERR_INVALIDCALL;
4863 prev = device->fb.render_targets[render_target_idx];
4864 if (render_target == prev)
4866 TRACE("Trying to do a NOP SetRenderTarget operation.\n");
4867 return WINED3D_OK;
4870 /* Render target 0 can't be set to NULL. */
4871 if (!render_target && !render_target_idx)
4873 WARN("Trying to set render target 0 to NULL.\n");
4874 return WINED3DERR_INVALIDCALL;
4877 if (render_target && !(render_target->resource.usage & WINED3DUSAGE_RENDERTARGET))
4879 FIXME("Surface %p doesn't have render target usage.\n", render_target);
4880 return WINED3DERR_INVALIDCALL;
4883 if (render_target)
4884 wined3d_surface_incref(render_target);
4885 device->fb.render_targets[render_target_idx] = render_target;
4886 /* Release after the assignment, to prevent device_resource_released()
4887 * from seeing the surface as still in use. */
4888 if (prev)
4889 wined3d_surface_decref(prev);
4891 /* Render target 0 is special. */
4892 if (!render_target_idx && set_viewport)
4894 /* Set the viewport and scissor rectangles, if requested. Tests show
4895 * that stateblock recording is ignored, the change goes directly
4896 * into the primary stateblock. */
4897 device->stateBlock->state.viewport.height = device->fb.render_targets[0]->resource.height;
4898 device->stateBlock->state.viewport.width = device->fb.render_targets[0]->resource.width;
4899 device->stateBlock->state.viewport.x = 0;
4900 device->stateBlock->state.viewport.y = 0;
4901 device->stateBlock->state.viewport.max_z = 1.0f;
4902 device->stateBlock->state.viewport.min_z = 0.0f;
4903 device_invalidate_state(device, STATE_VIEWPORT);
4905 device->stateBlock->state.scissor_rect.top = 0;
4906 device->stateBlock->state.scissor_rect.left = 0;
4907 device->stateBlock->state.scissor_rect.right = device->stateBlock->state.viewport.width;
4908 device->stateBlock->state.scissor_rect.bottom = device->stateBlock->state.viewport.height;
4909 device_invalidate_state(device, STATE_SCISSORRECT);
4912 device_invalidate_state(device, STATE_FRAMEBUFFER);
4914 return WINED3D_OK;
4917 HRESULT CDECL wined3d_device_set_depth_stencil(struct wined3d_device *device, struct wined3d_surface *depth_stencil)
4919 struct wined3d_surface *prev = device->fb.depth_stencil;
4921 TRACE("device %p, depth_stencil %p, old depth_stencil %p.\n",
4922 device, depth_stencil, prev);
4924 if (prev == depth_stencil)
4926 TRACE("Trying to do a NOP SetRenderTarget operation.\n");
4927 return WINED3D_OK;
4930 if (prev)
4932 if (device->swapchains[0]->desc.flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
4933 || prev->flags & SFLAG_DISCARD)
4935 surface_modify_ds_location(prev, SFLAG_DS_DISCARDED,
4936 prev->resource.width, prev->resource.height);
4937 if (prev == device->onscreen_depth_stencil)
4939 wined3d_surface_decref(device->onscreen_depth_stencil);
4940 device->onscreen_depth_stencil = NULL;
4945 device->fb.depth_stencil = depth_stencil;
4946 if (depth_stencil)
4947 wined3d_surface_incref(depth_stencil);
4949 if (!prev != !depth_stencil)
4951 /* Swapping NULL / non NULL depth stencil affects the depth and tests */
4952 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_ZENABLE));
4953 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_STENCILENABLE));
4954 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_STENCILWRITEMASK));
4955 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_DEPTHBIAS));
4957 else if (prev && prev->resource.format->depth_size != depth_stencil->resource.format->depth_size)
4959 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_DEPTHBIAS));
4961 if (prev)
4962 wined3d_surface_decref(prev);
4964 device_invalidate_state(device, STATE_FRAMEBUFFER);
4966 return WINED3D_OK;
4969 HRESULT CDECL wined3d_device_set_cursor_properties(struct wined3d_device *device,
4970 UINT x_hotspot, UINT y_hotspot, struct wined3d_surface *cursor_image)
4972 struct wined3d_mapped_rect mapped_rect;
4974 TRACE("device %p, x_hotspot %u, y_hotspot %u, cursor_image %p.\n",
4975 device, x_hotspot, y_hotspot, cursor_image);
4977 /* some basic validation checks */
4978 if (device->cursorTexture)
4980 struct wined3d_context *context = context_acquire(device, NULL);
4981 ENTER_GL();
4982 glDeleteTextures(1, &device->cursorTexture);
4983 LEAVE_GL();
4984 context_release(context);
4985 device->cursorTexture = 0;
4988 if (cursor_image)
4990 struct wined3d_mapped_rect rect;
4992 /* MSDN: Cursor must be A8R8G8B8 */
4993 if (cursor_image->resource.format->id != WINED3DFMT_B8G8R8A8_UNORM)
4995 WARN("surface %p has an invalid format.\n", cursor_image);
4996 return WINED3DERR_INVALIDCALL;
4999 /* MSDN: Cursor must be smaller than the display mode */
5000 if (cursor_image->resource.width > device->adapter->screen_size.cx
5001 || cursor_image->resource.height > device->adapter->screen_size.cy)
5003 WARN("Surface %p dimensions are %ux%u, but screen dimensions are %ux%u.\n",
5004 cursor_image, cursor_image->resource.width, cursor_image->resource.height,
5005 device->adapter->screen_size.cx, device->adapter->screen_size.cy);
5006 return WINED3DERR_INVALIDCALL;
5009 /* TODO: MSDN: Cursor sizes must be a power of 2 */
5011 /* Do not store the surface's pointer because the application may
5012 * release it after setting the cursor image. Windows doesn't
5013 * addref the set surface, so we can't do this either without
5014 * creating circular refcount dependencies. Copy out the gl texture
5015 * instead. */
5016 device->cursorWidth = cursor_image->resource.width;
5017 device->cursorHeight = cursor_image->resource.height;
5018 if (SUCCEEDED(wined3d_surface_map(cursor_image, &rect, NULL, WINED3DLOCK_READONLY)))
5020 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
5021 const struct wined3d_format *format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
5022 struct wined3d_context *context;
5023 char *mem, *bits = rect.data;
5024 GLint intfmt = format->glInternal;
5025 GLint gl_format = format->glFormat;
5026 GLint type = format->glType;
5027 INT height = device->cursorHeight;
5028 INT width = device->cursorWidth;
5029 INT bpp = format->byte_count;
5030 INT i;
5032 /* Reformat the texture memory (pitch and width can be
5033 * different) */
5034 mem = HeapAlloc(GetProcessHeap(), 0, width * height * bpp);
5035 for(i = 0; i < height; i++)
5036 memcpy(&mem[width * bpp * i], &bits[rect.row_pitch * i], width * bpp);
5037 wined3d_surface_unmap(cursor_image);
5039 context = context_acquire(device, NULL);
5041 ENTER_GL();
5043 if (gl_info->supported[APPLE_CLIENT_STORAGE])
5045 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
5046 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
5049 invalidate_active_texture(device, context);
5050 /* Create a new cursor texture */
5051 glGenTextures(1, &device->cursorTexture);
5052 checkGLcall("glGenTextures");
5053 context_bind_texture(context, GL_TEXTURE_2D, device->cursorTexture);
5054 /* Copy the bitmap memory into the cursor texture */
5055 glTexImage2D(GL_TEXTURE_2D, 0, intfmt, width, height, 0, gl_format, type, mem);
5056 checkGLcall("glTexImage2D");
5057 HeapFree(GetProcessHeap(), 0, mem);
5059 if (gl_info->supported[APPLE_CLIENT_STORAGE])
5061 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
5062 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
5065 LEAVE_GL();
5067 context_release(context);
5069 else
5071 FIXME("A cursor texture was not returned.\n");
5072 device->cursorTexture = 0;
5075 if (cursor_image->resource.width == 32 && cursor_image->resource.height == 32)
5077 /* Draw a hardware cursor */
5078 ICONINFO cursorInfo;
5079 HCURSOR cursor;
5080 /* Create and clear maskBits because it is not needed for
5081 * 32-bit cursors. 32x32 bits split into 32-bit chunks == 32
5082 * chunks. */
5083 DWORD *maskBits = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
5084 (cursor_image->resource.width * cursor_image->resource.height / 8));
5085 wined3d_surface_map(cursor_image, &mapped_rect, NULL,
5086 WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY);
5087 TRACE("width: %u height: %u.\n", cursor_image->resource.width, cursor_image->resource.height);
5089 cursorInfo.fIcon = FALSE;
5090 cursorInfo.xHotspot = x_hotspot;
5091 cursorInfo.yHotspot = y_hotspot;
5092 cursorInfo.hbmMask = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
5093 1, 1, maskBits);
5094 cursorInfo.hbmColor = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
5095 1, 32, mapped_rect.data);
5096 wined3d_surface_unmap(cursor_image);
5097 /* Create our cursor and clean up. */
5098 cursor = CreateIconIndirect(&cursorInfo);
5099 if (cursorInfo.hbmMask) DeleteObject(cursorInfo.hbmMask);
5100 if (cursorInfo.hbmColor) DeleteObject(cursorInfo.hbmColor);
5101 if (device->hardwareCursor) DestroyCursor(device->hardwareCursor);
5102 device->hardwareCursor = cursor;
5103 if (device->bCursorVisible) SetCursor( cursor );
5104 HeapFree(GetProcessHeap(), 0, maskBits);
5108 device->xHotSpot = x_hotspot;
5109 device->yHotSpot = y_hotspot;
5110 return WINED3D_OK;
5113 void CDECL wined3d_device_set_cursor_position(struct wined3d_device *device,
5114 int x_screen_space, int y_screen_space, DWORD flags)
5116 TRACE("device %p, x %d, y %d, flags %#x.\n",
5117 device, x_screen_space, y_screen_space, flags);
5119 device->xScreenSpace = x_screen_space;
5120 device->yScreenSpace = y_screen_space;
5122 if (device->hardwareCursor)
5124 POINT pt;
5126 GetCursorPos( &pt );
5127 if (x_screen_space == pt.x && y_screen_space == pt.y)
5128 return;
5129 SetCursorPos( x_screen_space, y_screen_space );
5131 /* Switch to the software cursor if position diverges from the hardware one. */
5132 GetCursorPos( &pt );
5133 if (x_screen_space != pt.x || y_screen_space != pt.y)
5135 if (device->bCursorVisible) SetCursor( NULL );
5136 DestroyCursor( device->hardwareCursor );
5137 device->hardwareCursor = 0;
5142 BOOL CDECL wined3d_device_show_cursor(struct wined3d_device *device, BOOL show)
5144 BOOL oldVisible = device->bCursorVisible;
5146 TRACE("device %p, show %#x.\n", device, show);
5149 * When ShowCursor is first called it should make the cursor appear at the OS's last
5150 * known cursor position.
5152 if (show && !oldVisible)
5154 POINT pt;
5155 GetCursorPos(&pt);
5156 device->xScreenSpace = pt.x;
5157 device->yScreenSpace = pt.y;
5160 if (device->hardwareCursor)
5162 device->bCursorVisible = show;
5163 if (show)
5164 SetCursor(device->hardwareCursor);
5165 else
5166 SetCursor(NULL);
5168 else
5170 if (device->cursorTexture)
5171 device->bCursorVisible = show;
5174 return oldVisible;
5177 void CDECL wined3d_device_evict_managed_resources(struct wined3d_device *device)
5179 struct wined3d_resource *resource, *cursor;
5181 TRACE("device %p.\n", device);
5183 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5185 TRACE("Checking resource %p for eviction.\n", resource);
5187 if (resource->pool == WINED3DPOOL_MANAGED)
5189 TRACE("Evicting %p.\n", resource);
5190 resource->resource_ops->resource_unload(resource);
5194 /* Invalidate stream sources, the buffer(s) may have been evicted. */
5195 device_invalidate_state(device, STATE_STREAMSRC);
5198 static HRESULT updateSurfaceDesc(struct wined3d_surface *surface,
5199 const struct wined3d_swapchain_desc *swapchain_desc)
5201 struct wined3d_device *device = surface->resource.device;
5202 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
5204 /* Reallocate proper memory for the front and back buffer and adjust their sizes */
5205 if (surface->flags & SFLAG_DIBSECTION)
5207 DeleteDC(surface->hDC);
5208 DeleteObject(surface->dib.DIBsection);
5209 surface->dib.bitmap_data = NULL;
5210 surface->resource.allocatedMemory = NULL;
5211 surface->flags &= ~SFLAG_DIBSECTION;
5213 surface->resource.width = swapchain_desc->backbuffer_width;
5214 surface->resource.height = swapchain_desc->backbuffer_height;
5215 if (gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] || gl_info->supported[ARB_TEXTURE_RECTANGLE]
5216 || gl_info->supported[WINED3D_GL_NORMALIZED_TEXRECT])
5218 surface->pow2Width = swapchain_desc->backbuffer_width;
5219 surface->pow2Height = swapchain_desc->backbuffer_height;
5221 else
5223 surface->pow2Width = surface->pow2Height = 1;
5224 while (surface->pow2Width < swapchain_desc->backbuffer_width)
5225 surface->pow2Width <<= 1;
5226 while (surface->pow2Height < swapchain_desc->backbuffer_height)
5227 surface->pow2Height <<= 1;
5230 if (!(surface->resource.usage & WINED3DUSAGE_DEPTHSTENCIL))
5231 surface->resource.format = wined3d_get_format(gl_info, swapchain_desc->backbuffer_format);
5232 surface->resource.multisample_type = swapchain_desc->multisample_type;
5233 surface->resource.multisample_quality = swapchain_desc->multisample_quality;
5235 if (device->d3d_initialized)
5236 surface->resource.resource_ops->resource_unload(&surface->resource);
5238 if (surface->pow2Width != swapchain_desc->backbuffer_width
5239 || surface->pow2Height != swapchain_desc->backbuffer_height)
5241 surface->flags |= SFLAG_NONPOW2;
5243 else
5245 surface->flags &= ~SFLAG_NONPOW2;
5247 HeapFree(GetProcessHeap(), 0, surface->resource.heapMemory);
5248 surface->resource.allocatedMemory = NULL;
5249 surface->resource.heapMemory = NULL;
5250 surface->resource.size = wined3d_surface_get_pitch(surface) * surface->pow2Width;
5252 /* Put all surfaces into sysmem - the drawable might disappear if the backbuffer was rendered
5253 * to a FBO */
5254 if (!surface_init_sysmem(surface))
5256 return E_OUTOFMEMORY;
5258 return WINED3D_OK;
5261 static BOOL is_display_mode_supported(const struct wined3d_device *device,
5262 const struct wined3d_swapchain_desc *swapchain_desc)
5264 struct wined3d_display_mode m;
5265 UINT i, count;
5266 HRESULT hr;
5268 /* All Windowed modes are supported, as is leaving the current mode */
5269 if (swapchain_desc->windowed)
5270 return TRUE;
5271 if (!swapchain_desc->backbuffer_width)
5272 return TRUE;
5273 if (!swapchain_desc->backbuffer_height)
5274 return TRUE;
5276 count = wined3d_get_adapter_mode_count(device->wined3d, device->adapter->ordinal, WINED3DFMT_UNKNOWN);
5277 for (i = 0; i < count; ++i)
5279 memset(&m, 0, sizeof(m));
5280 hr = wined3d_enum_adapter_modes(device->wined3d, device->adapter->ordinal, WINED3DFMT_UNKNOWN, i, &m);
5281 if (FAILED(hr))
5282 ERR("Failed to enumerate adapter mode.\n");
5283 if (m.width == swapchain_desc->backbuffer_width && m.height == swapchain_desc->backbuffer_height)
5284 /* Mode found, it is supported. */
5285 return TRUE;
5287 /* Mode not found -> not supported */
5288 return FALSE;
5291 /* Do not call while under the GL lock. */
5292 static void delete_opengl_contexts(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
5294 struct wined3d_resource *resource, *cursor;
5295 const struct wined3d_gl_info *gl_info;
5296 struct wined3d_context *context;
5297 struct wined3d_shader *shader;
5299 context = context_acquire(device, NULL);
5300 gl_info = context->gl_info;
5302 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5304 TRACE("Unloading resource %p.\n", resource);
5306 resource->resource_ops->resource_unload(resource);
5309 LIST_FOR_EACH_ENTRY(shader, &device->shaders, struct wined3d_shader, shader_list_entry)
5311 device->shader_backend->shader_destroy(shader);
5314 ENTER_GL();
5315 if (device->depth_blt_texture)
5317 glDeleteTextures(1, &device->depth_blt_texture);
5318 device->depth_blt_texture = 0;
5320 if (device->cursorTexture)
5322 glDeleteTextures(1, &device->cursorTexture);
5323 device->cursorTexture = 0;
5325 LEAVE_GL();
5327 device->blitter->free_private(device);
5328 device->frag_pipe->free_private(device);
5329 device->shader_backend->shader_free_private(device);
5330 destroy_dummy_textures(device, gl_info);
5332 context_release(context);
5334 while (device->context_count)
5336 swapchain_destroy_contexts(device->contexts[0]->swapchain);
5339 HeapFree(GetProcessHeap(), 0, swapchain->context);
5340 swapchain->context = NULL;
5343 /* Do not call while under the GL lock. */
5344 static HRESULT create_primary_opengl_context(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
5346 struct wined3d_context *context;
5347 struct wined3d_surface *target;
5348 HRESULT hr;
5350 /* Recreate the primary swapchain's context */
5351 swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(*swapchain->context));
5352 if (!swapchain->context)
5354 ERR("Failed to allocate memory for swapchain context array.\n");
5355 return E_OUTOFMEMORY;
5358 target = swapchain->back_buffers ? swapchain->back_buffers[0] : swapchain->front_buffer;
5359 if (!(context = context_create(swapchain, target, swapchain->ds_format)))
5361 WARN("Failed to create context.\n");
5362 HeapFree(GetProcessHeap(), 0, swapchain->context);
5363 return E_FAIL;
5366 swapchain->context[0] = context;
5367 swapchain->num_contexts = 1;
5368 create_dummy_textures(device, context);
5369 context_release(context);
5371 hr = device->shader_backend->shader_alloc_private(device);
5372 if (FAILED(hr))
5374 ERR("Failed to allocate shader private data, hr %#x.\n", hr);
5375 goto err;
5378 hr = device->frag_pipe->alloc_private(device);
5379 if (FAILED(hr))
5381 ERR("Failed to allocate fragment pipe private data, hr %#x.\n", hr);
5382 device->shader_backend->shader_free_private(device);
5383 goto err;
5386 hr = device->blitter->alloc_private(device);
5387 if (FAILED(hr))
5389 ERR("Failed to allocate blitter private data, hr %#x.\n", hr);
5390 device->frag_pipe->free_private(device);
5391 device->shader_backend->shader_free_private(device);
5392 goto err;
5395 return WINED3D_OK;
5397 err:
5398 context_acquire(device, NULL);
5399 destroy_dummy_textures(device, context->gl_info);
5400 context_release(context);
5401 context_destroy(device, context);
5402 HeapFree(GetProcessHeap(), 0, swapchain->context);
5403 swapchain->num_contexts = 0;
5404 return hr;
5407 /* Do not call while under the GL lock. */
5408 HRESULT CDECL wined3d_device_reset(struct wined3d_device *device,
5409 const struct wined3d_swapchain_desc *swapchain_desc,
5410 wined3d_device_reset_cb callback)
5412 struct wined3d_resource *resource, *cursor;
5413 struct wined3d_swapchain *swapchain;
5414 struct wined3d_display_mode mode;
5415 BOOL DisplayModeChanged = FALSE;
5416 BOOL update_desc = FALSE;
5417 HRESULT hr;
5419 TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
5421 stateblock_unbind_resources(device->stateBlock);
5423 if (device->onscreen_depth_stencil)
5425 wined3d_surface_decref(device->onscreen_depth_stencil);
5426 device->onscreen_depth_stencil = NULL;
5429 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5431 TRACE("Enumerating resource %p.\n", resource);
5432 if (FAILED(hr = callback(resource)))
5433 return hr;
5436 hr = wined3d_device_get_swapchain(device, 0, &swapchain);
5437 if (FAILED(hr))
5439 ERR("Failed to get the first implicit swapchain\n");
5440 return hr;
5443 if (!is_display_mode_supported(device, swapchain_desc))
5445 WARN("Rejecting reset() call because the requested display mode is not supported.\n");
5446 WARN("Requested mode: %ux%u.\n",
5447 swapchain_desc->backbuffer_width,
5448 swapchain_desc->backbuffer_height);
5449 wined3d_swapchain_decref(swapchain);
5450 return WINED3DERR_INVALIDCALL;
5453 /* Is it necessary to recreate the gl context? Actually every setting can be changed
5454 * on an existing gl context, so there's no real need for recreation.
5456 * TODO: Figure out how Reset influences resources in D3DPOOL_DEFAULT, D3DPOOL_SYSTEMMEMORY and D3DPOOL_MANAGED
5458 * TODO: Figure out what happens to explicit swapchains, or if we have more than one implicit swapchain
5460 TRACE("New params:\n");
5461 TRACE("backbuffer_width %u\n", swapchain_desc->backbuffer_width);
5462 TRACE("backbuffer_height %u\n", swapchain_desc->backbuffer_height);
5463 TRACE("backbuffer_format %s\n", debug_d3dformat(swapchain_desc->backbuffer_format));
5464 TRACE("backbuffer_count %u\n", swapchain_desc->backbuffer_count);
5465 TRACE("multisample_type %#x\n", swapchain_desc->multisample_type);
5466 TRACE("multisample_quality %u\n", swapchain_desc->multisample_quality);
5467 TRACE("swap_effect %#x\n", swapchain_desc->swap_effect);
5468 TRACE("device_window %p\n", swapchain_desc->device_window);
5469 TRACE("windowed %#x\n", swapchain_desc->windowed);
5470 TRACE("enable_auto_depth_stencil %#x\n", swapchain_desc->enable_auto_depth_stencil);
5471 if (swapchain_desc->enable_auto_depth_stencil)
5472 TRACE("auto_depth_stencil_format %s\n", debug_d3dformat(swapchain_desc->auto_depth_stencil_format));
5473 TRACE("flags %#x\n", swapchain_desc->flags);
5474 TRACE("refresh_rate %u\n", swapchain_desc->refresh_rate);
5475 TRACE("swap_interval %u\n", swapchain_desc->swap_interval);
5476 TRACE("auto_restore_display_mode %#x\n", swapchain_desc->auto_restore_display_mode);
5478 /* No special treatment of these parameters. Just store them */
5479 swapchain->desc.swap_effect = swapchain_desc->swap_effect;
5480 swapchain->desc.flags = swapchain_desc->flags;
5481 swapchain->desc.swap_interval = swapchain_desc->swap_interval;
5482 swapchain->desc.refresh_rate = swapchain_desc->refresh_rate;
5484 /* What to do about these? */
5485 if (swapchain_desc->backbuffer_count
5486 && swapchain_desc->backbuffer_count != swapchain->desc.backbuffer_count)
5487 FIXME("Cannot change the back buffer count yet.\n");
5489 if (swapchain_desc->device_window
5490 && swapchain_desc->device_window != swapchain->desc.device_window)
5491 FIXME("Cannot change the device window yet.\n");
5493 if (swapchain_desc->enable_auto_depth_stencil && !device->auto_depth_stencil)
5495 HRESULT hrc;
5497 TRACE("Creating the depth stencil buffer\n");
5499 hrc = device->device_parent->ops->create_depth_stencil(device->device_parent,
5500 swapchain_desc->backbuffer_width,
5501 swapchain_desc->backbuffer_height,
5502 swapchain_desc->auto_depth_stencil_format,
5503 swapchain_desc->multisample_type,
5504 swapchain_desc->multisample_quality,
5505 FALSE,
5506 &device->auto_depth_stencil);
5507 if (FAILED(hrc))
5509 ERR("Failed to create the depth stencil buffer.\n");
5510 wined3d_swapchain_decref(swapchain);
5511 return WINED3DERR_INVALIDCALL;
5515 if (device->onscreen_depth_stencil)
5517 wined3d_surface_decref(device->onscreen_depth_stencil);
5518 device->onscreen_depth_stencil = NULL;
5521 /* Reset the depth stencil */
5522 if (swapchain_desc->enable_auto_depth_stencil)
5523 wined3d_device_set_depth_stencil(device, device->auto_depth_stencil);
5524 else
5525 wined3d_device_set_depth_stencil(device, NULL);
5527 TRACE("Resetting stateblock\n");
5528 wined3d_stateblock_decref(device->updateStateBlock);
5529 wined3d_stateblock_decref(device->stateBlock);
5531 if (swapchain_desc->windowed)
5533 mode.width = swapchain->orig_width;
5534 mode.height = swapchain->orig_height;
5535 mode.refresh_rate = 0;
5536 mode.format_id = swapchain->desc.backbuffer_format;
5538 else
5540 mode.width = swapchain_desc->backbuffer_width;
5541 mode.height = swapchain_desc->backbuffer_height;
5542 mode.refresh_rate = swapchain_desc->refresh_rate;
5543 mode.format_id = swapchain_desc->backbuffer_format;
5546 /* Should Width == 800 && Height == 0 set 800x600? */
5547 if (swapchain_desc->backbuffer_width && swapchain_desc->backbuffer_height
5548 && (swapchain_desc->backbuffer_width != swapchain->desc.backbuffer_width
5549 || swapchain_desc->backbuffer_height != swapchain->desc.backbuffer_height))
5551 if (!swapchain_desc->windowed)
5552 DisplayModeChanged = TRUE;
5554 swapchain->desc.backbuffer_width = swapchain_desc->backbuffer_width;
5555 swapchain->desc.backbuffer_height = swapchain_desc->backbuffer_height;
5556 update_desc = TRUE;
5559 if (swapchain_desc->backbuffer_format != WINED3DFMT_UNKNOWN
5560 && swapchain_desc->backbuffer_format != swapchain->desc.backbuffer_format)
5562 swapchain->desc.backbuffer_format = swapchain_desc->backbuffer_format;
5563 update_desc = TRUE;
5566 if (swapchain_desc->multisample_type != swapchain->desc.multisample_type
5567 || swapchain_desc->multisample_quality != swapchain->desc.multisample_quality)
5569 swapchain->desc.multisample_type = swapchain_desc->multisample_type;
5570 swapchain->desc.multisample_quality = swapchain_desc->multisample_quality;
5571 update_desc = TRUE;
5574 if (update_desc)
5576 UINT i;
5578 hr = updateSurfaceDesc(swapchain->front_buffer, &swapchain->desc);
5579 if (FAILED(hr))
5581 wined3d_swapchain_decref(swapchain);
5582 return hr;
5585 for (i = 0; i < swapchain->desc.backbuffer_count; ++i)
5587 hr = updateSurfaceDesc(swapchain->back_buffers[i], &swapchain->desc);
5588 if (FAILED(hr))
5590 wined3d_swapchain_decref(swapchain);
5591 return hr;
5594 if (device->auto_depth_stencil)
5596 hr = updateSurfaceDesc(device->auto_depth_stencil, &swapchain->desc);
5597 if (FAILED(hr))
5599 wined3d_swapchain_decref(swapchain);
5600 return hr;
5605 if (device->d3d_initialized)
5606 delete_opengl_contexts(device, swapchain);
5608 if (!swapchain_desc->windowed != !swapchain->desc.windowed
5609 || DisplayModeChanged)
5611 wined3d_device_set_display_mode(device, 0, &mode);
5613 if (!swapchain_desc->windowed)
5615 if (swapchain->desc.windowed)
5617 HWND focus_window = device->create_parms.focus_window;
5618 if (!focus_window)
5619 focus_window = swapchain_desc->device_window;
5620 if (FAILED(hr = wined3d_device_acquire_focus_window(device, focus_window)))
5622 ERR("Failed to acquire focus window, hr %#x.\n", hr);
5623 wined3d_swapchain_decref(swapchain);
5624 return hr;
5627 /* switch from windowed to fs */
5628 wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5629 swapchain_desc->backbuffer_width,
5630 swapchain_desc->backbuffer_height);
5632 else
5634 /* Fullscreen -> fullscreen mode change */
5635 MoveWindow(swapchain->device_window, 0, 0,
5636 swapchain_desc->backbuffer_width,
5637 swapchain_desc->backbuffer_height,
5638 TRUE);
5641 else if (!swapchain->desc.windowed)
5643 /* Fullscreen -> windowed switch */
5644 wined3d_device_restore_fullscreen_window(device, swapchain->device_window);
5645 wined3d_device_release_focus_window(device);
5647 swapchain->desc.windowed = swapchain_desc->windowed;
5649 else if (!swapchain_desc->windowed)
5651 DWORD style = device->style;
5652 DWORD exStyle = device->exStyle;
5653 /* If we're in fullscreen, and the mode wasn't changed, we have to get the window back into
5654 * the right position. Some applications(Battlefield 2, Guild Wars) move it and then call
5655 * Reset to clear up their mess. Guild Wars also loses the device during that.
5657 device->style = 0;
5658 device->exStyle = 0;
5659 wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5660 swapchain_desc->backbuffer_width,
5661 swapchain_desc->backbuffer_height);
5662 device->style = style;
5663 device->exStyle = exStyle;
5666 /* Note: No parent needed for initial internal stateblock */
5667 hr = wined3d_stateblock_create(device, WINED3DSBT_INIT, &device->stateBlock);
5668 if (FAILED(hr))
5669 ERR("Resetting the stateblock failed with error %#x.\n", hr);
5670 else
5671 TRACE("Created stateblock %p.\n", device->stateBlock);
5672 device->updateStateBlock = device->stateBlock;
5673 wined3d_stateblock_incref(device->updateStateBlock);
5675 stateblock_init_default_state(device->stateBlock);
5677 swapchain_update_render_to_fbo(swapchain);
5678 swapchain_update_draw_bindings(swapchain);
5680 if (device->d3d_initialized)
5681 hr = create_primary_opengl_context(device, swapchain);
5682 wined3d_swapchain_decref(swapchain);
5684 /* All done. There is no need to reload resources or shaders, this will happen automatically on the
5685 * first use
5687 return hr;
5690 HRESULT CDECL wined3d_device_set_dialog_box_mode(struct wined3d_device *device, BOOL enable_dialogs)
5692 TRACE("device %p, enable_dialogs %#x.\n", device, enable_dialogs);
5694 if (!enable_dialogs) FIXME("Dialogs cannot be disabled yet.\n");
5696 return WINED3D_OK;
5700 HRESULT CDECL wined3d_device_get_creation_parameters(const struct wined3d_device *device,
5701 struct wined3d_device_creation_parameters *parameters)
5703 TRACE("device %p, parameters %p.\n", device, parameters);
5705 *parameters = device->create_parms;
5706 return WINED3D_OK;
5709 void CDECL wined3d_device_set_gamma_ramp(const struct wined3d_device *device,
5710 UINT swapchain_idx, DWORD flags, const struct wined3d_gamma_ramp *ramp)
5712 struct wined3d_swapchain *swapchain;
5714 TRACE("device %p, swapchain_idx %u, flags %#x, ramp %p.\n",
5715 device, swapchain_idx, flags, ramp);
5717 if (SUCCEEDED(wined3d_device_get_swapchain(device, swapchain_idx, &swapchain)))
5719 wined3d_swapchain_set_gamma_ramp(swapchain, flags, ramp);
5720 wined3d_swapchain_decref(swapchain);
5724 void CDECL wined3d_device_get_gamma_ramp(const struct wined3d_device *device,
5725 UINT swapchain_idx, struct wined3d_gamma_ramp *ramp)
5727 struct wined3d_swapchain *swapchain;
5729 TRACE("device %p, swapchain_idx %u, ramp %p.\n",
5730 device, swapchain_idx, ramp);
5732 if (SUCCEEDED(wined3d_device_get_swapchain(device, swapchain_idx, &swapchain)))
5734 wined3d_swapchain_get_gamma_ramp(swapchain, ramp);
5735 wined3d_swapchain_decref(swapchain);
5739 void device_resource_add(struct wined3d_device *device, struct wined3d_resource *resource)
5741 TRACE("device %p, resource %p.\n", device, resource);
5743 list_add_head(&device->resources, &resource->resource_list_entry);
5746 static void device_resource_remove(struct wined3d_device *device, struct wined3d_resource *resource)
5748 TRACE("device %p, resource %p.\n", device, resource);
5750 list_remove(&resource->resource_list_entry);
5753 void device_resource_released(struct wined3d_device *device, struct wined3d_resource *resource)
5755 WINED3DRESOURCETYPE type = resource->resourceType;
5756 unsigned int i;
5758 TRACE("device %p, resource %p, type %s.\n", device, resource, debug_d3dresourcetype(type));
5760 context_resource_released(device, resource, type);
5762 switch (type)
5764 case WINED3DRTYPE_SURFACE:
5766 struct wined3d_surface *surface = surface_from_resource(resource);
5768 if (!device->d3d_initialized) break;
5770 for (i = 0; i < device->adapter->gl_info.limits.buffers; ++i)
5772 if (device->fb.render_targets[i] == surface)
5774 ERR("Surface %p is still in use as render target %u.\n", surface, i);
5775 device->fb.render_targets[i] = NULL;
5779 if (device->fb.depth_stencil == surface)
5781 ERR("Surface %p is still in use as depth/stencil buffer.\n", surface);
5782 device->fb.depth_stencil = NULL;
5785 break;
5787 case WINED3DRTYPE_TEXTURE:
5788 case WINED3DRTYPE_CUBETEXTURE:
5789 case WINED3DRTYPE_VOLUMETEXTURE:
5790 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
5792 struct wined3d_texture *texture = wined3d_texture_from_resource(resource);
5794 if (device->stateBlock && device->stateBlock->state.textures[i] == texture)
5796 ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
5797 texture, device->stateBlock, i);
5798 device->stateBlock->state.textures[i] = NULL;
5801 if (device->updateStateBlock != device->stateBlock
5802 && device->updateStateBlock->state.textures[i] == texture)
5804 ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
5805 texture, device->updateStateBlock, i);
5806 device->updateStateBlock->state.textures[i] = NULL;
5809 break;
5811 case WINED3DRTYPE_BUFFER:
5813 struct wined3d_buffer *buffer = buffer_from_resource(resource);
5815 for (i = 0; i < MAX_STREAMS; ++i)
5817 if (device->stateBlock && device->stateBlock->state.streams[i].buffer == buffer)
5819 ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
5820 buffer, device->stateBlock, i);
5821 device->stateBlock->state.streams[i].buffer = NULL;
5824 if (device->updateStateBlock != device->stateBlock
5825 && device->updateStateBlock->state.streams[i].buffer == buffer)
5827 ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
5828 buffer, device->updateStateBlock, i);
5829 device->updateStateBlock->state.streams[i].buffer = NULL;
5834 if (device->stateBlock && device->stateBlock->state.index_buffer == buffer)
5836 ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
5837 buffer, device->stateBlock);
5838 device->stateBlock->state.index_buffer = NULL;
5841 if (device->updateStateBlock != device->stateBlock
5842 && device->updateStateBlock->state.index_buffer == buffer)
5844 ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
5845 buffer, device->updateStateBlock);
5846 device->updateStateBlock->state.index_buffer = NULL;
5849 break;
5851 default:
5852 break;
5855 /* Remove the resource from the resourceStore */
5856 device_resource_remove(device, resource);
5858 TRACE("Resource released.\n");
5861 HRESULT CDECL wined3d_device_get_surface_from_dc(const struct wined3d_device *device,
5862 HDC dc, struct wined3d_surface **surface)
5864 struct wined3d_resource *resource;
5866 TRACE("device %p, dc %p, surface %p.\n", device, dc, surface);
5868 if (!dc)
5869 return WINED3DERR_INVALIDCALL;
5871 LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
5873 if (resource->resourceType == WINED3DRTYPE_SURFACE)
5875 struct wined3d_surface *s = surface_from_resource(resource);
5877 if (s->hDC == dc)
5879 TRACE("Found surface %p for dc %p.\n", s, dc);
5880 *surface = s;
5881 return WINED3D_OK;
5886 return WINED3DERR_INVALIDCALL;
5889 HRESULT device_init(struct wined3d_device *device, struct wined3d *wined3d,
5890 UINT adapter_idx, enum wined3d_device_type device_type, HWND focus_window, DWORD flags,
5891 BYTE surface_alignment, struct wined3d_device_parent *device_parent)
5893 struct wined3d_adapter *adapter = &wined3d->adapters[adapter_idx];
5894 const struct fragment_pipeline *fragment_pipeline;
5895 struct wined3d_display_mode mode;
5896 struct shader_caps shader_caps;
5897 struct fragment_caps ffp_caps;
5898 unsigned int i;
5899 HRESULT hr;
5901 device->ref = 1;
5902 device->wined3d = wined3d;
5903 wined3d_incref(device->wined3d);
5904 device->adapter = wined3d->adapter_count ? adapter : NULL;
5905 device->device_parent = device_parent;
5906 list_init(&device->resources);
5907 list_init(&device->shaders);
5908 device->surface_alignment = surface_alignment;
5910 /* Get the initial screen setup for ddraw. */
5911 hr = wined3d_get_adapter_display_mode(wined3d, adapter_idx, &mode);
5912 if (FAILED(hr))
5914 ERR("Failed to get the adapter's display mode, hr %#x.\n", hr);
5915 wined3d_decref(device->wined3d);
5916 return hr;
5918 adapter->screen_size.cx = mode.width;
5919 adapter->screen_size.cy = mode.height;
5920 adapter->screen_format = mode.format_id;
5922 /* Save the creation parameters. */
5923 device->create_parms.adapter_idx = adapter_idx;
5924 device->create_parms.device_type = device_type;
5925 device->create_parms.focus_window = focus_window;
5926 device->create_parms.flags = flags;
5928 for (i = 0; i < PATCHMAP_SIZE; ++i) list_init(&device->patches[i]);
5930 select_shader_mode(&adapter->gl_info, &device->ps_selected_mode, &device->vs_selected_mode);
5931 device->shader_backend = adapter->shader_backend;
5933 if (device->shader_backend)
5935 device->shader_backend->shader_get_caps(&adapter->gl_info, &shader_caps);
5936 device->vshader_version = shader_caps.VertexShaderVersion;
5937 device->pshader_version = shader_caps.PixelShaderVersion;
5938 device->d3d_vshader_constantF = shader_caps.MaxVertexShaderConst;
5939 device->d3d_pshader_constantF = shader_caps.MaxPixelShaderConst;
5940 device->vs_clipping = shader_caps.VSClipping;
5942 fragment_pipeline = adapter->fragment_pipe;
5943 device->frag_pipe = fragment_pipeline;
5944 if (fragment_pipeline)
5946 fragment_pipeline->get_caps(&adapter->gl_info, &ffp_caps);
5947 device->max_ffp_textures = ffp_caps.MaxSimultaneousTextures;
5949 hr = compile_state_table(device->StateTable, device->multistate_funcs, &adapter->gl_info,
5950 ffp_vertexstate_template, fragment_pipeline, misc_state_template);
5951 if (FAILED(hr))
5953 ERR("Failed to compile state table, hr %#x.\n", hr);
5954 wined3d_decref(device->wined3d);
5955 return hr;
5958 device->blitter = adapter->blitter;
5960 hr = wined3d_stateblock_create(device, WINED3DSBT_INIT, &device->stateBlock);
5961 if (FAILED(hr))
5963 WARN("Failed to create stateblock.\n");
5964 for (i = 0; i < sizeof(device->multistate_funcs) / sizeof(device->multistate_funcs[0]); ++i)
5966 HeapFree(GetProcessHeap(), 0, device->multistate_funcs[i]);
5968 wined3d_decref(device->wined3d);
5969 return hr;
5972 TRACE("Created stateblock %p.\n", device->stateBlock);
5973 device->updateStateBlock = device->stateBlock;
5974 wined3d_stateblock_incref(device->updateStateBlock);
5976 return WINED3D_OK;
5980 void device_invalidate_state(const struct wined3d_device *device, DWORD state)
5982 DWORD rep = device->StateTable[state].representative;
5983 struct wined3d_context *context;
5984 DWORD idx;
5985 BYTE shift;
5986 UINT i;
5988 for (i = 0; i < device->context_count; ++i)
5990 context = device->contexts[i];
5991 if(isStateDirty(context, rep)) continue;
5993 context->dirtyArray[context->numDirtyEntries++] = rep;
5994 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
5995 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
5996 context->isStateDirty[idx] |= (1 << shift);
6000 void get_drawable_size_fbo(const struct wined3d_context *context, UINT *width, UINT *height)
6002 /* The drawable size of a fbo target is the opengl texture size, which is the power of two size. */
6003 *width = context->current_rt->pow2Width;
6004 *height = context->current_rt->pow2Height;
6007 void get_drawable_size_backbuffer(const struct wined3d_context *context, UINT *width, UINT *height)
6009 const struct wined3d_swapchain *swapchain = context->swapchain;
6010 /* The drawable size of a backbuffer / aux buffer offscreen target is the size of the
6011 * current context's drawable, which is the size of the back buffer of the swapchain
6012 * the active context belongs to. */
6013 *width = swapchain->desc.backbuffer_width;
6014 *height = swapchain->desc.backbuffer_height;
6017 LRESULT device_process_message(struct wined3d_device *device, HWND window, BOOL unicode,
6018 UINT message, WPARAM wparam, LPARAM lparam, WNDPROC proc)
6020 if (device->filter_messages)
6022 TRACE("Filtering message: window %p, message %#x, wparam %#lx, lparam %#lx.\n",
6023 window, message, wparam, lparam);
6024 if (unicode)
6025 return DefWindowProcW(window, message, wparam, lparam);
6026 else
6027 return DefWindowProcA(window, message, wparam, lparam);
6030 if (message == WM_DESTROY)
6032 TRACE("unregister window %p.\n", window);
6033 wined3d_unregister_window(window);
6035 if (device->focus_window == window) device->focus_window = NULL;
6036 else ERR("Window %p is not the focus window for device %p.\n", window, device);
6038 else if (message == WM_DISPLAYCHANGE)
6040 device->device_parent->ops->mode_changed(device->device_parent);
6043 if (unicode)
6044 return CallWindowProcW(proc, window, message, wparam, lparam);
6045 else
6046 return CallWindowProcA(proc, window, message, wparam, lparam);