wined3d: device_clear_render_targets() never fails.
[wine.git] / dlls / wined3d / device.c
blobad30afa2448333f8b9ee20cbab868c52ac6227d3
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 == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
148 *regnum = WINED3D_FFP_POSITION;
149 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
150 *regnum = WINED3D_FFP_BLENDWEIGHT;
151 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
152 *regnum = WINED3D_FFP_BLENDINDICES;
153 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
154 *regnum = WINED3D_FFP_NORMAL;
155 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
156 *regnum = WINED3D_FFP_PSIZE;
157 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
158 *regnum = WINED3D_FFP_DIFFUSE;
159 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
160 *regnum = WINED3D_FFP_SPECULAR;
161 else if (usage == WINED3D_DECL_USAGE_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 *all_vbo)
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 data.addr += element->offset;
240 TRACE("offset %u input_slot %u usage_idx %d\n", element->offset, element->input_slot, element->usage_idx);
242 if (use_vshader)
244 if (element->output_slot == ~0U)
246 /* TODO: Assuming vertexdeclarations are usually used with the
247 * same or a similar shader, it might be worth it to store the
248 * last used output slot and try that one first. */
249 stride_used = vshader_get_input(state->vertex_shader,
250 element->usage, element->usage_idx, &idx);
252 else
254 idx = element->output_slot;
255 stride_used = TRUE;
258 else
260 if (!element->ffp_valid)
262 WARN("Skipping unsupported fixed function element of format %s and usage %s\n",
263 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
264 stride_used = FALSE;
266 else
268 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
272 if (stride_used)
274 TRACE("Load %s array %u [usage %s, usage_idx %u, "
275 "input_slot %u, offset %u, stride %u, format %s, buffer_object %u]\n",
276 use_vshader ? "shader": "fixed function", idx,
277 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
278 element->offset, stride, debug_d3dformat(element->format->id), data.buffer_object);
280 data.addr += stream->offset;
282 stream_info->elements[idx].format = element->format;
283 stream_info->elements[idx].data = data;
284 stream_info->elements[idx].stride = stride;
285 stream_info->elements[idx].stream_idx = element->input_slot;
287 if (!device->adapter->gl_info.supported[ARB_VERTEX_ARRAY_BGRA]
288 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
290 stream_info->swizzle_map |= 1 << idx;
292 stream_info->use_map |= 1 << idx;
296 device->num_buffer_queries = 0;
297 if (!state->user_stream)
299 WORD map = stream_info->use_map;
300 if (all_vbo)
301 *all_vbo = TRUE;
303 /* PreLoad all the vertex buffers. */
304 for (i = 0; map; map >>= 1, ++i)
306 struct wined3d_stream_info_element *element;
307 struct wined3d_buffer *buffer;
309 if (!(map & 1)) continue;
311 element = &stream_info->elements[i];
312 buffer = state->streams[element->stream_idx].buffer;
313 wined3d_buffer_preload(buffer);
315 /* If the preload dropped the buffer object, update the stream info. */
316 if (buffer->buffer_object != element->data.buffer_object)
318 element->data.buffer_object = 0;
319 element->data.addr = buffer_get_sysmem(buffer, &device->adapter->gl_info)
320 + (ptrdiff_t)element->data.addr;
323 if (!buffer->buffer_object && all_vbo)
324 *all_vbo = FALSE;
326 if (buffer->query)
327 device->buffer_queries[device->num_buffer_queries++] = buffer->query;
330 else if (all_vbo)
332 *all_vbo = FALSE;
336 static void stream_info_element_from_strided(const struct wined3d_gl_info *gl_info,
337 const struct wined3d_strided_element *strided, struct wined3d_stream_info_element *e)
339 e->data.addr = strided->data;
340 e->data.buffer_object = 0;
341 e->format = wined3d_get_format(gl_info, strided->format);
342 e->stride = strided->stride;
343 e->stream_idx = 0;
346 static void device_stream_info_from_strided(const struct wined3d_gl_info *gl_info,
347 const struct wined3d_strided_data *strided, struct wined3d_stream_info *stream_info)
349 unsigned int i;
351 memset(stream_info, 0, sizeof(*stream_info));
353 if (strided->position.data)
354 stream_info_element_from_strided(gl_info, &strided->position, &stream_info->elements[WINED3D_FFP_POSITION]);
355 if (strided->normal.data)
356 stream_info_element_from_strided(gl_info, &strided->normal, &stream_info->elements[WINED3D_FFP_NORMAL]);
357 if (strided->diffuse.data)
358 stream_info_element_from_strided(gl_info, &strided->diffuse, &stream_info->elements[WINED3D_FFP_DIFFUSE]);
359 if (strided->specular.data)
360 stream_info_element_from_strided(gl_info, &strided->specular, &stream_info->elements[WINED3D_FFP_SPECULAR]);
362 for (i = 0; i < WINED3DDP_MAXTEXCOORD; ++i)
364 if (strided->tex_coords[i].data)
365 stream_info_element_from_strided(gl_info, &strided->tex_coords[i],
366 &stream_info->elements[WINED3D_FFP_TEXCOORD0 + i]);
369 stream_info->position_transformed = strided->position_transformed;
371 for (i = 0; i < sizeof(stream_info->elements) / sizeof(*stream_info->elements); ++i)
373 if (!stream_info->elements[i].format) continue;
375 if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
376 && stream_info->elements[i].format->id == WINED3DFMT_B8G8R8A8_UNORM)
378 stream_info->swizzle_map |= 1 << i;
380 stream_info->use_map |= 1 << i;
384 static void device_trace_strided_stream_info(const struct wined3d_stream_info *stream_info)
386 TRACE("Strided Data:\n");
387 TRACE_STRIDED(stream_info, WINED3D_FFP_POSITION);
388 TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDWEIGHT);
389 TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDINDICES);
390 TRACE_STRIDED(stream_info, WINED3D_FFP_NORMAL);
391 TRACE_STRIDED(stream_info, WINED3D_FFP_PSIZE);
392 TRACE_STRIDED(stream_info, WINED3D_FFP_DIFFUSE);
393 TRACE_STRIDED(stream_info, WINED3D_FFP_SPECULAR);
394 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD0);
395 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD1);
396 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD2);
397 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD3);
398 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD4);
399 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD5);
400 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD6);
401 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD7);
404 /* Context activation is done by the caller. */
405 void device_update_stream_info(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
407 struct wined3d_stream_info *stream_info = &device->strided_streams;
408 const struct wined3d_state *state = &device->stateBlock->state;
409 BOOL all_vbo;
411 if (device->up_strided)
413 /* Note: this is a ddraw fixed-function code path. */
414 TRACE("=============================== Strided Input ================================\n");
415 device_stream_info_from_strided(gl_info, device->up_strided, stream_info);
416 if (TRACE_ON(d3d)) device_trace_strided_stream_info(stream_info);
417 all_vbo = FALSE;
419 else
421 TRACE("============================= Vertex Declaration =============================\n");
422 device_stream_info_from_declaration(device, stream_info, &all_vbo);
425 if (state->vertex_shader && !stream_info->position_transformed)
427 if (state->vertex_declaration->half_float_conv_needed && !all_vbo)
429 TRACE("Using drawStridedSlow with vertex shaders for FLOAT16 conversion.\n");
430 device->useDrawStridedSlow = TRUE;
432 else
434 device->useDrawStridedSlow = FALSE;
437 else
439 WORD slow_mask = (1 << WINED3D_FFP_PSIZE);
440 slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
441 & ((1 << WINED3D_FFP_DIFFUSE) | (1 << WINED3D_FFP_SPECULAR));
443 if ((stream_info->position_transformed || (stream_info->use_map & slow_mask)) && !all_vbo)
445 device->useDrawStridedSlow = TRUE;
447 else
449 device->useDrawStridedSlow = FALSE;
454 static void device_preload_texture(const struct wined3d_state *state, unsigned int idx)
456 struct wined3d_texture *texture;
457 enum WINED3DSRGB srgb;
459 if (!(texture = state->textures[idx])) return;
460 srgb = state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE] ? SRGB_SRGB : SRGB_RGB;
461 texture->texture_ops->texture_preload(texture, srgb);
464 void device_preload_textures(const struct wined3d_device *device)
466 const struct wined3d_state *state = &device->stateBlock->state;
467 unsigned int i;
469 if (use_vs(state))
471 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
473 if (state->vertex_shader->reg_maps.sampler_type[i])
474 device_preload_texture(state, MAX_FRAGMENT_SAMPLERS + i);
478 if (use_ps(state))
480 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
482 if (state->pixel_shader->reg_maps.sampler_type[i])
483 device_preload_texture(state, i);
486 else
488 WORD ffu_map = device->fixed_function_usage_map;
490 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
492 if (ffu_map & 1)
493 device_preload_texture(state, i);
498 BOOL device_context_add(struct wined3d_device *device, struct wined3d_context *context)
500 struct wined3d_context **new_array;
502 TRACE("Adding context %p.\n", context);
504 if (!device->contexts) new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_array));
505 else new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts,
506 sizeof(*new_array) * (device->context_count + 1));
508 if (!new_array)
510 ERR("Failed to grow the context array.\n");
511 return FALSE;
514 new_array[device->context_count++] = context;
515 device->contexts = new_array;
516 return TRUE;
519 void device_context_remove(struct wined3d_device *device, struct wined3d_context *context)
521 struct wined3d_context **new_array;
522 BOOL found = FALSE;
523 UINT i;
525 TRACE("Removing context %p.\n", context);
527 for (i = 0; i < device->context_count; ++i)
529 if (device->contexts[i] == context)
531 found = TRUE;
532 break;
536 if (!found)
538 ERR("Context %p doesn't exist in context array.\n", context);
539 return;
542 if (!--device->context_count)
544 HeapFree(GetProcessHeap(), 0, device->contexts);
545 device->contexts = NULL;
546 return;
549 memmove(&device->contexts[i], &device->contexts[i + 1], (device->context_count - i) * sizeof(*device->contexts));
550 new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts, device->context_count * sizeof(*device->contexts));
551 if (!new_array)
553 ERR("Failed to shrink context array. Oh well.\n");
554 return;
557 device->contexts = new_array;
560 /* Do not call while under the GL lock. */
561 void device_switch_onscreen_ds(struct wined3d_device *device,
562 struct wined3d_context *context, struct wined3d_surface *depth_stencil)
564 if (device->onscreen_depth_stencil)
566 surface_load_ds_location(device->onscreen_depth_stencil, context, SFLAG_INTEXTURE);
568 surface_modify_ds_location(device->onscreen_depth_stencil, SFLAG_INTEXTURE,
569 device->onscreen_depth_stencil->ds_current_size.cx,
570 device->onscreen_depth_stencil->ds_current_size.cy);
571 wined3d_surface_decref(device->onscreen_depth_stencil);
573 device->onscreen_depth_stencil = depth_stencil;
574 wined3d_surface_incref(device->onscreen_depth_stencil);
577 static BOOL is_full_clear(const struct wined3d_surface *target, const RECT *draw_rect, const RECT *clear_rect)
579 /* partial draw rect */
580 if (draw_rect->left || draw_rect->top
581 || draw_rect->right < target->resource.width
582 || draw_rect->bottom < target->resource.height)
583 return FALSE;
585 /* partial clear rect */
586 if (clear_rect && (clear_rect->left > 0 || clear_rect->top > 0
587 || clear_rect->right < target->resource.width
588 || clear_rect->bottom < target->resource.height))
589 return FALSE;
591 return TRUE;
594 static void prepare_ds_clear(struct wined3d_surface *ds, struct wined3d_context *context,
595 DWORD location, const RECT *draw_rect, UINT rect_count, const RECT *clear_rect, RECT *out_rect)
597 RECT current_rect, r;
599 if (ds->flags & location)
600 SetRect(&current_rect, 0, 0,
601 ds->ds_current_size.cx,
602 ds->ds_current_size.cy);
603 else
604 SetRectEmpty(&current_rect);
606 IntersectRect(&r, draw_rect, &current_rect);
607 if (EqualRect(&r, draw_rect))
609 /* current_rect ⊇ draw_rect, modify only. */
610 SetRect(out_rect, 0, 0, ds->ds_current_size.cx, ds->ds_current_size.cy);
611 return;
614 if (EqualRect(&r, &current_rect))
616 /* draw_rect ⊇ current_rect, test if we're doing a full clear. */
618 if (!clear_rect)
620 /* Full clear, modify only. */
621 *out_rect = *draw_rect;
622 return;
625 IntersectRect(&r, draw_rect, clear_rect);
626 if (EqualRect(&r, draw_rect))
628 /* clear_rect ⊇ draw_rect, modify only. */
629 *out_rect = *draw_rect;
630 return;
634 /* Full load. */
635 surface_load_ds_location(ds, context, location);
636 SetRect(out_rect, 0, 0, ds->ds_current_size.cx, ds->ds_current_size.cy);
639 /* Do not call while under the GL lock. */
640 void device_clear_render_targets(struct wined3d_device *device, UINT rt_count, const struct wined3d_fb_state *fb,
641 UINT rect_count, const RECT *rects, const RECT *draw_rect, DWORD flags, const struct wined3d_color *color,
642 float depth, DWORD stencil)
644 const RECT *clear_rect = (rect_count > 0 && rects) ? (const RECT *)rects : NULL;
645 struct wined3d_surface *target = rt_count ? fb->render_targets[0] : NULL;
646 UINT drawable_width, drawable_height;
647 struct wined3d_context *context;
648 GLbitfield clear_mask = 0;
649 BOOL render_offscreen;
650 unsigned int i;
651 RECT ds_rect;
653 /* When we're clearing parts of the drawable, make sure that the target surface is well up to date in the
654 * drawable. After the clear we'll mark the drawable up to date, so we have to make sure that this is true
655 * for the cleared parts, and the untouched parts.
657 * If we're clearing the whole target there is no need to copy it into the drawable, it will be overwritten
658 * anyway. If we're not clearing the color buffer we don't have to copy either since we're not going to set
659 * the drawable up to date. We have to check all settings that limit the clear area though. Do not bother
660 * checking all this if the dest surface is in the drawable anyway. */
661 if (flags & WINED3DCLEAR_TARGET && !is_full_clear(target, draw_rect, clear_rect))
663 for (i = 0; i < rt_count; ++i)
665 struct wined3d_surface *rt = fb->render_targets[i];
666 if (rt)
667 surface_load_location(rt, rt->draw_binding, NULL);
671 context = context_acquire(device, target);
672 if (!context->valid)
674 context_release(context);
675 WARN("Invalid context, skipping clear.\n");
676 return;
679 if (target)
681 render_offscreen = context->render_offscreen;
682 target->get_drawable_size(context, &drawable_width, &drawable_height);
684 else
686 render_offscreen = TRUE;
687 drawable_width = fb->depth_stencil->pow2Width;
688 drawable_height = fb->depth_stencil->pow2Height;
691 if (flags & WINED3DCLEAR_ZBUFFER)
693 DWORD location = render_offscreen ? fb->depth_stencil->draw_binding : SFLAG_INDRAWABLE;
695 if (!render_offscreen && fb->depth_stencil != device->onscreen_depth_stencil)
696 device_switch_onscreen_ds(device, context, fb->depth_stencil);
697 prepare_ds_clear(fb->depth_stencil, context, location,
698 draw_rect, rect_count, clear_rect, &ds_rect);
701 if (!context_apply_clear_state(context, device, rt_count, fb))
703 context_release(context);
704 WARN("Failed to apply clear state, skipping clear.\n");
705 return;
708 ENTER_GL();
710 /* Only set the values up once, as they are not changing. */
711 if (flags & WINED3DCLEAR_STENCIL)
713 if (context->gl_info->supported[EXT_STENCIL_TWO_SIDE])
715 glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
716 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_TWOSIDEDSTENCILMODE));
718 glStencilMask(~0U);
719 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILWRITEMASK));
720 glClearStencil(stencil);
721 checkGLcall("glClearStencil");
722 clear_mask = clear_mask | GL_STENCIL_BUFFER_BIT;
725 if (flags & WINED3DCLEAR_ZBUFFER)
727 DWORD location = render_offscreen ? fb->depth_stencil->draw_binding : SFLAG_INDRAWABLE;
729 surface_modify_ds_location(fb->depth_stencil, location, ds_rect.right, ds_rect.bottom);
731 glDepthMask(GL_TRUE);
732 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZWRITEENABLE));
733 glClearDepth(depth);
734 checkGLcall("glClearDepth");
735 clear_mask = clear_mask | GL_DEPTH_BUFFER_BIT;
738 if (flags & WINED3DCLEAR_TARGET)
740 for (i = 0; i < rt_count; ++i)
742 struct wined3d_surface *rt = fb->render_targets[i];
744 if (rt)
745 surface_modify_location(rt, rt->draw_binding, TRUE);
748 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
749 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
750 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
751 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
752 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
753 glClearColor(color->r, color->g, color->b, color->a);
754 checkGLcall("glClearColor");
755 clear_mask = clear_mask | GL_COLOR_BUFFER_BIT;
758 if (!clear_rect)
760 if (render_offscreen)
762 glScissor(draw_rect->left, draw_rect->top,
763 draw_rect->right - draw_rect->left, draw_rect->bottom - draw_rect->top);
765 else
767 glScissor(draw_rect->left, drawable_height - draw_rect->bottom,
768 draw_rect->right - draw_rect->left, draw_rect->bottom - draw_rect->top);
770 checkGLcall("glScissor");
771 glClear(clear_mask);
772 checkGLcall("glClear");
774 else
776 RECT current_rect;
778 /* Now process each rect in turn. */
779 for (i = 0; i < rect_count; ++i)
781 /* Note that GL uses lower left, width/height. */
782 IntersectRect(&current_rect, draw_rect, &clear_rect[i]);
784 TRACE("clear_rect[%u] %s, current_rect %s.\n", i,
785 wine_dbgstr_rect(&clear_rect[i]),
786 wine_dbgstr_rect(&current_rect));
788 /* Tests show that rectangles where x1 > x2 or y1 > y2 are ignored silently.
789 * The rectangle is not cleared, no error is returned, but further rectangles are
790 * still cleared if they are valid. */
791 if (current_rect.left > current_rect.right || current_rect.top > current_rect.bottom)
793 TRACE("Rectangle with negative dimensions, ignoring.\n");
794 continue;
797 if (render_offscreen)
799 glScissor(current_rect.left, current_rect.top,
800 current_rect.right - current_rect.left, current_rect.bottom - current_rect.top);
802 else
804 glScissor(current_rect.left, drawable_height - current_rect.bottom,
805 current_rect.right - current_rect.left, current_rect.bottom - current_rect.top);
807 checkGLcall("glScissor");
809 glClear(clear_mask);
810 checkGLcall("glClear");
814 LEAVE_GL();
816 if (wined3d_settings.strict_draw_ordering || (flags & WINED3DCLEAR_TARGET
817 && target->container.type == WINED3D_CONTAINER_SWAPCHAIN
818 && target->container.u.swapchain->front_buffer == target))
819 wglFlush(); /* Flush to ensure ordering across contexts. */
821 context_release(context);
824 ULONG CDECL wined3d_device_incref(struct wined3d_device *device)
826 ULONG refcount = InterlockedIncrement(&device->ref);
828 TRACE("%p increasing refcount to %u.\n", device, refcount);
830 return refcount;
833 ULONG CDECL wined3d_device_decref(struct wined3d_device *device)
835 ULONG refcount = InterlockedDecrement(&device->ref);
837 TRACE("%p decreasing refcount to %u.\n", device, refcount);
839 if (!refcount)
841 struct wined3d_stateblock *stateblock;
842 UINT i;
844 if (wined3d_stateblock_decref(device->updateStateBlock)
845 && device->updateStateBlock != device->stateBlock)
846 FIXME("Something's still holding the update stateblock.\n");
847 device->updateStateBlock = NULL;
849 stateblock = device->stateBlock;
850 device->stateBlock = NULL;
851 if (wined3d_stateblock_decref(stateblock))
852 FIXME("Something's still holding the stateblock.\n");
854 for (i = 0; i < sizeof(device->multistate_funcs) / sizeof(device->multistate_funcs[0]); ++i)
856 HeapFree(GetProcessHeap(), 0, device->multistate_funcs[i]);
857 device->multistate_funcs[i] = NULL;
860 if (!list_empty(&device->resources))
862 struct wined3d_resource *resource;
864 FIXME("Device released with resources still bound, acceptable but unexpected.\n");
866 LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
868 FIXME("Leftover resource %p with type %s (%#x).\n",
869 resource, debug_d3dresourcetype(resource->type), resource->type);
873 if (device->contexts)
874 ERR("Context array not freed!\n");
875 if (device->hardwareCursor)
876 DestroyCursor(device->hardwareCursor);
877 device->hardwareCursor = 0;
879 wined3d_decref(device->wined3d);
880 device->wined3d = NULL;
881 HeapFree(GetProcessHeap(), 0, device);
882 TRACE("Freed device %p.\n", device);
885 return refcount;
888 UINT CDECL wined3d_device_get_swapchain_count(const struct wined3d_device *device)
890 TRACE("device %p.\n", device);
892 return device->swapchain_count;
895 HRESULT CDECL wined3d_device_get_swapchain(const struct wined3d_device *device,
896 UINT swapchain_idx, struct wined3d_swapchain **swapchain)
898 TRACE("device %p, swapchain_idx %u, swapchain %p.\n",
899 device, swapchain_idx, swapchain);
901 if (swapchain_idx >= device->swapchain_count)
903 WARN("swapchain_idx %u >= swapchain_count %u.\n",
904 swapchain_idx, device->swapchain_count);
905 *swapchain = NULL;
907 return WINED3DERR_INVALIDCALL;
910 *swapchain = device->swapchains[swapchain_idx];
911 wined3d_swapchain_incref(*swapchain);
912 TRACE("Returning %p.\n", *swapchain);
914 return WINED3D_OK;
917 static void device_load_logo(struct wined3d_device *device, const char *filename)
919 struct wined3d_color_key color_key;
920 HBITMAP hbm;
921 BITMAP bm;
922 HRESULT hr;
923 HDC dcb = NULL, dcs = NULL;
925 hbm = LoadImageA(NULL, filename, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
926 if(hbm)
928 GetObjectA(hbm, sizeof(BITMAP), &bm);
929 dcb = CreateCompatibleDC(NULL);
930 if(!dcb) goto out;
931 SelectObject(dcb, hbm);
933 else
935 /* Create a 32x32 white surface to indicate that wined3d is used, but the specified image
936 * couldn't be loaded
938 memset(&bm, 0, sizeof(bm));
939 bm.bmWidth = 32;
940 bm.bmHeight = 32;
943 hr = wined3d_surface_create(device, bm.bmWidth, bm.bmHeight, WINED3DFMT_B5G6R5_UNORM, 0, 0,
944 WINED3D_POOL_DEFAULT, WINED3D_MULTISAMPLE_NONE, 0, WINED3D_SURFACE_TYPE_OPENGL, WINED3D_SURFACE_MAPPABLE,
945 NULL, &wined3d_null_parent_ops, &device->logo_surface);
946 if (FAILED(hr))
948 ERR("Wine logo requested, but failed to create surface, hr %#x.\n", hr);
949 goto out;
952 if (dcb)
954 if (FAILED(hr = wined3d_surface_getdc(device->logo_surface, &dcs)))
955 goto out;
956 BitBlt(dcs, 0, 0, bm.bmWidth, bm.bmHeight, dcb, 0, 0, SRCCOPY);
957 wined3d_surface_releasedc(device->logo_surface, dcs);
959 color_key.color_space_low_value = 0;
960 color_key.color_space_high_value = 0;
961 wined3d_surface_set_color_key(device->logo_surface, WINEDDCKEY_SRCBLT, &color_key);
963 else
965 const struct wined3d_color c = {1.0f, 1.0f, 1.0f, 1.0f};
966 /* Fill the surface with a white color to show that wined3d is there */
967 wined3d_device_color_fill(device, device->logo_surface, NULL, &c);
970 out:
971 if (dcb) DeleteDC(dcb);
972 if (hbm) DeleteObject(hbm);
975 /* Context activation is done by the caller. */
976 static void create_dummy_textures(struct wined3d_device *device, struct wined3d_context *context)
978 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
979 unsigned int i, j, count;
980 /* Under DirectX you can sample even if no texture is bound, whereas
981 * OpenGL will only allow that when a valid texture is bound.
982 * We emulate this by creating dummy textures and binding them
983 * to each texture stage when the currently set D3D texture is NULL. */
984 ENTER_GL();
986 if (gl_info->supported[APPLE_CLIENT_STORAGE])
988 /* The dummy texture does not have client storage backing */
989 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
990 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
993 count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
994 for (i = 0; i < count; ++i)
996 DWORD color = 0x000000ff;
998 /* Make appropriate texture active */
999 context_active_texture(context, gl_info, i);
1001 glGenTextures(1, &device->dummy_texture_2d[i]);
1002 checkGLcall("glGenTextures");
1003 TRACE("Dummy 2D texture %u given name %u.\n", i, device->dummy_texture_2d[i]);
1005 glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1006 checkGLcall("glBindTexture");
1008 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1009 checkGLcall("glTexImage2D");
1011 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1013 glGenTextures(1, &device->dummy_texture_rect[i]);
1014 checkGLcall("glGenTextures");
1015 TRACE("Dummy rectangle texture %u given name %u.\n", i, device->dummy_texture_rect[i]);
1017 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1018 checkGLcall("glBindTexture");
1020 glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1021 checkGLcall("glTexImage2D");
1024 if (gl_info->supported[EXT_TEXTURE3D])
1026 glGenTextures(1, &device->dummy_texture_3d[i]);
1027 checkGLcall("glGenTextures");
1028 TRACE("Dummy 3D texture %u given name %u.\n", i, device->dummy_texture_3d[i]);
1030 glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1031 checkGLcall("glBindTexture");
1033 GL_EXTCALL(glTexImage3DEXT(GL_TEXTURE_3D, 0, GL_RGBA8, 1, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color));
1034 checkGLcall("glTexImage3D");
1037 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1039 glGenTextures(1, &device->dummy_texture_cube[i]);
1040 checkGLcall("glGenTextures");
1041 TRACE("Dummy cube texture %u given name %u.\n", i, device->dummy_texture_cube[i]);
1043 glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1044 checkGLcall("glBindTexture");
1046 for (j = GL_TEXTURE_CUBE_MAP_POSITIVE_X; j <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; ++j)
1048 glTexImage2D(j, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1049 checkGLcall("glTexImage2D");
1054 if (gl_info->supported[APPLE_CLIENT_STORAGE])
1056 /* Reenable because if supported it is enabled by default */
1057 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1058 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1061 LEAVE_GL();
1064 /* Context activation is done by the caller. */
1065 static void destroy_dummy_textures(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
1067 unsigned int count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1069 ENTER_GL();
1070 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1072 glDeleteTextures(count, device->dummy_texture_cube);
1073 checkGLcall("glDeleteTextures(count, device->dummy_texture_cube)");
1076 if (gl_info->supported[EXT_TEXTURE3D])
1078 glDeleteTextures(count, device->dummy_texture_3d);
1079 checkGLcall("glDeleteTextures(count, device->dummy_texture_3d)");
1082 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1084 glDeleteTextures(count, device->dummy_texture_rect);
1085 checkGLcall("glDeleteTextures(count, device->dummy_texture_rect)");
1088 glDeleteTextures(count, device->dummy_texture_2d);
1089 checkGLcall("glDeleteTextures(count, device->dummy_texture_2d)");
1090 LEAVE_GL();
1092 memset(device->dummy_texture_cube, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_cube));
1093 memset(device->dummy_texture_3d, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_3d));
1094 memset(device->dummy_texture_rect, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_rect));
1095 memset(device->dummy_texture_2d, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_2d));
1098 static LONG fullscreen_style(LONG style)
1100 /* Make sure the window is managed, otherwise we won't get keyboard input. */
1101 style |= WS_POPUP | WS_SYSMENU;
1102 style &= ~(WS_CAPTION | WS_THICKFRAME);
1104 return style;
1107 static LONG fullscreen_exstyle(LONG exstyle)
1109 /* Filter out window decorations. */
1110 exstyle &= ~(WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);
1112 return exstyle;
1115 void CDECL wined3d_device_setup_fullscreen_window(struct wined3d_device *device, HWND window, UINT w, UINT h)
1117 BOOL filter_messages;
1118 LONG style, exstyle;
1120 TRACE("Setting up window %p for fullscreen mode.\n", window);
1122 if (device->style || device->exStyle)
1124 ERR("Changing the window style for window %p, but another style (%08x, %08x) is already stored.\n",
1125 window, device->style, device->exStyle);
1128 device->style = GetWindowLongW(window, GWL_STYLE);
1129 device->exStyle = GetWindowLongW(window, GWL_EXSTYLE);
1131 style = fullscreen_style(device->style);
1132 exstyle = fullscreen_exstyle(device->exStyle);
1134 TRACE("Old style was %08x, %08x, setting to %08x, %08x.\n",
1135 device->style, device->exStyle, style, exstyle);
1137 filter_messages = device->filter_messages;
1138 device->filter_messages = TRUE;
1140 SetWindowLongW(window, GWL_STYLE, style);
1141 SetWindowLongW(window, GWL_EXSTYLE, exstyle);
1142 SetWindowPos(window, HWND_TOP, 0, 0, w, h, SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOACTIVATE);
1144 device->filter_messages = filter_messages;
1147 void CDECL wined3d_device_restore_fullscreen_window(struct wined3d_device *device, HWND window)
1149 BOOL filter_messages;
1150 LONG style, exstyle;
1152 if (!device->style && !device->exStyle) return;
1154 TRACE("Restoring window style of window %p to %08x, %08x.\n",
1155 window, device->style, device->exStyle);
1157 style = GetWindowLongW(window, GWL_STYLE);
1158 exstyle = GetWindowLongW(window, GWL_EXSTYLE);
1160 filter_messages = device->filter_messages;
1161 device->filter_messages = TRUE;
1163 /* Only restore the style if the application didn't modify it during the
1164 * fullscreen phase. Some applications change it before calling Reset()
1165 * when switching between windowed and fullscreen modes (HL2), some
1166 * depend on the original style (Eve Online). */
1167 if (style == fullscreen_style(device->style) && exstyle == fullscreen_exstyle(device->exStyle))
1169 SetWindowLongW(window, GWL_STYLE, device->style);
1170 SetWindowLongW(window, GWL_EXSTYLE, device->exStyle);
1172 SetWindowPos(window, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
1174 device->filter_messages = filter_messages;
1176 /* Delete the old values. */
1177 device->style = 0;
1178 device->exStyle = 0;
1181 HRESULT CDECL wined3d_device_acquire_focus_window(struct wined3d_device *device, HWND window)
1183 TRACE("device %p, window %p.\n", device, window);
1185 if (!wined3d_register_window(window, device))
1187 ERR("Failed to register window %p.\n", window);
1188 return E_FAIL;
1191 InterlockedExchangePointer((void **)&device->focus_window, window);
1192 SetWindowPos(window, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
1194 return WINED3D_OK;
1197 void CDECL wined3d_device_release_focus_window(struct wined3d_device *device)
1199 TRACE("device %p.\n", device);
1201 if (device->focus_window) wined3d_unregister_window(device->focus_window);
1202 InterlockedExchangePointer((void **)&device->focus_window, NULL);
1205 HRESULT CDECL wined3d_device_init_3d(struct wined3d_device *device,
1206 struct wined3d_swapchain_desc *swapchain_desc)
1208 static const struct wined3d_color black = {0.0f, 0.0f, 0.0f, 0.0f};
1209 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1210 struct wined3d_swapchain *swapchain = NULL;
1211 struct wined3d_context *context;
1212 HRESULT hr;
1213 DWORD state;
1214 unsigned int i;
1216 TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
1218 if (device->d3d_initialized)
1219 return WINED3DERR_INVALIDCALL;
1220 if (!device->adapter->opengl)
1221 return WINED3DERR_INVALIDCALL;
1223 device->valid_rt_mask = 0;
1224 for (i = 0; i < gl_info->limits.buffers; ++i)
1225 device->valid_rt_mask |= (1 << i);
1226 device->fb.render_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1227 sizeof(*device->fb.render_targets) * gl_info->limits.buffers);
1229 /* Initialize the texture unit mapping to a 1:1 mapping */
1230 for (state = 0; state < MAX_COMBINED_SAMPLERS; ++state)
1232 if (state < gl_info->limits.fragment_samplers)
1234 device->texUnitMap[state] = state;
1235 device->rev_tex_unit_map[state] = state;
1237 else
1239 device->texUnitMap[state] = WINED3D_UNMAPPED_STAGE;
1240 device->rev_tex_unit_map[state] = WINED3D_UNMAPPED_STAGE;
1244 /* Setup the implicit swapchain. This also initializes a context. */
1245 TRACE("Creating implicit swapchain\n");
1246 hr = device->device_parent->ops->create_swapchain(device->device_parent,
1247 swapchain_desc, &swapchain);
1248 if (FAILED(hr))
1250 WARN("Failed to create implicit swapchain\n");
1251 goto err_out;
1254 device->swapchain_count = 1;
1255 device->swapchains = HeapAlloc(GetProcessHeap(), 0, device->swapchain_count * sizeof(*device->swapchains));
1256 if (!device->swapchains)
1258 ERR("Out of memory!\n");
1259 goto err_out;
1261 device->swapchains[0] = swapchain;
1263 if (swapchain->back_buffers && swapchain->back_buffers[0])
1265 TRACE("Setting rendertarget to %p.\n", swapchain->back_buffers);
1266 device->fb.render_targets[0] = swapchain->back_buffers[0];
1268 else
1270 TRACE("Setting rendertarget to %p.\n", swapchain->front_buffer);
1271 device->fb.render_targets[0] = swapchain->front_buffer;
1273 wined3d_surface_incref(device->fb.render_targets[0]);
1275 /* Depth Stencil support */
1276 device->fb.depth_stencil = device->auto_depth_stencil;
1277 if (device->fb.depth_stencil)
1278 wined3d_surface_incref(device->fb.depth_stencil);
1280 hr = device->shader_backend->shader_alloc_private(device);
1281 if (FAILED(hr))
1283 TRACE("Shader private data couldn't be allocated\n");
1284 goto err_out;
1286 hr = device->frag_pipe->alloc_private(device);
1287 if (FAILED(hr))
1289 TRACE("Fragment pipeline private data couldn't be allocated\n");
1290 goto err_out;
1292 hr = device->blitter->alloc_private(device);
1293 if (FAILED(hr))
1295 TRACE("Blitter private data couldn't be allocated\n");
1296 goto err_out;
1299 /* Set up some starting GL setup */
1301 /* Setup all the devices defaults */
1302 stateblock_init_default_state(device->stateBlock);
1304 context = context_acquire(device, swapchain->front_buffer);
1306 create_dummy_textures(device, context);
1308 ENTER_GL();
1310 /* Initialize the current view state */
1311 device->view_ident = 1;
1312 device->contexts[0]->last_was_rhw = 0;
1314 switch (wined3d_settings.offscreen_rendering_mode)
1316 case ORM_FBO:
1317 device->offscreenBuffer = GL_COLOR_ATTACHMENT0;
1318 break;
1320 case ORM_BACKBUFFER:
1322 if (context_get_current()->aux_buffers > 0)
1324 TRACE("Using auxiliary buffer for offscreen rendering\n");
1325 device->offscreenBuffer = GL_AUX0;
1327 else
1329 TRACE("Using back buffer for offscreen rendering\n");
1330 device->offscreenBuffer = GL_BACK;
1335 TRACE("All defaults now set up, leaving 3D init.\n");
1336 LEAVE_GL();
1338 context_release(context);
1340 /* Clear the screen */
1341 wined3d_device_clear(device, 0, NULL, WINED3DCLEAR_TARGET
1342 | (swapchain_desc->enable_auto_depth_stencil ? WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL : 0),
1343 &black, 1.0f, 0);
1345 device->d3d_initialized = TRUE;
1347 if (wined3d_settings.logo)
1348 device_load_logo(device, wined3d_settings.logo);
1349 return WINED3D_OK;
1351 err_out:
1352 HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1353 HeapFree(GetProcessHeap(), 0, device->swapchains);
1354 device->swapchain_count = 0;
1355 if (swapchain)
1356 wined3d_swapchain_decref(swapchain);
1357 if (device->blit_priv)
1358 device->blitter->free_private(device);
1359 if (device->fragment_priv)
1360 device->frag_pipe->free_private(device);
1361 if (device->shader_priv)
1362 device->shader_backend->shader_free_private(device);
1364 return hr;
1367 HRESULT CDECL wined3d_device_init_gdi(struct wined3d_device *device,
1368 struct wined3d_swapchain_desc *swapchain_desc)
1370 struct wined3d_swapchain *swapchain = NULL;
1371 HRESULT hr;
1373 TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
1375 /* Setup the implicit swapchain */
1376 TRACE("Creating implicit swapchain\n");
1377 hr = device->device_parent->ops->create_swapchain(device->device_parent,
1378 swapchain_desc, &swapchain);
1379 if (FAILED(hr))
1381 WARN("Failed to create implicit swapchain\n");
1382 goto err_out;
1385 device->swapchain_count = 1;
1386 device->swapchains = HeapAlloc(GetProcessHeap(), 0, device->swapchain_count * sizeof(*device->swapchains));
1387 if (!device->swapchains)
1389 ERR("Out of memory!\n");
1390 goto err_out;
1392 device->swapchains[0] = swapchain;
1393 return WINED3D_OK;
1395 err_out:
1396 wined3d_swapchain_decref(swapchain);
1397 return hr;
1400 HRESULT CDECL wined3d_device_uninit_3d(struct wined3d_device *device)
1402 struct wined3d_resource *resource, *cursor;
1403 const struct wined3d_gl_info *gl_info;
1404 struct wined3d_context *context;
1405 struct wined3d_surface *surface;
1406 UINT i;
1408 TRACE("device %p.\n", device);
1410 if (!device->d3d_initialized)
1411 return WINED3DERR_INVALIDCALL;
1413 /* Force making the context current again, to verify it is still valid
1414 * (workaround for broken drivers) */
1415 context_set_current(NULL);
1416 /* I don't think that the interface guarantees that the device is destroyed from the same thread
1417 * it was created. Thus make sure a context is active for the glDelete* calls
1419 context = context_acquire(device, NULL);
1420 gl_info = context->gl_info;
1422 if (device->logo_surface)
1423 wined3d_surface_decref(device->logo_surface);
1425 stateblock_unbind_resources(device->stateBlock);
1427 /* Unload resources */
1428 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
1430 TRACE("Unloading resource %p.\n", resource);
1432 resource->resource_ops->resource_unload(resource);
1435 TRACE("Deleting high order patches\n");
1436 for (i = 0; i < PATCHMAP_SIZE; ++i)
1438 struct wined3d_rect_patch *patch;
1439 struct list *e1, *e2;
1441 LIST_FOR_EACH_SAFE(e1, e2, &device->patches[i])
1443 patch = LIST_ENTRY(e1, struct wined3d_rect_patch, entry);
1444 wined3d_device_delete_patch(device, patch->Handle);
1448 /* Delete the mouse cursor texture */
1449 if (device->cursorTexture)
1451 ENTER_GL();
1452 glDeleteTextures(1, &device->cursorTexture);
1453 LEAVE_GL();
1454 device->cursorTexture = 0;
1457 /* Destroy the depth blt resources, they will be invalid after the reset. Also free shader
1458 * private data, it might contain opengl pointers
1460 if (device->depth_blt_texture)
1462 ENTER_GL();
1463 glDeleteTextures(1, &device->depth_blt_texture);
1464 LEAVE_GL();
1465 device->depth_blt_texture = 0;
1468 /* Destroy the shader backend. Note that this has to happen after all shaders are destroyed. */
1469 device->blitter->free_private(device);
1470 device->frag_pipe->free_private(device);
1471 device->shader_backend->shader_free_private(device);
1473 /* Release the buffers (with sanity checks)*/
1474 if (device->onscreen_depth_stencil)
1476 surface = device->onscreen_depth_stencil;
1477 device->onscreen_depth_stencil = NULL;
1478 wined3d_surface_decref(surface);
1481 if (device->fb.depth_stencil)
1483 surface = device->fb.depth_stencil;
1485 TRACE("Releasing depth/stencil buffer %p.\n", surface);
1487 device->fb.depth_stencil = NULL;
1488 wined3d_surface_decref(surface);
1491 if (device->auto_depth_stencil)
1493 surface = device->auto_depth_stencil;
1494 device->auto_depth_stencil = NULL;
1495 if (wined3d_surface_decref(surface))
1496 FIXME("Something's still holding the auto depth stencil buffer (%p).\n", surface);
1499 for (i = 1; i < gl_info->limits.buffers; ++i)
1501 wined3d_device_set_render_target(device, i, NULL, FALSE);
1504 surface = device->fb.render_targets[0];
1505 TRACE("Setting rendertarget 0 to NULL\n");
1506 device->fb.render_targets[0] = NULL;
1507 TRACE("Releasing the render target at %p\n", surface);
1508 wined3d_surface_decref(surface);
1510 context_release(context);
1512 for (i = 0; i < device->swapchain_count; ++i)
1514 TRACE("Releasing the implicit swapchain %u.\n", i);
1515 if (wined3d_swapchain_decref(device->swapchains[i]))
1516 FIXME("Something's still holding the implicit swapchain.\n");
1519 HeapFree(GetProcessHeap(), 0, device->swapchains);
1520 device->swapchains = NULL;
1521 device->swapchain_count = 0;
1523 HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1524 device->fb.render_targets = NULL;
1526 device->d3d_initialized = FALSE;
1528 return WINED3D_OK;
1531 HRESULT CDECL wined3d_device_uninit_gdi(struct wined3d_device *device)
1533 unsigned int i;
1535 for (i = 0; i < device->swapchain_count; ++i)
1537 TRACE("Releasing the implicit swapchain %u.\n", i);
1538 if (wined3d_swapchain_decref(device->swapchains[i]))
1539 FIXME("Something's still holding the implicit swapchain.\n");
1542 HeapFree(GetProcessHeap(), 0, device->swapchains);
1543 device->swapchains = NULL;
1544 device->swapchain_count = 0;
1545 return WINED3D_OK;
1548 /* Enables thread safety in the wined3d device and its resources. Called by DirectDraw
1549 * from SetCooperativeLevel if DDSCL_MULTITHREADED is specified, and by d3d8/9 from
1550 * CreateDevice if D3DCREATE_MULTITHREADED is passed.
1552 * There is no way to deactivate thread safety once it is enabled.
1554 void CDECL wined3d_device_set_multithreaded(struct wined3d_device *device)
1556 TRACE("device %p.\n", device);
1558 /* For now just store the flag (needed in case of ddraw). */
1559 device->create_parms.flags |= WINED3DCREATE_MULTITHREADED;
1562 HRESULT CDECL wined3d_device_set_display_mode(struct wined3d_device *device,
1563 UINT swapchain_idx, const struct wined3d_display_mode *mode)
1565 struct wined3d_adapter *adapter = device->adapter;
1566 const struct wined3d_format *format = wined3d_get_format(&adapter->gl_info, mode->format_id);
1567 DEVMODEW devmode;
1568 LONG ret;
1569 RECT clip_rc;
1571 TRACE("device %p, swapchain_idx %u, mode %p (%ux%u@%u %s).\n", device, swapchain_idx, mode,
1572 mode->width, mode->height, mode->refresh_rate, debug_d3dformat(mode->format_id));
1574 /* Resize the screen even without a window:
1575 * The app could have unset it with SetCooperativeLevel, but not called
1576 * RestoreDisplayMode first. Then the release will call RestoreDisplayMode,
1577 * but we don't have any hwnd
1580 memset(&devmode, 0, sizeof(devmode));
1581 devmode.dmSize = sizeof(devmode);
1582 devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1583 devmode.dmBitsPerPel = format->byte_count * CHAR_BIT;
1584 devmode.dmPelsWidth = mode->width;
1585 devmode.dmPelsHeight = mode->height;
1587 devmode.dmDisplayFrequency = mode->refresh_rate;
1588 if (mode->refresh_rate)
1589 devmode.dmFields |= DM_DISPLAYFREQUENCY;
1591 /* Only change the mode if necessary */
1592 if (adapter->screen_size.cx == mode->width && adapter->screen_size.cy == mode->height
1593 && adapter->screen_format == mode->format_id && !mode->refresh_rate)
1594 return WINED3D_OK;
1596 ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL);
1597 if (ret != DISP_CHANGE_SUCCESSFUL)
1599 if (devmode.dmDisplayFrequency)
1601 WARN("ChangeDisplaySettingsExW failed, trying without the refresh rate\n");
1602 devmode.dmFields &= ~DM_DISPLAYFREQUENCY;
1603 devmode.dmDisplayFrequency = 0;
1604 ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL) != DISP_CHANGE_SUCCESSFUL;
1606 if(ret != DISP_CHANGE_SUCCESSFUL) {
1607 return WINED3DERR_NOTAVAILABLE;
1611 /* Store the new values */
1612 adapter->screen_size.cx = mode->width;
1613 adapter->screen_size.cy = mode->height;
1614 adapter->screen_format = mode->format_id;
1616 /* And finally clip mouse to our screen */
1617 SetRect(&clip_rc, 0, 0, mode->width, mode->height);
1618 ClipCursor(&clip_rc);
1620 return WINED3D_OK;
1623 HRESULT CDECL wined3d_device_get_wined3d(const struct wined3d_device *device, struct wined3d **wined3d)
1625 TRACE("device %p, wined3d %p.\n", device, wined3d);
1627 *wined3d = device->wined3d;
1628 wined3d_incref(*wined3d);
1630 TRACE("Returning %p.\n", *wined3d);
1632 return WINED3D_OK;
1635 UINT CDECL wined3d_device_get_available_texture_mem(const struct wined3d_device *device)
1637 TRACE("device %p.\n", device);
1639 TRACE("Emulating %d MB, returning %d MB left.\n",
1640 device->adapter->TextureRam / (1024 * 1024),
1641 (device->adapter->TextureRam - device->adapter->UsedTextureRam) / (1024 * 1024));
1643 return device->adapter->TextureRam - device->adapter->UsedTextureRam;
1646 HRESULT CDECL wined3d_device_set_stream_source(struct wined3d_device *device, UINT stream_idx,
1647 struct wined3d_buffer *buffer, UINT offset, UINT stride)
1649 struct wined3d_stream_state *stream;
1650 struct wined3d_buffer *prev_buffer;
1652 TRACE("device %p, stream_idx %u, buffer %p, offset %u, stride %u.\n",
1653 device, stream_idx, buffer, offset, stride);
1655 if (stream_idx >= MAX_STREAMS)
1657 WARN("Stream index %u out of range.\n", stream_idx);
1658 return WINED3DERR_INVALIDCALL;
1660 else if (offset & 0x3)
1662 WARN("Offset %u is not 4 byte aligned.\n", offset);
1663 return WINED3DERR_INVALIDCALL;
1666 stream = &device->updateStateBlock->state.streams[stream_idx];
1667 prev_buffer = stream->buffer;
1669 device->updateStateBlock->changed.streamSource |= 1 << stream_idx;
1671 if (prev_buffer == buffer
1672 && stream->stride == stride
1673 && stream->offset == offset)
1675 TRACE("Application is setting the old values over, nothing to do.\n");
1676 return WINED3D_OK;
1679 stream->buffer = buffer;
1680 if (buffer)
1682 stream->stride = stride;
1683 stream->offset = offset;
1686 /* Handle recording of state blocks. */
1687 if (device->isRecordingState)
1689 TRACE("Recording... not performing anything.\n");
1690 if (buffer)
1691 wined3d_buffer_incref(buffer);
1692 if (prev_buffer)
1693 wined3d_buffer_decref(prev_buffer);
1694 return WINED3D_OK;
1697 if (buffer)
1699 InterlockedIncrement(&buffer->bind_count);
1700 wined3d_buffer_incref(buffer);
1702 if (prev_buffer)
1704 InterlockedDecrement(&prev_buffer->bind_count);
1705 wined3d_buffer_decref(prev_buffer);
1708 device_invalidate_state(device, STATE_STREAMSRC);
1710 return WINED3D_OK;
1713 HRESULT CDECL wined3d_device_get_stream_source(const struct wined3d_device *device,
1714 UINT stream_idx, struct wined3d_buffer **buffer, UINT *offset, UINT *stride)
1716 struct wined3d_stream_state *stream;
1718 TRACE("device %p, stream_idx %u, buffer %p, offset %p, stride %p.\n",
1719 device, stream_idx, buffer, offset, stride);
1721 if (stream_idx >= MAX_STREAMS)
1723 WARN("Stream index %u out of range.\n", stream_idx);
1724 return WINED3DERR_INVALIDCALL;
1727 stream = &device->stateBlock->state.streams[stream_idx];
1728 *buffer = stream->buffer;
1729 if (*buffer)
1730 wined3d_buffer_incref(*buffer);
1731 if (offset)
1732 *offset = stream->offset;
1733 *stride = stream->stride;
1735 return WINED3D_OK;
1738 HRESULT CDECL wined3d_device_set_stream_source_freq(struct wined3d_device *device, UINT stream_idx, UINT divider)
1740 struct wined3d_stream_state *stream;
1741 UINT old_flags, old_freq;
1743 TRACE("device %p, stream_idx %u, divider %#x.\n", device, stream_idx, divider);
1745 /* Verify input. At least in d3d9 this is invalid. */
1746 if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && (divider & WINED3DSTREAMSOURCE_INDEXEDDATA))
1748 WARN("INSTANCEDATA and INDEXEDDATA were set, returning D3DERR_INVALIDCALL.\n");
1749 return WINED3DERR_INVALIDCALL;
1751 if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && !stream_idx)
1753 WARN("INSTANCEDATA used on stream 0, returning D3DERR_INVALIDCALL.\n");
1754 return WINED3DERR_INVALIDCALL;
1756 if (!divider)
1758 WARN("Divider is 0, returning D3DERR_INVALIDCALL.\n");
1759 return WINED3DERR_INVALIDCALL;
1762 stream = &device->updateStateBlock->state.streams[stream_idx];
1763 old_flags = stream->flags;
1764 old_freq = stream->frequency;
1766 stream->flags = divider & (WINED3DSTREAMSOURCE_INSTANCEDATA | WINED3DSTREAMSOURCE_INDEXEDDATA);
1767 stream->frequency = divider & 0x7fffff;
1769 device->updateStateBlock->changed.streamFreq |= 1 << stream_idx;
1771 if (stream->frequency != old_freq || stream->flags != old_flags)
1772 device_invalidate_state(device, STATE_STREAMSRC);
1774 return WINED3D_OK;
1777 HRESULT CDECL wined3d_device_get_stream_source_freq(const struct wined3d_device *device,
1778 UINT stream_idx, UINT *divider)
1780 struct wined3d_stream_state *stream;
1782 TRACE("device %p, stream_idx %u, divider %p.\n", device, stream_idx, divider);
1784 stream = &device->updateStateBlock->state.streams[stream_idx];
1785 *divider = stream->flags | stream->frequency;
1787 TRACE("Returning %#x.\n", *divider);
1789 return WINED3D_OK;
1792 HRESULT CDECL wined3d_device_set_transform(struct wined3d_device *device,
1793 enum wined3d_transform_state d3dts, const struct wined3d_matrix *matrix)
1795 TRACE("device %p, state %s, matrix %p.\n",
1796 device, debug_d3dtstype(d3dts), matrix);
1798 /* Handle recording of state blocks. */
1799 if (device->isRecordingState)
1801 TRACE("Recording... not performing anything.\n");
1802 device->updateStateBlock->changed.transform[d3dts >> 5] |= 1 << (d3dts & 0x1f);
1803 device->updateStateBlock->state.transforms[d3dts] = *matrix;
1804 return WINED3D_OK;
1807 /* If the new matrix is the same as the current one,
1808 * we cut off any further processing. this seems to be a reasonable
1809 * optimization because as was noticed, some apps (warcraft3 for example)
1810 * tend towards setting the same matrix repeatedly for some reason.
1812 * From here on we assume that the new matrix is different, wherever it matters. */
1813 if (!memcmp(&device->stateBlock->state.transforms[d3dts].u.m[0][0], matrix, sizeof(*matrix)))
1815 TRACE("The application is setting the same matrix over again.\n");
1816 return WINED3D_OK;
1819 conv_mat(matrix, &device->stateBlock->state.transforms[d3dts].u.m[0][0]);
1821 /* ScreenCoord = ProjectionMat * ViewMat * WorldMat * ObjectCoord
1822 * where ViewMat = Camera space, WorldMat = world space.
1824 * In OpenGL, camera and world space is combined into GL_MODELVIEW
1825 * matrix. The Projection matrix stay projection matrix. */
1827 if (d3dts == WINED3D_TS_VIEW)
1828 device->view_ident = !memcmp(matrix, identity, 16 * sizeof(float));
1830 if (d3dts < WINED3D_TS_WORLD_MATRIX(device->adapter->gl_info.limits.blends))
1831 device_invalidate_state(device, STATE_TRANSFORM(d3dts));
1833 return WINED3D_OK;
1837 HRESULT CDECL wined3d_device_get_transform(const struct wined3d_device *device,
1838 enum wined3d_transform_state state, struct wined3d_matrix *matrix)
1840 TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1842 *matrix = device->stateBlock->state.transforms[state];
1844 return WINED3D_OK;
1847 HRESULT CDECL wined3d_device_multiply_transform(struct wined3d_device *device,
1848 enum wined3d_transform_state state, const struct wined3d_matrix *matrix)
1850 const struct wined3d_matrix *mat = NULL;
1851 struct wined3d_matrix temp;
1853 TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1855 /* Note: Using 'updateStateBlock' rather than 'stateblock' in the code
1856 * below means it will be recorded in a state block change, but it
1857 * works regardless where it is recorded.
1858 * If this is found to be wrong, change to StateBlock. */
1859 if (state > HIGHEST_TRANSFORMSTATE)
1861 WARN("Unhandled transform state %#x.\n", state);
1862 return WINED3D_OK;
1865 mat = &device->updateStateBlock->state.transforms[state];
1866 multiply_matrix(&temp, mat, matrix);
1868 /* Apply change via set transform - will reapply to eg. lights this way. */
1869 return wined3d_device_set_transform(device, state, &temp);
1872 /* Note lights are real special cases. Although the device caps state only
1873 * e.g. 8 are supported, you can reference any indexes you want as long as
1874 * that number max are enabled at any one point in time. Therefore since the
1875 * indices can be anything, we need a hashmap of them. However, this causes
1876 * stateblock problems. When capturing the state block, I duplicate the
1877 * hashmap, but when recording, just build a chain pretty much of commands to
1878 * be replayed. */
1879 HRESULT CDECL wined3d_device_set_light(struct wined3d_device *device,
1880 UINT light_idx, const struct wined3d_light *light)
1882 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
1883 struct wined3d_light_info *object = NULL;
1884 struct list *e;
1885 float rho;
1887 TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
1889 /* Check the parameter range. Need for speed most wanted sets junk lights
1890 * which confuse the GL driver. */
1891 if (!light)
1892 return WINED3DERR_INVALIDCALL;
1894 switch (light->type)
1896 case WINED3D_LIGHT_POINT:
1897 case WINED3D_LIGHT_SPOT:
1898 case WINED3D_LIGHT_PARALLELPOINT:
1899 case WINED3D_LIGHT_GLSPOT:
1900 /* Incorrect attenuation values can cause the gl driver to crash.
1901 * Happens with Need for speed most wanted. */
1902 if (light->attenuation0 < 0.0f || light->attenuation1 < 0.0f || light->attenuation2 < 0.0f)
1904 WARN("Attenuation is negative, returning WINED3DERR_INVALIDCALL.\n");
1905 return WINED3DERR_INVALIDCALL;
1907 break;
1909 case WINED3D_LIGHT_DIRECTIONAL:
1910 /* Ignores attenuation */
1911 break;
1913 default:
1914 WARN("Light type out of range, returning WINED3DERR_INVALIDCALL\n");
1915 return WINED3DERR_INVALIDCALL;
1918 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
1920 object = LIST_ENTRY(e, struct wined3d_light_info, entry);
1921 if (object->OriginalIndex == light_idx)
1922 break;
1923 object = NULL;
1926 if (!object)
1928 TRACE("Adding new light\n");
1929 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1930 if (!object)
1932 ERR("Out of memory error when allocating a light\n");
1933 return E_OUTOFMEMORY;
1935 list_add_head(&device->updateStateBlock->state.light_map[hash_idx], &object->entry);
1936 object->glIndex = -1;
1937 object->OriginalIndex = light_idx;
1940 /* Initialize the object. */
1941 TRACE("Light %d setting to type %d, Diffuse(%f,%f,%f,%f), Specular(%f,%f,%f,%f), Ambient(%f,%f,%f,%f)\n",
1942 light_idx, light->type,
1943 light->diffuse.r, light->diffuse.g, light->diffuse.b, light->diffuse.a,
1944 light->specular.r, light->specular.g, light->specular.b, light->specular.a,
1945 light->ambient.r, light->ambient.g, light->ambient.b, light->ambient.a);
1946 TRACE("... Pos(%f,%f,%f), Dir(%f,%f,%f)\n", light->position.x, light->position.y, light->position.z,
1947 light->direction.x, light->direction.y, light->direction.z);
1948 TRACE("... Range(%f), Falloff(%f), Theta(%f), Phi(%f)\n",
1949 light->range, light->falloff, light->theta, light->phi);
1951 /* Save away the information. */
1952 object->OriginalParms = *light;
1954 switch (light->type)
1956 case WINED3D_LIGHT_POINT:
1957 /* Position */
1958 object->lightPosn[0] = light->position.x;
1959 object->lightPosn[1] = light->position.y;
1960 object->lightPosn[2] = light->position.z;
1961 object->lightPosn[3] = 1.0f;
1962 object->cutoff = 180.0f;
1963 /* FIXME: Range */
1964 break;
1966 case WINED3D_LIGHT_DIRECTIONAL:
1967 /* Direction */
1968 object->lightPosn[0] = -light->direction.x;
1969 object->lightPosn[1] = -light->direction.y;
1970 object->lightPosn[2] = -light->direction.z;
1971 object->lightPosn[3] = 0.0f;
1972 object->exponent = 0.0f;
1973 object->cutoff = 180.0f;
1974 break;
1976 case WINED3D_LIGHT_SPOT:
1977 /* Position */
1978 object->lightPosn[0] = light->position.x;
1979 object->lightPosn[1] = light->position.y;
1980 object->lightPosn[2] = light->position.z;
1981 object->lightPosn[3] = 1.0f;
1983 /* Direction */
1984 object->lightDirn[0] = light->direction.x;
1985 object->lightDirn[1] = light->direction.y;
1986 object->lightDirn[2] = light->direction.z;
1987 object->lightDirn[3] = 1.0f;
1989 /* opengl-ish and d3d-ish spot lights use too different models
1990 * for the light "intensity" as a function of the angle towards
1991 * the main light direction, so we only can approximate very
1992 * roughly. However, spot lights are rather rarely used in games
1993 * (if ever used at all). Furthermore if still used, probably
1994 * nobody pays attention to such details. */
1995 if (!light->falloff)
1997 /* Falloff = 0 is easy, because d3d's and opengl's spot light
1998 * equations have the falloff resp. exponent parameter as an
1999 * exponent, so the spot light lighting will always be 1.0 for
2000 * both of them, and we don't have to care for the rest of the
2001 * rather complex calculation. */
2002 object->exponent = 0.0f;
2004 else
2006 rho = light->theta + (light->phi - light->theta) / (2 * light->falloff);
2007 if (rho < 0.0001f)
2008 rho = 0.0001f;
2009 object->exponent = -0.3f / logf(cosf(rho / 2));
2012 if (object->exponent > 128.0f)
2013 object->exponent = 128.0f;
2015 object->cutoff = (float)(light->phi * 90 / M_PI);
2016 /* FIXME: Range */
2017 break;
2019 default:
2020 FIXME("Unrecognized light type %#x.\n", light->type);
2023 /* Update the live definitions if the light is currently assigned a glIndex. */
2024 if (object->glIndex != -1 && !device->isRecordingState)
2025 device_invalidate_state(device, STATE_ACTIVELIGHT(object->glIndex));
2027 return WINED3D_OK;
2030 HRESULT CDECL wined3d_device_get_light(const struct wined3d_device *device,
2031 UINT light_idx, struct wined3d_light *light)
2033 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2034 struct wined3d_light_info *light_info = NULL;
2035 struct list *e;
2037 TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
2039 LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
2041 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2042 if (light_info->OriginalIndex == light_idx)
2043 break;
2044 light_info = NULL;
2047 if (!light_info)
2049 TRACE("Light information requested but light not defined\n");
2050 return WINED3DERR_INVALIDCALL;
2053 *light = light_info->OriginalParms;
2054 return WINED3D_OK;
2057 HRESULT CDECL wined3d_device_set_light_enable(struct wined3d_device *device, UINT light_idx, BOOL enable)
2059 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2060 struct wined3d_light_info *light_info = NULL;
2061 struct list *e;
2063 TRACE("device %p, light_idx %u, enable %#x.\n", device, light_idx, enable);
2065 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2067 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2068 if (light_info->OriginalIndex == light_idx)
2069 break;
2070 light_info = NULL;
2072 TRACE("Found light %p.\n", light_info);
2074 /* Special case - enabling an undefined light creates one with a strict set of parameters. */
2075 if (!light_info)
2077 TRACE("Light enabled requested but light not defined, so defining one!\n");
2078 wined3d_device_set_light(device, light_idx, &WINED3D_default_light);
2080 /* Search for it again! Should be fairly quick as near head of list. */
2081 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2083 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2084 if (light_info->OriginalIndex == light_idx)
2085 break;
2086 light_info = NULL;
2088 if (!light_info)
2090 FIXME("Adding default lights has failed dismally\n");
2091 return WINED3DERR_INVALIDCALL;
2095 if (!enable)
2097 if (light_info->glIndex != -1)
2099 if (!device->isRecordingState)
2100 device_invalidate_state(device, STATE_ACTIVELIGHT(light_info->glIndex));
2102 device->updateStateBlock->state.lights[light_info->glIndex] = NULL;
2103 light_info->glIndex = -1;
2105 else
2107 TRACE("Light already disabled, nothing to do\n");
2109 light_info->enabled = FALSE;
2111 else
2113 light_info->enabled = TRUE;
2114 if (light_info->glIndex != -1)
2116 TRACE("Nothing to do as light was enabled\n");
2118 else
2120 unsigned int i;
2121 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2122 /* Find a free GL light. */
2123 for (i = 0; i < gl_info->limits.lights; ++i)
2125 if (!device->updateStateBlock->state.lights[i])
2127 device->updateStateBlock->state.lights[i] = light_info;
2128 light_info->glIndex = i;
2129 break;
2132 if (light_info->glIndex == -1)
2134 /* Our tests show that Windows returns D3D_OK in this situation, even with
2135 * D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE devices. This
2136 * is consistent among ddraw, d3d8 and d3d9. GetLightEnable returns TRUE
2137 * as well for those lights.
2139 * TODO: Test how this affects rendering. */
2140 WARN("Too many concurrently active lights\n");
2141 return WINED3D_OK;
2144 /* i == light_info->glIndex */
2145 if (!device->isRecordingState)
2146 device_invalidate_state(device, STATE_ACTIVELIGHT(i));
2150 return WINED3D_OK;
2153 HRESULT CDECL wined3d_device_get_light_enable(const struct wined3d_device *device, UINT light_idx, BOOL *enable)
2155 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2156 struct wined3d_light_info *light_info = NULL;
2157 struct list *e;
2159 TRACE("device %p, light_idx %u, enable %p.\n", device, light_idx, enable);
2161 LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
2163 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2164 if (light_info->OriginalIndex == light_idx)
2165 break;
2166 light_info = NULL;
2169 if (!light_info)
2171 TRACE("Light enabled state requested but light not defined.\n");
2172 return WINED3DERR_INVALIDCALL;
2174 /* true is 128 according to SetLightEnable */
2175 *enable = light_info->enabled ? 128 : 0;
2176 return WINED3D_OK;
2179 HRESULT CDECL wined3d_device_set_clip_plane(struct wined3d_device *device, UINT plane_idx, const float *plane)
2181 TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2183 /* Validate plane_idx. */
2184 if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2186 TRACE("Application has requested clipplane this device doesn't support.\n");
2187 return WINED3DERR_INVALIDCALL;
2190 device->updateStateBlock->changed.clipplane |= 1 << plane_idx;
2192 if (device->updateStateBlock->state.clip_planes[plane_idx][0] == plane[0]
2193 && device->updateStateBlock->state.clip_planes[plane_idx][1] == plane[1]
2194 && device->updateStateBlock->state.clip_planes[plane_idx][2] == plane[2]
2195 && device->updateStateBlock->state.clip_planes[plane_idx][3] == plane[3])
2197 TRACE("Application is setting old values over, nothing to do.\n");
2198 return WINED3D_OK;
2201 device->updateStateBlock->state.clip_planes[plane_idx][0] = plane[0];
2202 device->updateStateBlock->state.clip_planes[plane_idx][1] = plane[1];
2203 device->updateStateBlock->state.clip_planes[plane_idx][2] = plane[2];
2204 device->updateStateBlock->state.clip_planes[plane_idx][3] = plane[3];
2206 /* Handle recording of state blocks. */
2207 if (device->isRecordingState)
2209 TRACE("Recording... not performing anything.\n");
2210 return WINED3D_OK;
2213 device_invalidate_state(device, STATE_CLIPPLANE(plane_idx));
2215 return WINED3D_OK;
2218 HRESULT CDECL wined3d_device_get_clip_plane(const struct wined3d_device *device, UINT plane_idx, float *plane)
2220 TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2222 /* Validate plane_idx. */
2223 if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2225 TRACE("Application has requested clipplane this device doesn't support.\n");
2226 return WINED3DERR_INVALIDCALL;
2229 plane[0] = (float)device->stateBlock->state.clip_planes[plane_idx][0];
2230 plane[1] = (float)device->stateBlock->state.clip_planes[plane_idx][1];
2231 plane[2] = (float)device->stateBlock->state.clip_planes[plane_idx][2];
2232 plane[3] = (float)device->stateBlock->state.clip_planes[plane_idx][3];
2234 return WINED3D_OK;
2237 HRESULT CDECL wined3d_device_set_clip_status(struct wined3d_device *device,
2238 const struct wined3d_clip_status *clip_status)
2240 FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2242 if (!clip_status)
2243 return WINED3DERR_INVALIDCALL;
2245 return WINED3D_OK;
2248 HRESULT CDECL wined3d_device_get_clip_status(const struct wined3d_device *device,
2249 struct wined3d_clip_status *clip_status)
2251 FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2253 if (!clip_status)
2254 return WINED3DERR_INVALIDCALL;
2256 return WINED3D_OK;
2259 HRESULT CDECL wined3d_device_set_material(struct wined3d_device *device, const struct wined3d_material *material)
2261 TRACE("device %p, material %p.\n", device, material);
2263 device->updateStateBlock->changed.material = TRUE;
2264 device->updateStateBlock->state.material = *material;
2266 /* Handle recording of state blocks */
2267 if (device->isRecordingState)
2269 TRACE("Recording... not performing anything.\n");
2270 return WINED3D_OK;
2273 device_invalidate_state(device, STATE_MATERIAL);
2275 return WINED3D_OK;
2278 HRESULT CDECL wined3d_device_get_material(const struct wined3d_device *device, struct wined3d_material *material)
2280 TRACE("device %p, material %p.\n", device, material);
2282 *material = device->updateStateBlock->state.material;
2284 TRACE("diffuse {%.8e, %.8e, %.8e, %.8e}\n",
2285 material->diffuse.r, material->diffuse.g,
2286 material->diffuse.b, material->diffuse.a);
2287 TRACE("ambient {%.8e, %.8e, %.8e, %.8e}\n",
2288 material->ambient.r, material->ambient.g,
2289 material->ambient.b, material->ambient.a);
2290 TRACE("specular {%.8e, %.8e, %.8e, %.8e}\n",
2291 material->specular.r, material->specular.g,
2292 material->specular.b, material->specular.a);
2293 TRACE("emissive {%.8e, %.8e, %.8e, %.8e}\n",
2294 material->emissive.r, material->emissive.g,
2295 material->emissive.b, material->emissive.a);
2296 TRACE("power %.8e.\n", material->power);
2298 return WINED3D_OK;
2301 HRESULT CDECL wined3d_device_set_index_buffer(struct wined3d_device *device,
2302 struct wined3d_buffer *buffer, enum wined3d_format_id format_id)
2304 struct wined3d_buffer *prev_buffer;
2306 TRACE("device %p, buffer %p, format %s.\n",
2307 device, buffer, debug_d3dformat(format_id));
2309 prev_buffer = device->updateStateBlock->state.index_buffer;
2311 device->updateStateBlock->changed.indices = TRUE;
2312 device->updateStateBlock->state.index_buffer = buffer;
2313 device->updateStateBlock->state.index_format = format_id;
2315 /* Handle recording of state blocks. */
2316 if (device->isRecordingState)
2318 TRACE("Recording... not performing anything.\n");
2319 if (buffer)
2320 wined3d_buffer_incref(buffer);
2321 if (prev_buffer)
2322 wined3d_buffer_decref(prev_buffer);
2323 return WINED3D_OK;
2326 if (prev_buffer != buffer)
2328 device_invalidate_state(device, STATE_INDEXBUFFER);
2329 if (buffer)
2331 InterlockedIncrement(&buffer->bind_count);
2332 wined3d_buffer_incref(buffer);
2334 if (prev_buffer)
2336 InterlockedDecrement(&prev_buffer->bind_count);
2337 wined3d_buffer_decref(prev_buffer);
2341 return WINED3D_OK;
2344 HRESULT CDECL wined3d_device_get_index_buffer(const struct wined3d_device *device, struct wined3d_buffer **buffer)
2346 TRACE("device %p, buffer %p.\n", device, buffer);
2348 *buffer = device->stateBlock->state.index_buffer;
2350 if (*buffer)
2351 wined3d_buffer_incref(*buffer);
2353 TRACE("Returning %p.\n", *buffer);
2355 return WINED3D_OK;
2358 /* Method to offer d3d9 a simple way to set the base vertex index without messing with the index buffer */
2359 HRESULT CDECL wined3d_device_set_base_vertex_index(struct wined3d_device *device, INT base_index)
2361 TRACE("device %p, base_index %d.\n", device, base_index);
2363 if (device->updateStateBlock->state.base_vertex_index == base_index)
2365 TRACE("Application is setting the old value over, nothing to do\n");
2366 return WINED3D_OK;
2369 device->updateStateBlock->state.base_vertex_index = base_index;
2371 if (device->isRecordingState)
2373 TRACE("Recording... not performing anything\n");
2374 return WINED3D_OK;
2376 return WINED3D_OK;
2379 INT CDECL wined3d_device_get_base_vertex_index(const struct wined3d_device *device)
2381 TRACE("device %p.\n", device);
2383 return device->stateBlock->state.base_vertex_index;
2386 HRESULT CDECL wined3d_device_set_viewport(struct wined3d_device *device, const struct wined3d_viewport *viewport)
2388 TRACE("device %p, viewport %p.\n", device, viewport);
2389 TRACE("x %u, y %u, w %u, h %u, min_z %.8e, max_z %.8e.\n",
2390 viewport->x, viewport->y, viewport->width, viewport->height, viewport->min_z, viewport->max_z);
2392 device->updateStateBlock->changed.viewport = TRUE;
2393 device->updateStateBlock->state.viewport = *viewport;
2395 /* Handle recording of state blocks */
2396 if (device->isRecordingState)
2398 TRACE("Recording... not performing anything\n");
2399 return WINED3D_OK;
2402 device_invalidate_state(device, STATE_VIEWPORT);
2404 return WINED3D_OK;
2407 HRESULT CDECL wined3d_device_get_viewport(const struct wined3d_device *device, struct wined3d_viewport *viewport)
2409 TRACE("device %p, viewport %p.\n", device, viewport);
2411 *viewport = device->stateBlock->state.viewport;
2413 return WINED3D_OK;
2416 HRESULT CDECL wined3d_device_set_render_state(struct wined3d_device *device,
2417 enum wined3d_render_state state, DWORD value)
2419 DWORD old_value = device->stateBlock->state.render_states[state];
2421 TRACE("device %p, state %s (%#x), value %#x.\n", device, debug_d3drenderstate(state), state, value);
2423 device->updateStateBlock->changed.renderState[state >> 5] |= 1 << (state & 0x1f);
2424 device->updateStateBlock->state.render_states[state] = value;
2426 /* Handle recording of state blocks. */
2427 if (device->isRecordingState)
2429 TRACE("Recording... not performing anything.\n");
2430 return WINED3D_OK;
2433 /* Compared here and not before the assignment to allow proper stateblock recording. */
2434 if (value == old_value)
2435 TRACE("Application is setting the old value over, nothing to do.\n");
2436 else
2437 device_invalidate_state(device, STATE_RENDER(state));
2439 return WINED3D_OK;
2442 HRESULT CDECL wined3d_device_get_render_state(const struct wined3d_device *device,
2443 enum wined3d_render_state state, DWORD *value)
2445 TRACE("device %p, state %s (%#x), value %p.\n", device, debug_d3drenderstate(state), state, value);
2447 *value = device->stateBlock->state.render_states[state];
2449 return WINED3D_OK;
2452 HRESULT CDECL wined3d_device_set_sampler_state(struct wined3d_device *device,
2453 UINT sampler_idx, enum wined3d_sampler_state state, DWORD value)
2455 DWORD old_value;
2457 TRACE("device %p, sampler_idx %u, state %s, value %#x.\n",
2458 device, sampler_idx, debug_d3dsamplerstate(state), value);
2460 if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2461 sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2463 if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2464 / sizeof(*device->stateBlock->state.sampler_states))
2466 WARN("Invalid sampler %u.\n", sampler_idx);
2467 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2470 old_value = device->stateBlock->state.sampler_states[sampler_idx][state];
2471 device->updateStateBlock->state.sampler_states[sampler_idx][state] = value;
2472 device->updateStateBlock->changed.samplerState[sampler_idx] |= 1 << state;
2474 /* Handle recording of state blocks. */
2475 if (device->isRecordingState)
2477 TRACE("Recording... not performing anything.\n");
2478 return WINED3D_OK;
2481 if (old_value == value)
2483 TRACE("Application is setting the old value over, nothing to do.\n");
2484 return WINED3D_OK;
2487 device_invalidate_state(device, STATE_SAMPLER(sampler_idx));
2489 return WINED3D_OK;
2492 HRESULT CDECL wined3d_device_get_sampler_state(const struct wined3d_device *device,
2493 UINT sampler_idx, enum wined3d_sampler_state state, DWORD *value)
2495 TRACE("device %p, sampler_idx %u, state %s, value %p.\n",
2496 device, sampler_idx, debug_d3dsamplerstate(state), value);
2498 if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2499 sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2501 if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2502 / sizeof(*device->stateBlock->state.sampler_states))
2504 WARN("Invalid sampler %u.\n", sampler_idx);
2505 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2508 *value = device->stateBlock->state.sampler_states[sampler_idx][state];
2509 TRACE("Returning %#x.\n", *value);
2511 return WINED3D_OK;
2514 HRESULT CDECL wined3d_device_set_scissor_rect(struct wined3d_device *device, const RECT *rect)
2516 TRACE("device %p, rect %s.\n", device, wine_dbgstr_rect(rect));
2518 device->updateStateBlock->changed.scissorRect = TRUE;
2519 if (EqualRect(&device->updateStateBlock->state.scissor_rect, rect))
2521 TRACE("App is setting the old scissor rectangle over, nothing to do.\n");
2522 return WINED3D_OK;
2524 CopyRect(&device->updateStateBlock->state.scissor_rect, rect);
2526 if (device->isRecordingState)
2528 TRACE("Recording... not performing anything.\n");
2529 return WINED3D_OK;
2532 device_invalidate_state(device, STATE_SCISSORRECT);
2534 return WINED3D_OK;
2537 HRESULT CDECL wined3d_device_get_scissor_rect(const struct wined3d_device *device, RECT *rect)
2539 TRACE("device %p, rect %p.\n", device, rect);
2541 *rect = device->updateStateBlock->state.scissor_rect;
2542 TRACE("Returning rect %s.\n", wine_dbgstr_rect(rect));
2544 return WINED3D_OK;
2547 HRESULT CDECL wined3d_device_set_vertex_declaration(struct wined3d_device *device,
2548 struct wined3d_vertex_declaration *declaration)
2550 struct wined3d_vertex_declaration *prev = device->updateStateBlock->state.vertex_declaration;
2552 TRACE("device %p, declaration %p.\n", device, declaration);
2554 if (declaration)
2555 wined3d_vertex_declaration_incref(declaration);
2556 if (prev)
2557 wined3d_vertex_declaration_decref(prev);
2559 device->updateStateBlock->state.vertex_declaration = declaration;
2560 device->updateStateBlock->changed.vertexDecl = TRUE;
2562 if (device->isRecordingState)
2564 TRACE("Recording... not performing anything.\n");
2565 return WINED3D_OK;
2567 else if (declaration == prev)
2569 /* Checked after the assignment to allow proper stateblock recording. */
2570 TRACE("Application is setting the old declaration over, nothing to do.\n");
2571 return WINED3D_OK;
2574 device_invalidate_state(device, STATE_VDECL);
2575 return WINED3D_OK;
2578 HRESULT CDECL wined3d_device_get_vertex_declaration(const struct wined3d_device *device,
2579 struct wined3d_vertex_declaration **declaration)
2581 TRACE("device %p, declaration %p.\n", device, declaration);
2583 *declaration = device->stateBlock->state.vertex_declaration;
2584 if (*declaration)
2585 wined3d_vertex_declaration_incref(*declaration);
2587 return WINED3D_OK;
2590 HRESULT CDECL wined3d_device_set_vertex_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2592 struct wined3d_shader *prev = device->updateStateBlock->state.vertex_shader;
2594 TRACE("device %p, shader %p.\n", device, shader);
2596 device->updateStateBlock->state.vertex_shader = shader;
2597 device->updateStateBlock->changed.vertexShader = TRUE;
2599 if (device->isRecordingState)
2601 if (shader)
2602 wined3d_shader_incref(shader);
2603 if (prev)
2604 wined3d_shader_decref(prev);
2605 TRACE("Recording... not performing anything.\n");
2606 return WINED3D_OK;
2609 if (shader == prev)
2611 TRACE("Application is setting the old shader over, nothing to do.\n");
2612 return WINED3D_OK;
2615 if (shader)
2616 wined3d_shader_incref(shader);
2617 if (prev)
2618 wined3d_shader_decref(prev);
2620 device_invalidate_state(device, STATE_VSHADER);
2622 return WINED3D_OK;
2625 struct wined3d_shader * CDECL wined3d_device_get_vertex_shader(const struct wined3d_device *device)
2627 struct wined3d_shader *shader;
2629 TRACE("device %p.\n", device);
2631 shader = device->stateBlock->state.vertex_shader;
2632 if (shader)
2633 wined3d_shader_incref(shader);
2635 TRACE("Returning %p.\n", shader);
2636 return shader;
2639 HRESULT CDECL wined3d_device_set_vs_consts_b(struct wined3d_device *device,
2640 UINT start_register, const BOOL *constants, UINT bool_count)
2642 UINT count = min(bool_count, MAX_CONST_B - start_register);
2643 UINT i;
2645 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2646 device, start_register, constants, bool_count);
2648 if (!constants || start_register >= MAX_CONST_B)
2649 return WINED3DERR_INVALIDCALL;
2651 memcpy(&device->updateStateBlock->state.vs_consts_b[start_register], constants, count * sizeof(BOOL));
2652 for (i = 0; i < count; ++i)
2653 TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
2655 for (i = start_register; i < count + start_register; ++i)
2656 device->updateStateBlock->changed.vertexShaderConstantsB |= (1 << i);
2658 if (!device->isRecordingState)
2659 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2661 return WINED3D_OK;
2664 HRESULT CDECL wined3d_device_get_vs_consts_b(const struct wined3d_device *device,
2665 UINT start_register, BOOL *constants, UINT bool_count)
2667 UINT count = min(bool_count, MAX_CONST_B - start_register);
2669 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2670 device, start_register, constants, bool_count);
2672 if (!constants || start_register >= MAX_CONST_B)
2673 return WINED3DERR_INVALIDCALL;
2675 memcpy(constants, &device->stateBlock->state.vs_consts_b[start_register], count * sizeof(BOOL));
2677 return WINED3D_OK;
2680 HRESULT CDECL wined3d_device_set_vs_consts_i(struct wined3d_device *device,
2681 UINT start_register, const int *constants, UINT vector4i_count)
2683 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2684 UINT i;
2686 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2687 device, start_register, constants, vector4i_count);
2689 if (!constants || start_register >= MAX_CONST_I)
2690 return WINED3DERR_INVALIDCALL;
2692 memcpy(&device->updateStateBlock->state.vs_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
2693 for (i = 0; i < count; ++i)
2694 TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
2695 constants[i * 4], constants[i * 4 + 1],
2696 constants[i * 4 + 2], constants[i * 4 + 3]);
2698 for (i = start_register; i < count + start_register; ++i)
2699 device->updateStateBlock->changed.vertexShaderConstantsI |= (1 << i);
2701 if (!device->isRecordingState)
2702 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2704 return WINED3D_OK;
2707 HRESULT CDECL wined3d_device_get_vs_consts_i(const struct wined3d_device *device,
2708 UINT start_register, int *constants, UINT vector4i_count)
2710 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2712 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2713 device, start_register, constants, vector4i_count);
2715 if (!constants || start_register >= MAX_CONST_I)
2716 return WINED3DERR_INVALIDCALL;
2718 memcpy(constants, &device->stateBlock->state.vs_consts_i[start_register * 4], count * sizeof(int) * 4);
2719 return WINED3D_OK;
2722 HRESULT CDECL wined3d_device_set_vs_consts_f(struct wined3d_device *device,
2723 UINT start_register, const float *constants, UINT vector4f_count)
2725 UINT i;
2727 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2728 device, start_register, constants, vector4f_count);
2730 /* Specifically test start_register > limit to catch MAX_UINT overflows
2731 * when adding start_register + vector4f_count. */
2732 if (!constants
2733 || start_register + vector4f_count > device->d3d_vshader_constantF
2734 || start_register > device->d3d_vshader_constantF)
2735 return WINED3DERR_INVALIDCALL;
2737 memcpy(&device->updateStateBlock->state.vs_consts_f[start_register * 4],
2738 constants, vector4f_count * sizeof(float) * 4);
2739 if (TRACE_ON(d3d))
2741 for (i = 0; i < vector4f_count; ++i)
2742 TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
2743 constants[i * 4], constants[i * 4 + 1],
2744 constants[i * 4 + 2], constants[i * 4 + 3]);
2747 if (!device->isRecordingState)
2749 device->shader_backend->shader_update_float_vertex_constants(device, start_register, vector4f_count);
2750 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2753 memset(device->updateStateBlock->changed.vertexShaderConstantsF + start_register, 1,
2754 sizeof(*device->updateStateBlock->changed.vertexShaderConstantsF) * vector4f_count);
2756 return WINED3D_OK;
2759 HRESULT CDECL wined3d_device_get_vs_consts_f(const struct wined3d_device *device,
2760 UINT start_register, float *constants, UINT vector4f_count)
2762 int count = min(vector4f_count, device->d3d_vshader_constantF - start_register);
2764 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2765 device, start_register, constants, vector4f_count);
2767 if (!constants || count < 0)
2768 return WINED3DERR_INVALIDCALL;
2770 memcpy(constants, &device->stateBlock->state.vs_consts_f[start_register * 4], count * sizeof(float) * 4);
2772 return WINED3D_OK;
2775 static void device_invalidate_texture_stage(const struct wined3d_device *device, DWORD stage)
2777 DWORD i;
2779 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2781 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, i));
2785 static void device_map_stage(struct wined3d_device *device, DWORD stage, DWORD unit)
2787 DWORD i = device->rev_tex_unit_map[unit];
2788 DWORD j = device->texUnitMap[stage];
2790 device->texUnitMap[stage] = unit;
2791 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2792 device->texUnitMap[i] = WINED3D_UNMAPPED_STAGE;
2794 device->rev_tex_unit_map[unit] = stage;
2795 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2796 device->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2799 static void device_update_fixed_function_usage_map(struct wined3d_device *device)
2801 UINT i;
2803 device->fixed_function_usage_map = 0;
2804 for (i = 0; i < MAX_TEXTURES; ++i)
2806 const struct wined3d_state *state = &device->stateBlock->state;
2807 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2808 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2809 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2810 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2811 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2812 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2813 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2814 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2816 /* Not used, and disable higher stages. */
2817 if (color_op == WINED3D_TOP_DISABLE)
2818 break;
2820 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2821 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2822 || ((color_arg3 == WINED3DTA_TEXTURE)
2823 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2824 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2825 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2826 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2827 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2828 device->fixed_function_usage_map |= (1 << i);
2830 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2831 && i < MAX_TEXTURES - 1)
2832 device->fixed_function_usage_map |= (1 << (i + 1));
2836 static void device_map_fixed_function_samplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2838 unsigned int i, tex;
2839 WORD ffu_map;
2841 device_update_fixed_function_usage_map(device);
2842 ffu_map = device->fixed_function_usage_map;
2844 if (device->max_ffp_textures == gl_info->limits.texture_stages
2845 || device->stateBlock->state.lowest_disabled_stage <= device->max_ffp_textures)
2847 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2849 if (!(ffu_map & 1)) continue;
2851 if (device->texUnitMap[i] != i)
2853 device_map_stage(device, i, i);
2854 device_invalidate_state(device, STATE_SAMPLER(i));
2855 device_invalidate_texture_stage(device, i);
2858 return;
2861 /* Now work out the mapping */
2862 tex = 0;
2863 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2865 if (!(ffu_map & 1)) continue;
2867 if (device->texUnitMap[i] != tex)
2869 device_map_stage(device, i, tex);
2870 device_invalidate_state(device, STATE_SAMPLER(i));
2871 device_invalidate_texture_stage(device, i);
2874 ++tex;
2878 static void device_map_psamplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2880 const enum wined3d_sampler_texture_type *sampler_type =
2881 device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2882 unsigned int i;
2884 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2886 if (sampler_type[i] && device->texUnitMap[i] != i)
2888 device_map_stage(device, i, i);
2889 device_invalidate_state(device, STATE_SAMPLER(i));
2890 if (i < gl_info->limits.texture_stages)
2891 device_invalidate_texture_stage(device, i);
2896 static BOOL device_unit_free_for_vs(const struct wined3d_device *device,
2897 const enum wined3d_sampler_texture_type *pshader_sampler_tokens,
2898 const enum wined3d_sampler_texture_type *vshader_sampler_tokens, DWORD unit)
2900 DWORD current_mapping = device->rev_tex_unit_map[unit];
2902 /* Not currently used */
2903 if (current_mapping == WINED3D_UNMAPPED_STAGE) return TRUE;
2905 if (current_mapping < MAX_FRAGMENT_SAMPLERS) {
2906 /* Used by a fragment sampler */
2908 if (!pshader_sampler_tokens) {
2909 /* No pixel shader, check fixed function */
2910 return current_mapping >= MAX_TEXTURES || !(device->fixed_function_usage_map & (1 << current_mapping));
2913 /* Pixel shader, check the shader's sampler map */
2914 return !pshader_sampler_tokens[current_mapping];
2917 /* Used by a vertex sampler */
2918 return !vshader_sampler_tokens[current_mapping - MAX_FRAGMENT_SAMPLERS];
2921 static void device_map_vsamplers(struct wined3d_device *device, BOOL ps, const struct wined3d_gl_info *gl_info)
2923 const enum wined3d_sampler_texture_type *vshader_sampler_type =
2924 device->stateBlock->state.vertex_shader->reg_maps.sampler_type;
2925 const enum wined3d_sampler_texture_type *pshader_sampler_type = NULL;
2926 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2927 int i;
2929 if (ps)
2931 /* Note that we only care if a sampler is sampled or not, not the sampler's specific type.
2932 * Otherwise we'd need to call shader_update_samplers() here for 1.x pixelshaders. */
2933 pshader_sampler_type = device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2936 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
2937 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2938 if (vshader_sampler_type[i])
2940 if (device->texUnitMap[vsampler_idx] != WINED3D_UNMAPPED_STAGE)
2942 /* Already mapped somewhere */
2943 continue;
2946 while (start >= 0)
2948 if (device_unit_free_for_vs(device, pshader_sampler_type, vshader_sampler_type, start))
2950 device_map_stage(device, vsampler_idx, start);
2951 device_invalidate_state(device, STATE_SAMPLER(vsampler_idx));
2953 --start;
2954 break;
2957 --start;
2963 void device_update_tex_unit_map(struct wined3d_device *device)
2965 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2966 const struct wined3d_state *state = &device->stateBlock->state;
2967 BOOL vs = use_vs(state);
2968 BOOL ps = use_ps(state);
2970 * Rules are:
2971 * -> Pixel shaders need a 1:1 map. In theory the shader input could be mapped too, but
2972 * that would be really messy and require shader recompilation
2973 * -> When the mapping of a stage is changed, sampler and ALL texture stage states have
2974 * to be reset. Because of that try to work with a 1:1 mapping as much as possible
2976 if (ps)
2977 device_map_psamplers(device, gl_info);
2978 else
2979 device_map_fixed_function_samplers(device, gl_info);
2981 if (vs)
2982 device_map_vsamplers(device, ps, gl_info);
2985 HRESULT CDECL wined3d_device_set_pixel_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2987 struct wined3d_shader *prev = device->updateStateBlock->state.pixel_shader;
2989 TRACE("device %p, shader %p.\n", device, shader);
2991 device->updateStateBlock->state.pixel_shader = shader;
2992 device->updateStateBlock->changed.pixelShader = TRUE;
2994 if (device->isRecordingState)
2996 if (shader)
2997 wined3d_shader_incref(shader);
2998 if (prev)
2999 wined3d_shader_decref(prev);
3000 TRACE("Recording... not performing anything.\n");
3001 return WINED3D_OK;
3004 if (shader == prev)
3006 TRACE("Application is setting the old shader over, nothing to do.\n");
3007 return WINED3D_OK;
3010 if (shader)
3011 wined3d_shader_incref(shader);
3012 if (prev)
3013 wined3d_shader_decref(prev);
3015 device_invalidate_state(device, STATE_PIXELSHADER);
3017 return WINED3D_OK;
3020 struct wined3d_shader * CDECL wined3d_device_get_pixel_shader(const struct wined3d_device *device)
3022 struct wined3d_shader *shader;
3024 TRACE("device %p.\n", device);
3026 shader = device->stateBlock->state.pixel_shader;
3027 if (shader)
3028 wined3d_shader_incref(shader);
3030 TRACE("Returning %p.\n", shader);
3031 return shader;
3034 HRESULT CDECL wined3d_device_set_ps_consts_b(struct wined3d_device *device,
3035 UINT start_register, const BOOL *constants, UINT bool_count)
3037 UINT count = min(bool_count, MAX_CONST_B - start_register);
3038 UINT i;
3040 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
3041 device, start_register, constants, bool_count);
3043 if (!constants || start_register >= MAX_CONST_B)
3044 return WINED3DERR_INVALIDCALL;
3046 memcpy(&device->updateStateBlock->state.ps_consts_b[start_register], constants, count * sizeof(BOOL));
3047 for (i = 0; i < count; ++i)
3048 TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
3050 for (i = start_register; i < count + start_register; ++i)
3051 device->updateStateBlock->changed.pixelShaderConstantsB |= (1 << i);
3053 if (!device->isRecordingState)
3054 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3056 return WINED3D_OK;
3059 HRESULT CDECL wined3d_device_get_ps_consts_b(const struct wined3d_device *device,
3060 UINT start_register, BOOL *constants, UINT bool_count)
3062 UINT count = min(bool_count, MAX_CONST_B - start_register);
3064 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
3065 device, start_register, constants, bool_count);
3067 if (!constants || start_register >= MAX_CONST_B)
3068 return WINED3DERR_INVALIDCALL;
3070 memcpy(constants, &device->stateBlock->state.ps_consts_b[start_register], count * sizeof(BOOL));
3072 return WINED3D_OK;
3075 HRESULT CDECL wined3d_device_set_ps_consts_i(struct wined3d_device *device,
3076 UINT start_register, const int *constants, UINT vector4i_count)
3078 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
3079 UINT i;
3081 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
3082 device, start_register, constants, vector4i_count);
3084 if (!constants || start_register >= MAX_CONST_I)
3085 return WINED3DERR_INVALIDCALL;
3087 memcpy(&device->updateStateBlock->state.ps_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
3088 for (i = 0; i < count; ++i)
3089 TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
3090 constants[i * 4], constants[i * 4 + 1],
3091 constants[i * 4 + 2], constants[i * 4 + 3]);
3093 for (i = start_register; i < count + start_register; ++i)
3094 device->updateStateBlock->changed.pixelShaderConstantsI |= (1 << i);
3096 if (!device->isRecordingState)
3097 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3099 return WINED3D_OK;
3102 HRESULT CDECL wined3d_device_get_ps_consts_i(const struct wined3d_device *device,
3103 UINT start_register, int *constants, UINT vector4i_count)
3105 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
3107 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
3108 device, start_register, constants, vector4i_count);
3110 if (!constants || start_register >= MAX_CONST_I)
3111 return WINED3DERR_INVALIDCALL;
3113 memcpy(constants, &device->stateBlock->state.ps_consts_i[start_register * 4], count * sizeof(int) * 4);
3115 return WINED3D_OK;
3118 HRESULT CDECL wined3d_device_set_ps_consts_f(struct wined3d_device *device,
3119 UINT start_register, const float *constants, UINT vector4f_count)
3121 UINT i;
3123 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3124 device, start_register, constants, vector4f_count);
3126 /* Specifically test start_register > limit to catch MAX_UINT overflows
3127 * when adding start_register + vector4f_count. */
3128 if (!constants
3129 || start_register + vector4f_count > device->d3d_pshader_constantF
3130 || start_register > device->d3d_pshader_constantF)
3131 return WINED3DERR_INVALIDCALL;
3133 memcpy(&device->updateStateBlock->state.ps_consts_f[start_register * 4],
3134 constants, vector4f_count * sizeof(float) * 4);
3135 if (TRACE_ON(d3d))
3137 for (i = 0; i < vector4f_count; ++i)
3138 TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
3139 constants[i * 4], constants[i * 4 + 1],
3140 constants[i * 4 + 2], constants[i * 4 + 3]);
3143 if (!device->isRecordingState)
3145 device->shader_backend->shader_update_float_pixel_constants(device, start_register, vector4f_count);
3146 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3149 memset(device->updateStateBlock->changed.pixelShaderConstantsF + start_register, 1,
3150 sizeof(*device->updateStateBlock->changed.pixelShaderConstantsF) * vector4f_count);
3152 return WINED3D_OK;
3155 HRESULT CDECL wined3d_device_get_ps_consts_f(const struct wined3d_device *device,
3156 UINT start_register, float *constants, UINT vector4f_count)
3158 int count = min(vector4f_count, device->d3d_pshader_constantF - start_register);
3160 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3161 device, start_register, constants, vector4f_count);
3163 if (!constants || count < 0)
3164 return WINED3DERR_INVALIDCALL;
3166 memcpy(constants, &device->stateBlock->state.ps_consts_f[start_register * 4], count * sizeof(float) * 4);
3168 return WINED3D_OK;
3171 /* Context activation is done by the caller. */
3172 /* Do not call while under the GL lock. */
3173 #define copy_and_next(dest, src, size) memcpy(dest, src, size); dest += (size)
3174 static HRESULT process_vertices_strided(const struct wined3d_device *device, DWORD dwDestIndex, DWORD dwCount,
3175 const struct wined3d_stream_info *stream_info, struct wined3d_buffer *dest, DWORD flags,
3176 DWORD DestFVF)
3178 struct wined3d_matrix mat, proj_mat, view_mat, world_mat;
3179 struct wined3d_viewport vp;
3180 UINT vertex_size;
3181 unsigned int i;
3182 BYTE *dest_ptr;
3183 BOOL doClip;
3184 DWORD numTextures;
3185 HRESULT hr;
3187 if (stream_info->use_map & (1 << WINED3D_FFP_NORMAL))
3189 WARN(" lighting state not saved yet... Some strange stuff may happen !\n");
3192 if (!(stream_info->use_map & (1 << WINED3D_FFP_POSITION)))
3194 ERR("Source has no position mask\n");
3195 return WINED3DERR_INVALIDCALL;
3198 if (device->stateBlock->state.render_states[WINED3D_RS_CLIPPING])
3200 static BOOL warned = FALSE;
3202 * The clipping code is not quite correct. Some things need
3203 * to be checked against IDirect3DDevice3 (!), d3d8 and d3d9,
3204 * so disable clipping for now.
3205 * (The graphics in Half-Life are broken, and my processvertices
3206 * test crashes with IDirect3DDevice3)
3207 doClip = TRUE;
3209 doClip = FALSE;
3210 if(!warned) {
3211 warned = TRUE;
3212 FIXME("Clipping is broken and disabled for now\n");
3215 else
3216 doClip = FALSE;
3218 vertex_size = get_flexible_vertex_size(DestFVF);
3219 if (FAILED(hr = wined3d_buffer_map(dest, dwDestIndex * vertex_size, dwCount * vertex_size, &dest_ptr, 0)))
3221 WARN("Failed to map buffer, hr %#x.\n", hr);
3222 return hr;
3225 wined3d_device_get_transform(device, WINED3D_TS_VIEW, &view_mat);
3226 wined3d_device_get_transform(device, WINED3D_TS_PROJECTION, &proj_mat);
3227 wined3d_device_get_transform(device, WINED3D_TS_WORLD_MATRIX(0), &world_mat);
3229 TRACE("View mat:\n");
3230 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);
3231 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);
3232 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);
3233 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);
3235 TRACE("Proj mat:\n");
3236 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);
3237 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);
3238 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);
3239 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);
3241 TRACE("World mat:\n");
3242 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);
3243 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);
3244 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);
3245 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);
3247 /* Get the viewport */
3248 wined3d_device_get_viewport(device, &vp);
3249 TRACE("viewport x %u, y %u, width %u, height %u, min_z %.8e, max_z %.8e.\n",
3250 vp.x, vp.y, vp.width, vp.height, vp.min_z, vp.max_z);
3252 multiply_matrix(&mat,&view_mat,&world_mat);
3253 multiply_matrix(&mat,&proj_mat,&mat);
3255 numTextures = (DestFVF & WINED3DFVF_TEXCOUNT_MASK) >> WINED3DFVF_TEXCOUNT_SHIFT;
3257 for (i = 0; i < dwCount; i+= 1) {
3258 unsigned int tex_index;
3260 if ( ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZ ) ||
3261 ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW ) ) {
3262 /* The position first */
3263 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_POSITION];
3264 const float *p = (const float *)(element->data.addr + i * element->stride);
3265 float x, y, z, rhw;
3266 TRACE("In: ( %06.2f %06.2f %06.2f )\n", p[0], p[1], p[2]);
3268 /* Multiplication with world, view and projection matrix */
3269 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);
3270 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);
3271 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);
3272 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);
3274 TRACE("x=%f y=%f z=%f rhw=%f\n", x, y, z, rhw);
3276 /* WARNING: The following things are taken from d3d7 and were not yet checked
3277 * against d3d8 or d3d9!
3280 /* Clipping conditions: From msdn
3282 * A vertex is clipped if it does not match the following requirements
3283 * -rhw < x <= rhw
3284 * -rhw < y <= rhw
3285 * 0 < z <= rhw
3286 * 0 < rhw ( Not in d3d7, but tested in d3d7)
3288 * If clipping is on is determined by the D3DVOP_CLIP flag in D3D7, and
3289 * by the D3DRS_CLIPPING in D3D9(according to the msdn, not checked)
3293 if( !doClip ||
3294 ( (-rhw -eps < x) && (-rhw -eps < y) && ( -eps < z) &&
3295 (x <= rhw + eps) && (y <= rhw + eps ) && (z <= rhw + eps) &&
3296 ( rhw > eps ) ) ) {
3298 /* "Normal" viewport transformation (not clipped)
3299 * 1) The values are divided by rhw
3300 * 2) The y axis is negative, so multiply it with -1
3301 * 3) Screen coordinates go from -(Width/2) to +(Width/2) and
3302 * -(Height/2) to +(Height/2). The z range is MinZ to MaxZ
3303 * 4) Multiply x with Width/2 and add Width/2
3304 * 5) The same for the height
3305 * 6) Add the viewpoint X and Y to the 2D coordinates and
3306 * The minimum Z value to z
3307 * 7) rhw = 1 / rhw Reciprocal of Homogeneous W....
3309 * Well, basically it's simply a linear transformation into viewport
3310 * coordinates
3313 x /= rhw;
3314 y /= rhw;
3315 z /= rhw;
3317 y *= -1;
3319 x *= vp.width / 2;
3320 y *= vp.height / 2;
3321 z *= vp.max_z - vp.min_z;
3323 x += vp.width / 2 + vp.x;
3324 y += vp.height / 2 + vp.y;
3325 z += vp.min_z;
3327 rhw = 1 / rhw;
3328 } else {
3329 /* That vertex got clipped
3330 * Contrary to OpenGL it is not dropped completely, it just
3331 * undergoes a different calculation.
3333 TRACE("Vertex got clipped\n");
3334 x += rhw;
3335 y += rhw;
3337 x /= 2;
3338 y /= 2;
3340 /* Msdn mentions that Direct3D9 keeps a list of clipped vertices
3341 * outside of the main vertex buffer memory. That needs some more
3342 * investigation...
3346 TRACE("Writing (%f %f %f) %f\n", x, y, z, rhw);
3349 ( (float *) dest_ptr)[0] = x;
3350 ( (float *) dest_ptr)[1] = y;
3351 ( (float *) dest_ptr)[2] = z;
3352 ( (float *) dest_ptr)[3] = rhw; /* SIC, see ddraw test! */
3354 dest_ptr += 3 * sizeof(float);
3356 if ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW)
3357 dest_ptr += sizeof(float);
3360 if (DestFVF & WINED3DFVF_PSIZE)
3361 dest_ptr += sizeof(DWORD);
3363 if (DestFVF & WINED3DFVF_NORMAL)
3365 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_NORMAL];
3366 const float *normal = (const float *)(element->data.addr + i * element->stride);
3367 /* AFAIK this should go into the lighting information */
3368 FIXME("Didn't expect the destination to have a normal\n");
3369 copy_and_next(dest_ptr, normal, 3 * sizeof(float));
3372 if (DestFVF & WINED3DFVF_DIFFUSE)
3374 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_DIFFUSE];
3375 const DWORD *color_d = (const DWORD *)(element->data.addr + i * element->stride);
3376 if (!(stream_info->use_map & (1 << WINED3D_FFP_DIFFUSE)))
3378 static BOOL warned = FALSE;
3380 if(!warned) {
3381 ERR("No diffuse color in source, but destination has one\n");
3382 warned = TRUE;
3385 *( (DWORD *) dest_ptr) = 0xffffffff;
3386 dest_ptr += sizeof(DWORD);
3388 else
3390 copy_and_next(dest_ptr, color_d, sizeof(DWORD));
3394 if (DestFVF & WINED3DFVF_SPECULAR)
3396 /* What's the color value in the feedback buffer? */
3397 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_SPECULAR];
3398 const DWORD *color_s = (const DWORD *)(element->data.addr + i * element->stride);
3399 if (!(stream_info->use_map & (1 << WINED3D_FFP_SPECULAR)))
3401 static BOOL warned = FALSE;
3403 if(!warned) {
3404 ERR("No specular color in source, but destination has one\n");
3405 warned = TRUE;
3408 *( (DWORD *) dest_ptr) = 0xFF000000;
3409 dest_ptr += sizeof(DWORD);
3411 else
3413 copy_and_next(dest_ptr, color_s, sizeof(DWORD));
3417 for (tex_index = 0; tex_index < numTextures; ++tex_index)
3419 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_TEXCOORD0 + tex_index];
3420 const float *tex_coord = (const float *)(element->data.addr + i * element->stride);
3421 if (!(stream_info->use_map & (1 << (WINED3D_FFP_TEXCOORD0 + tex_index))))
3423 ERR("No source texture, but destination requests one\n");
3424 dest_ptr += GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float);
3426 else
3428 copy_and_next(dest_ptr, tex_coord, GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float));
3433 wined3d_buffer_unmap(dest);
3435 return WINED3D_OK;
3437 #undef copy_and_next
3439 /* Do not call while under the GL lock. */
3440 HRESULT CDECL wined3d_device_process_vertices(struct wined3d_device *device,
3441 UINT src_start_idx, UINT dst_idx, UINT vertex_count, struct wined3d_buffer *dst_buffer,
3442 const struct wined3d_vertex_declaration *declaration, DWORD flags, DWORD dst_fvf)
3444 struct wined3d_state *state = &device->stateBlock->state;
3445 struct wined3d_stream_info stream_info;
3446 const struct wined3d_gl_info *gl_info;
3447 BOOL streamWasUP = state->user_stream;
3448 struct wined3d_context *context;
3449 struct wined3d_shader *vs;
3450 unsigned int i;
3451 HRESULT hr;
3453 TRACE("device %p, src_start_idx %u, dst_idx %u, vertex_count %u, "
3454 "dst_buffer %p, declaration %p, flags %#x, dst_fvf %#x.\n",
3455 device, src_start_idx, dst_idx, vertex_count,
3456 dst_buffer, declaration, flags, dst_fvf);
3458 if (declaration)
3459 FIXME("Output vertex declaration not implemented yet.\n");
3461 /* Need any context to write to the vbo. */
3462 context = context_acquire(device, NULL);
3463 gl_info = context->gl_info;
3465 /* ProcessVertices reads from vertex buffers, which have to be assigned.
3466 * DrawPrimitive and DrawPrimitiveUP control the streamIsUP flag, thus
3467 * restore it afterwards. */
3468 vs = state->vertex_shader;
3469 state->vertex_shader = NULL;
3470 state->user_stream = FALSE;
3471 device_stream_info_from_declaration(device, &stream_info, NULL);
3472 state->user_stream = streamWasUP;
3473 state->vertex_shader = vs;
3475 /* We can't convert FROM a VBO, and vertex buffers used to source into
3476 * process_vertices() are unlikely to ever be used for drawing. Release
3477 * VBOs in those buffers and fix up the stream_info structure.
3479 * Also apply the start index. */
3480 for (i = 0; i < (sizeof(stream_info.elements) / sizeof(*stream_info.elements)); ++i)
3482 struct wined3d_stream_info_element *e;
3484 if (!(stream_info.use_map & (1 << i)))
3485 continue;
3487 e = &stream_info.elements[i];
3488 if (e->data.buffer_object)
3490 struct wined3d_buffer *vb = state->streams[e->stream_idx].buffer;
3491 e->data.buffer_object = 0;
3492 e->data.addr = (BYTE *)((ULONG_PTR)e->data.addr + (ULONG_PTR)buffer_get_sysmem(vb, gl_info));
3493 ENTER_GL();
3494 GL_EXTCALL(glDeleteBuffersARB(1, &vb->buffer_object));
3495 vb->buffer_object = 0;
3496 LEAVE_GL();
3498 if (e->data.addr)
3499 e->data.addr += e->stride * src_start_idx;
3502 hr = process_vertices_strided(device, dst_idx, vertex_count,
3503 &stream_info, dst_buffer, flags, dst_fvf);
3505 context_release(context);
3507 return hr;
3510 HRESULT CDECL wined3d_device_set_texture_stage_state(struct wined3d_device *device,
3511 UINT stage, enum wined3d_texture_stage_state state, DWORD value)
3513 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3514 DWORD old_value;
3516 TRACE("device %p, stage %u, state %s, value %#x.\n",
3517 device, stage, debug_d3dtexturestate(state), value);
3519 if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3521 WARN("Invalid state %#x passed.\n", state);
3522 return WINED3D_OK;
3525 if (stage >= gl_info->limits.texture_stages)
3527 WARN("Attempting to set stage %u which is higher than the max stage %u, ignoring.\n",
3528 stage, gl_info->limits.texture_stages - 1);
3529 return WINED3D_OK;
3532 old_value = device->updateStateBlock->state.texture_states[stage][state];
3533 device->updateStateBlock->changed.textureState[stage] |= 1 << state;
3534 device->updateStateBlock->state.texture_states[stage][state] = value;
3536 if (device->isRecordingState)
3538 TRACE("Recording... not performing anything.\n");
3539 return WINED3D_OK;
3542 /* Checked after the assignments to allow proper stateblock recording. */
3543 if (old_value == value)
3545 TRACE("Application is setting the old value over, nothing to do.\n");
3546 return WINED3D_OK;
3549 if (stage > device->stateBlock->state.lowest_disabled_stage
3550 && device->StateTable[STATE_TEXTURESTAGE(0, state)].representative
3551 == STATE_TEXTURESTAGE(0, WINED3D_TSS_COLOR_OP))
3553 /* Colorop change above lowest disabled stage? That won't change
3554 * anything in the GL setup. Changes in other states are important on
3555 * disabled stages too. */
3556 return WINED3D_OK;
3559 if (state == WINED3D_TSS_COLOR_OP)
3561 unsigned int i;
3563 if (value == WINED3D_TOP_DISABLE && old_value != WINED3D_TOP_DISABLE)
3565 /* Previously enabled stage disabled now. Make sure to dirtify
3566 * all enabled stages above stage, they have to be disabled.
3568 * The current stage is dirtified below. */
3569 for (i = stage + 1; i < device->stateBlock->state.lowest_disabled_stage; ++i)
3571 TRACE("Additionally dirtifying stage %u.\n", i);
3572 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
3574 device->stateBlock->state.lowest_disabled_stage = stage;
3575 TRACE("New lowest disabled: %u.\n", stage);
3577 else if (value != WINED3D_TOP_DISABLE && old_value == WINED3D_TOP_DISABLE)
3579 /* Previously disabled stage enabled. Stages above it may need
3580 * enabling. Stage must be lowest_disabled_stage here, if it's
3581 * bigger success is returned above, and stages below the lowest
3582 * disabled stage can't be enabled (because they are enabled
3583 * already).
3585 * Again stage stage doesn't need to be dirtified here, it is
3586 * handled below. */
3587 for (i = stage + 1; i < gl_info->limits.texture_stages; ++i)
3589 if (device->updateStateBlock->state.texture_states[i][WINED3D_TSS_COLOR_OP] == WINED3D_TOP_DISABLE)
3590 break;
3591 TRACE("Additionally dirtifying stage %u due to enable.\n", i);
3592 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
3594 device->stateBlock->state.lowest_disabled_stage = i;
3595 TRACE("New lowest disabled: %u.\n", i);
3599 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, state));
3601 return WINED3D_OK;
3604 HRESULT CDECL wined3d_device_get_texture_stage_state(const struct wined3d_device *device,
3605 UINT stage, enum wined3d_texture_stage_state state, DWORD *value)
3607 TRACE("device %p, stage %u, state %s, value %p.\n",
3608 device, stage, debug_d3dtexturestate(state), value);
3610 if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3612 WARN("Invalid state %#x passed.\n", state);
3613 return WINED3D_OK;
3616 *value = device->updateStateBlock->state.texture_states[stage][state];
3617 TRACE("Returning %#x.\n", *value);
3619 return WINED3D_OK;
3622 HRESULT CDECL wined3d_device_set_texture(struct wined3d_device *device,
3623 UINT stage, struct wined3d_texture *texture)
3625 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3626 struct wined3d_texture *prev;
3628 TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3630 if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3631 stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3633 /* Windows accepts overflowing this array... we do not. */
3634 if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3636 WARN("Ignoring invalid stage %u.\n", stage);
3637 return WINED3D_OK;
3640 if (texture && texture->resource.pool == WINED3D_POOL_SCRATCH)
3642 WARN("Rejecting attempt to set scratch texture.\n");
3643 return WINED3DERR_INVALIDCALL;
3646 device->updateStateBlock->changed.textures |= 1 << stage;
3648 prev = device->updateStateBlock->state.textures[stage];
3649 TRACE("Previous texture %p.\n", prev);
3651 if (texture == prev)
3653 TRACE("App is setting the same texture again, nothing to do.\n");
3654 return WINED3D_OK;
3657 TRACE("Setting new texture to %p.\n", texture);
3658 device->updateStateBlock->state.textures[stage] = texture;
3660 if (device->isRecordingState)
3662 TRACE("Recording... not performing anything\n");
3664 if (texture) wined3d_texture_incref(texture);
3665 if (prev) wined3d_texture_decref(prev);
3667 return WINED3D_OK;
3670 if (texture)
3672 LONG bind_count = InterlockedIncrement(&texture->bind_count);
3674 wined3d_texture_incref(texture);
3676 if (!prev || texture->target != prev->target)
3677 device_invalidate_state(device, STATE_PIXELSHADER);
3679 if (!prev && stage < gl_info->limits.texture_stages)
3681 /* The source arguments for color and alpha ops have different
3682 * meanings when a NULL texture is bound, so the COLOR_OP and
3683 * ALPHA_OP have to be dirtified. */
3684 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_COLOR_OP));
3685 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_ALPHA_OP));
3688 if (bind_count == 1)
3689 texture->sampler = stage;
3692 if (prev)
3694 LONG bind_count = InterlockedDecrement(&prev->bind_count);
3696 wined3d_texture_decref(prev);
3698 if (!texture && stage < gl_info->limits.texture_stages)
3700 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_COLOR_OP));
3701 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_ALPHA_OP));
3704 if (bind_count && prev->sampler == stage)
3706 unsigned int i;
3708 /* Search for other stages the texture is bound to. Shouldn't
3709 * happen if applications bind textures to a single stage only. */
3710 TRACE("Searching for other stages the texture is bound to.\n");
3711 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
3713 if (device->updateStateBlock->state.textures[i] == prev)
3715 TRACE("Texture is also bound to stage %u.\n", i);
3716 prev->sampler = i;
3717 break;
3723 device_invalidate_state(device, STATE_SAMPLER(stage));
3725 return WINED3D_OK;
3728 HRESULT CDECL wined3d_device_get_texture(const struct wined3d_device *device,
3729 UINT stage, struct wined3d_texture **texture)
3731 TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3733 if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3734 stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3736 if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3738 WARN("Ignoring invalid stage %u.\n", stage);
3739 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
3742 *texture = device->stateBlock->state.textures[stage];
3743 if (*texture)
3744 wined3d_texture_incref(*texture);
3746 TRACE("Returning %p.\n", *texture);
3748 return WINED3D_OK;
3751 HRESULT CDECL wined3d_device_get_back_buffer(const struct wined3d_device *device, UINT swapchain_idx,
3752 UINT backbuffer_idx, enum wined3d_backbuffer_type backbuffer_type, struct wined3d_surface **backbuffer)
3754 struct wined3d_swapchain *swapchain;
3755 HRESULT hr;
3757 TRACE("device %p, swapchain_idx %u, backbuffer_idx %u, backbuffer_type %#x, backbuffer %p.\n",
3758 device, swapchain_idx, backbuffer_idx, backbuffer_type, backbuffer);
3760 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
3761 if (FAILED(hr))
3763 WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
3764 return hr;
3767 hr = wined3d_swapchain_get_back_buffer(swapchain, backbuffer_idx, backbuffer_type, backbuffer);
3768 wined3d_swapchain_decref(swapchain);
3769 if (FAILED(hr))
3771 WARN("Failed to get backbuffer %u, hr %#x.\n", backbuffer_idx, hr);
3772 return hr;
3775 return WINED3D_OK;
3778 HRESULT CDECL wined3d_device_get_device_caps(const struct wined3d_device *device, WINED3DCAPS *caps)
3780 TRACE("device %p, caps %p.\n", device, caps);
3782 return wined3d_get_device_caps(device->wined3d, device->adapter->ordinal,
3783 device->create_parms.device_type, caps);
3786 HRESULT CDECL wined3d_device_get_display_mode(const struct wined3d_device *device,
3787 UINT swapchain_idx, struct wined3d_display_mode *mode)
3789 struct wined3d_swapchain *swapchain;
3790 HRESULT hr;
3792 TRACE("device %p, swapchain_idx %u, mode %p.\n", device, swapchain_idx, mode);
3794 if (swapchain_idx)
3796 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
3797 if (SUCCEEDED(hr))
3799 hr = wined3d_swapchain_get_display_mode(swapchain, mode);
3800 wined3d_swapchain_decref(swapchain);
3803 else
3805 const struct wined3d_adapter *adapter = device->adapter;
3807 /* Don't read the real display mode, but return the stored mode
3808 * instead. X11 can't change the color depth, and some apps are
3809 * pretty angry if they SetDisplayMode from 24 to 16 bpp and find out
3810 * that GetDisplayMode still returns 24 bpp.
3812 * Also don't relay to the swapchain because with ddraw it's possible
3813 * that there isn't a swapchain at all. */
3814 mode->width = adapter->screen_size.cx;
3815 mode->height = adapter->screen_size.cy;
3816 mode->format_id = adapter->screen_format;
3817 mode->refresh_rate = 0;
3818 hr = WINED3D_OK;
3821 return hr;
3824 HRESULT CDECL wined3d_device_begin_stateblock(struct wined3d_device *device)
3826 struct wined3d_stateblock *stateblock;
3827 HRESULT hr;
3829 TRACE("device %p.\n", device);
3831 if (device->isRecordingState)
3832 return WINED3DERR_INVALIDCALL;
3834 hr = wined3d_stateblock_create(device, WINED3D_SBT_RECORDED, &stateblock);
3835 if (FAILED(hr))
3836 return hr;
3838 wined3d_stateblock_decref(device->updateStateBlock);
3839 device->updateStateBlock = stateblock;
3840 device->isRecordingState = TRUE;
3842 TRACE("Recording stateblock %p.\n", stateblock);
3844 return WINED3D_OK;
3847 HRESULT CDECL wined3d_device_end_stateblock(struct wined3d_device *device,
3848 struct wined3d_stateblock **stateblock)
3850 struct wined3d_stateblock *object = device->updateStateBlock;
3852 TRACE("device %p, stateblock %p.\n", device, stateblock);
3854 if (!device->isRecordingState)
3856 WARN("Not recording.\n");
3857 *stateblock = NULL;
3858 return WINED3DERR_INVALIDCALL;
3861 stateblock_init_contained_states(object);
3863 *stateblock = object;
3864 device->isRecordingState = FALSE;
3865 device->updateStateBlock = device->stateBlock;
3866 wined3d_stateblock_incref(device->updateStateBlock);
3868 TRACE("Returning stateblock %p.\n", *stateblock);
3870 return WINED3D_OK;
3873 HRESULT CDECL wined3d_device_begin_scene(struct wined3d_device *device)
3875 /* At the moment we have no need for any functionality at the beginning
3876 * of a scene. */
3877 TRACE("device %p.\n", device);
3879 if (device->inScene)
3881 WARN("Already in scene, returning WINED3DERR_INVALIDCALL.\n");
3882 return WINED3DERR_INVALIDCALL;
3884 device->inScene = TRUE;
3885 return WINED3D_OK;
3888 HRESULT CDECL wined3d_device_end_scene(struct wined3d_device *device)
3890 struct wined3d_context *context;
3892 TRACE("device %p.\n", device);
3894 if (!device->inScene)
3896 WARN("Not in scene, returning WINED3DERR_INVALIDCALL.\n");
3897 return WINED3DERR_INVALIDCALL;
3900 context = context_acquire(device, NULL);
3901 /* We only have to do this if we need to read the, swapbuffers performs a flush for us */
3902 wglFlush();
3903 /* No checkGLcall here to avoid locking the lock just for checking a call that hardly ever
3904 * fails. */
3905 context_release(context);
3907 device->inScene = FALSE;
3908 return WINED3D_OK;
3911 HRESULT CDECL wined3d_device_present(const struct wined3d_device *device, const RECT *src_rect,
3912 const RECT *dst_rect, HWND dst_window_override, const RGNDATA *dirty_region)
3914 UINT i;
3916 TRACE("device %p, src_rect %s, dst_rect %s, dst_window_override %p, dirty_region %p.\n",
3917 device, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect),
3918 dst_window_override, dirty_region);
3920 for (i = 0; i < device->swapchain_count; ++i)
3922 wined3d_swapchain_present(device->swapchains[i], src_rect,
3923 dst_rect, dst_window_override, dirty_region, 0);
3926 return WINED3D_OK;
3929 /* Do not call while under the GL lock. */
3930 HRESULT CDECL wined3d_device_clear(struct wined3d_device *device, DWORD rect_count,
3931 const RECT *rects, DWORD flags, const struct wined3d_color *color, float depth, DWORD stencil)
3933 RECT draw_rect;
3935 TRACE("device %p, rect_count %u, rects %p, flags %#x, color {%.8e, %.8e, %.8e, %.8e}, depth %.8e, stencil %u.\n",
3936 device, rect_count, rects, flags, color->r, color->g, color->b, color->a, depth, stencil);
3938 if (flags & (WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL))
3940 struct wined3d_surface *ds = device->fb.depth_stencil;
3941 if (!ds)
3943 WARN("Clearing depth and/or stencil without a depth stencil buffer attached, returning WINED3DERR_INVALIDCALL\n");
3944 /* TODO: What about depth stencil buffers without stencil bits? */
3945 return WINED3DERR_INVALIDCALL;
3947 else if (flags & WINED3DCLEAR_TARGET)
3949 if (ds->resource.width < device->fb.render_targets[0]->resource.width
3950 || ds->resource.height < device->fb.render_targets[0]->resource.height)
3952 WARN("Silently ignoring depth and target clear with mismatching sizes\n");
3953 return WINED3D_OK;
3958 wined3d_get_draw_rect(&device->stateBlock->state, &draw_rect);
3959 device_clear_render_targets(device, device->adapter->gl_info.limits.buffers,
3960 &device->fb, rect_count, rects, &draw_rect, flags, color, depth, stencil);
3962 return WINED3D_OK;
3965 void CDECL wined3d_device_set_primitive_type(struct wined3d_device *device,
3966 enum wined3d_primitive_type primitive_type)
3968 TRACE("device %p, primitive_type %s\n", device, debug_d3dprimitivetype(primitive_type));
3970 device->updateStateBlock->changed.primitive_type = TRUE;
3971 device->updateStateBlock->state.gl_primitive_type = gl_primitive_type_from_d3d(primitive_type);
3974 void CDECL wined3d_device_get_primitive_type(const struct wined3d_device *device,
3975 enum wined3d_primitive_type *primitive_type)
3977 TRACE("device %p, primitive_type %p\n", device, primitive_type);
3979 *primitive_type = d3d_primitive_type_from_gl(device->stateBlock->state.gl_primitive_type);
3981 TRACE("Returning %s\n", debug_d3dprimitivetype(*primitive_type));
3984 HRESULT CDECL wined3d_device_draw_primitive(struct wined3d_device *device, UINT start_vertex, UINT vertex_count)
3986 TRACE("device %p, start_vertex %u, vertex_count %u.\n", device, start_vertex, vertex_count);
3988 if (!device->stateBlock->state.vertex_declaration)
3990 WARN("Called without a valid vertex declaration set.\n");
3991 return WINED3DERR_INVALIDCALL;
3994 /* The index buffer is not needed here, but restore it, otherwise it is hell to keep track of */
3995 if (device->stateBlock->state.user_stream)
3997 device_invalidate_state(device, STATE_INDEXBUFFER);
3998 device->stateBlock->state.user_stream = FALSE;
4001 if (device->stateBlock->state.load_base_vertex_index)
4003 device->stateBlock->state.load_base_vertex_index = 0;
4004 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4007 /* Account for the loading offset due to index buffers. Instead of
4008 * reloading all sources correct it with the startvertex parameter. */
4009 drawPrimitive(device, vertex_count, start_vertex, 0, NULL);
4010 return WINED3D_OK;
4013 HRESULT CDECL wined3d_device_draw_indexed_primitive(struct wined3d_device *device, UINT start_idx, UINT index_count)
4015 struct wined3d_buffer *index_buffer;
4016 UINT index_size = 2;
4017 GLuint vbo;
4018 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4020 TRACE("device %p, start_idx %u, index_count %u.\n", device, start_idx, index_count);
4022 index_buffer = device->stateBlock->state.index_buffer;
4023 if (!index_buffer)
4025 /* D3D9 returns D3DERR_INVALIDCALL when DrawIndexedPrimitive is called
4026 * without an index buffer set. (The first time at least...)
4027 * D3D8 simply dies, but I doubt it can do much harm to return
4028 * D3DERR_INVALIDCALL there as well. */
4029 WARN("Called without a valid index buffer set, returning WINED3DERR_INVALIDCALL.\n");
4030 return WINED3DERR_INVALIDCALL;
4033 if (!device->stateBlock->state.vertex_declaration)
4035 WARN("Called without a valid vertex declaration set.\n");
4036 return WINED3DERR_INVALIDCALL;
4039 if (device->stateBlock->state.user_stream)
4041 device_invalidate_state(device, STATE_INDEXBUFFER);
4042 device->stateBlock->state.user_stream = FALSE;
4044 vbo = index_buffer->buffer_object;
4046 if (device->stateBlock->state.index_format == WINED3DFMT_R16_UINT)
4047 index_size = 2;
4048 else
4049 index_size = 4;
4051 if (!gl_info->supported[ARB_DRAW_ELEMENTS_BASE_VERTEX] &&
4052 device->stateBlock->state.load_base_vertex_index != device->stateBlock->state.base_vertex_index)
4054 device->stateBlock->state.load_base_vertex_index = device->stateBlock->state.base_vertex_index;
4055 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4058 drawPrimitive(device, index_count, start_idx, index_size,
4059 vbo ? NULL : index_buffer->resource.allocatedMemory);
4061 return WINED3D_OK;
4064 HRESULT CDECL wined3d_device_draw_primitive_up(struct wined3d_device *device, UINT vertex_count,
4065 const void *stream_data, UINT stream_stride)
4067 struct wined3d_stream_state *stream;
4068 struct wined3d_buffer *vb;
4070 TRACE("device %p, vertex count %u, stream_data %p, stream_stride %u.\n",
4071 device, vertex_count, stream_data, stream_stride);
4073 if (!device->stateBlock->state.vertex_declaration)
4075 WARN("Called without a valid vertex declaration set.\n");
4076 return WINED3DERR_INVALIDCALL;
4079 /* Note in the following, it's not this type, but that's the purpose of streamIsUP */
4080 stream = &device->stateBlock->state.streams[0];
4081 vb = stream->buffer;
4082 stream->buffer = (struct wined3d_buffer *)stream_data;
4083 if (vb)
4084 wined3d_buffer_decref(vb);
4085 stream->offset = 0;
4086 stream->stride = stream_stride;
4087 device->stateBlock->state.user_stream = TRUE;
4088 if (device->stateBlock->state.load_base_vertex_index)
4090 device->stateBlock->state.load_base_vertex_index = 0;
4091 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4094 /* TODO: Only mark dirty if drawing from a different UP address */
4095 device_invalidate_state(device, STATE_STREAMSRC);
4097 drawPrimitive(device, vertex_count, 0, 0, NULL);
4099 /* MSDN specifies stream zero settings must be set to NULL */
4100 stream->buffer = NULL;
4101 stream->stride = 0;
4103 /* stream zero settings set to null at end, as per the msdn. No need to
4104 * mark dirty here, the app has to set the new stream sources or use UP
4105 * drawing again. */
4106 return WINED3D_OK;
4109 HRESULT CDECL wined3d_device_draw_indexed_primitive_up(struct wined3d_device *device,
4110 UINT index_count, const void *index_data, enum wined3d_format_id index_data_format_id,
4111 const void *stream_data, UINT stream_stride)
4113 struct wined3d_stream_state *stream;
4114 struct wined3d_buffer *vb, *ib;
4115 UINT index_size;
4117 TRACE("device %p, index_count %u, index_data %p, index_data_format %s, stream_data %p, stream_stride %u.\n",
4118 device, index_count, index_data, debug_d3dformat(index_data_format_id), stream_data, stream_stride);
4120 if (!device->stateBlock->state.vertex_declaration)
4122 WARN("(%p) : Called without a valid vertex declaration set\n", device);
4123 return WINED3DERR_INVALIDCALL;
4126 if (index_data_format_id == WINED3DFMT_R16_UINT)
4127 index_size = 2;
4128 else
4129 index_size = 4;
4131 stream = &device->stateBlock->state.streams[0];
4132 vb = stream->buffer;
4133 stream->buffer = (struct wined3d_buffer *)stream_data;
4134 if (vb)
4135 wined3d_buffer_decref(vb);
4136 stream->offset = 0;
4137 stream->stride = stream_stride;
4138 device->stateBlock->state.user_stream = TRUE;
4140 /* Set to 0 as per msdn. Do it now due to the stream source loading during drawPrimitive */
4141 device->stateBlock->state.base_vertex_index = 0;
4142 if (device->stateBlock->state.load_base_vertex_index)
4144 device->stateBlock->state.load_base_vertex_index = 0;
4145 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4147 /* Invalidate the state until we have nicer tracking of the stream source pointers */
4148 device_invalidate_state(device, STATE_STREAMSRC);
4149 device_invalidate_state(device, STATE_INDEXBUFFER);
4151 drawPrimitive(device, index_count, 0, index_size, index_data);
4153 /* MSDN specifies stream zero settings and index buffer must be set to NULL */
4154 stream->buffer = NULL;
4155 stream->stride = 0;
4156 ib = device->stateBlock->state.index_buffer;
4157 if (ib)
4159 wined3d_buffer_decref(ib);
4160 device->stateBlock->state.index_buffer = NULL;
4162 /* No need to mark the stream source state dirty here. Either the app calls UP drawing again, or it has to call
4163 * SetStreamSource to specify a vertex buffer
4166 return WINED3D_OK;
4169 HRESULT CDECL wined3d_device_draw_primitive_strided(struct wined3d_device *device,
4170 UINT vertex_count, const struct wined3d_strided_data *strided_data)
4172 /* Mark the state dirty until we have nicer tracking. It's fine to change
4173 * baseVertexIndex because that call is only called by ddraw which does
4174 * not need that value. */
4175 device_invalidate_state(device, STATE_VDECL);
4176 device_invalidate_state(device, STATE_STREAMSRC);
4177 device_invalidate_state(device, STATE_INDEXBUFFER);
4179 device->stateBlock->state.base_vertex_index = 0;
4180 device->up_strided = strided_data;
4181 drawPrimitive(device, vertex_count, 0, 0, NULL);
4182 device->up_strided = NULL;
4184 /* Invalidate the states again to make sure the values from the stateblock
4185 * are properly applied in the next regular draw. Note that the application-
4186 * provided strided data has ovwritten pretty much the entire vertex and
4187 * and index stream related states */
4188 device_invalidate_state(device, STATE_VDECL);
4189 device_invalidate_state(device, STATE_STREAMSRC);
4190 device_invalidate_state(device, STATE_INDEXBUFFER);
4191 return WINED3D_OK;
4194 HRESULT CDECL wined3d_device_draw_indexed_primitive_strided(struct wined3d_device *device,
4195 UINT index_count, const struct wined3d_strided_data *strided_data,
4196 UINT vertex_count, const void *index_data, enum wined3d_format_id index_data_format_id)
4198 UINT index_size = index_data_format_id == WINED3DFMT_R32_UINT ? 4 : 2;
4200 /* Mark the state dirty until we have nicer tracking
4201 * its fine to change baseVertexIndex because that call is only called by ddraw which does not need
4202 * that value.
4204 device_invalidate_state(device, STATE_VDECL);
4205 device_invalidate_state(device, STATE_STREAMSRC);
4206 device_invalidate_state(device, STATE_INDEXBUFFER);
4208 device->stateBlock->state.user_stream = TRUE;
4209 device->stateBlock->state.base_vertex_index = 0;
4210 device->up_strided = strided_data;
4211 drawPrimitive(device, index_count, 0, index_size, index_data);
4212 device->up_strided = NULL;
4214 device_invalidate_state(device, STATE_VDECL);
4215 device_invalidate_state(device, STATE_STREAMSRC);
4216 device_invalidate_state(device, STATE_INDEXBUFFER);
4217 return WINED3D_OK;
4220 /* This is a helper function for UpdateTexture, there is no UpdateVolume method in D3D. */
4221 static HRESULT device_update_volume(struct wined3d_device *device,
4222 struct wined3d_volume *src_volume, struct wined3d_volume *dst_volume)
4224 struct wined3d_map_desc src;
4225 struct wined3d_map_desc dst;
4226 HRESULT hr;
4228 TRACE("device %p, src_volume %p, dst_volume %p.\n",
4229 device, src_volume, dst_volume);
4231 /* TODO: Implement direct loading into the gl volume instead of using
4232 * memcpy and dirtification to improve loading performance. */
4233 hr = wined3d_volume_map(src_volume, &src, NULL, WINED3DLOCK_READONLY);
4234 if (FAILED(hr)) return hr;
4235 hr = wined3d_volume_map(dst_volume, &dst, NULL, WINED3DLOCK_DISCARD);
4236 if (FAILED(hr))
4238 wined3d_volume_unmap(src_volume);
4239 return hr;
4242 memcpy(dst.data, src.data, dst_volume->resource.size);
4244 hr = wined3d_volume_unmap(dst_volume);
4245 if (FAILED(hr))
4246 wined3d_volume_unmap(src_volume);
4247 else
4248 hr = wined3d_volume_unmap(src_volume);
4250 return hr;
4253 HRESULT CDECL wined3d_device_update_texture(struct wined3d_device *device,
4254 struct wined3d_texture *src_texture, struct wined3d_texture *dst_texture)
4256 enum wined3d_resource_type type;
4257 unsigned int level_count, i;
4258 HRESULT hr;
4260 TRACE("device %p, src_texture %p, dst_texture %p.\n", device, src_texture, dst_texture);
4262 /* Verify that the source and destination textures are non-NULL. */
4263 if (!src_texture || !dst_texture)
4265 WARN("Source and destination textures must be non-NULL, returning WINED3DERR_INVALIDCALL.\n");
4266 return WINED3DERR_INVALIDCALL;
4269 if (src_texture == dst_texture)
4271 WARN("Source and destination are the same object, returning WINED3DERR_INVALIDCALL.\n");
4272 return WINED3DERR_INVALIDCALL;
4275 /* Verify that the source and destination textures are the same type. */
4276 type = src_texture->resource.type;
4277 if (dst_texture->resource.type != type)
4279 WARN("Source and destination have different types, returning WINED3DERR_INVALIDCALL.\n");
4280 return WINED3DERR_INVALIDCALL;
4283 /* Check that both textures have the identical numbers of levels. */
4284 level_count = wined3d_texture_get_level_count(src_texture);
4285 if (wined3d_texture_get_level_count(dst_texture) != level_count)
4287 WARN("Source and destination have different level counts, returning WINED3DERR_INVALIDCALL.\n");
4288 return WINED3DERR_INVALIDCALL;
4291 /* Make sure that the destination texture is loaded. */
4292 dst_texture->texture_ops->texture_preload(dst_texture, SRGB_RGB);
4294 /* Update every surface level of the texture. */
4295 switch (type)
4297 case WINED3D_RTYPE_TEXTURE:
4299 struct wined3d_surface *src_surface;
4300 struct wined3d_surface *dst_surface;
4302 for (i = 0; i < level_count; ++i)
4304 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4305 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4306 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4307 if (FAILED(hr))
4309 WARN("Failed to update surface, hr %#x.\n", hr);
4310 return hr;
4313 break;
4316 case WINED3D_RTYPE_CUBE_TEXTURE:
4318 struct wined3d_surface *src_surface;
4319 struct wined3d_surface *dst_surface;
4321 for (i = 0; i < level_count * 6; ++i)
4323 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4324 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4325 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4326 if (FAILED(hr))
4328 WARN("Failed to update surface, hr %#x.\n", hr);
4329 return hr;
4332 break;
4335 case WINED3D_RTYPE_VOLUME_TEXTURE:
4337 for (i = 0; i < level_count; ++i)
4339 hr = device_update_volume(device,
4340 volume_from_resource(wined3d_texture_get_sub_resource(src_texture, i)),
4341 volume_from_resource(wined3d_texture_get_sub_resource(dst_texture, i)));
4342 if (FAILED(hr))
4344 WARN("Failed to update volume, hr %#x.\n", hr);
4345 return hr;
4348 break;
4351 default:
4352 FIXME("Unsupported texture type %#x.\n", type);
4353 return WINED3DERR_INVALIDCALL;
4356 return WINED3D_OK;
4359 HRESULT CDECL wined3d_device_get_front_buffer_data(const struct wined3d_device *device,
4360 UINT swapchain_idx, struct wined3d_surface *dst_surface)
4362 struct wined3d_swapchain *swapchain;
4363 HRESULT hr;
4365 TRACE("device %p, swapchain_idx %u, dst_surface %p.\n", device, swapchain_idx, dst_surface);
4367 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
4368 if (FAILED(hr)) return hr;
4370 hr = wined3d_swapchain_get_front_buffer_data(swapchain, dst_surface);
4371 wined3d_swapchain_decref(swapchain);
4373 return hr;
4376 HRESULT CDECL wined3d_device_validate_device(const struct wined3d_device *device, DWORD *num_passes)
4378 const struct wined3d_state *state = &device->stateBlock->state;
4379 struct wined3d_texture *texture;
4380 DWORD i;
4382 TRACE("device %p, num_passes %p.\n", device, num_passes);
4384 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
4386 if (state->sampler_states[i][WINED3D_SAMP_MIN_FILTER] == WINED3D_TEXF_NONE)
4388 WARN("Sampler state %u has minfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4389 return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4391 if (state->sampler_states[i][WINED3D_SAMP_MAG_FILTER] == WINED3D_TEXF_NONE)
4393 WARN("Sampler state %u has magfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4394 return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4397 texture = state->textures[i];
4398 if (!texture || texture->resource.format->flags & WINED3DFMT_FLAG_FILTERING) continue;
4400 if (state->sampler_states[i][WINED3D_SAMP_MAG_FILTER] != WINED3D_TEXF_POINT)
4402 WARN("Non-filterable texture and mag filter enabled on samper %u, returning E_FAIL\n", i);
4403 return E_FAIL;
4405 if (state->sampler_states[i][WINED3D_SAMP_MIN_FILTER] != WINED3D_TEXF_POINT)
4407 WARN("Non-filterable texture and min filter enabled on samper %u, returning E_FAIL\n", i);
4408 return E_FAIL;
4410 if (state->sampler_states[i][WINED3D_SAMP_MIP_FILTER] != WINED3D_TEXF_NONE
4411 && state->sampler_states[i][WINED3D_SAMP_MIP_FILTER] != WINED3D_TEXF_POINT)
4413 WARN("Non-filterable texture and mip filter enabled on samper %u, returning E_FAIL\n", i);
4414 return E_FAIL;
4418 if (state->render_states[WINED3D_RS_ZENABLE] || state->render_states[WINED3D_RS_ZWRITEENABLE]
4419 || state->render_states[WINED3D_RS_STENCILENABLE])
4421 struct wined3d_surface *ds = device->fb.depth_stencil;
4422 struct wined3d_surface *target = device->fb.render_targets[0];
4424 if(ds && target
4425 && (ds->resource.width < target->resource.width || ds->resource.height < target->resource.height))
4427 WARN("Depth stencil is smaller than the color buffer, returning D3DERR_CONFLICTINGRENDERSTATE\n");
4428 return WINED3DERR_CONFLICTINGRENDERSTATE;
4432 /* return a sensible default */
4433 *num_passes = 1;
4435 TRACE("returning D3D_OK\n");
4436 return WINED3D_OK;
4439 HRESULT CDECL wined3d_device_set_software_vertex_processing(struct wined3d_device *device, BOOL software)
4441 static BOOL warned;
4443 TRACE("device %p, software %#x.\n", device, software);
4445 if (!warned)
4447 FIXME("device %p, software %#x stub!\n", device, software);
4448 warned = TRUE;
4451 device->softwareVertexProcessing = software;
4453 return WINED3D_OK;
4456 BOOL CDECL wined3d_device_get_software_vertex_processing(const struct wined3d_device *device)
4458 static BOOL warned;
4460 TRACE("device %p.\n", device);
4462 if (!warned)
4464 TRACE("device %p stub!\n", device);
4465 warned = TRUE;
4468 return device->softwareVertexProcessing;
4471 HRESULT CDECL wined3d_device_get_raster_status(const struct wined3d_device *device,
4472 UINT swapchain_idx, struct wined3d_raster_status *raster_status)
4474 struct wined3d_swapchain *swapchain;
4475 HRESULT hr;
4477 TRACE("device %p, swapchain_idx %u, raster_status %p.\n",
4478 device, swapchain_idx, raster_status);
4480 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
4481 if (FAILED(hr))
4483 WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
4484 return hr;
4487 hr = wined3d_swapchain_get_raster_status(swapchain, raster_status);
4488 wined3d_swapchain_decref(swapchain);
4489 if (FAILED(hr))
4491 WARN("Failed to get raster status, hr %#x.\n", hr);
4492 return hr;
4495 return WINED3D_OK;
4498 HRESULT CDECL wined3d_device_set_npatch_mode(struct wined3d_device *device, float segments)
4500 static BOOL warned;
4502 TRACE("device %p, segments %.8e.\n", device, segments);
4504 if (segments != 0.0f)
4506 if (!warned)
4508 FIXME("device %p, segments %.8e stub!\n", device, segments);
4509 warned = TRUE;
4513 return WINED3D_OK;
4516 float CDECL wined3d_device_get_npatch_mode(const struct wined3d_device *device)
4518 static BOOL warned;
4520 TRACE("device %p.\n", device);
4522 if (!warned)
4524 FIXME("device %p stub!\n", device);
4525 warned = TRUE;
4528 return 0.0f;
4531 HRESULT CDECL wined3d_device_update_surface(struct wined3d_device *device,
4532 struct wined3d_surface *src_surface, const RECT *src_rect,
4533 struct wined3d_surface *dst_surface, const POINT *dst_point)
4535 TRACE("device %p, src_surface %p, src_rect %s, dst_surface %p, dst_point %s.\n",
4536 device, src_surface, wine_dbgstr_rect(src_rect),
4537 dst_surface, wine_dbgstr_point(dst_point));
4539 if (src_surface->resource.pool != WINED3D_POOL_SYSTEM_MEM || dst_surface->resource.pool != WINED3D_POOL_DEFAULT)
4541 WARN("source %p must be SYSTEMMEM and dest %p must be DEFAULT, returning WINED3DERR_INVALIDCALL\n",
4542 src_surface, dst_surface);
4543 return WINED3DERR_INVALIDCALL;
4546 return surface_upload_from_surface(dst_surface, dst_point, src_surface, src_rect);
4549 HRESULT CDECL wined3d_device_draw_rect_patch(struct wined3d_device *device, UINT handle,
4550 const float *num_segs, const struct wined3d_rect_patch_info *rect_patch_info)
4552 struct wined3d_rect_patch *patch;
4553 GLenum old_primitive_type;
4554 unsigned int i;
4555 struct list *e;
4556 BOOL found;
4558 TRACE("device %p, handle %#x, num_segs %p, rect_patch_info %p.\n",
4559 device, handle, num_segs, rect_patch_info);
4561 if (!(handle || rect_patch_info))
4563 /* TODO: Write a test for the return value, thus the FIXME */
4564 FIXME("Both handle and rect_patch_info are NULL.\n");
4565 return WINED3DERR_INVALIDCALL;
4568 if (handle)
4570 i = PATCHMAP_HASHFUNC(handle);
4571 found = FALSE;
4572 LIST_FOR_EACH(e, &device->patches[i])
4574 patch = LIST_ENTRY(e, struct wined3d_rect_patch, entry);
4575 if (patch->Handle == handle)
4577 found = TRUE;
4578 break;
4582 if (!found)
4584 TRACE("Patch does not exist. Creating a new one\n");
4585 patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4586 patch->Handle = handle;
4587 list_add_head(&device->patches[i], &patch->entry);
4588 } else {
4589 TRACE("Found existing patch %p\n", patch);
4592 else
4594 /* Since opengl does not load tesselated vertex attributes into numbered vertex
4595 * attributes we have to tesselate, read back, and draw. This needs a patch
4596 * management structure instance. Create one.
4598 * A possible improvement is to check if a vertex shader is used, and if not directly
4599 * draw the patch.
4601 FIXME("Drawing an uncached patch. This is slow\n");
4602 patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4605 if (num_segs[0] != patch->numSegs[0] || num_segs[1] != patch->numSegs[1]
4606 || num_segs[2] != patch->numSegs[2] || num_segs[3] != patch->numSegs[3]
4607 || (rect_patch_info && memcmp(rect_patch_info, &patch->rect_patch_info, sizeof(*rect_patch_info))))
4609 HRESULT hr;
4610 TRACE("Tesselation density or patch info changed, retesselating\n");
4612 if (rect_patch_info)
4613 patch->rect_patch_info = *rect_patch_info;
4615 patch->numSegs[0] = num_segs[0];
4616 patch->numSegs[1] = num_segs[1];
4617 patch->numSegs[2] = num_segs[2];
4618 patch->numSegs[3] = num_segs[3];
4620 hr = tesselate_rectpatch(device, patch);
4621 if (FAILED(hr))
4623 WARN("Patch tesselation failed.\n");
4625 /* Do not release the handle to store the params of the patch */
4626 if (!handle)
4627 HeapFree(GetProcessHeap(), 0, patch);
4629 return hr;
4633 old_primitive_type = device->stateBlock->state.gl_primitive_type;
4634 device->stateBlock->state.gl_primitive_type = GL_TRIANGLES;
4635 wined3d_device_draw_primitive_strided(device, patch->numSegs[0] * patch->numSegs[1] * 2 * 3, &patch->strided);
4636 device->stateBlock->state.gl_primitive_type = old_primitive_type;
4638 /* Destroy uncached patches */
4639 if (!handle)
4641 HeapFree(GetProcessHeap(), 0, patch->mem);
4642 HeapFree(GetProcessHeap(), 0, patch);
4644 return WINED3D_OK;
4647 HRESULT CDECL wined3d_device_draw_tri_patch(struct wined3d_device *device, UINT handle,
4648 const float *segment_count, const struct wined3d_tri_patch_info *patch_info)
4650 FIXME("device %p, handle %#x, segment_count %p, patch_info %p stub!\n",
4651 device, handle, segment_count, patch_info);
4653 return WINED3D_OK;
4656 HRESULT CDECL wined3d_device_delete_patch(struct wined3d_device *device, UINT handle)
4658 struct wined3d_rect_patch *patch;
4659 struct list *e;
4660 int i;
4662 TRACE("device %p, handle %#x.\n", device, handle);
4664 i = PATCHMAP_HASHFUNC(handle);
4665 LIST_FOR_EACH(e, &device->patches[i])
4667 patch = LIST_ENTRY(e, struct wined3d_rect_patch, entry);
4668 if (patch->Handle == handle)
4670 TRACE("Deleting patch %p\n", patch);
4671 list_remove(&patch->entry);
4672 HeapFree(GetProcessHeap(), 0, patch->mem);
4673 HeapFree(GetProcessHeap(), 0, patch);
4674 return WINED3D_OK;
4678 /* TODO: Write a test for the return value */
4679 FIXME("Attempt to destroy nonexistent patch\n");
4680 return WINED3DERR_INVALIDCALL;
4683 /* Do not call while under the GL lock. */
4684 HRESULT CDECL wined3d_device_color_fill(struct wined3d_device *device,
4685 struct wined3d_surface *surface, const RECT *rect, const struct wined3d_color *color)
4687 RECT r;
4689 TRACE("device %p, surface %p, rect %s, color {%.8e, %.8e, %.8e, %.8e}.\n",
4690 device, surface, wine_dbgstr_rect(rect),
4691 color->r, color->g, color->b, color->a);
4693 if (surface->resource.pool != WINED3D_POOL_DEFAULT && surface->resource.pool != WINED3D_POOL_SYSTEM_MEM)
4695 WARN("Color-fill not allowed on %s surfaces.\n", debug_d3dpool(surface->resource.pool));
4696 return WINED3DERR_INVALIDCALL;
4699 if (!rect)
4701 SetRect(&r, 0, 0, surface->resource.width, surface->resource.height);
4702 rect = &r;
4705 return surface_color_fill(surface, rect, color);
4708 /* Do not call while under the GL lock. */
4709 void CDECL wined3d_device_clear_rendertarget_view(struct wined3d_device *device,
4710 struct wined3d_rendertarget_view *rendertarget_view, const struct wined3d_color *color)
4712 struct wined3d_resource *resource;
4713 HRESULT hr;
4714 RECT rect;
4716 resource = rendertarget_view->resource;
4717 if (resource->type != WINED3D_RTYPE_SURFACE)
4719 FIXME("Only supported on surface resources\n");
4720 return;
4723 SetRect(&rect, 0, 0, resource->width, resource->height);
4724 hr = surface_color_fill(surface_from_resource(resource), &rect, color);
4725 if (FAILED(hr)) ERR("Color fill failed, hr %#x.\n", hr);
4728 HRESULT CDECL wined3d_device_get_render_target(const struct wined3d_device *device,
4729 UINT render_target_idx, struct wined3d_surface **render_target)
4731 TRACE("device %p, render_target_idx %u, render_target %p.\n",
4732 device, render_target_idx, render_target);
4734 if (render_target_idx >= device->adapter->gl_info.limits.buffers)
4736 WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
4737 return WINED3DERR_INVALIDCALL;
4740 *render_target = device->fb.render_targets[render_target_idx];
4741 TRACE("Returning render target %p.\n", *render_target);
4743 if (!*render_target)
4744 return WINED3DERR_NOTFOUND;
4746 wined3d_surface_incref(*render_target);
4748 return WINED3D_OK;
4751 HRESULT CDECL wined3d_device_get_depth_stencil(const struct wined3d_device *device,
4752 struct wined3d_surface **depth_stencil)
4754 TRACE("device %p, depth_stencil %p.\n", device, depth_stencil);
4756 *depth_stencil = device->fb.depth_stencil;
4757 TRACE("Returning depth/stencil surface %p.\n", *depth_stencil);
4759 if (!*depth_stencil)
4760 return WINED3DERR_NOTFOUND;
4762 wined3d_surface_incref(*depth_stencil);
4764 return WINED3D_OK;
4767 HRESULT CDECL wined3d_device_set_render_target(struct wined3d_device *device,
4768 UINT render_target_idx, struct wined3d_surface *render_target, BOOL set_viewport)
4770 struct wined3d_surface *prev;
4772 TRACE("device %p, render_target_idx %u, render_target %p, set_viewport %#x.\n",
4773 device, render_target_idx, render_target, set_viewport);
4775 if (render_target_idx >= device->adapter->gl_info.limits.buffers)
4777 WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
4778 return WINED3DERR_INVALIDCALL;
4781 prev = device->fb.render_targets[render_target_idx];
4782 if (render_target == prev)
4784 TRACE("Trying to do a NOP SetRenderTarget operation.\n");
4785 return WINED3D_OK;
4788 /* Render target 0 can't be set to NULL. */
4789 if (!render_target && !render_target_idx)
4791 WARN("Trying to set render target 0 to NULL.\n");
4792 return WINED3DERR_INVALIDCALL;
4795 if (render_target && !(render_target->resource.usage & WINED3DUSAGE_RENDERTARGET))
4797 FIXME("Surface %p doesn't have render target usage.\n", render_target);
4798 return WINED3DERR_INVALIDCALL;
4801 if (render_target)
4802 wined3d_surface_incref(render_target);
4803 device->fb.render_targets[render_target_idx] = render_target;
4804 /* Release after the assignment, to prevent device_resource_released()
4805 * from seeing the surface as still in use. */
4806 if (prev)
4807 wined3d_surface_decref(prev);
4809 /* Render target 0 is special. */
4810 if (!render_target_idx && set_viewport)
4812 /* Set the viewport and scissor rectangles, if requested. Tests show
4813 * that stateblock recording is ignored, the change goes directly
4814 * into the primary stateblock. */
4815 device->stateBlock->state.viewport.height = device->fb.render_targets[0]->resource.height;
4816 device->stateBlock->state.viewport.width = device->fb.render_targets[0]->resource.width;
4817 device->stateBlock->state.viewport.x = 0;
4818 device->stateBlock->state.viewport.y = 0;
4819 device->stateBlock->state.viewport.max_z = 1.0f;
4820 device->stateBlock->state.viewport.min_z = 0.0f;
4821 device_invalidate_state(device, STATE_VIEWPORT);
4823 device->stateBlock->state.scissor_rect.top = 0;
4824 device->stateBlock->state.scissor_rect.left = 0;
4825 device->stateBlock->state.scissor_rect.right = device->stateBlock->state.viewport.width;
4826 device->stateBlock->state.scissor_rect.bottom = device->stateBlock->state.viewport.height;
4827 device_invalidate_state(device, STATE_SCISSORRECT);
4830 device_invalidate_state(device, STATE_FRAMEBUFFER);
4832 return WINED3D_OK;
4835 HRESULT CDECL wined3d_device_set_depth_stencil(struct wined3d_device *device, struct wined3d_surface *depth_stencil)
4837 struct wined3d_surface *prev = device->fb.depth_stencil;
4839 TRACE("device %p, depth_stencil %p, old depth_stencil %p.\n",
4840 device, depth_stencil, prev);
4842 if (prev == depth_stencil)
4844 TRACE("Trying to do a NOP SetRenderTarget operation.\n");
4845 return WINED3D_OK;
4848 if (prev)
4850 if (device->swapchains[0]->desc.flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
4851 || prev->flags & SFLAG_DISCARD)
4853 surface_modify_ds_location(prev, SFLAG_DISCARDED,
4854 prev->resource.width, prev->resource.height);
4855 if (prev == device->onscreen_depth_stencil)
4857 wined3d_surface_decref(device->onscreen_depth_stencil);
4858 device->onscreen_depth_stencil = NULL;
4863 device->fb.depth_stencil = depth_stencil;
4864 if (depth_stencil)
4865 wined3d_surface_incref(depth_stencil);
4867 if (!prev != !depth_stencil)
4869 /* Swapping NULL / non NULL depth stencil affects the depth and tests */
4870 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_ZENABLE));
4871 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_STENCILENABLE));
4872 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_STENCILWRITEMASK));
4873 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_DEPTHBIAS));
4875 else if (prev && prev->resource.format->depth_size != depth_stencil->resource.format->depth_size)
4877 device_invalidate_state(device, STATE_RENDER(WINED3D_RS_DEPTHBIAS));
4879 if (prev)
4880 wined3d_surface_decref(prev);
4882 device_invalidate_state(device, STATE_FRAMEBUFFER);
4884 return WINED3D_OK;
4887 HRESULT CDECL wined3d_device_set_cursor_properties(struct wined3d_device *device,
4888 UINT x_hotspot, UINT y_hotspot, struct wined3d_surface *cursor_image)
4890 TRACE("device %p, x_hotspot %u, y_hotspot %u, cursor_image %p.\n",
4891 device, x_hotspot, y_hotspot, cursor_image);
4893 /* some basic validation checks */
4894 if (device->cursorTexture)
4896 struct wined3d_context *context = context_acquire(device, NULL);
4897 ENTER_GL();
4898 glDeleteTextures(1, &device->cursorTexture);
4899 LEAVE_GL();
4900 context_release(context);
4901 device->cursorTexture = 0;
4904 if (cursor_image)
4906 struct wined3d_map_desc map_desc;
4908 /* MSDN: Cursor must be A8R8G8B8 */
4909 if (cursor_image->resource.format->id != WINED3DFMT_B8G8R8A8_UNORM)
4911 WARN("surface %p has an invalid format.\n", cursor_image);
4912 return WINED3DERR_INVALIDCALL;
4915 /* MSDN: Cursor must be smaller than the display mode */
4916 if (cursor_image->resource.width > device->adapter->screen_size.cx
4917 || cursor_image->resource.height > device->adapter->screen_size.cy)
4919 WARN("Surface %p dimensions are %ux%u, but screen dimensions are %ux%u.\n",
4920 cursor_image, cursor_image->resource.width, cursor_image->resource.height,
4921 device->adapter->screen_size.cx, device->adapter->screen_size.cy);
4922 return WINED3DERR_INVALIDCALL;
4925 /* TODO: MSDN: Cursor sizes must be a power of 2 */
4927 /* Do not store the surface's pointer because the application may
4928 * release it after setting the cursor image. Windows doesn't
4929 * addref the set surface, so we can't do this either without
4930 * creating circular refcount dependencies. Copy out the gl texture
4931 * instead. */
4932 device->cursorWidth = cursor_image->resource.width;
4933 device->cursorHeight = cursor_image->resource.height;
4934 if (SUCCEEDED(wined3d_surface_map(cursor_image, &map_desc, NULL, WINED3DLOCK_READONLY)))
4936 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4937 const struct wined3d_format *format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
4938 struct wined3d_context *context;
4939 char *mem, *bits = map_desc.data;
4940 GLint intfmt = format->glInternal;
4941 GLint gl_format = format->glFormat;
4942 GLint type = format->glType;
4943 INT height = device->cursorHeight;
4944 INT width = device->cursorWidth;
4945 INT bpp = format->byte_count;
4946 INT i;
4948 /* Reformat the texture memory (pitch and width can be
4949 * different) */
4950 mem = HeapAlloc(GetProcessHeap(), 0, width * height * bpp);
4951 for (i = 0; i < height; ++i)
4952 memcpy(&mem[width * bpp * i], &bits[map_desc.row_pitch * i], width * bpp);
4953 wined3d_surface_unmap(cursor_image);
4955 context = context_acquire(device, NULL);
4957 ENTER_GL();
4959 if (gl_info->supported[APPLE_CLIENT_STORAGE])
4961 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
4962 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
4965 invalidate_active_texture(device, context);
4966 /* Create a new cursor texture */
4967 glGenTextures(1, &device->cursorTexture);
4968 checkGLcall("glGenTextures");
4969 context_bind_texture(context, GL_TEXTURE_2D, device->cursorTexture);
4970 /* Copy the bitmap memory into the cursor texture */
4971 glTexImage2D(GL_TEXTURE_2D, 0, intfmt, width, height, 0, gl_format, type, mem);
4972 checkGLcall("glTexImage2D");
4973 HeapFree(GetProcessHeap(), 0, mem);
4975 if (gl_info->supported[APPLE_CLIENT_STORAGE])
4977 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
4978 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
4981 LEAVE_GL();
4983 context_release(context);
4985 else
4987 FIXME("A cursor texture was not returned.\n");
4988 device->cursorTexture = 0;
4991 if (cursor_image->resource.width == 32 && cursor_image->resource.height == 32)
4993 UINT mask_size = cursor_image->resource.width * cursor_image->resource.height / 8;
4994 ICONINFO cursorInfo;
4995 DWORD *maskBits;
4996 HCURSOR cursor;
4998 /* 32-bit user32 cursors ignore the alpha channel if it's all
4999 * zeroes, and use the mask instead. Fill the mask with all ones
5000 * to ensure we still get a fully transparent cursor. */
5001 maskBits = HeapAlloc(GetProcessHeap(), 0, mask_size);
5002 memset(maskBits, 0xff, mask_size);
5003 wined3d_surface_map(cursor_image, &map_desc, NULL,
5004 WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY);
5005 TRACE("width: %u height: %u.\n", cursor_image->resource.width, cursor_image->resource.height);
5007 cursorInfo.fIcon = FALSE;
5008 cursorInfo.xHotspot = x_hotspot;
5009 cursorInfo.yHotspot = y_hotspot;
5010 cursorInfo.hbmMask = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
5011 1, 1, maskBits);
5012 cursorInfo.hbmColor = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
5013 1, 32, map_desc.data);
5014 wined3d_surface_unmap(cursor_image);
5015 /* Create our cursor and clean up. */
5016 cursor = CreateIconIndirect(&cursorInfo);
5017 if (cursorInfo.hbmMask) DeleteObject(cursorInfo.hbmMask);
5018 if (cursorInfo.hbmColor) DeleteObject(cursorInfo.hbmColor);
5019 if (device->hardwareCursor) DestroyCursor(device->hardwareCursor);
5020 device->hardwareCursor = cursor;
5021 if (device->bCursorVisible) SetCursor( cursor );
5022 HeapFree(GetProcessHeap(), 0, maskBits);
5026 device->xHotSpot = x_hotspot;
5027 device->yHotSpot = y_hotspot;
5028 return WINED3D_OK;
5031 void CDECL wined3d_device_set_cursor_position(struct wined3d_device *device,
5032 int x_screen_space, int y_screen_space, DWORD flags)
5034 TRACE("device %p, x %d, y %d, flags %#x.\n",
5035 device, x_screen_space, y_screen_space, flags);
5037 device->xScreenSpace = x_screen_space;
5038 device->yScreenSpace = y_screen_space;
5040 if (device->hardwareCursor)
5042 POINT pt;
5044 GetCursorPos( &pt );
5045 if (x_screen_space == pt.x && y_screen_space == pt.y)
5046 return;
5047 SetCursorPos( x_screen_space, y_screen_space );
5049 /* Switch to the software cursor if position diverges from the hardware one. */
5050 GetCursorPos( &pt );
5051 if (x_screen_space != pt.x || y_screen_space != pt.y)
5053 if (device->bCursorVisible) SetCursor( NULL );
5054 DestroyCursor( device->hardwareCursor );
5055 device->hardwareCursor = 0;
5060 BOOL CDECL wined3d_device_show_cursor(struct wined3d_device *device, BOOL show)
5062 BOOL oldVisible = device->bCursorVisible;
5064 TRACE("device %p, show %#x.\n", device, show);
5067 * When ShowCursor is first called it should make the cursor appear at the OS's last
5068 * known cursor position.
5070 if (show && !oldVisible)
5072 POINT pt;
5073 GetCursorPos(&pt);
5074 device->xScreenSpace = pt.x;
5075 device->yScreenSpace = pt.y;
5078 if (device->hardwareCursor)
5080 device->bCursorVisible = show;
5081 if (show)
5082 SetCursor(device->hardwareCursor);
5083 else
5084 SetCursor(NULL);
5086 else
5088 if (device->cursorTexture)
5089 device->bCursorVisible = show;
5092 return oldVisible;
5095 void CDECL wined3d_device_evict_managed_resources(struct wined3d_device *device)
5097 struct wined3d_resource *resource, *cursor;
5099 TRACE("device %p.\n", device);
5101 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5103 TRACE("Checking resource %p for eviction.\n", resource);
5105 if (resource->pool == WINED3D_POOL_MANAGED)
5107 TRACE("Evicting %p.\n", resource);
5108 resource->resource_ops->resource_unload(resource);
5112 /* Invalidate stream sources, the buffer(s) may have been evicted. */
5113 device_invalidate_state(device, STATE_STREAMSRC);
5116 static BOOL is_display_mode_supported(const struct wined3d_device *device,
5117 const struct wined3d_swapchain_desc *swapchain_desc)
5119 struct wined3d_display_mode m;
5120 UINT i, count;
5121 HRESULT hr;
5123 /* All Windowed modes are supported, as is leaving the current mode */
5124 if (swapchain_desc->windowed)
5125 return TRUE;
5126 if (!swapchain_desc->backbuffer_width)
5127 return TRUE;
5128 if (!swapchain_desc->backbuffer_height)
5129 return TRUE;
5131 count = wined3d_get_adapter_mode_count(device->wined3d, device->adapter->ordinal, WINED3DFMT_UNKNOWN);
5132 for (i = 0; i < count; ++i)
5134 memset(&m, 0, sizeof(m));
5135 hr = wined3d_enum_adapter_modes(device->wined3d, device->adapter->ordinal, WINED3DFMT_UNKNOWN, i, &m);
5136 if (FAILED(hr))
5137 ERR("Failed to enumerate adapter mode.\n");
5138 if (m.width == swapchain_desc->backbuffer_width && m.height == swapchain_desc->backbuffer_height)
5139 /* Mode found, it is supported. */
5140 return TRUE;
5142 /* Mode not found -> not supported */
5143 return FALSE;
5146 /* Do not call while under the GL lock. */
5147 static void delete_opengl_contexts(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
5149 struct wined3d_resource *resource, *cursor;
5150 const struct wined3d_gl_info *gl_info;
5151 struct wined3d_context *context;
5152 struct wined3d_shader *shader;
5154 context = context_acquire(device, NULL);
5155 gl_info = context->gl_info;
5157 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5159 TRACE("Unloading resource %p.\n", resource);
5161 resource->resource_ops->resource_unload(resource);
5164 LIST_FOR_EACH_ENTRY(shader, &device->shaders, struct wined3d_shader, shader_list_entry)
5166 device->shader_backend->shader_destroy(shader);
5169 ENTER_GL();
5170 if (device->depth_blt_texture)
5172 glDeleteTextures(1, &device->depth_blt_texture);
5173 device->depth_blt_texture = 0;
5175 if (device->cursorTexture)
5177 glDeleteTextures(1, &device->cursorTexture);
5178 device->cursorTexture = 0;
5180 LEAVE_GL();
5182 device->blitter->free_private(device);
5183 device->frag_pipe->free_private(device);
5184 device->shader_backend->shader_free_private(device);
5185 destroy_dummy_textures(device, gl_info);
5187 context_release(context);
5189 while (device->context_count)
5191 swapchain_destroy_contexts(device->contexts[0]->swapchain);
5194 HeapFree(GetProcessHeap(), 0, swapchain->context);
5195 swapchain->context = NULL;
5198 /* Do not call while under the GL lock. */
5199 static HRESULT create_primary_opengl_context(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
5201 struct wined3d_context *context;
5202 struct wined3d_surface *target;
5203 HRESULT hr;
5205 /* Recreate the primary swapchain's context */
5206 swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(*swapchain->context));
5207 if (!swapchain->context)
5209 ERR("Failed to allocate memory for swapchain context array.\n");
5210 return E_OUTOFMEMORY;
5213 target = swapchain->back_buffers ? swapchain->back_buffers[0] : swapchain->front_buffer;
5214 if (!(context = context_create(swapchain, target, swapchain->ds_format)))
5216 WARN("Failed to create context.\n");
5217 HeapFree(GetProcessHeap(), 0, swapchain->context);
5218 return E_FAIL;
5221 swapchain->context[0] = context;
5222 swapchain->num_contexts = 1;
5223 create_dummy_textures(device, context);
5224 context_release(context);
5226 hr = device->shader_backend->shader_alloc_private(device);
5227 if (FAILED(hr))
5229 ERR("Failed to allocate shader private data, hr %#x.\n", hr);
5230 goto err;
5233 hr = device->frag_pipe->alloc_private(device);
5234 if (FAILED(hr))
5236 ERR("Failed to allocate fragment pipe private data, hr %#x.\n", hr);
5237 device->shader_backend->shader_free_private(device);
5238 goto err;
5241 hr = device->blitter->alloc_private(device);
5242 if (FAILED(hr))
5244 ERR("Failed to allocate blitter private data, hr %#x.\n", hr);
5245 device->frag_pipe->free_private(device);
5246 device->shader_backend->shader_free_private(device);
5247 goto err;
5250 return WINED3D_OK;
5252 err:
5253 context_acquire(device, NULL);
5254 destroy_dummy_textures(device, context->gl_info);
5255 context_release(context);
5256 context_destroy(device, context);
5257 HeapFree(GetProcessHeap(), 0, swapchain->context);
5258 swapchain->num_contexts = 0;
5259 return hr;
5262 /* Do not call while under the GL lock. */
5263 HRESULT CDECL wined3d_device_reset(struct wined3d_device *device,
5264 const struct wined3d_swapchain_desc *swapchain_desc,
5265 wined3d_device_reset_cb callback)
5267 struct wined3d_resource *resource, *cursor;
5268 struct wined3d_swapchain *swapchain;
5269 struct wined3d_display_mode mode;
5270 BOOL DisplayModeChanged = FALSE;
5271 BOOL update_desc = FALSE;
5272 HRESULT hr;
5274 TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
5276 stateblock_unbind_resources(device->stateBlock);
5278 if (device->onscreen_depth_stencil)
5280 wined3d_surface_decref(device->onscreen_depth_stencil);
5281 device->onscreen_depth_stencil = NULL;
5284 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5286 TRACE("Enumerating resource %p.\n", resource);
5287 if (FAILED(hr = callback(resource)))
5288 return hr;
5291 hr = wined3d_device_get_swapchain(device, 0, &swapchain);
5292 if (FAILED(hr))
5294 ERR("Failed to get the first implicit swapchain\n");
5295 return hr;
5298 if (!is_display_mode_supported(device, swapchain_desc))
5300 WARN("Rejecting reset() call because the requested display mode is not supported.\n");
5301 WARN("Requested mode: %ux%u.\n",
5302 swapchain_desc->backbuffer_width,
5303 swapchain_desc->backbuffer_height);
5304 wined3d_swapchain_decref(swapchain);
5305 return WINED3DERR_INVALIDCALL;
5308 /* Is it necessary to recreate the gl context? Actually every setting can be changed
5309 * on an existing gl context, so there's no real need for recreation.
5311 * TODO: Figure out how Reset influences resources in D3DPOOL_DEFAULT, D3DPOOL_SYSTEMMEMORY and D3DPOOL_MANAGED
5313 * TODO: Figure out what happens to explicit swapchains, or if we have more than one implicit swapchain
5315 TRACE("New params:\n");
5316 TRACE("backbuffer_width %u\n", swapchain_desc->backbuffer_width);
5317 TRACE("backbuffer_height %u\n", swapchain_desc->backbuffer_height);
5318 TRACE("backbuffer_format %s\n", debug_d3dformat(swapchain_desc->backbuffer_format));
5319 TRACE("backbuffer_count %u\n", swapchain_desc->backbuffer_count);
5320 TRACE("multisample_type %#x\n", swapchain_desc->multisample_type);
5321 TRACE("multisample_quality %u\n", swapchain_desc->multisample_quality);
5322 TRACE("swap_effect %#x\n", swapchain_desc->swap_effect);
5323 TRACE("device_window %p\n", swapchain_desc->device_window);
5324 TRACE("windowed %#x\n", swapchain_desc->windowed);
5325 TRACE("enable_auto_depth_stencil %#x\n", swapchain_desc->enable_auto_depth_stencil);
5326 if (swapchain_desc->enable_auto_depth_stencil)
5327 TRACE("auto_depth_stencil_format %s\n", debug_d3dformat(swapchain_desc->auto_depth_stencil_format));
5328 TRACE("flags %#x\n", swapchain_desc->flags);
5329 TRACE("refresh_rate %u\n", swapchain_desc->refresh_rate);
5330 TRACE("swap_interval %u\n", swapchain_desc->swap_interval);
5331 TRACE("auto_restore_display_mode %#x\n", swapchain_desc->auto_restore_display_mode);
5333 /* No special treatment of these parameters. Just store them */
5334 swapchain->desc.swap_effect = swapchain_desc->swap_effect;
5335 swapchain->desc.flags = swapchain_desc->flags;
5336 swapchain->desc.swap_interval = swapchain_desc->swap_interval;
5337 swapchain->desc.refresh_rate = swapchain_desc->refresh_rate;
5339 /* What to do about these? */
5340 if (swapchain_desc->backbuffer_count
5341 && swapchain_desc->backbuffer_count != swapchain->desc.backbuffer_count)
5342 FIXME("Cannot change the back buffer count yet.\n");
5344 if (swapchain_desc->device_window
5345 && swapchain_desc->device_window != swapchain->desc.device_window)
5347 TRACE("Changing the device window from %p to %p.\n",
5348 swapchain->desc.device_window, swapchain_desc->device_window);
5349 swapchain->desc.device_window = swapchain_desc->device_window;
5350 swapchain->device_window = swapchain_desc->device_window;
5351 wined3d_swapchain_set_window(swapchain, NULL);
5354 if (swapchain_desc->enable_auto_depth_stencil && !device->auto_depth_stencil)
5356 HRESULT hrc;
5358 TRACE("Creating the depth stencil buffer\n");
5360 hrc = device->device_parent->ops->create_depth_stencil(device->device_parent,
5361 swapchain_desc->backbuffer_width,
5362 swapchain_desc->backbuffer_height,
5363 swapchain_desc->auto_depth_stencil_format,
5364 swapchain_desc->multisample_type,
5365 swapchain_desc->multisample_quality,
5366 FALSE,
5367 &device->auto_depth_stencil);
5368 if (FAILED(hrc))
5370 ERR("Failed to create the depth stencil buffer.\n");
5371 wined3d_swapchain_decref(swapchain);
5372 return WINED3DERR_INVALIDCALL;
5376 if (device->onscreen_depth_stencil)
5378 wined3d_surface_decref(device->onscreen_depth_stencil);
5379 device->onscreen_depth_stencil = NULL;
5382 /* Reset the depth stencil */
5383 if (swapchain_desc->enable_auto_depth_stencil)
5384 wined3d_device_set_depth_stencil(device, device->auto_depth_stencil);
5385 else
5386 wined3d_device_set_depth_stencil(device, NULL);
5388 TRACE("Resetting stateblock\n");
5389 wined3d_stateblock_decref(device->updateStateBlock);
5390 wined3d_stateblock_decref(device->stateBlock);
5392 if (swapchain_desc->windowed)
5394 mode.width = swapchain->orig_width;
5395 mode.height = swapchain->orig_height;
5396 mode.refresh_rate = 0;
5397 mode.format_id = swapchain->desc.backbuffer_format;
5399 else
5401 mode.width = swapchain_desc->backbuffer_width;
5402 mode.height = swapchain_desc->backbuffer_height;
5403 mode.refresh_rate = swapchain_desc->refresh_rate;
5404 mode.format_id = swapchain_desc->backbuffer_format;
5407 /* Should Width == 800 && Height == 0 set 800x600? */
5408 if (swapchain_desc->backbuffer_width && swapchain_desc->backbuffer_height
5409 && (swapchain_desc->backbuffer_width != swapchain->desc.backbuffer_width
5410 || swapchain_desc->backbuffer_height != swapchain->desc.backbuffer_height))
5412 if (!swapchain_desc->windowed)
5413 DisplayModeChanged = TRUE;
5415 swapchain->desc.backbuffer_width = swapchain_desc->backbuffer_width;
5416 swapchain->desc.backbuffer_height = swapchain_desc->backbuffer_height;
5417 update_desc = TRUE;
5420 if (swapchain_desc->backbuffer_format != WINED3DFMT_UNKNOWN
5421 && swapchain_desc->backbuffer_format != swapchain->desc.backbuffer_format)
5423 swapchain->desc.backbuffer_format = swapchain_desc->backbuffer_format;
5424 update_desc = TRUE;
5427 if (swapchain_desc->multisample_type != swapchain->desc.multisample_type
5428 || swapchain_desc->multisample_quality != swapchain->desc.multisample_quality)
5430 swapchain->desc.multisample_type = swapchain_desc->multisample_type;
5431 swapchain->desc.multisample_quality = swapchain_desc->multisample_quality;
5432 update_desc = TRUE;
5435 if (update_desc)
5437 UINT i;
5439 hr = wined3d_surface_update_desc(swapchain->front_buffer, swapchain->desc.backbuffer_width,
5440 swapchain->desc.backbuffer_height, swapchain->desc.backbuffer_format,
5441 swapchain->desc.multisample_type, swapchain->desc.multisample_quality);
5442 if (FAILED(hr))
5444 wined3d_swapchain_decref(swapchain);
5445 return hr;
5448 for (i = 0; i < swapchain->desc.backbuffer_count; ++i)
5450 hr = wined3d_surface_update_desc(swapchain->back_buffers[i], swapchain->desc.backbuffer_width,
5451 swapchain->desc.backbuffer_height, swapchain->desc.backbuffer_format,
5452 swapchain->desc.multisample_type, swapchain->desc.multisample_quality);
5453 if (FAILED(hr))
5455 wined3d_swapchain_decref(swapchain);
5456 return hr;
5459 if (device->auto_depth_stencil)
5461 hr = wined3d_surface_update_desc(device->auto_depth_stencil, swapchain->desc.backbuffer_width,
5462 swapchain->desc.backbuffer_height, device->auto_depth_stencil->resource.format->id,
5463 swapchain->desc.multisample_type, swapchain->desc.multisample_quality);
5464 if (FAILED(hr))
5466 wined3d_swapchain_decref(swapchain);
5467 return hr;
5472 if (device->d3d_initialized)
5473 delete_opengl_contexts(device, swapchain);
5475 if (!swapchain_desc->windowed != !swapchain->desc.windowed
5476 || DisplayModeChanged)
5478 wined3d_device_set_display_mode(device, 0, &mode);
5480 if (!swapchain_desc->windowed)
5482 if (swapchain->desc.windowed)
5484 HWND focus_window = device->create_parms.focus_window;
5485 if (!focus_window)
5486 focus_window = swapchain_desc->device_window;
5487 if (FAILED(hr = wined3d_device_acquire_focus_window(device, focus_window)))
5489 ERR("Failed to acquire focus window, hr %#x.\n", hr);
5490 wined3d_swapchain_decref(swapchain);
5491 return hr;
5494 /* switch from windowed to fs */
5495 wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5496 swapchain_desc->backbuffer_width,
5497 swapchain_desc->backbuffer_height);
5499 else
5501 /* Fullscreen -> fullscreen mode change */
5502 MoveWindow(swapchain->device_window, 0, 0,
5503 swapchain_desc->backbuffer_width,
5504 swapchain_desc->backbuffer_height,
5505 TRUE);
5508 else if (!swapchain->desc.windowed)
5510 /* Fullscreen -> windowed switch */
5511 wined3d_device_restore_fullscreen_window(device, swapchain->device_window);
5512 wined3d_device_release_focus_window(device);
5514 swapchain->desc.windowed = swapchain_desc->windowed;
5516 else if (!swapchain_desc->windowed)
5518 DWORD style = device->style;
5519 DWORD exStyle = device->exStyle;
5520 /* If we're in fullscreen, and the mode wasn't changed, we have to get the window back into
5521 * the right position. Some applications(Battlefield 2, Guild Wars) move it and then call
5522 * Reset to clear up their mess. Guild Wars also loses the device during that.
5524 device->style = 0;
5525 device->exStyle = 0;
5526 wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5527 swapchain_desc->backbuffer_width,
5528 swapchain_desc->backbuffer_height);
5529 device->style = style;
5530 device->exStyle = exStyle;
5533 /* Note: No parent needed for initial internal stateblock */
5534 hr = wined3d_stateblock_create(device, WINED3D_SBT_INIT, &device->stateBlock);
5535 if (FAILED(hr))
5536 ERR("Resetting the stateblock failed with error %#x.\n", hr);
5537 else
5538 TRACE("Created stateblock %p.\n", device->stateBlock);
5539 device->updateStateBlock = device->stateBlock;
5540 wined3d_stateblock_incref(device->updateStateBlock);
5542 stateblock_init_default_state(device->stateBlock);
5544 swapchain_update_render_to_fbo(swapchain);
5545 swapchain_update_draw_bindings(swapchain);
5547 if (device->d3d_initialized)
5548 hr = create_primary_opengl_context(device, swapchain);
5549 wined3d_swapchain_decref(swapchain);
5551 /* All done. There is no need to reload resources or shaders, this will happen automatically on the
5552 * first use
5554 return hr;
5557 HRESULT CDECL wined3d_device_set_dialog_box_mode(struct wined3d_device *device, BOOL enable_dialogs)
5559 TRACE("device %p, enable_dialogs %#x.\n", device, enable_dialogs);
5561 if (!enable_dialogs) FIXME("Dialogs cannot be disabled yet.\n");
5563 return WINED3D_OK;
5567 HRESULT CDECL wined3d_device_get_creation_parameters(const struct wined3d_device *device,
5568 struct wined3d_device_creation_parameters *parameters)
5570 TRACE("device %p, parameters %p.\n", device, parameters);
5572 *parameters = device->create_parms;
5573 return WINED3D_OK;
5576 void CDECL wined3d_device_set_gamma_ramp(const struct wined3d_device *device,
5577 UINT swapchain_idx, DWORD flags, const struct wined3d_gamma_ramp *ramp)
5579 struct wined3d_swapchain *swapchain;
5581 TRACE("device %p, swapchain_idx %u, flags %#x, ramp %p.\n",
5582 device, swapchain_idx, flags, ramp);
5584 if (SUCCEEDED(wined3d_device_get_swapchain(device, swapchain_idx, &swapchain)))
5586 wined3d_swapchain_set_gamma_ramp(swapchain, flags, ramp);
5587 wined3d_swapchain_decref(swapchain);
5591 void CDECL wined3d_device_get_gamma_ramp(const struct wined3d_device *device,
5592 UINT swapchain_idx, struct wined3d_gamma_ramp *ramp)
5594 struct wined3d_swapchain *swapchain;
5596 TRACE("device %p, swapchain_idx %u, ramp %p.\n",
5597 device, swapchain_idx, ramp);
5599 if (SUCCEEDED(wined3d_device_get_swapchain(device, swapchain_idx, &swapchain)))
5601 wined3d_swapchain_get_gamma_ramp(swapchain, ramp);
5602 wined3d_swapchain_decref(swapchain);
5606 void device_resource_add(struct wined3d_device *device, struct wined3d_resource *resource)
5608 TRACE("device %p, resource %p.\n", device, resource);
5610 list_add_head(&device->resources, &resource->resource_list_entry);
5613 static void device_resource_remove(struct wined3d_device *device, struct wined3d_resource *resource)
5615 TRACE("device %p, resource %p.\n", device, resource);
5617 list_remove(&resource->resource_list_entry);
5620 void device_resource_released(struct wined3d_device *device, struct wined3d_resource *resource)
5622 enum wined3d_resource_type type = resource->type;
5623 unsigned int i;
5625 TRACE("device %p, resource %p, type %s.\n", device, resource, debug_d3dresourcetype(type));
5627 context_resource_released(device, resource, type);
5629 switch (type)
5631 case WINED3D_RTYPE_SURFACE:
5633 struct wined3d_surface *surface = surface_from_resource(resource);
5635 if (!device->d3d_initialized) break;
5637 for (i = 0; i < device->adapter->gl_info.limits.buffers; ++i)
5639 if (device->fb.render_targets[i] == surface)
5641 ERR("Surface %p is still in use as render target %u.\n", surface, i);
5642 device->fb.render_targets[i] = NULL;
5646 if (device->fb.depth_stencil == surface)
5648 ERR("Surface %p is still in use as depth/stencil buffer.\n", surface);
5649 device->fb.depth_stencil = NULL;
5652 break;
5654 case WINED3D_RTYPE_TEXTURE:
5655 case WINED3D_RTYPE_CUBE_TEXTURE:
5656 case WINED3D_RTYPE_VOLUME_TEXTURE:
5657 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
5659 struct wined3d_texture *texture = wined3d_texture_from_resource(resource);
5661 if (device->stateBlock && device->stateBlock->state.textures[i] == texture)
5663 ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
5664 texture, device->stateBlock, i);
5665 device->stateBlock->state.textures[i] = NULL;
5668 if (device->updateStateBlock != device->stateBlock
5669 && device->updateStateBlock->state.textures[i] == texture)
5671 ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
5672 texture, device->updateStateBlock, i);
5673 device->updateStateBlock->state.textures[i] = NULL;
5676 break;
5678 case WINED3D_RTYPE_BUFFER:
5680 struct wined3d_buffer *buffer = buffer_from_resource(resource);
5682 for (i = 0; i < MAX_STREAMS; ++i)
5684 if (device->stateBlock && device->stateBlock->state.streams[i].buffer == buffer)
5686 ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
5687 buffer, device->stateBlock, i);
5688 device->stateBlock->state.streams[i].buffer = NULL;
5691 if (device->updateStateBlock != device->stateBlock
5692 && device->updateStateBlock->state.streams[i].buffer == buffer)
5694 ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
5695 buffer, device->updateStateBlock, i);
5696 device->updateStateBlock->state.streams[i].buffer = NULL;
5701 if (device->stateBlock && device->stateBlock->state.index_buffer == buffer)
5703 ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
5704 buffer, device->stateBlock);
5705 device->stateBlock->state.index_buffer = NULL;
5708 if (device->updateStateBlock != device->stateBlock
5709 && device->updateStateBlock->state.index_buffer == buffer)
5711 ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
5712 buffer, device->updateStateBlock);
5713 device->updateStateBlock->state.index_buffer = NULL;
5716 break;
5718 default:
5719 break;
5722 /* Remove the resource from the resourceStore */
5723 device_resource_remove(device, resource);
5725 TRACE("Resource released.\n");
5728 HRESULT CDECL wined3d_device_get_surface_from_dc(const struct wined3d_device *device,
5729 HDC dc, struct wined3d_surface **surface)
5731 struct wined3d_resource *resource;
5733 TRACE("device %p, dc %p, surface %p.\n", device, dc, surface);
5735 if (!dc)
5736 return WINED3DERR_INVALIDCALL;
5738 LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
5740 if (resource->type == WINED3D_RTYPE_SURFACE)
5742 struct wined3d_surface *s = surface_from_resource(resource);
5744 if (s->hDC == dc)
5746 TRACE("Found surface %p for dc %p.\n", s, dc);
5747 *surface = s;
5748 return WINED3D_OK;
5753 return WINED3DERR_INVALIDCALL;
5756 HRESULT device_init(struct wined3d_device *device, struct wined3d *wined3d,
5757 UINT adapter_idx, enum wined3d_device_type device_type, HWND focus_window, DWORD flags,
5758 BYTE surface_alignment, struct wined3d_device_parent *device_parent)
5760 struct wined3d_adapter *adapter = &wined3d->adapters[adapter_idx];
5761 const struct fragment_pipeline *fragment_pipeline;
5762 struct wined3d_display_mode mode;
5763 struct shader_caps shader_caps;
5764 struct fragment_caps ffp_caps;
5765 unsigned int i;
5766 HRESULT hr;
5768 device->ref = 1;
5769 device->wined3d = wined3d;
5770 wined3d_incref(device->wined3d);
5771 device->adapter = wined3d->adapter_count ? adapter : NULL;
5772 device->device_parent = device_parent;
5773 list_init(&device->resources);
5774 list_init(&device->shaders);
5775 device->surface_alignment = surface_alignment;
5777 /* Get the initial screen setup for ddraw. */
5778 hr = wined3d_get_adapter_display_mode(wined3d, adapter_idx, &mode);
5779 if (FAILED(hr))
5781 ERR("Failed to get the adapter's display mode, hr %#x.\n", hr);
5782 wined3d_decref(device->wined3d);
5783 return hr;
5785 adapter->screen_size.cx = mode.width;
5786 adapter->screen_size.cy = mode.height;
5787 adapter->screen_format = mode.format_id;
5789 /* Save the creation parameters. */
5790 device->create_parms.adapter_idx = adapter_idx;
5791 device->create_parms.device_type = device_type;
5792 device->create_parms.focus_window = focus_window;
5793 device->create_parms.flags = flags;
5795 for (i = 0; i < PATCHMAP_SIZE; ++i) list_init(&device->patches[i]);
5797 select_shader_mode(&adapter->gl_info, &device->ps_selected_mode, &device->vs_selected_mode);
5798 device->shader_backend = adapter->shader_backend;
5800 if (device->shader_backend)
5802 device->shader_backend->shader_get_caps(&adapter->gl_info, &shader_caps);
5803 device->vshader_version = shader_caps.VertexShaderVersion;
5804 device->pshader_version = shader_caps.PixelShaderVersion;
5805 device->d3d_vshader_constantF = shader_caps.MaxVertexShaderConst;
5806 device->d3d_pshader_constantF = shader_caps.MaxPixelShaderConst;
5807 device->vs_clipping = shader_caps.VSClipping;
5809 fragment_pipeline = adapter->fragment_pipe;
5810 device->frag_pipe = fragment_pipeline;
5811 if (fragment_pipeline)
5813 fragment_pipeline->get_caps(&adapter->gl_info, &ffp_caps);
5814 device->max_ffp_textures = ffp_caps.MaxSimultaneousTextures;
5816 hr = compile_state_table(device->StateTable, device->multistate_funcs, &adapter->gl_info,
5817 ffp_vertexstate_template, fragment_pipeline, misc_state_template);
5818 if (FAILED(hr))
5820 ERR("Failed to compile state table, hr %#x.\n", hr);
5821 wined3d_decref(device->wined3d);
5822 return hr;
5825 device->blitter = adapter->blitter;
5827 hr = wined3d_stateblock_create(device, WINED3D_SBT_INIT, &device->stateBlock);
5828 if (FAILED(hr))
5830 WARN("Failed to create stateblock.\n");
5831 for (i = 0; i < sizeof(device->multistate_funcs) / sizeof(device->multistate_funcs[0]); ++i)
5833 HeapFree(GetProcessHeap(), 0, device->multistate_funcs[i]);
5835 wined3d_decref(device->wined3d);
5836 return hr;
5839 TRACE("Created stateblock %p.\n", device->stateBlock);
5840 device->updateStateBlock = device->stateBlock;
5841 wined3d_stateblock_incref(device->updateStateBlock);
5843 return WINED3D_OK;
5847 void device_invalidate_state(const struct wined3d_device *device, DWORD state)
5849 DWORD rep = device->StateTable[state].representative;
5850 struct wined3d_context *context;
5851 DWORD idx;
5852 BYTE shift;
5853 UINT i;
5855 for (i = 0; i < device->context_count; ++i)
5857 context = device->contexts[i];
5858 if(isStateDirty(context, rep)) continue;
5860 context->dirtyArray[context->numDirtyEntries++] = rep;
5861 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
5862 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
5863 context->isStateDirty[idx] |= (1 << shift);
5867 void get_drawable_size_fbo(const struct wined3d_context *context, UINT *width, UINT *height)
5869 /* The drawable size of a fbo target is the opengl texture size, which is the power of two size. */
5870 *width = context->current_rt->pow2Width;
5871 *height = context->current_rt->pow2Height;
5874 void get_drawable_size_backbuffer(const struct wined3d_context *context, UINT *width, UINT *height)
5876 const struct wined3d_swapchain *swapchain = context->swapchain;
5877 /* The drawable size of a backbuffer / aux buffer offscreen target is the size of the
5878 * current context's drawable, which is the size of the back buffer of the swapchain
5879 * the active context belongs to. */
5880 *width = swapchain->desc.backbuffer_width;
5881 *height = swapchain->desc.backbuffer_height;
5884 LRESULT device_process_message(struct wined3d_device *device, HWND window, BOOL unicode,
5885 UINT message, WPARAM wparam, LPARAM lparam, WNDPROC proc)
5887 if (device->filter_messages)
5889 TRACE("Filtering message: window %p, message %#x, wparam %#lx, lparam %#lx.\n",
5890 window, message, wparam, lparam);
5891 if (unicode)
5892 return DefWindowProcW(window, message, wparam, lparam);
5893 else
5894 return DefWindowProcA(window, message, wparam, lparam);
5897 if (message == WM_DESTROY)
5899 TRACE("unregister window %p.\n", window);
5900 wined3d_unregister_window(window);
5902 if (InterlockedCompareExchangePointer((void **)&device->focus_window, NULL, window) != window)
5903 ERR("Window %p is not the focus window for device %p.\n", window, device);
5905 else if (message == WM_DISPLAYCHANGE)
5907 device->device_parent->ops->mode_changed(device->device_parent);
5910 if (unicode)
5911 return CallWindowProcW(proc, window, message, wparam, lparam);
5912 else
5913 return CallWindowProcA(proc, window, message, wparam, lparam);