msvcrt: Add validity checks for _mbstrlen_l.
[wine/multimedia.git] / dlls / wined3d / device.c
blobaca9306cc61d404a7b67d8e6feb84fac250ee85f
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 WINED3DLIGHT_DIRECTIONAL, /* Type */
40 { 1.0f, 1.0f, 1.0f, 0.0f }, /* Diffuse r,g,b,a */
41 { 0.0f, 0.0f, 0.0f, 0.0f }, /* Specular r,g,b,a */
42 { 0.0f, 0.0f, 0.0f, 0.0f }, /* Ambient r,g,b,a, */
43 { 0.0f, 0.0f, 0.0f }, /* Position x,y,z */
44 { 0.0f, 0.0f, 1.0f }, /* Direction x,y,z */
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(WINED3DPRIMITIVETYPE primitive_type)
67 switch(primitive_type)
69 case WINED3DPT_POINTLIST:
70 return GL_POINTS;
72 case WINED3DPT_LINELIST:
73 return GL_LINES;
75 case WINED3DPT_LINESTRIP:
76 return GL_LINE_STRIP;
78 case WINED3DPT_TRIANGLELIST:
79 return GL_TRIANGLES;
81 case WINED3DPT_TRIANGLESTRIP:
82 return GL_TRIANGLE_STRIP;
84 case WINED3DPT_TRIANGLEFAN:
85 return GL_TRIANGLE_FAN;
87 case WINED3DPT_LINELIST_ADJ:
88 return GL_LINES_ADJACENCY_ARB;
90 case WINED3DPT_LINESTRIP_ADJ:
91 return GL_LINE_STRIP_ADJACENCY_ARB;
93 case WINED3DPT_TRIANGLELIST_ADJ:
94 return GL_TRIANGLES_ADJACENCY_ARB;
96 case WINED3DPT_TRIANGLESTRIP_ADJ:
97 return GL_TRIANGLE_STRIP_ADJACENCY_ARB;
99 default:
100 FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
101 return GL_NONE;
105 static WINED3DPRIMITIVETYPE d3d_primitive_type_from_gl(GLenum primitive_type)
107 switch(primitive_type)
109 case GL_POINTS:
110 return WINED3DPT_POINTLIST;
112 case GL_LINES:
113 return WINED3DPT_LINELIST;
115 case GL_LINE_STRIP:
116 return WINED3DPT_LINESTRIP;
118 case GL_TRIANGLES:
119 return WINED3DPT_TRIANGLELIST;
121 case GL_TRIANGLE_STRIP:
122 return WINED3DPT_TRIANGLESTRIP;
124 case GL_TRIANGLE_FAN:
125 return WINED3DPT_TRIANGLEFAN;
127 case GL_LINES_ADJACENCY_ARB:
128 return WINED3DPT_LINELIST_ADJ;
130 case GL_LINE_STRIP_ADJACENCY_ARB:
131 return WINED3DPT_LINESTRIP_ADJ;
133 case GL_TRIANGLES_ADJACENCY_ARB:
134 return WINED3DPT_TRIANGLELIST_ADJ;
136 case GL_TRIANGLE_STRIP_ADJACENCY_ARB:
137 return WINED3DPT_TRIANGLESTRIP_ADJ;
139 default:
140 FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
141 return WINED3DPT_UNDEFINED;
145 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
147 if ((usage == WINED3DDECLUSAGE_POSITION || usage == WINED3DDECLUSAGE_POSITIONT) && !usage_idx)
148 *regnum = WINED3D_FFP_POSITION;
149 else if (usage == WINED3DDECLUSAGE_BLENDWEIGHT && !usage_idx)
150 *regnum = WINED3D_FFP_BLENDWEIGHT;
151 else if (usage == WINED3DDECLUSAGE_BLENDINDICES && !usage_idx)
152 *regnum = WINED3D_FFP_BLENDINDICES;
153 else if (usage == WINED3DDECLUSAGE_NORMAL && !usage_idx)
154 *regnum = WINED3D_FFP_NORMAL;
155 else if (usage == WINED3DDECLUSAGE_PSIZE && !usage_idx)
156 *regnum = WINED3D_FFP_PSIZE;
157 else if (usage == WINED3DDECLUSAGE_COLOR && !usage_idx)
158 *regnum = WINED3D_FFP_DIFFUSE;
159 else if (usage == WINED3DDECLUSAGE_COLOR && usage_idx == 1)
160 *regnum = WINED3D_FFP_SPECULAR;
161 else if (usage == WINED3DDECLUSAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
162 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
163 else
165 FIXME("Unsupported input stream [usage=%s, usage_idx=%u]\n", debug_d3ddeclusage(usage), usage_idx);
166 *regnum = ~0U;
167 return FALSE;
170 return TRUE;
173 /* Context activation is done by the caller. */
174 void device_stream_info_from_declaration(struct wined3d_device *device,
175 struct wined3d_stream_info *stream_info, BOOL *fixup)
177 const struct wined3d_state *state = &device->stateBlock->state;
178 /* We need to deal with frequency data! */
179 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
180 BOOL use_vshader;
181 unsigned int i;
183 stream_info->use_map = 0;
184 stream_info->swizzle_map = 0;
186 /* Check for transformed vertices, disable vertex shader if present. */
187 stream_info->position_transformed = declaration->position_transformed;
188 use_vshader = state->vertex_shader && !declaration->position_transformed;
190 /* Translate the declaration into strided data. */
191 for (i = 0; i < declaration->element_count; ++i)
193 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
194 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
195 struct wined3d_buffer *buffer = stream->buffer;
196 struct wined3d_bo_address data;
197 BOOL stride_used;
198 unsigned int idx;
199 DWORD stride;
201 TRACE("%p Element %p (%u of %u)\n", declaration->elements,
202 element, i + 1, declaration->element_count);
204 if (!buffer) continue;
206 data.buffer_object = 0;
207 data.addr = NULL;
209 stride = stream->stride;
210 if (state->user_stream)
212 TRACE("Stream %u is UP, %p\n", element->input_slot, buffer);
213 data.buffer_object = 0;
214 data.addr = (BYTE *)buffer;
216 else
218 TRACE("Stream %u isn't UP, %p\n", element->input_slot, buffer);
219 buffer_get_memory(buffer, &device->adapter->gl_info, &data);
221 /* Can't use vbo's if the base vertex index is negative. OpenGL doesn't accept negative offsets
222 * (or rather offsets bigger than the vbo, because the pointer is unsigned), so use system memory
223 * sources. In most sane cases the pointer - offset will still be > 0, otherwise it will wrap
224 * around to some big value. Hope that with the indices, the driver wraps it back internally. If
225 * not, drawStridedSlow is needed, including a vertex buffer path. */
226 if (state->load_base_vertex_index < 0)
228 WARN("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
229 state->load_base_vertex_index);
230 data.buffer_object = 0;
231 data.addr = buffer_get_sysmem(buffer, &device->adapter->gl_info);
232 if ((UINT_PTR)data.addr < -state->load_base_vertex_index * stride)
234 FIXME("System memory vertex data load offset is negative!\n");
238 if (fixup)
240 if (data.buffer_object)
241 *fixup = TRUE;
242 else if (*fixup && !use_vshader
243 && (element->usage == WINED3DDECLUSAGE_COLOR
244 || element->usage == WINED3DDECLUSAGE_POSITIONT))
246 static BOOL warned = FALSE;
247 if (!warned)
249 /* This may be bad with the fixed function pipeline. */
250 FIXME("Missing vbo streams with unfixed colors or transformed position, expect problems\n");
251 warned = TRUE;
256 data.addr += element->offset;
258 TRACE("offset %u input_slot %u usage_idx %d\n", element->offset, element->input_slot, element->usage_idx);
260 if (use_vshader)
262 if (element->output_slot == ~0U)
264 /* TODO: Assuming vertexdeclarations are usually used with the
265 * same or a similar shader, it might be worth it to store the
266 * last used output slot and try that one first. */
267 stride_used = vshader_get_input(state->vertex_shader,
268 element->usage, element->usage_idx, &idx);
270 else
272 idx = element->output_slot;
273 stride_used = TRUE;
276 else
278 if (!element->ffp_valid)
280 WARN("Skipping unsupported fixed function element of format %s and usage %s\n",
281 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
282 stride_used = FALSE;
284 else
286 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
290 if (stride_used)
292 TRACE("Load %s array %u [usage %s, usage_idx %u, "
293 "input_slot %u, offset %u, stride %u, format %s, buffer_object %u]\n",
294 use_vshader ? "shader": "fixed function", idx,
295 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
296 element->offset, stride, debug_d3dformat(element->format->id), data.buffer_object);
298 data.addr += stream->offset;
300 stream_info->elements[idx].format = element->format;
301 stream_info->elements[idx].data = data;
302 stream_info->elements[idx].stride = stride;
303 stream_info->elements[idx].stream_idx = element->input_slot;
305 if (!device->adapter->gl_info.supported[ARB_VERTEX_ARRAY_BGRA]
306 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
308 stream_info->swizzle_map |= 1 << idx;
310 stream_info->use_map |= 1 << idx;
314 device->num_buffer_queries = 0;
315 if (!state->user_stream)
317 WORD map = stream_info->use_map;
319 /* PreLoad all the vertex buffers. */
320 for (i = 0; map; map >>= 1, ++i)
322 struct wined3d_stream_info_element *element;
323 struct wined3d_buffer *buffer;
325 if (!(map & 1)) continue;
327 element = &stream_info->elements[i];
328 buffer = state->streams[element->stream_idx].buffer;
329 wined3d_buffer_preload(buffer);
331 /* If the preload dropped the buffer object, update the stream info. */
332 if (buffer->buffer_object != element->data.buffer_object)
334 element->data.buffer_object = 0;
335 element->data.addr = buffer_get_sysmem(buffer, &device->adapter->gl_info)
336 + (ptrdiff_t)element->data.addr;
339 if (buffer->query)
340 device->buffer_queries[device->num_buffer_queries++] = buffer->query;
345 static void stream_info_element_from_strided(const struct wined3d_gl_info *gl_info,
346 const struct WineDirect3DStridedData *strided, struct wined3d_stream_info_element *e)
348 e->data.addr = strided->lpData;
349 e->data.buffer_object = 0;
350 e->format = wined3d_get_format(gl_info, strided->format);
351 e->stride = strided->dwStride;
352 e->stream_idx = 0;
355 static void device_stream_info_from_strided(const struct wined3d_gl_info *gl_info,
356 const struct WineDirect3DVertexStridedData *strided, struct wined3d_stream_info *stream_info)
358 unsigned int i;
360 memset(stream_info, 0, sizeof(*stream_info));
362 if (strided->position.lpData)
363 stream_info_element_from_strided(gl_info, &strided->position, &stream_info->elements[WINED3D_FFP_POSITION]);
364 if (strided->normal.lpData)
365 stream_info_element_from_strided(gl_info, &strided->normal, &stream_info->elements[WINED3D_FFP_NORMAL]);
366 if (strided->diffuse.lpData)
367 stream_info_element_from_strided(gl_info, &strided->diffuse, &stream_info->elements[WINED3D_FFP_DIFFUSE]);
368 if (strided->specular.lpData)
369 stream_info_element_from_strided(gl_info, &strided->specular, &stream_info->elements[WINED3D_FFP_SPECULAR]);
371 for (i = 0; i < WINED3DDP_MAXTEXCOORD; ++i)
373 if (strided->texCoords[i].lpData)
374 stream_info_element_from_strided(gl_info, &strided->texCoords[i],
375 &stream_info->elements[WINED3D_FFP_TEXCOORD0 + i]);
378 stream_info->position_transformed = strided->position_transformed;
380 for (i = 0; i < sizeof(stream_info->elements) / sizeof(*stream_info->elements); ++i)
382 if (!stream_info->elements[i].format) continue;
384 if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
385 && stream_info->elements[i].format->id == WINED3DFMT_B8G8R8A8_UNORM)
387 stream_info->swizzle_map |= 1 << i;
389 stream_info->use_map |= 1 << i;
393 static void device_trace_strided_stream_info(const struct wined3d_stream_info *stream_info)
395 TRACE("Strided Data:\n");
396 TRACE_STRIDED(stream_info, WINED3D_FFP_POSITION);
397 TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDWEIGHT);
398 TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDINDICES);
399 TRACE_STRIDED(stream_info, WINED3D_FFP_NORMAL);
400 TRACE_STRIDED(stream_info, WINED3D_FFP_PSIZE);
401 TRACE_STRIDED(stream_info, WINED3D_FFP_DIFFUSE);
402 TRACE_STRIDED(stream_info, WINED3D_FFP_SPECULAR);
403 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD0);
404 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD1);
405 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD2);
406 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD3);
407 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD4);
408 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD5);
409 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD6);
410 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD7);
413 /* Context activation is done by the caller. */
414 void device_update_stream_info(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
416 struct wined3d_stream_info *stream_info = &device->strided_streams;
417 const struct wined3d_state *state = &device->stateBlock->state;
418 BOOL fixup = FALSE;
420 if (device->up_strided)
422 /* Note: this is a ddraw fixed-function code path. */
423 TRACE("=============================== Strided Input ================================\n");
424 device_stream_info_from_strided(gl_info, device->up_strided, stream_info);
425 if (TRACE_ON(d3d)) device_trace_strided_stream_info(stream_info);
427 else
429 TRACE("============================= Vertex Declaration =============================\n");
430 device_stream_info_from_declaration(device, stream_info, &fixup);
433 if (state->vertex_shader && !stream_info->position_transformed)
435 if (state->vertex_declaration->half_float_conv_needed && !fixup)
437 TRACE("Using drawStridedSlow with vertex shaders for FLOAT16 conversion.\n");
438 device->useDrawStridedSlow = TRUE;
440 else
442 device->useDrawStridedSlow = FALSE;
445 else
447 WORD slow_mask = (1 << WINED3D_FFP_PSIZE);
448 slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
449 & ((1 << WINED3D_FFP_DIFFUSE) | (1 << WINED3D_FFP_SPECULAR));
451 if ((stream_info->position_transformed || (stream_info->use_map & slow_mask)) && !fixup)
453 device->useDrawStridedSlow = TRUE;
455 else
457 device->useDrawStridedSlow = FALSE;
462 static void device_preload_texture(const struct wined3d_state *state, unsigned int idx)
464 struct wined3d_texture *texture;
465 enum WINED3DSRGB srgb;
467 if (!(texture = state->textures[idx])) return;
468 srgb = state->sampler_states[idx][WINED3DSAMP_SRGBTEXTURE] ? SRGB_SRGB : SRGB_RGB;
469 texture->texture_ops->texture_preload(texture, srgb);
472 void device_preload_textures(const struct wined3d_device *device)
474 const struct wined3d_state *state = &device->stateBlock->state;
475 unsigned int i;
477 if (use_vs(state))
479 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
481 if (state->vertex_shader->reg_maps.sampler_type[i])
482 device_preload_texture(state, MAX_FRAGMENT_SAMPLERS + i);
486 if (use_ps(state))
488 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
490 if (state->pixel_shader->reg_maps.sampler_type[i])
491 device_preload_texture(state, i);
494 else
496 WORD ffu_map = device->fixed_function_usage_map;
498 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
500 if (ffu_map & 1)
501 device_preload_texture(state, i);
506 BOOL device_context_add(struct wined3d_device *device, struct wined3d_context *context)
508 struct wined3d_context **new_array;
510 TRACE("Adding context %p.\n", context);
512 if (!device->contexts) new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_array));
513 else new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts,
514 sizeof(*new_array) * (device->context_count + 1));
516 if (!new_array)
518 ERR("Failed to grow the context array.\n");
519 return FALSE;
522 new_array[device->context_count++] = context;
523 device->contexts = new_array;
524 return TRUE;
527 void device_context_remove(struct wined3d_device *device, struct wined3d_context *context)
529 struct wined3d_context **new_array;
530 BOOL found = FALSE;
531 UINT i;
533 TRACE("Removing context %p.\n", context);
535 for (i = 0; i < device->context_count; ++i)
537 if (device->contexts[i] == context)
539 found = TRUE;
540 break;
544 if (!found)
546 ERR("Context %p doesn't exist in context array.\n", context);
547 return;
550 if (!--device->context_count)
552 HeapFree(GetProcessHeap(), 0, device->contexts);
553 device->contexts = NULL;
554 return;
557 memmove(&device->contexts[i], &device->contexts[i + 1], (device->context_count - i) * sizeof(*device->contexts));
558 new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts, device->context_count * sizeof(*device->contexts));
559 if (!new_array)
561 ERR("Failed to shrink context array. Oh well.\n");
562 return;
565 device->contexts = new_array;
568 /* Do not call while under the GL lock. */
569 void device_switch_onscreen_ds(struct wined3d_device *device,
570 struct wined3d_context *context, struct wined3d_surface *depth_stencil)
572 if (device->onscreen_depth_stencil)
574 surface_load_ds_location(device->onscreen_depth_stencil, context, SFLAG_DS_OFFSCREEN);
575 surface_modify_ds_location(device->onscreen_depth_stencil, SFLAG_DS_OFFSCREEN,
576 device->onscreen_depth_stencil->ds_current_size.cx,
577 device->onscreen_depth_stencil->ds_current_size.cy);
578 wined3d_surface_decref(device->onscreen_depth_stencil);
580 device->onscreen_depth_stencil = depth_stencil;
581 wined3d_surface_incref(device->onscreen_depth_stencil);
584 static BOOL is_full_clear(const struct wined3d_surface *target, const RECT *draw_rect, const RECT *clear_rect)
586 /* partial draw rect */
587 if (draw_rect->left || draw_rect->top
588 || draw_rect->right < target->resource.width
589 || draw_rect->bottom < target->resource.height)
590 return FALSE;
592 /* partial clear rect */
593 if (clear_rect && (clear_rect->left > 0 || clear_rect->top > 0
594 || clear_rect->right < target->resource.width
595 || clear_rect->bottom < target->resource.height))
596 return FALSE;
598 return TRUE;
601 static void prepare_ds_clear(struct wined3d_surface *ds, struct wined3d_context *context,
602 DWORD location, const RECT *draw_rect, UINT rect_count, const RECT *clear_rect)
604 RECT current_rect, r;
606 if (ds->flags & location)
607 SetRect(&current_rect, 0, 0,
608 ds->ds_current_size.cx,
609 ds->ds_current_size.cy);
610 else
611 SetRectEmpty(&current_rect);
613 IntersectRect(&r, draw_rect, &current_rect);
614 if (EqualRect(&r, draw_rect))
616 /* current_rect ⊇ draw_rect, modify only. */
617 surface_modify_ds_location(ds, location, ds->ds_current_size.cx, ds->ds_current_size.cy);
618 return;
621 if (EqualRect(&r, &current_rect))
623 /* draw_rect ⊇ current_rect, test if we're doing a full clear. */
625 if (!clear_rect)
627 /* Full clear, modify only. */
628 surface_modify_ds_location(ds, location, draw_rect->right, draw_rect->bottom);
629 return;
632 IntersectRect(&r, draw_rect, clear_rect);
633 if (EqualRect(&r, draw_rect))
635 /* clear_rect ⊇ draw_rect, modify only. */
636 surface_modify_ds_location(ds, location, draw_rect->right, draw_rect->bottom);
637 return;
641 /* Full load. */
642 surface_load_ds_location(ds, context, location);
643 surface_modify_ds_location(ds, location, ds->ds_current_size.cx, ds->ds_current_size.cy);
646 /* Do not call while under the GL lock. */
647 HRESULT device_clear_render_targets(struct wined3d_device *device, UINT rt_count, const struct wined3d_fb_state *fb,
648 UINT rect_count, const RECT *rects, const RECT *draw_rect, DWORD flags, const struct wined3d_color *color,
649 float depth, DWORD stencil)
651 const RECT *clear_rect = (rect_count > 0 && rects) ? (const RECT *)rects : NULL;
652 struct wined3d_surface *target = rt_count ? fb->render_targets[0] : NULL;
653 UINT drawable_width, drawable_height;
654 struct wined3d_context *context;
655 GLbitfield clear_mask = 0;
656 BOOL render_offscreen;
657 unsigned int i;
659 /* When we're clearing parts of the drawable, make sure that the target surface is well up to date in the
660 * drawable. After the clear we'll mark the drawable up to date, so we have to make sure that this is true
661 * for the cleared parts, and the untouched parts.
663 * If we're clearing the whole target there is no need to copy it into the drawable, it will be overwritten
664 * anyway. If we're not clearing the color buffer we don't have to copy either since we're not going to set
665 * the drawable up to date. We have to check all settings that limit the clear area though. Do not bother
666 * checking all this if the dest surface is in the drawable anyway. */
667 if (flags & WINED3DCLEAR_TARGET && !is_full_clear(target, draw_rect, clear_rect))
669 for (i = 0; i < rt_count; ++i)
671 struct wined3d_surface *rt = fb->render_targets[i];
672 if (rt)
673 surface_load_location(rt, rt->draw_binding, NULL);
677 context = context_acquire(device, target);
678 if (!context->valid)
680 context_release(context);
681 WARN("Invalid context, skipping clear.\n");
682 return WINED3D_OK;
685 if (target)
687 render_offscreen = context->render_offscreen;
688 target->get_drawable_size(context, &drawable_width, &drawable_height);
690 else
692 render_offscreen = TRUE;
693 drawable_width = fb->depth_stencil->pow2Width;
694 drawable_height = fb->depth_stencil->pow2Height;
697 if (flags & WINED3DCLEAR_ZBUFFER)
699 DWORD location = render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
701 if (location == SFLAG_DS_ONSCREEN && fb->depth_stencil != device->onscreen_depth_stencil)
702 device_switch_onscreen_ds(device, context, fb->depth_stencil);
703 prepare_ds_clear(fb->depth_stencil, context, location, draw_rect, rect_count, clear_rect);
706 if (!context_apply_clear_state(context, device, rt_count, fb))
708 context_release(context);
709 WARN("Failed to apply clear state, skipping clear.\n");
710 return WINED3D_OK;
713 ENTER_GL();
715 /* Only set the values up once, as they are not changing. */
716 if (flags & WINED3DCLEAR_STENCIL)
718 if (context->gl_info->supported[EXT_STENCIL_TWO_SIDE])
720 glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
721 context_invalidate_state(context, STATE_RENDER(WINED3DRS_TWOSIDEDSTENCILMODE));
723 glStencilMask(~0U);
724 context_invalidate_state(context, STATE_RENDER(WINED3DRS_STENCILWRITEMASK));
725 glClearStencil(stencil);
726 checkGLcall("glClearStencil");
727 clear_mask = clear_mask | GL_STENCIL_BUFFER_BIT;
730 if (flags & WINED3DCLEAR_ZBUFFER)
732 surface_modify_location(fb->depth_stencil, fb->depth_stencil->draw_binding, TRUE);
734 glDepthMask(GL_TRUE);
735 context_invalidate_state(context, STATE_RENDER(WINED3DRS_ZWRITEENABLE));
736 glClearDepth(depth);
737 checkGLcall("glClearDepth");
738 clear_mask = clear_mask | GL_DEPTH_BUFFER_BIT;
741 if (flags & WINED3DCLEAR_TARGET)
743 for (i = 0; i < rt_count; ++i)
745 struct wined3d_surface *rt = fb->render_targets[i];
747 if (rt)
748 surface_modify_location(rt, rt->draw_binding, TRUE);
751 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
752 context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE));
753 context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1));
754 context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2));
755 context_invalidate_state(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3));
756 glClearColor(color->r, color->g, color->b, color->a);
757 checkGLcall("glClearColor");
758 clear_mask = clear_mask | GL_COLOR_BUFFER_BIT;
761 if (!clear_rect)
763 if (render_offscreen)
765 glScissor(draw_rect->left, draw_rect->top,
766 draw_rect->right - draw_rect->left, draw_rect->bottom - draw_rect->top);
768 else
770 glScissor(draw_rect->left, drawable_height - draw_rect->bottom,
771 draw_rect->right - draw_rect->left, draw_rect->bottom - draw_rect->top);
773 checkGLcall("glScissor");
774 glClear(clear_mask);
775 checkGLcall("glClear");
777 else
779 RECT current_rect;
781 /* Now process each rect in turn. */
782 for (i = 0; i < rect_count; ++i)
784 /* Note that GL uses lower left, width/height. */
785 IntersectRect(&current_rect, draw_rect, &clear_rect[i]);
787 TRACE("clear_rect[%u] %s, current_rect %s.\n", i,
788 wine_dbgstr_rect(&clear_rect[i]),
789 wine_dbgstr_rect(&current_rect));
791 /* Tests show that rectangles where x1 > x2 or y1 > y2 are ignored silently.
792 * The rectangle is not cleared, no error is returned, but further rectangles are
793 * still cleared if they are valid. */
794 if (current_rect.left > current_rect.right || current_rect.top > current_rect.bottom)
796 TRACE("Rectangle with negative dimensions, ignoring.\n");
797 continue;
800 if (render_offscreen)
802 glScissor(current_rect.left, current_rect.top,
803 current_rect.right - current_rect.left, current_rect.bottom - current_rect.top);
805 else
807 glScissor(current_rect.left, drawable_height - current_rect.bottom,
808 current_rect.right - current_rect.left, current_rect.bottom - current_rect.top);
810 checkGLcall("glScissor");
812 glClear(clear_mask);
813 checkGLcall("glClear");
817 LEAVE_GL();
819 if (wined3d_settings.strict_draw_ordering || (flags & WINED3DCLEAR_TARGET
820 && target->container.type == WINED3D_CONTAINER_SWAPCHAIN
821 && target->container.u.swapchain->front_buffer == target))
822 wglFlush(); /* Flush to ensure ordering across contexts. */
824 context_release(context);
826 return WINED3D_OK;
829 ULONG CDECL wined3d_device_incref(struct wined3d_device *device)
831 ULONG refcount = InterlockedIncrement(&device->ref);
833 TRACE("%p increasing refcount to %u.\n", device, refcount);
835 return refcount;
838 ULONG CDECL wined3d_device_decref(struct wined3d_device *device)
840 ULONG refcount = InterlockedDecrement(&device->ref);
842 TRACE("%p decreasing refcount to %u.\n", device, refcount);
844 if (!refcount)
846 UINT i;
848 for (i = 0; i < sizeof(device->multistate_funcs) / sizeof(device->multistate_funcs[0]); ++i)
850 HeapFree(GetProcessHeap(), 0, device->multistate_funcs[i]);
851 device->multistate_funcs[i] = NULL;
854 if (!list_empty(&device->resources))
856 struct wined3d_resource *resource;
858 FIXME("Device released with resources still bound, acceptable but unexpected.\n");
860 LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
862 FIXME("Leftover resource %p with type %s (%#x).\n",
863 resource, debug_d3dresourcetype(resource->resourceType), resource->resourceType);
867 if (device->contexts)
868 ERR("Context array not freed!\n");
869 if (device->hardwareCursor)
870 DestroyCursor(device->hardwareCursor);
871 device->hardwareCursor = 0;
873 wined3d_decref(device->wined3d);
874 device->wined3d = NULL;
875 HeapFree(GetProcessHeap(), 0, device);
876 TRACE("Freed device %p.\n", device);
879 return refcount;
882 UINT CDECL wined3d_device_get_swapchain_count(const struct wined3d_device *device)
884 TRACE("device %p.\n", device);
886 return device->swapchain_count;
889 HRESULT CDECL wined3d_device_get_swapchain(const struct wined3d_device *device,
890 UINT swapchain_idx, struct wined3d_swapchain **swapchain)
892 TRACE("device %p, swapchain_idx %u, swapchain %p.\n",
893 device, swapchain_idx, swapchain);
895 if (swapchain_idx >= device->swapchain_count)
897 WARN("swapchain_idx %u >= swapchain_count %u.\n",
898 swapchain_idx, device->swapchain_count);
899 *swapchain = NULL;
901 return WINED3DERR_INVALIDCALL;
904 *swapchain = device->swapchains[swapchain_idx];
905 wined3d_swapchain_incref(*swapchain);
906 TRACE("Returning %p.\n", *swapchain);
908 return WINED3D_OK;
911 static void device_load_logo(struct wined3d_device *device, const char *filename)
913 HBITMAP hbm;
914 BITMAP bm;
915 HRESULT hr;
916 HDC dcb = NULL, dcs = NULL;
917 WINEDDCOLORKEY colorkey;
919 hbm = LoadImageA(NULL, filename, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
920 if(hbm)
922 GetObjectA(hbm, sizeof(BITMAP), &bm);
923 dcb = CreateCompatibleDC(NULL);
924 if(!dcb) goto out;
925 SelectObject(dcb, hbm);
927 else
929 /* Create a 32x32 white surface to indicate that wined3d is used, but the specified image
930 * couldn't be loaded
932 memset(&bm, 0, sizeof(bm));
933 bm.bmWidth = 32;
934 bm.bmHeight = 32;
937 hr = wined3d_surface_create(device, bm.bmWidth, bm.bmHeight, WINED3DFMT_B5G6R5_UNORM, 0, 0,
938 WINED3DPOOL_DEFAULT, WINED3DMULTISAMPLE_NONE, 0, SURFACE_OPENGL, WINED3D_SURFACE_MAPPABLE,
939 NULL, &wined3d_null_parent_ops, &device->logo_surface);
940 if (FAILED(hr))
942 ERR("Wine logo requested, but failed to create surface, hr %#x.\n", hr);
943 goto out;
946 if (dcb)
948 if (FAILED(hr = wined3d_surface_getdc(device->logo_surface, &dcs)))
949 goto out;
950 BitBlt(dcs, 0, 0, bm.bmWidth, bm.bmHeight, dcb, 0, 0, SRCCOPY);
951 wined3d_surface_releasedc(device->logo_surface, dcs);
953 colorkey.dwColorSpaceLowValue = 0;
954 colorkey.dwColorSpaceHighValue = 0;
955 wined3d_surface_set_color_key(device->logo_surface, WINEDDCKEY_SRCBLT, &colorkey);
957 else
959 const struct wined3d_color c = {1.0f, 1.0f, 1.0f, 1.0f};
960 /* Fill the surface with a white color to show that wined3d is there */
961 wined3d_device_color_fill(device, device->logo_surface, NULL, &c);
964 out:
965 if (dcb) DeleteDC(dcb);
966 if (hbm) DeleteObject(hbm);
969 /* Context activation is done by the caller. */
970 static void create_dummy_textures(struct wined3d_device *device, struct wined3d_context *context)
972 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
973 unsigned int i, j, count;
974 /* Under DirectX you can sample even if no texture is bound, whereas
975 * OpenGL will only allow that when a valid texture is bound.
976 * We emulate this by creating dummy textures and binding them
977 * to each texture stage when the currently set D3D texture is NULL. */
978 ENTER_GL();
980 if (gl_info->supported[APPLE_CLIENT_STORAGE])
982 /* The dummy texture does not have client storage backing */
983 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
984 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
987 count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
988 for (i = 0; i < count; ++i)
990 DWORD color = 0x000000ff;
992 /* Make appropriate texture active */
993 context_active_texture(context, gl_info, i);
995 glGenTextures(1, &device->dummy_texture_2d[i]);
996 checkGLcall("glGenTextures");
997 TRACE("Dummy 2D texture %u given name %u.\n", i, device->dummy_texture_2d[i]);
999 glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1000 checkGLcall("glBindTexture");
1002 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1003 checkGLcall("glTexImage2D");
1005 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1007 glGenTextures(1, &device->dummy_texture_rect[i]);
1008 checkGLcall("glGenTextures");
1009 TRACE("Dummy rectangle texture %u given name %u.\n", i, device->dummy_texture_rect[i]);
1011 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1012 checkGLcall("glBindTexture");
1014 glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1015 checkGLcall("glTexImage2D");
1018 if (gl_info->supported[EXT_TEXTURE3D])
1020 glGenTextures(1, &device->dummy_texture_3d[i]);
1021 checkGLcall("glGenTextures");
1022 TRACE("Dummy 3D texture %u given name %u.\n", i, device->dummy_texture_3d[i]);
1024 glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1025 checkGLcall("glBindTexture");
1027 GL_EXTCALL(glTexImage3DEXT(GL_TEXTURE_3D, 0, GL_RGBA8, 1, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color));
1028 checkGLcall("glTexImage3D");
1031 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1033 glGenTextures(1, &device->dummy_texture_cube[i]);
1034 checkGLcall("glGenTextures");
1035 TRACE("Dummy cube texture %u given name %u.\n", i, device->dummy_texture_cube[i]);
1037 glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1038 checkGLcall("glBindTexture");
1040 for (j = GL_TEXTURE_CUBE_MAP_POSITIVE_X; j <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; ++j)
1042 glTexImage2D(j, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1043 checkGLcall("glTexImage2D");
1048 if (gl_info->supported[APPLE_CLIENT_STORAGE])
1050 /* Reenable because if supported it is enabled by default */
1051 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1052 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1055 LEAVE_GL();
1058 /* Context activation is done by the caller. */
1059 static void destroy_dummy_textures(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
1061 unsigned int count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1063 ENTER_GL();
1064 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1066 glDeleteTextures(count, device->dummy_texture_cube);
1067 checkGLcall("glDeleteTextures(count, device->dummy_texture_cube)");
1070 if (gl_info->supported[EXT_TEXTURE3D])
1072 glDeleteTextures(count, device->dummy_texture_3d);
1073 checkGLcall("glDeleteTextures(count, device->dummy_texture_3d)");
1076 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1078 glDeleteTextures(count, device->dummy_texture_rect);
1079 checkGLcall("glDeleteTextures(count, device->dummy_texture_rect)");
1082 glDeleteTextures(count, device->dummy_texture_2d);
1083 checkGLcall("glDeleteTextures(count, device->dummy_texture_2d)");
1084 LEAVE_GL();
1086 memset(device->dummy_texture_cube, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_cube));
1087 memset(device->dummy_texture_3d, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_3d));
1088 memset(device->dummy_texture_rect, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_rect));
1089 memset(device->dummy_texture_2d, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_2d));
1092 static LONG fullscreen_style(LONG style)
1094 /* Make sure the window is managed, otherwise we won't get keyboard input. */
1095 style |= WS_POPUP | WS_SYSMENU;
1096 style &= ~(WS_CAPTION | WS_THICKFRAME);
1098 return style;
1101 static LONG fullscreen_exstyle(LONG exstyle)
1103 /* Filter out window decorations. */
1104 exstyle &= ~(WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);
1106 return exstyle;
1109 void CDECL wined3d_device_setup_fullscreen_window(struct wined3d_device *device, HWND window, UINT w, UINT h)
1111 BOOL filter_messages;
1112 LONG style, exstyle;
1114 TRACE("Setting up window %p for fullscreen mode.\n", window);
1116 if (device->style || device->exStyle)
1118 ERR("Changing the window style for window %p, but another style (%08x, %08x) is already stored.\n",
1119 window, device->style, device->exStyle);
1122 device->style = GetWindowLongW(window, GWL_STYLE);
1123 device->exStyle = GetWindowLongW(window, GWL_EXSTYLE);
1125 style = fullscreen_style(device->style);
1126 exstyle = fullscreen_exstyle(device->exStyle);
1128 TRACE("Old style was %08x, %08x, setting to %08x, %08x.\n",
1129 device->style, device->exStyle, style, exstyle);
1131 filter_messages = device->filter_messages;
1132 device->filter_messages = TRUE;
1134 SetWindowLongW(window, GWL_STYLE, style);
1135 SetWindowLongW(window, GWL_EXSTYLE, exstyle);
1136 SetWindowPos(window, HWND_TOP, 0, 0, w, h, SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOACTIVATE);
1138 device->filter_messages = filter_messages;
1141 void CDECL wined3d_device_restore_fullscreen_window(struct wined3d_device *device, HWND window)
1143 BOOL filter_messages;
1144 LONG style, exstyle;
1146 if (!device->style && !device->exStyle) return;
1148 TRACE("Restoring window style of window %p to %08x, %08x.\n",
1149 window, device->style, device->exStyle);
1151 style = GetWindowLongW(window, GWL_STYLE);
1152 exstyle = GetWindowLongW(window, GWL_EXSTYLE);
1154 filter_messages = device->filter_messages;
1155 device->filter_messages = TRUE;
1157 /* Only restore the style if the application didn't modify it during the
1158 * fullscreen phase. Some applications change it before calling Reset()
1159 * when switching between windowed and fullscreen modes (HL2), some
1160 * depend on the original style (Eve Online). */
1161 if (style == fullscreen_style(device->style) && exstyle == fullscreen_exstyle(device->exStyle))
1163 SetWindowLongW(window, GWL_STYLE, device->style);
1164 SetWindowLongW(window, GWL_EXSTYLE, device->exStyle);
1166 SetWindowPos(window, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
1168 device->filter_messages = filter_messages;
1170 /* Delete the old values. */
1171 device->style = 0;
1172 device->exStyle = 0;
1175 HRESULT CDECL wined3d_device_acquire_focus_window(struct wined3d_device *device, HWND window)
1177 TRACE("device %p, window %p.\n", device, window);
1179 if (!wined3d_register_window(window, device))
1181 ERR("Failed to register window %p.\n", window);
1182 return E_FAIL;
1185 device->focus_window = window;
1186 SetWindowPos(window, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
1188 return WINED3D_OK;
1191 void CDECL wined3d_device_release_focus_window(struct wined3d_device *device)
1193 TRACE("device %p.\n", device);
1195 if (device->focus_window) wined3d_unregister_window(device->focus_window);
1196 device->focus_window = NULL;
1199 HRESULT CDECL wined3d_device_init_3d(struct wined3d_device *device,
1200 WINED3DPRESENT_PARAMETERS *present_parameters)
1202 static const struct wined3d_color black = {0.0f, 0.0f, 0.0f, 0.0f};
1203 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1204 struct wined3d_swapchain *swapchain = NULL;
1205 struct wined3d_context *context;
1206 HRESULT hr;
1207 DWORD state;
1208 unsigned int i;
1210 TRACE("device %p, present_parameters %p.\n", device, present_parameters);
1212 if (device->d3d_initialized)
1213 return WINED3DERR_INVALIDCALL;
1214 if (!device->adapter->opengl)
1215 return WINED3DERR_INVALIDCALL;
1217 TRACE("Creating stateblock.\n");
1218 hr = wined3d_stateblock_create(device, WINED3DSBT_INIT, &device->stateBlock);
1219 if (FAILED(hr))
1221 WARN("Failed to create stateblock\n");
1222 goto err_out;
1225 TRACE("Created stateblock %p.\n", device->stateBlock);
1226 device->updateStateBlock = device->stateBlock;
1227 wined3d_stateblock_incref(device->updateStateBlock);
1229 device->valid_rt_mask = 0;
1230 for (i = 0; i < gl_info->limits.buffers; ++i)
1231 device->valid_rt_mask |= (1 << i);
1232 device->fb.render_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1233 sizeof(*device->fb.render_targets) * gl_info->limits.buffers);
1235 /* Initialize the texture unit mapping to a 1:1 mapping */
1236 for (state = 0; state < MAX_COMBINED_SAMPLERS; ++state)
1238 if (state < gl_info->limits.fragment_samplers)
1240 device->texUnitMap[state] = state;
1241 device->rev_tex_unit_map[state] = state;
1243 else
1245 device->texUnitMap[state] = WINED3D_UNMAPPED_STAGE;
1246 device->rev_tex_unit_map[state] = WINED3D_UNMAPPED_STAGE;
1250 /* Setup the implicit swapchain. This also initializes a context. */
1251 TRACE("Creating implicit swapchain\n");
1252 hr = device->device_parent->ops->create_swapchain(device->device_parent,
1253 present_parameters, &swapchain);
1254 if (FAILED(hr))
1256 WARN("Failed to create implicit swapchain\n");
1257 goto err_out;
1260 device->swapchain_count = 1;
1261 device->swapchains = HeapAlloc(GetProcessHeap(), 0, device->swapchain_count * sizeof(*device->swapchains));
1262 if (!device->swapchains)
1264 ERR("Out of memory!\n");
1265 goto err_out;
1267 device->swapchains[0] = swapchain;
1269 if (swapchain->back_buffers && swapchain->back_buffers[0])
1271 TRACE("Setting rendertarget to %p.\n", swapchain->back_buffers);
1272 device->fb.render_targets[0] = swapchain->back_buffers[0];
1274 else
1276 TRACE("Setting rendertarget to %p.\n", swapchain->front_buffer);
1277 device->fb.render_targets[0] = swapchain->front_buffer;
1279 wined3d_surface_incref(device->fb.render_targets[0]);
1281 /* Depth Stencil support */
1282 device->fb.depth_stencil = device->auto_depth_stencil;
1283 if (device->fb.depth_stencil)
1284 wined3d_surface_incref(device->fb.depth_stencil);
1286 hr = device->shader_backend->shader_alloc_private(device);
1287 if (FAILED(hr))
1289 TRACE("Shader private data couldn't be allocated\n");
1290 goto err_out;
1292 hr = device->frag_pipe->alloc_private(device);
1293 if (FAILED(hr))
1295 TRACE("Fragment pipeline private data couldn't be allocated\n");
1296 goto err_out;
1298 hr = device->blitter->alloc_private(device);
1299 if (FAILED(hr))
1301 TRACE("Blitter private data couldn't be allocated\n");
1302 goto err_out;
1305 /* Set up some starting GL setup */
1307 /* Setup all the devices defaults */
1308 stateblock_init_default_state(device->stateBlock);
1310 context = context_acquire(device, swapchain->front_buffer);
1312 create_dummy_textures(device, context);
1314 ENTER_GL();
1316 /* Initialize the current view state */
1317 device->view_ident = 1;
1318 device->contexts[0]->last_was_rhw = 0;
1320 switch (wined3d_settings.offscreen_rendering_mode)
1322 case ORM_FBO:
1323 device->offscreenBuffer = GL_COLOR_ATTACHMENT0;
1324 break;
1326 case ORM_BACKBUFFER:
1328 if (context_get_current()->aux_buffers > 0)
1330 TRACE("Using auxiliary buffer for offscreen rendering\n");
1331 device->offscreenBuffer = GL_AUX0;
1333 else
1335 TRACE("Using back buffer for offscreen rendering\n");
1336 device->offscreenBuffer = GL_BACK;
1341 TRACE("All defaults now set up, leaving 3D init.\n");
1342 LEAVE_GL();
1344 context_release(context);
1346 /* Clear the screen */
1347 wined3d_device_clear(device, 0, NULL, WINED3DCLEAR_TARGET
1348 | (present_parameters->EnableAutoDepthStencil ? WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL : 0),
1349 &black, 1.0f, 0);
1351 device->d3d_initialized = TRUE;
1353 if (wined3d_settings.logo)
1354 device_load_logo(device, wined3d_settings.logo);
1355 return WINED3D_OK;
1357 err_out:
1358 HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1359 HeapFree(GetProcessHeap(), 0, device->swapchains);
1360 device->swapchain_count = 0;
1361 if (swapchain)
1362 wined3d_swapchain_decref(swapchain);
1363 if (device->stateBlock)
1365 wined3d_stateblock_decref(device->stateBlock);
1366 device->stateBlock = NULL;
1368 if (device->blit_priv)
1369 device->blitter->free_private(device);
1370 if (device->fragment_priv)
1371 device->frag_pipe->free_private(device);
1372 if (device->shader_priv)
1373 device->shader_backend->shader_free_private(device);
1375 return hr;
1378 HRESULT CDECL wined3d_device_init_gdi(struct wined3d_device *device,
1379 WINED3DPRESENT_PARAMETERS *present_parameters)
1381 struct wined3d_swapchain *swapchain = NULL;
1382 HRESULT hr;
1384 TRACE("device %p, present_parameters %p.\n", device, present_parameters);
1386 /* Setup the implicit swapchain */
1387 TRACE("Creating implicit swapchain\n");
1388 hr = device->device_parent->ops->create_swapchain(device->device_parent,
1389 present_parameters, &swapchain);
1390 if (FAILED(hr))
1392 WARN("Failed to create implicit swapchain\n");
1393 goto err_out;
1396 device->swapchain_count = 1;
1397 device->swapchains = HeapAlloc(GetProcessHeap(), 0, device->swapchain_count * sizeof(*device->swapchains));
1398 if (!device->swapchains)
1400 ERR("Out of memory!\n");
1401 goto err_out;
1403 device->swapchains[0] = swapchain;
1404 return WINED3D_OK;
1406 err_out:
1407 wined3d_swapchain_decref(swapchain);
1408 return hr;
1411 HRESULT CDECL wined3d_device_uninit_3d(struct wined3d_device *device)
1413 struct wined3d_resource *resource, *cursor;
1414 const struct wined3d_gl_info *gl_info;
1415 struct wined3d_context *context;
1416 struct wined3d_surface *surface;
1417 UINT i;
1419 TRACE("device %p.\n", device);
1421 if (!device->d3d_initialized)
1422 return WINED3DERR_INVALIDCALL;
1424 /* Force making the context current again, to verify it is still valid
1425 * (workaround for broken drivers) */
1426 context_set_current(NULL);
1427 /* I don't think that the interface guarantees that the device is destroyed from the same thread
1428 * it was created. Thus make sure a context is active for the glDelete* calls
1430 context = context_acquire(device, NULL);
1431 gl_info = context->gl_info;
1433 if (device->logo_surface)
1434 wined3d_surface_decref(device->logo_surface);
1436 /* Unload resources */
1437 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
1439 TRACE("Unloading resource %p.\n", resource);
1441 resource->resource_ops->resource_unload(resource);
1444 TRACE("Deleting high order patches\n");
1445 for(i = 0; i < PATCHMAP_SIZE; i++) {
1446 struct list *e1, *e2;
1447 struct WineD3DRectPatch *patch;
1448 LIST_FOR_EACH_SAFE(e1, e2, &device->patches[i])
1450 patch = LIST_ENTRY(e1, struct WineD3DRectPatch, entry);
1451 wined3d_device_delete_patch(device, patch->Handle);
1455 /* Delete the mouse cursor texture */
1456 if (device->cursorTexture)
1458 ENTER_GL();
1459 glDeleteTextures(1, &device->cursorTexture);
1460 LEAVE_GL();
1461 device->cursorTexture = 0;
1464 /* Destroy the depth blt resources, they will be invalid after the reset. Also free shader
1465 * private data, it might contain opengl pointers
1467 if (device->depth_blt_texture)
1469 ENTER_GL();
1470 glDeleteTextures(1, &device->depth_blt_texture);
1471 LEAVE_GL();
1472 device->depth_blt_texture = 0;
1475 /* Release the update stateblock */
1476 if (wined3d_stateblock_decref(device->updateStateBlock))
1478 if (device->updateStateBlock != device->stateBlock)
1479 FIXME("Something's still holding the update stateblock.\n");
1481 device->updateStateBlock = NULL;
1484 struct wined3d_stateblock *stateblock = device->stateBlock;
1485 device->stateBlock = NULL;
1487 /* Release the stateblock */
1488 if (wined3d_stateblock_decref(stateblock))
1489 FIXME("Something's still holding the stateblock.\n");
1492 /* Destroy the shader backend. Note that this has to happen after all shaders are destroyed. */
1493 device->blitter->free_private(device);
1494 device->frag_pipe->free_private(device);
1495 device->shader_backend->shader_free_private(device);
1497 /* Release the buffers (with sanity checks)*/
1498 if (device->onscreen_depth_stencil)
1500 surface = device->onscreen_depth_stencil;
1501 device->onscreen_depth_stencil = NULL;
1502 wined3d_surface_decref(surface);
1505 if (device->fb.depth_stencil)
1507 surface = device->fb.depth_stencil;
1509 TRACE("Releasing depth/stencil buffer %p.\n", surface);
1511 device->fb.depth_stencil = NULL;
1512 if (wined3d_surface_decref(surface)
1513 && surface != device->auto_depth_stencil)
1514 ERR("Something is still holding a reference to depth/stencil buffer %p.\n", surface);
1517 if (device->auto_depth_stencil)
1519 surface = device->auto_depth_stencil;
1520 device->auto_depth_stencil = NULL;
1521 if (wined3d_surface_decref(surface))
1522 FIXME("Something's still holding the auto depth stencil buffer (%p).\n", surface);
1525 for (i = 1; i < gl_info->limits.buffers; ++i)
1527 wined3d_device_set_render_target(device, i, NULL, FALSE);
1530 surface = device->fb.render_targets[0];
1531 TRACE("Setting rendertarget 0 to NULL\n");
1532 device->fb.render_targets[0] = NULL;
1533 TRACE("Releasing the render target at %p\n", surface);
1534 wined3d_surface_decref(surface);
1536 context_release(context);
1538 for (i = 0; i < device->swapchain_count; ++i)
1540 TRACE("Releasing the implicit swapchain %u.\n", i);
1541 if (wined3d_swapchain_decref(device->swapchains[i]))
1542 FIXME("Something's still holding the implicit swapchain.\n");
1545 HeapFree(GetProcessHeap(), 0, device->swapchains);
1546 device->swapchains = NULL;
1547 device->swapchain_count = 0;
1549 HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1550 device->fb.render_targets = NULL;
1552 device->d3d_initialized = FALSE;
1554 return WINED3D_OK;
1557 HRESULT CDECL wined3d_device_uninit_gdi(struct wined3d_device *device)
1559 unsigned int i;
1561 for (i = 0; i < device->swapchain_count; ++i)
1563 TRACE("Releasing the implicit swapchain %u.\n", i);
1564 if (wined3d_swapchain_decref(device->swapchains[i]))
1565 FIXME("Something's still holding the implicit swapchain.\n");
1568 HeapFree(GetProcessHeap(), 0, device->swapchains);
1569 device->swapchains = NULL;
1570 device->swapchain_count = 0;
1571 return WINED3D_OK;
1574 /* Enables thread safety in the wined3d device and its resources. Called by DirectDraw
1575 * from SetCooperativeLevel if DDSCL_MULTITHREADED is specified, and by d3d8/9 from
1576 * CreateDevice if D3DCREATE_MULTITHREADED is passed.
1578 * There is no way to deactivate thread safety once it is enabled.
1580 void CDECL wined3d_device_set_multithreaded(struct wined3d_device *device)
1582 TRACE("device %p.\n", device);
1584 /* For now just store the flag (needed in case of ddraw). */
1585 device->create_parms.flags |= WINED3DCREATE_MULTITHREADED;
1588 HRESULT CDECL wined3d_device_set_display_mode(struct wined3d_device *device,
1589 UINT swapchain_idx, const struct wined3d_display_mode *mode)
1591 struct wined3d_adapter *adapter = device->adapter;
1592 const struct wined3d_format *format = wined3d_get_format(&adapter->gl_info, mode->format_id);
1593 DEVMODEW devmode;
1594 LONG ret;
1595 RECT clip_rc;
1597 TRACE("device %p, swapchain_idx %u, mode %p (%ux%u@%u %s).\n", device, swapchain_idx, mode,
1598 mode->width, mode->height, mode->refresh_rate, debug_d3dformat(mode->format_id));
1600 /* Resize the screen even without a window:
1601 * The app could have unset it with SetCooperativeLevel, but not called
1602 * RestoreDisplayMode first. Then the release will call RestoreDisplayMode,
1603 * but we don't have any hwnd
1606 memset(&devmode, 0, sizeof(devmode));
1607 devmode.dmSize = sizeof(devmode);
1608 devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1609 devmode.dmBitsPerPel = format->byte_count * CHAR_BIT;
1610 devmode.dmPelsWidth = mode->width;
1611 devmode.dmPelsHeight = mode->height;
1613 devmode.dmDisplayFrequency = mode->refresh_rate;
1614 if (mode->refresh_rate)
1615 devmode.dmFields |= DM_DISPLAYFREQUENCY;
1617 /* Only change the mode if necessary */
1618 if (adapter->screen_size.cx == mode->width && adapter->screen_size.cy == mode->height
1619 && adapter->screen_format == mode->format_id && !mode->refresh_rate)
1620 return WINED3D_OK;
1622 ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL);
1623 if (ret != DISP_CHANGE_SUCCESSFUL)
1625 if (devmode.dmDisplayFrequency)
1627 WARN("ChangeDisplaySettingsExW failed, trying without the refresh rate\n");
1628 devmode.dmFields &= ~DM_DISPLAYFREQUENCY;
1629 devmode.dmDisplayFrequency = 0;
1630 ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL) != DISP_CHANGE_SUCCESSFUL;
1632 if(ret != DISP_CHANGE_SUCCESSFUL) {
1633 return WINED3DERR_NOTAVAILABLE;
1637 /* Store the new values */
1638 adapter->screen_size.cx = mode->width;
1639 adapter->screen_size.cy = mode->height;
1640 adapter->screen_format = mode->format_id;
1642 /* And finally clip mouse to our screen */
1643 SetRect(&clip_rc, 0, 0, mode->width, mode->height);
1644 ClipCursor(&clip_rc);
1646 return WINED3D_OK;
1649 HRESULT CDECL wined3d_device_get_wined3d(const struct wined3d_device *device, struct wined3d **wined3d)
1651 TRACE("device %p, wined3d %p.\n", device, wined3d);
1653 *wined3d = device->wined3d;
1654 wined3d_incref(*wined3d);
1656 TRACE("Returning %p.\n", *wined3d);
1658 return WINED3D_OK;
1661 UINT CDECL wined3d_device_get_available_texture_mem(const struct wined3d_device *device)
1663 TRACE("device %p.\n", device);
1665 TRACE("Emulating %d MB, returning %d MB left.\n",
1666 device->adapter->TextureRam / (1024 * 1024),
1667 (device->adapter->TextureRam - device->adapter->UsedTextureRam) / (1024 * 1024));
1669 return device->adapter->TextureRam - device->adapter->UsedTextureRam;
1672 HRESULT CDECL wined3d_device_set_stream_source(struct wined3d_device *device, UINT stream_idx,
1673 struct wined3d_buffer *buffer, UINT offset, UINT stride)
1675 struct wined3d_stream_state *stream;
1676 struct wined3d_buffer *prev_buffer;
1678 TRACE("device %p, stream_idx %u, buffer %p, offset %u, stride %u.\n",
1679 device, stream_idx, buffer, offset, stride);
1681 if (stream_idx >= MAX_STREAMS)
1683 WARN("Stream index %u out of range.\n", stream_idx);
1684 return WINED3DERR_INVALIDCALL;
1686 else if (offset & 0x3)
1688 WARN("Offset %u is not 4 byte aligned.\n", offset);
1689 return WINED3DERR_INVALIDCALL;
1692 stream = &device->updateStateBlock->state.streams[stream_idx];
1693 prev_buffer = stream->buffer;
1695 device->updateStateBlock->changed.streamSource |= 1 << stream_idx;
1697 if (prev_buffer == buffer
1698 && stream->stride == stride
1699 && stream->offset == offset)
1701 TRACE("Application is setting the old values over, nothing to do.\n");
1702 return WINED3D_OK;
1705 stream->buffer = buffer;
1706 if (buffer)
1708 stream->stride = stride;
1709 stream->offset = offset;
1712 /* Handle recording of state blocks. */
1713 if (device->isRecordingState)
1715 TRACE("Recording... not performing anything.\n");
1716 if (buffer)
1717 wined3d_buffer_incref(buffer);
1718 if (prev_buffer)
1719 wined3d_buffer_decref(prev_buffer);
1720 return WINED3D_OK;
1723 if (buffer)
1725 InterlockedIncrement(&buffer->bind_count);
1726 wined3d_buffer_incref(buffer);
1728 if (prev_buffer)
1730 InterlockedDecrement(&prev_buffer->bind_count);
1731 wined3d_buffer_decref(prev_buffer);
1734 device_invalidate_state(device, STATE_STREAMSRC);
1736 return WINED3D_OK;
1739 HRESULT CDECL wined3d_device_get_stream_source(const struct wined3d_device *device,
1740 UINT stream_idx, struct wined3d_buffer **buffer, UINT *offset, UINT *stride)
1742 struct wined3d_stream_state *stream;
1744 TRACE("device %p, stream_idx %u, buffer %p, offset %p, stride %p.\n",
1745 device, stream_idx, buffer, offset, stride);
1747 if (stream_idx >= MAX_STREAMS)
1749 WARN("Stream index %u out of range.\n", stream_idx);
1750 return WINED3DERR_INVALIDCALL;
1753 stream = &device->stateBlock->state.streams[stream_idx];
1754 *buffer = stream->buffer;
1755 if (*buffer)
1756 wined3d_buffer_incref(*buffer);
1757 if (offset)
1758 *offset = stream->offset;
1759 *stride = stream->stride;
1761 return WINED3D_OK;
1764 HRESULT CDECL wined3d_device_set_stream_source_freq(struct wined3d_device *device, UINT stream_idx, UINT divider)
1766 struct wined3d_stream_state *stream;
1767 UINT old_flags, old_freq;
1769 TRACE("device %p, stream_idx %u, divider %#x.\n", device, stream_idx, divider);
1771 /* Verify input. At least in d3d9 this is invalid. */
1772 if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && (divider & WINED3DSTREAMSOURCE_INDEXEDDATA))
1774 WARN("INSTANCEDATA and INDEXEDDATA were set, returning D3DERR_INVALIDCALL.\n");
1775 return WINED3DERR_INVALIDCALL;
1777 if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && !stream_idx)
1779 WARN("INSTANCEDATA used on stream 0, returning D3DERR_INVALIDCALL.\n");
1780 return WINED3DERR_INVALIDCALL;
1782 if (!divider)
1784 WARN("Divider is 0, returning D3DERR_INVALIDCALL.\n");
1785 return WINED3DERR_INVALIDCALL;
1788 stream = &device->updateStateBlock->state.streams[stream_idx];
1789 old_flags = stream->flags;
1790 old_freq = stream->frequency;
1792 stream->flags = divider & (WINED3DSTREAMSOURCE_INSTANCEDATA | WINED3DSTREAMSOURCE_INDEXEDDATA);
1793 stream->frequency = divider & 0x7fffff;
1795 device->updateStateBlock->changed.streamFreq |= 1 << stream_idx;
1797 if (stream->frequency != old_freq || stream->flags != old_flags)
1798 device_invalidate_state(device, STATE_STREAMSRC);
1800 return WINED3D_OK;
1803 HRESULT CDECL wined3d_device_get_stream_source_freq(const struct wined3d_device *device,
1804 UINT stream_idx, UINT *divider)
1806 struct wined3d_stream_state *stream;
1808 TRACE("device %p, stream_idx %u, divider %p.\n", device, stream_idx, divider);
1810 stream = &device->updateStateBlock->state.streams[stream_idx];
1811 *divider = stream->flags | stream->frequency;
1813 TRACE("Returning %#x.\n", *divider);
1815 return WINED3D_OK;
1818 HRESULT CDECL wined3d_device_set_transform(struct wined3d_device *device,
1819 WINED3DTRANSFORMSTATETYPE d3dts, const struct wined3d_matrix *matrix)
1821 TRACE("device %p, state %s, matrix %p.\n",
1822 device, debug_d3dtstype(d3dts), matrix);
1824 /* Handle recording of state blocks. */
1825 if (device->isRecordingState)
1827 TRACE("Recording... not performing anything.\n");
1828 device->updateStateBlock->changed.transform[d3dts >> 5] |= 1 << (d3dts & 0x1f);
1829 device->updateStateBlock->state.transforms[d3dts] = *matrix;
1830 return WINED3D_OK;
1833 /* If the new matrix is the same as the current one,
1834 * we cut off any further processing. this seems to be a reasonable
1835 * optimization because as was noticed, some apps (warcraft3 for example)
1836 * tend towards setting the same matrix repeatedly for some reason.
1838 * From here on we assume that the new matrix is different, wherever it matters. */
1839 if (!memcmp(&device->stateBlock->state.transforms[d3dts].u.m[0][0], matrix, sizeof(*matrix)))
1841 TRACE("The application is setting the same matrix over again.\n");
1842 return WINED3D_OK;
1845 conv_mat(matrix, &device->stateBlock->state.transforms[d3dts].u.m[0][0]);
1847 /* ScreenCoord = ProjectionMat * ViewMat * WorldMat * ObjectCoord
1848 * where ViewMat = Camera space, WorldMat = world space.
1850 * In OpenGL, camera and world space is combined into GL_MODELVIEW
1851 * matrix. The Projection matrix stay projection matrix. */
1853 if (d3dts == WINED3DTS_VIEW)
1854 device->view_ident = !memcmp(matrix, identity, 16 * sizeof(float));
1856 if (d3dts < WINED3DTS_WORLDMATRIX(device->adapter->gl_info.limits.blends))
1857 device_invalidate_state(device, STATE_TRANSFORM(d3dts));
1859 return WINED3D_OK;
1863 HRESULT CDECL wined3d_device_get_transform(const struct wined3d_device *device,
1864 WINED3DTRANSFORMSTATETYPE state, struct wined3d_matrix *matrix)
1866 TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1868 *matrix = device->stateBlock->state.transforms[state];
1870 return WINED3D_OK;
1873 HRESULT CDECL wined3d_device_multiply_transform(struct wined3d_device *device,
1874 WINED3DTRANSFORMSTATETYPE state, const struct wined3d_matrix *matrix)
1876 const struct wined3d_matrix *mat = NULL;
1877 struct wined3d_matrix temp;
1879 TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1881 /* Note: Using 'updateStateBlock' rather than 'stateblock' in the code
1882 * below means it will be recorded in a state block change, but it
1883 * works regardless where it is recorded.
1884 * If this is found to be wrong, change to StateBlock. */
1885 if (state > HIGHEST_TRANSFORMSTATE)
1887 WARN("Unhandled transform state %#x.\n", state);
1888 return WINED3D_OK;
1891 mat = &device->updateStateBlock->state.transforms[state];
1892 multiply_matrix(&temp, mat, matrix);
1894 /* Apply change via set transform - will reapply to eg. lights this way. */
1895 return wined3d_device_set_transform(device, state, &temp);
1898 /* Note lights are real special cases. Although the device caps state only
1899 * e.g. 8 are supported, you can reference any indexes you want as long as
1900 * that number max are enabled at any one point in time. Therefore since the
1901 * indices can be anything, we need a hashmap of them. However, this causes
1902 * stateblock problems. When capturing the state block, I duplicate the
1903 * hashmap, but when recording, just build a chain pretty much of commands to
1904 * be replayed. */
1905 HRESULT CDECL wined3d_device_set_light(struct wined3d_device *device,
1906 UINT light_idx, const struct wined3d_light *light)
1908 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
1909 struct wined3d_light_info *object = NULL;
1910 struct list *e;
1911 float rho;
1913 TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
1915 /* Check the parameter range. Need for speed most wanted sets junk lights
1916 * which confuse the GL driver. */
1917 if (!light)
1918 return WINED3DERR_INVALIDCALL;
1920 switch (light->type)
1922 case WINED3DLIGHT_POINT:
1923 case WINED3DLIGHT_SPOT:
1924 case WINED3DLIGHT_PARALLELPOINT:
1925 case WINED3DLIGHT_GLSPOT:
1926 /* Incorrect attenuation values can cause the gl driver to crash.
1927 * Happens with Need for speed most wanted. */
1928 if (light->attenuation0 < 0.0f || light->attenuation1 < 0.0f || light->attenuation2 < 0.0f)
1930 WARN("Attenuation is negative, returning WINED3DERR_INVALIDCALL.\n");
1931 return WINED3DERR_INVALIDCALL;
1933 break;
1935 case WINED3DLIGHT_DIRECTIONAL:
1936 /* Ignores attenuation */
1937 break;
1939 default:
1940 WARN("Light type out of range, returning WINED3DERR_INVALIDCALL\n");
1941 return WINED3DERR_INVALIDCALL;
1944 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
1946 object = LIST_ENTRY(e, struct wined3d_light_info, entry);
1947 if (object->OriginalIndex == light_idx)
1948 break;
1949 object = NULL;
1952 if (!object)
1954 TRACE("Adding new light\n");
1955 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1956 if (!object)
1958 ERR("Out of memory error when allocating a light\n");
1959 return E_OUTOFMEMORY;
1961 list_add_head(&device->updateStateBlock->state.light_map[hash_idx], &object->entry);
1962 object->glIndex = -1;
1963 object->OriginalIndex = light_idx;
1966 /* Initialize the object. */
1967 TRACE("Light %d setting to type %d, Diffuse(%f,%f,%f,%f), Specular(%f,%f,%f,%f), Ambient(%f,%f,%f,%f)\n",
1968 light_idx, light->type,
1969 light->diffuse.r, light->diffuse.g, light->diffuse.b, light->diffuse.a,
1970 light->specular.r, light->specular.g, light->specular.b, light->specular.a,
1971 light->ambient.r, light->ambient.g, light->ambient.b, light->ambient.a);
1972 TRACE("... Pos(%f,%f,%f), Dir(%f,%f,%f)\n", light->position.x, light->position.y, light->position.z,
1973 light->direction.x, light->direction.y, light->direction.z);
1974 TRACE("... Range(%f), Falloff(%f), Theta(%f), Phi(%f)\n",
1975 light->range, light->falloff, light->theta, light->phi);
1977 /* Save away the information. */
1978 object->OriginalParms = *light;
1980 switch (light->type)
1982 case WINED3DLIGHT_POINT:
1983 /* Position */
1984 object->lightPosn[0] = light->position.x;
1985 object->lightPosn[1] = light->position.y;
1986 object->lightPosn[2] = light->position.z;
1987 object->lightPosn[3] = 1.0f;
1988 object->cutoff = 180.0f;
1989 /* FIXME: Range */
1990 break;
1992 case WINED3DLIGHT_DIRECTIONAL:
1993 /* Direction */
1994 object->lightPosn[0] = -light->direction.x;
1995 object->lightPosn[1] = -light->direction.y;
1996 object->lightPosn[2] = -light->direction.z;
1997 object->lightPosn[3] = 0.0f;
1998 object->exponent = 0.0f;
1999 object->cutoff = 180.0f;
2000 break;
2002 case WINED3DLIGHT_SPOT:
2003 /* Position */
2004 object->lightPosn[0] = light->position.x;
2005 object->lightPosn[1] = light->position.y;
2006 object->lightPosn[2] = light->position.z;
2007 object->lightPosn[3] = 1.0f;
2009 /* Direction */
2010 object->lightDirn[0] = light->direction.x;
2011 object->lightDirn[1] = light->direction.y;
2012 object->lightDirn[2] = light->direction.z;
2013 object->lightDirn[3] = 1.0f;
2015 /* opengl-ish and d3d-ish spot lights use too different models
2016 * for the light "intensity" as a function of the angle towards
2017 * the main light direction, so we only can approximate very
2018 * roughly. However, spot lights are rather rarely used in games
2019 * (if ever used at all). Furthermore if still used, probably
2020 * nobody pays attention to such details. */
2021 if (!light->falloff)
2023 /* Falloff = 0 is easy, because d3d's and opengl's spot light
2024 * equations have the falloff resp. exponent parameter as an
2025 * exponent, so the spot light lighting will always be 1.0 for
2026 * both of them, and we don't have to care for the rest of the
2027 * rather complex calculation. */
2028 object->exponent = 0.0f;
2030 else
2032 rho = light->theta + (light->phi - light->theta) / (2 * light->falloff);
2033 if (rho < 0.0001f)
2034 rho = 0.0001f;
2035 object->exponent = -0.3f / logf(cosf(rho / 2));
2038 if (object->exponent > 128.0f)
2039 object->exponent = 128.0f;
2041 object->cutoff = (float)(light->phi * 90 / M_PI);
2042 /* FIXME: Range */
2043 break;
2045 default:
2046 FIXME("Unrecognized light type %#x.\n", light->type);
2049 /* Update the live definitions if the light is currently assigned a glIndex. */
2050 if (object->glIndex != -1 && !device->isRecordingState)
2051 device_invalidate_state(device, STATE_ACTIVELIGHT(object->glIndex));
2053 return WINED3D_OK;
2056 HRESULT CDECL wined3d_device_get_light(const struct wined3d_device *device,
2057 UINT light_idx, struct wined3d_light *light)
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, light %p.\n", device, light_idx, light);
2065 LIST_FOR_EACH(e, &device->stateBlock->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;
2073 if (!light_info)
2075 TRACE("Light information requested but light not defined\n");
2076 return WINED3DERR_INVALIDCALL;
2079 *light = light_info->OriginalParms;
2080 return WINED3D_OK;
2083 HRESULT CDECL wined3d_device_set_light_enable(struct wined3d_device *device, UINT light_idx, BOOL enable)
2085 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2086 struct wined3d_light_info *light_info = NULL;
2087 struct list *e;
2089 TRACE("device %p, light_idx %u, enable %#x.\n", device, light_idx, enable);
2091 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2093 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2094 if (light_info->OriginalIndex == light_idx)
2095 break;
2096 light_info = NULL;
2098 TRACE("Found light %p.\n", light_info);
2100 /* Special case - enabling an undefined light creates one with a strict set of parameters. */
2101 if (!light_info)
2103 TRACE("Light enabled requested but light not defined, so defining one!\n");
2104 wined3d_device_set_light(device, light_idx, &WINED3D_default_light);
2106 /* Search for it again! Should be fairly quick as near head of list. */
2107 LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2109 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2110 if (light_info->OriginalIndex == light_idx)
2111 break;
2112 light_info = NULL;
2114 if (!light_info)
2116 FIXME("Adding default lights has failed dismally\n");
2117 return WINED3DERR_INVALIDCALL;
2121 if (!enable)
2123 if (light_info->glIndex != -1)
2125 if (!device->isRecordingState)
2126 device_invalidate_state(device, STATE_ACTIVELIGHT(light_info->glIndex));
2128 device->updateStateBlock->state.lights[light_info->glIndex] = NULL;
2129 light_info->glIndex = -1;
2131 else
2133 TRACE("Light already disabled, nothing to do\n");
2135 light_info->enabled = FALSE;
2137 else
2139 light_info->enabled = TRUE;
2140 if (light_info->glIndex != -1)
2142 TRACE("Nothing to do as light was enabled\n");
2144 else
2146 unsigned int i;
2147 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2148 /* Find a free GL light. */
2149 for (i = 0; i < gl_info->limits.lights; ++i)
2151 if (!device->updateStateBlock->state.lights[i])
2153 device->updateStateBlock->state.lights[i] = light_info;
2154 light_info->glIndex = i;
2155 break;
2158 if (light_info->glIndex == -1)
2160 /* Our tests show that Windows returns D3D_OK in this situation, even with
2161 * D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE devices. This
2162 * is consistent among ddraw, d3d8 and d3d9. GetLightEnable returns TRUE
2163 * as well for those lights.
2165 * TODO: Test how this affects rendering. */
2166 WARN("Too many concurrently active lights\n");
2167 return WINED3D_OK;
2170 /* i == light_info->glIndex */
2171 if (!device->isRecordingState)
2172 device_invalidate_state(device, STATE_ACTIVELIGHT(i));
2176 return WINED3D_OK;
2179 HRESULT CDECL wined3d_device_get_light_enable(const struct wined3d_device *device, UINT light_idx, BOOL *enable)
2181 UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2182 struct wined3d_light_info *light_info = NULL;
2183 struct list *e;
2185 TRACE("device %p, light_idx %u, enable %p.\n", device, light_idx, enable);
2187 LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
2189 light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2190 if (light_info->OriginalIndex == light_idx)
2191 break;
2192 light_info = NULL;
2195 if (!light_info)
2197 TRACE("Light enabled state requested but light not defined.\n");
2198 return WINED3DERR_INVALIDCALL;
2200 /* true is 128 according to SetLightEnable */
2201 *enable = light_info->enabled ? 128 : 0;
2202 return WINED3D_OK;
2205 HRESULT CDECL wined3d_device_set_clip_plane(struct wined3d_device *device, UINT plane_idx, const float *plane)
2207 TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2209 /* Validate plane_idx. */
2210 if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2212 TRACE("Application has requested clipplane this device doesn't support.\n");
2213 return WINED3DERR_INVALIDCALL;
2216 device->updateStateBlock->changed.clipplane |= 1 << plane_idx;
2218 if (device->updateStateBlock->state.clip_planes[plane_idx][0] == plane[0]
2219 && device->updateStateBlock->state.clip_planes[plane_idx][1] == plane[1]
2220 && device->updateStateBlock->state.clip_planes[plane_idx][2] == plane[2]
2221 && device->updateStateBlock->state.clip_planes[plane_idx][3] == plane[3])
2223 TRACE("Application is setting old values over, nothing to do.\n");
2224 return WINED3D_OK;
2227 device->updateStateBlock->state.clip_planes[plane_idx][0] = plane[0];
2228 device->updateStateBlock->state.clip_planes[plane_idx][1] = plane[1];
2229 device->updateStateBlock->state.clip_planes[plane_idx][2] = plane[2];
2230 device->updateStateBlock->state.clip_planes[plane_idx][3] = plane[3];
2232 /* Handle recording of state blocks. */
2233 if (device->isRecordingState)
2235 TRACE("Recording... not performing anything.\n");
2236 return WINED3D_OK;
2239 device_invalidate_state(device, STATE_CLIPPLANE(plane_idx));
2241 return WINED3D_OK;
2244 HRESULT CDECL wined3d_device_get_clip_plane(const struct wined3d_device *device, UINT plane_idx, float *plane)
2246 TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2248 /* Validate plane_idx. */
2249 if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2251 TRACE("Application has requested clipplane this device doesn't support.\n");
2252 return WINED3DERR_INVALIDCALL;
2255 plane[0] = (float)device->stateBlock->state.clip_planes[plane_idx][0];
2256 plane[1] = (float)device->stateBlock->state.clip_planes[plane_idx][1];
2257 plane[2] = (float)device->stateBlock->state.clip_planes[plane_idx][2];
2258 plane[3] = (float)device->stateBlock->state.clip_planes[plane_idx][3];
2260 return WINED3D_OK;
2263 HRESULT CDECL wined3d_device_set_clip_status(struct wined3d_device *device,
2264 const struct wined3d_clip_status *clip_status)
2266 FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2268 if (!clip_status)
2269 return WINED3DERR_INVALIDCALL;
2271 return WINED3D_OK;
2274 HRESULT CDECL wined3d_device_get_clip_status(const struct wined3d_device *device,
2275 struct wined3d_clip_status *clip_status)
2277 FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2279 if (!clip_status)
2280 return WINED3DERR_INVALIDCALL;
2282 return WINED3D_OK;
2285 HRESULT CDECL wined3d_device_set_material(struct wined3d_device *device, const struct wined3d_material *material)
2287 TRACE("device %p, material %p.\n", device, material);
2289 device->updateStateBlock->changed.material = TRUE;
2290 device->updateStateBlock->state.material = *material;
2292 /* Handle recording of state blocks */
2293 if (device->isRecordingState)
2295 TRACE("Recording... not performing anything.\n");
2296 return WINED3D_OK;
2299 device_invalidate_state(device, STATE_MATERIAL);
2301 return WINED3D_OK;
2304 HRESULT CDECL wined3d_device_get_material(const struct wined3d_device *device, struct wined3d_material *material)
2306 TRACE("device %p, material %p.\n", device, material);
2308 *material = device->updateStateBlock->state.material;
2310 TRACE("diffuse {%.8e, %.8e, %.8e, %.8e}\n",
2311 material->diffuse.r, material->diffuse.g,
2312 material->diffuse.b, material->diffuse.a);
2313 TRACE("ambient {%.8e, %.8e, %.8e, %.8e}\n",
2314 material->ambient.r, material->ambient.g,
2315 material->ambient.b, material->ambient.a);
2316 TRACE("specular {%.8e, %.8e, %.8e, %.8e}\n",
2317 material->specular.r, material->specular.g,
2318 material->specular.b, material->specular.a);
2319 TRACE("emissive {%.8e, %.8e, %.8e, %.8e}\n",
2320 material->emissive.r, material->emissive.g,
2321 material->emissive.b, material->emissive.a);
2322 TRACE("power %.8e.\n", material->power);
2324 return WINED3D_OK;
2327 HRESULT CDECL wined3d_device_set_index_buffer(struct wined3d_device *device,
2328 struct wined3d_buffer *buffer, enum wined3d_format_id format_id)
2330 struct wined3d_buffer *prev_buffer;
2332 TRACE("device %p, buffer %p, format %s.\n",
2333 device, buffer, debug_d3dformat(format_id));
2335 prev_buffer = device->updateStateBlock->state.index_buffer;
2337 device->updateStateBlock->changed.indices = TRUE;
2338 device->updateStateBlock->state.index_buffer = buffer;
2339 device->updateStateBlock->state.index_format = format_id;
2341 /* Handle recording of state blocks. */
2342 if (device->isRecordingState)
2344 TRACE("Recording... not performing anything.\n");
2345 if (buffer)
2346 wined3d_buffer_incref(buffer);
2347 if (prev_buffer)
2348 wined3d_buffer_decref(prev_buffer);
2349 return WINED3D_OK;
2352 if (prev_buffer != buffer)
2354 device_invalidate_state(device, STATE_INDEXBUFFER);
2355 if (buffer)
2357 InterlockedIncrement(&buffer->bind_count);
2358 wined3d_buffer_incref(buffer);
2360 if (prev_buffer)
2362 InterlockedDecrement(&prev_buffer->bind_count);
2363 wined3d_buffer_decref(prev_buffer);
2367 return WINED3D_OK;
2370 HRESULT CDECL wined3d_device_get_index_buffer(const struct wined3d_device *device, struct wined3d_buffer **buffer)
2372 TRACE("device %p, buffer %p.\n", device, buffer);
2374 *buffer = device->stateBlock->state.index_buffer;
2376 if (*buffer)
2377 wined3d_buffer_incref(*buffer);
2379 TRACE("Returning %p.\n", *buffer);
2381 return WINED3D_OK;
2384 /* Method to offer d3d9 a simple way to set the base vertex index without messing with the index buffer */
2385 HRESULT CDECL wined3d_device_set_base_vertex_index(struct wined3d_device *device, INT base_index)
2387 TRACE("device %p, base_index %d.\n", device, base_index);
2389 if (device->updateStateBlock->state.base_vertex_index == base_index)
2391 TRACE("Application is setting the old value over, nothing to do\n");
2392 return WINED3D_OK;
2395 device->updateStateBlock->state.base_vertex_index = base_index;
2397 if (device->isRecordingState)
2399 TRACE("Recording... not performing anything\n");
2400 return WINED3D_OK;
2402 return WINED3D_OK;
2405 INT CDECL wined3d_device_get_base_vertex_index(const struct wined3d_device *device)
2407 TRACE("device %p.\n", device);
2409 return device->stateBlock->state.base_vertex_index;
2412 HRESULT CDECL wined3d_device_set_viewport(struct wined3d_device *device, const struct wined3d_viewport *viewport)
2414 TRACE("device %p, viewport %p.\n", device, viewport);
2415 TRACE("x %u, y %u, w %u, h %u, min_z %.8e, max_z %.8e.\n",
2416 viewport->x, viewport->y, viewport->width, viewport->height, viewport->min_z, viewport->max_z);
2418 device->updateStateBlock->changed.viewport = TRUE;
2419 device->updateStateBlock->state.viewport = *viewport;
2421 /* Handle recording of state blocks */
2422 if (device->isRecordingState)
2424 TRACE("Recording... not performing anything\n");
2425 return WINED3D_OK;
2428 device_invalidate_state(device, STATE_VIEWPORT);
2430 return WINED3D_OK;
2433 HRESULT CDECL wined3d_device_get_viewport(const struct wined3d_device *device, struct wined3d_viewport *viewport)
2435 TRACE("device %p, viewport %p.\n", device, viewport);
2437 *viewport = device->stateBlock->state.viewport;
2439 return WINED3D_OK;
2442 HRESULT CDECL wined3d_device_set_render_state(struct wined3d_device *device,
2443 WINED3DRENDERSTATETYPE state, DWORD value)
2445 DWORD old_value = device->stateBlock->state.render_states[state];
2447 TRACE("device %p, state %s (%#x), value %#x.\n", device, debug_d3drenderstate(state), state, value);
2449 device->updateStateBlock->changed.renderState[state >> 5] |= 1 << (state & 0x1f);
2450 device->updateStateBlock->state.render_states[state] = value;
2452 /* Handle recording of state blocks. */
2453 if (device->isRecordingState)
2455 TRACE("Recording... not performing anything.\n");
2456 return WINED3D_OK;
2459 /* Compared here and not before the assignment to allow proper stateblock recording. */
2460 if (value == old_value)
2461 TRACE("Application is setting the old value over, nothing to do.\n");
2462 else
2463 device_invalidate_state(device, STATE_RENDER(state));
2465 return WINED3D_OK;
2468 HRESULT CDECL wined3d_device_get_render_state(const struct wined3d_device *device,
2469 WINED3DRENDERSTATETYPE state, DWORD *value)
2471 TRACE("device %p, state %s (%#x), value %p.\n", device, debug_d3drenderstate(state), state, value);
2473 *value = device->stateBlock->state.render_states[state];
2475 return WINED3D_OK;
2478 HRESULT CDECL wined3d_device_set_sampler_state(struct wined3d_device *device,
2479 UINT sampler_idx, WINED3DSAMPLERSTATETYPE state, DWORD value)
2481 DWORD old_value;
2483 TRACE("device %p, sampler_idx %u, state %s, value %#x.\n",
2484 device, sampler_idx, debug_d3dsamplerstate(state), value);
2486 if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2487 sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2489 if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2490 / sizeof(*device->stateBlock->state.sampler_states))
2492 WARN("Invalid sampler %u.\n", sampler_idx);
2493 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2496 old_value = device->stateBlock->state.sampler_states[sampler_idx][state];
2497 device->updateStateBlock->state.sampler_states[sampler_idx][state] = value;
2498 device->updateStateBlock->changed.samplerState[sampler_idx] |= 1 << state;
2500 /* Handle recording of state blocks. */
2501 if (device->isRecordingState)
2503 TRACE("Recording... not performing anything.\n");
2504 return WINED3D_OK;
2507 if (old_value == value)
2509 TRACE("Application is setting the old value over, nothing to do.\n");
2510 return WINED3D_OK;
2513 device_invalidate_state(device, STATE_SAMPLER(sampler_idx));
2515 return WINED3D_OK;
2518 HRESULT CDECL wined3d_device_get_sampler_state(const struct wined3d_device *device,
2519 UINT sampler_idx, WINED3DSAMPLERSTATETYPE state, DWORD *value)
2521 TRACE("device %p, sampler_idx %u, state %s, value %p.\n",
2522 device, sampler_idx, debug_d3dsamplerstate(state), value);
2524 if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2525 sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2527 if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2528 / sizeof(*device->stateBlock->state.sampler_states))
2530 WARN("Invalid sampler %u.\n", sampler_idx);
2531 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2534 *value = device->stateBlock->state.sampler_states[sampler_idx][state];
2535 TRACE("Returning %#x.\n", *value);
2537 return WINED3D_OK;
2540 HRESULT CDECL wined3d_device_set_scissor_rect(struct wined3d_device *device, const RECT *rect)
2542 TRACE("device %p, rect %s.\n", device, wine_dbgstr_rect(rect));
2544 device->updateStateBlock->changed.scissorRect = TRUE;
2545 if (EqualRect(&device->updateStateBlock->state.scissor_rect, rect))
2547 TRACE("App is setting the old scissor rectangle over, nothing to do.\n");
2548 return WINED3D_OK;
2550 CopyRect(&device->updateStateBlock->state.scissor_rect, rect);
2552 if (device->isRecordingState)
2554 TRACE("Recording... not performing anything.\n");
2555 return WINED3D_OK;
2558 device_invalidate_state(device, STATE_SCISSORRECT);
2560 return WINED3D_OK;
2563 HRESULT CDECL wined3d_device_get_scissor_rect(const struct wined3d_device *device, RECT *rect)
2565 TRACE("device %p, rect %p.\n", device, rect);
2567 *rect = device->updateStateBlock->state.scissor_rect;
2568 TRACE("Returning rect %s.\n", wine_dbgstr_rect(rect));
2570 return WINED3D_OK;
2573 HRESULT CDECL wined3d_device_set_vertex_declaration(struct wined3d_device *device,
2574 struct wined3d_vertex_declaration *declaration)
2576 struct wined3d_vertex_declaration *prev = device->updateStateBlock->state.vertex_declaration;
2578 TRACE("device %p, declaration %p.\n", device, declaration);
2580 if (declaration)
2581 wined3d_vertex_declaration_incref(declaration);
2582 if (prev)
2583 wined3d_vertex_declaration_decref(prev);
2585 device->updateStateBlock->state.vertex_declaration = declaration;
2586 device->updateStateBlock->changed.vertexDecl = TRUE;
2588 if (device->isRecordingState)
2590 TRACE("Recording... not performing anything.\n");
2591 return WINED3D_OK;
2593 else if (declaration == prev)
2595 /* Checked after the assignment to allow proper stateblock recording. */
2596 TRACE("Application is setting the old declaration over, nothing to do.\n");
2597 return WINED3D_OK;
2600 device_invalidate_state(device, STATE_VDECL);
2601 return WINED3D_OK;
2604 HRESULT CDECL wined3d_device_get_vertex_declaration(const struct wined3d_device *device,
2605 struct wined3d_vertex_declaration **declaration)
2607 TRACE("device %p, declaration %p.\n", device, declaration);
2609 *declaration = device->stateBlock->state.vertex_declaration;
2610 if (*declaration)
2611 wined3d_vertex_declaration_incref(*declaration);
2613 return WINED3D_OK;
2616 HRESULT CDECL wined3d_device_set_vertex_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2618 struct wined3d_shader *prev = device->updateStateBlock->state.vertex_shader;
2620 TRACE("device %p, shader %p.\n", device, shader);
2622 device->updateStateBlock->state.vertex_shader = shader;
2623 device->updateStateBlock->changed.vertexShader = TRUE;
2625 if (device->isRecordingState)
2627 if (shader)
2628 wined3d_shader_incref(shader);
2629 if (prev)
2630 wined3d_shader_decref(prev);
2631 TRACE("Recording... not performing anything.\n");
2632 return WINED3D_OK;
2635 if (shader == prev)
2637 TRACE("Application is setting the old shader over, nothing to do.\n");
2638 return WINED3D_OK;
2641 if (shader)
2642 wined3d_shader_incref(shader);
2643 if (prev)
2644 wined3d_shader_decref(prev);
2646 device_invalidate_state(device, STATE_VSHADER);
2648 return WINED3D_OK;
2651 struct wined3d_shader * CDECL wined3d_device_get_vertex_shader(const struct wined3d_device *device)
2653 struct wined3d_shader *shader;
2655 TRACE("device %p.\n", device);
2657 shader = device->stateBlock->state.vertex_shader;
2658 if (shader)
2659 wined3d_shader_incref(shader);
2661 TRACE("Returning %p.\n", shader);
2662 return shader;
2665 HRESULT CDECL wined3d_device_set_vs_consts_b(struct wined3d_device *device,
2666 UINT start_register, const BOOL *constants, UINT bool_count)
2668 UINT count = min(bool_count, MAX_CONST_B - start_register);
2669 UINT i;
2671 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2672 device, start_register, constants, bool_count);
2674 if (!constants || start_register >= MAX_CONST_B)
2675 return WINED3DERR_INVALIDCALL;
2677 memcpy(&device->updateStateBlock->state.vs_consts_b[start_register], constants, count * sizeof(BOOL));
2678 for (i = 0; i < count; ++i)
2679 TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
2681 for (i = start_register; i < count + start_register; ++i)
2682 device->updateStateBlock->changed.vertexShaderConstantsB |= (1 << i);
2684 if (!device->isRecordingState)
2685 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2687 return WINED3D_OK;
2690 HRESULT CDECL wined3d_device_get_vs_consts_b(const struct wined3d_device *device,
2691 UINT start_register, BOOL *constants, UINT bool_count)
2693 UINT count = min(bool_count, MAX_CONST_B - start_register);
2695 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2696 device, start_register, constants, bool_count);
2698 if (!constants || start_register >= MAX_CONST_B)
2699 return WINED3DERR_INVALIDCALL;
2701 memcpy(constants, &device->stateBlock->state.vs_consts_b[start_register], count * sizeof(BOOL));
2703 return WINED3D_OK;
2706 HRESULT CDECL wined3d_device_set_vs_consts_i(struct wined3d_device *device,
2707 UINT start_register, const int *constants, UINT vector4i_count)
2709 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2710 UINT i;
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(&device->updateStateBlock->state.vs_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
2719 for (i = 0; i < count; ++i)
2720 TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
2721 constants[i * 4], constants[i * 4 + 1],
2722 constants[i * 4 + 2], constants[i * 4 + 3]);
2724 for (i = start_register; i < count + start_register; ++i)
2725 device->updateStateBlock->changed.vertexShaderConstantsI |= (1 << i);
2727 if (!device->isRecordingState)
2728 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2730 return WINED3D_OK;
2733 HRESULT CDECL wined3d_device_get_vs_consts_i(const struct wined3d_device *device,
2734 UINT start_register, int *constants, UINT vector4i_count)
2736 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2738 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2739 device, start_register, constants, vector4i_count);
2741 if (!constants || start_register >= MAX_CONST_I)
2742 return WINED3DERR_INVALIDCALL;
2744 memcpy(constants, &device->stateBlock->state.vs_consts_i[start_register * 4], count * sizeof(int) * 4);
2745 return WINED3D_OK;
2748 HRESULT CDECL wined3d_device_set_vs_consts_f(struct wined3d_device *device,
2749 UINT start_register, const float *constants, UINT vector4f_count)
2751 UINT i;
2753 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2754 device, start_register, constants, vector4f_count);
2756 /* Specifically test start_register > limit to catch MAX_UINT overflows
2757 * when adding start_register + vector4f_count. */
2758 if (!constants
2759 || start_register + vector4f_count > device->d3d_vshader_constantF
2760 || start_register > device->d3d_vshader_constantF)
2761 return WINED3DERR_INVALIDCALL;
2763 memcpy(&device->updateStateBlock->state.vs_consts_f[start_register * 4],
2764 constants, vector4f_count * sizeof(float) * 4);
2765 if (TRACE_ON(d3d))
2767 for (i = 0; i < vector4f_count; ++i)
2768 TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
2769 constants[i * 4], constants[i * 4 + 1],
2770 constants[i * 4 + 2], constants[i * 4 + 3]);
2773 if (!device->isRecordingState)
2775 device->shader_backend->shader_update_float_vertex_constants(device, start_register, vector4f_count);
2776 device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2779 memset(device->updateStateBlock->changed.vertexShaderConstantsF + start_register, 1,
2780 sizeof(*device->updateStateBlock->changed.vertexShaderConstantsF) * vector4f_count);
2782 return WINED3D_OK;
2785 HRESULT CDECL wined3d_device_get_vs_consts_f(const struct wined3d_device *device,
2786 UINT start_register, float *constants, UINT vector4f_count)
2788 int count = min(vector4f_count, device->d3d_vshader_constantF - start_register);
2790 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2791 device, start_register, constants, vector4f_count);
2793 if (!constants || count < 0)
2794 return WINED3DERR_INVALIDCALL;
2796 memcpy(constants, &device->stateBlock->state.vs_consts_f[start_register * 4], count * sizeof(float) * 4);
2798 return WINED3D_OK;
2801 static void device_invalidate_texture_stage(const struct wined3d_device *device, DWORD stage)
2803 DWORD i;
2805 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2807 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, i));
2811 static void device_map_stage(struct wined3d_device *device, DWORD stage, DWORD unit)
2813 DWORD i = device->rev_tex_unit_map[unit];
2814 DWORD j = device->texUnitMap[stage];
2816 device->texUnitMap[stage] = unit;
2817 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2818 device->texUnitMap[i] = WINED3D_UNMAPPED_STAGE;
2820 device->rev_tex_unit_map[unit] = stage;
2821 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2822 device->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2825 static void device_update_fixed_function_usage_map(struct wined3d_device *device)
2827 UINT i;
2829 device->fixed_function_usage_map = 0;
2830 for (i = 0; i < MAX_TEXTURES; ++i)
2832 const struct wined3d_state *state = &device->stateBlock->state;
2833 WINED3DTEXTUREOP color_op = state->texture_states[i][WINED3DTSS_COLOROP];
2834 WINED3DTEXTUREOP alpha_op = state->texture_states[i][WINED3DTSS_ALPHAOP];
2835 DWORD color_arg1 = state->texture_states[i][WINED3DTSS_COLORARG1] & WINED3DTA_SELECTMASK;
2836 DWORD color_arg2 = state->texture_states[i][WINED3DTSS_COLORARG2] & WINED3DTA_SELECTMASK;
2837 DWORD color_arg3 = state->texture_states[i][WINED3DTSS_COLORARG0] & WINED3DTA_SELECTMASK;
2838 DWORD alpha_arg1 = state->texture_states[i][WINED3DTSS_ALPHAARG1] & WINED3DTA_SELECTMASK;
2839 DWORD alpha_arg2 = state->texture_states[i][WINED3DTSS_ALPHAARG2] & WINED3DTA_SELECTMASK;
2840 DWORD alpha_arg3 = state->texture_states[i][WINED3DTSS_ALPHAARG0] & WINED3DTA_SELECTMASK;
2842 if (color_op == WINED3DTOP_DISABLE) {
2843 /* Not used, and disable higher stages */
2844 break;
2847 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3DTOP_SELECTARG2)
2848 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3DTOP_SELECTARG1)
2849 || ((color_arg3 == WINED3DTA_TEXTURE)
2850 && (color_op == WINED3DTOP_MULTIPLYADD || color_op == WINED3DTOP_LERP))
2851 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3DTOP_SELECTARG2)
2852 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3DTOP_SELECTARG1)
2853 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2854 && (alpha_op == WINED3DTOP_MULTIPLYADD || alpha_op == WINED3DTOP_LERP)))
2855 device->fixed_function_usage_map |= (1 << i);
2857 if ((color_op == WINED3DTOP_BUMPENVMAP || color_op == WINED3DTOP_BUMPENVMAPLUMINANCE) && i < MAX_TEXTURES - 1)
2858 device->fixed_function_usage_map |= (1 << (i + 1));
2862 static void device_map_fixed_function_samplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2864 unsigned int i, tex;
2865 WORD ffu_map;
2867 device_update_fixed_function_usage_map(device);
2868 ffu_map = device->fixed_function_usage_map;
2870 if (device->max_ffp_textures == gl_info->limits.texture_stages
2871 || device->stateBlock->state.lowest_disabled_stage <= device->max_ffp_textures)
2873 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2875 if (!(ffu_map & 1)) continue;
2877 if (device->texUnitMap[i] != i)
2879 device_map_stage(device, i, i);
2880 device_invalidate_state(device, STATE_SAMPLER(i));
2881 device_invalidate_texture_stage(device, i);
2884 return;
2887 /* Now work out the mapping */
2888 tex = 0;
2889 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2891 if (!(ffu_map & 1)) continue;
2893 if (device->texUnitMap[i] != tex)
2895 device_map_stage(device, i, tex);
2896 device_invalidate_state(device, STATE_SAMPLER(i));
2897 device_invalidate_texture_stage(device, i);
2900 ++tex;
2904 static void device_map_psamplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2906 const enum wined3d_sampler_texture_type *sampler_type =
2907 device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2908 unsigned int i;
2910 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2912 if (sampler_type[i] && device->texUnitMap[i] != i)
2914 device_map_stage(device, i, i);
2915 device_invalidate_state(device, STATE_SAMPLER(i));
2916 if (i < gl_info->limits.texture_stages)
2917 device_invalidate_texture_stage(device, i);
2922 static BOOL device_unit_free_for_vs(const struct wined3d_device *device,
2923 const enum wined3d_sampler_texture_type *pshader_sampler_tokens,
2924 const enum wined3d_sampler_texture_type *vshader_sampler_tokens, DWORD unit)
2926 DWORD current_mapping = device->rev_tex_unit_map[unit];
2928 /* Not currently used */
2929 if (current_mapping == WINED3D_UNMAPPED_STAGE) return TRUE;
2931 if (current_mapping < MAX_FRAGMENT_SAMPLERS) {
2932 /* Used by a fragment sampler */
2934 if (!pshader_sampler_tokens) {
2935 /* No pixel shader, check fixed function */
2936 return current_mapping >= MAX_TEXTURES || !(device->fixed_function_usage_map & (1 << current_mapping));
2939 /* Pixel shader, check the shader's sampler map */
2940 return !pshader_sampler_tokens[current_mapping];
2943 /* Used by a vertex sampler */
2944 return !vshader_sampler_tokens[current_mapping - MAX_FRAGMENT_SAMPLERS];
2947 static void device_map_vsamplers(struct wined3d_device *device, BOOL ps, const struct wined3d_gl_info *gl_info)
2949 const enum wined3d_sampler_texture_type *vshader_sampler_type =
2950 device->stateBlock->state.vertex_shader->reg_maps.sampler_type;
2951 const enum wined3d_sampler_texture_type *pshader_sampler_type = NULL;
2952 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2953 int i;
2955 if (ps)
2957 /* Note that we only care if a sampler is sampled or not, not the sampler's specific type.
2958 * Otherwise we'd need to call shader_update_samplers() here for 1.x pixelshaders. */
2959 pshader_sampler_type = device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2962 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
2963 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2964 if (vshader_sampler_type[i])
2966 if (device->texUnitMap[vsampler_idx] != WINED3D_UNMAPPED_STAGE)
2968 /* Already mapped somewhere */
2969 continue;
2972 while (start >= 0)
2974 if (device_unit_free_for_vs(device, pshader_sampler_type, vshader_sampler_type, start))
2976 device_map_stage(device, vsampler_idx, start);
2977 device_invalidate_state(device, STATE_SAMPLER(vsampler_idx));
2979 --start;
2980 break;
2983 --start;
2989 void device_update_tex_unit_map(struct wined3d_device *device)
2991 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2992 const struct wined3d_state *state = &device->stateBlock->state;
2993 BOOL vs = use_vs(state);
2994 BOOL ps = use_ps(state);
2996 * Rules are:
2997 * -> Pixel shaders need a 1:1 map. In theory the shader input could be mapped too, but
2998 * that would be really messy and require shader recompilation
2999 * -> When the mapping of a stage is changed, sampler and ALL texture stage states have
3000 * to be reset. Because of that try to work with a 1:1 mapping as much as possible
3002 if (ps)
3003 device_map_psamplers(device, gl_info);
3004 else
3005 device_map_fixed_function_samplers(device, gl_info);
3007 if (vs)
3008 device_map_vsamplers(device, ps, gl_info);
3011 HRESULT CDECL wined3d_device_set_pixel_shader(struct wined3d_device *device, struct wined3d_shader *shader)
3013 struct wined3d_shader *prev = device->updateStateBlock->state.pixel_shader;
3015 TRACE("device %p, shader %p.\n", device, shader);
3017 device->updateStateBlock->state.pixel_shader = shader;
3018 device->updateStateBlock->changed.pixelShader = TRUE;
3020 if (device->isRecordingState)
3022 if (shader)
3023 wined3d_shader_incref(shader);
3024 if (prev)
3025 wined3d_shader_decref(prev);
3026 TRACE("Recording... not performing anything.\n");
3027 return WINED3D_OK;
3030 if (shader == prev)
3032 TRACE("Application is setting the old shader over, nothing to do.\n");
3033 return WINED3D_OK;
3036 if (shader)
3037 wined3d_shader_incref(shader);
3038 if (prev)
3039 wined3d_shader_decref(prev);
3041 device_invalidate_state(device, STATE_PIXELSHADER);
3043 return WINED3D_OK;
3046 struct wined3d_shader * CDECL wined3d_device_get_pixel_shader(const struct wined3d_device *device)
3048 struct wined3d_shader *shader;
3050 TRACE("device %p.\n", device);
3052 shader = device->stateBlock->state.pixel_shader;
3053 if (shader)
3054 wined3d_shader_incref(shader);
3056 TRACE("Returning %p.\n", shader);
3057 return shader;
3060 HRESULT CDECL wined3d_device_set_ps_consts_b(struct wined3d_device *device,
3061 UINT start_register, const BOOL *constants, UINT bool_count)
3063 UINT count = min(bool_count, MAX_CONST_B - start_register);
3064 UINT i;
3066 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
3067 device, start_register, constants, bool_count);
3069 if (!constants || start_register >= MAX_CONST_B)
3070 return WINED3DERR_INVALIDCALL;
3072 memcpy(&device->updateStateBlock->state.ps_consts_b[start_register], constants, count * sizeof(BOOL));
3073 for (i = 0; i < count; ++i)
3074 TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
3076 for (i = start_register; i < count + start_register; ++i)
3077 device->updateStateBlock->changed.pixelShaderConstantsB |= (1 << i);
3079 if (!device->isRecordingState)
3080 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3082 return WINED3D_OK;
3085 HRESULT CDECL wined3d_device_get_ps_consts_b(const struct wined3d_device *device,
3086 UINT start_register, BOOL *constants, UINT bool_count)
3088 UINT count = min(bool_count, MAX_CONST_B - start_register);
3090 TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
3091 device, start_register, constants, bool_count);
3093 if (!constants || start_register >= MAX_CONST_B)
3094 return WINED3DERR_INVALIDCALL;
3096 memcpy(constants, &device->stateBlock->state.ps_consts_b[start_register], count * sizeof(BOOL));
3098 return WINED3D_OK;
3101 HRESULT CDECL wined3d_device_set_ps_consts_i(struct wined3d_device *device,
3102 UINT start_register, const int *constants, UINT vector4i_count)
3104 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
3105 UINT i;
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(&device->updateStateBlock->state.ps_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
3114 for (i = 0; i < count; ++i)
3115 TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
3116 constants[i * 4], constants[i * 4 + 1],
3117 constants[i * 4 + 2], constants[i * 4 + 3]);
3119 for (i = start_register; i < count + start_register; ++i)
3120 device->updateStateBlock->changed.pixelShaderConstantsI |= (1 << i);
3122 if (!device->isRecordingState)
3123 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3125 return WINED3D_OK;
3128 HRESULT CDECL wined3d_device_get_ps_consts_i(const struct wined3d_device *device,
3129 UINT start_register, int *constants, UINT vector4i_count)
3131 UINT count = min(vector4i_count, MAX_CONST_I - start_register);
3133 TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
3134 device, start_register, constants, vector4i_count);
3136 if (!constants || start_register >= MAX_CONST_I)
3137 return WINED3DERR_INVALIDCALL;
3139 memcpy(constants, &device->stateBlock->state.ps_consts_i[start_register * 4], count * sizeof(int) * 4);
3141 return WINED3D_OK;
3144 HRESULT CDECL wined3d_device_set_ps_consts_f(struct wined3d_device *device,
3145 UINT start_register, const float *constants, UINT vector4f_count)
3147 UINT i;
3149 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3150 device, start_register, constants, vector4f_count);
3152 /* Specifically test start_register > limit to catch MAX_UINT overflows
3153 * when adding start_register + vector4f_count. */
3154 if (!constants
3155 || start_register + vector4f_count > device->d3d_pshader_constantF
3156 || start_register > device->d3d_pshader_constantF)
3157 return WINED3DERR_INVALIDCALL;
3159 memcpy(&device->updateStateBlock->state.ps_consts_f[start_register * 4],
3160 constants, vector4f_count * sizeof(float) * 4);
3161 if (TRACE_ON(d3d))
3163 for (i = 0; i < vector4f_count; ++i)
3164 TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
3165 constants[i * 4], constants[i * 4 + 1],
3166 constants[i * 4 + 2], constants[i * 4 + 3]);
3169 if (!device->isRecordingState)
3171 device->shader_backend->shader_update_float_pixel_constants(device, start_register, vector4f_count);
3172 device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3175 memset(device->updateStateBlock->changed.pixelShaderConstantsF + start_register, 1,
3176 sizeof(*device->updateStateBlock->changed.pixelShaderConstantsF) * vector4f_count);
3178 return WINED3D_OK;
3181 HRESULT CDECL wined3d_device_get_ps_consts_f(const struct wined3d_device *device,
3182 UINT start_register, float *constants, UINT vector4f_count)
3184 int count = min(vector4f_count, device->d3d_pshader_constantF - start_register);
3186 TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3187 device, start_register, constants, vector4f_count);
3189 if (!constants || count < 0)
3190 return WINED3DERR_INVALIDCALL;
3192 memcpy(constants, &device->stateBlock->state.ps_consts_f[start_register * 4], count * sizeof(float) * 4);
3194 return WINED3D_OK;
3197 /* Context activation is done by the caller. */
3198 /* Do not call while under the GL lock. */
3199 #define copy_and_next(dest, src, size) memcpy(dest, src, size); dest += (size)
3200 static HRESULT process_vertices_strided(const struct wined3d_device *device, DWORD dwDestIndex, DWORD dwCount,
3201 const struct wined3d_stream_info *stream_info, struct wined3d_buffer *dest, DWORD flags,
3202 DWORD DestFVF)
3204 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3205 char *dest_ptr, *dest_conv = NULL, *dest_conv_addr = NULL;
3206 struct wined3d_matrix mat, proj_mat, view_mat, world_mat;
3207 struct wined3d_viewport vp;
3208 unsigned int i;
3209 BOOL doClip;
3210 DWORD numTextures;
3212 if (stream_info->use_map & (1 << WINED3D_FFP_NORMAL))
3214 WARN(" lighting state not saved yet... Some strange stuff may happen !\n");
3217 if (!(stream_info->use_map & (1 << WINED3D_FFP_POSITION)))
3219 ERR("Source has no position mask\n");
3220 return WINED3DERR_INVALIDCALL;
3223 if (!dest->resource.allocatedMemory)
3224 buffer_get_sysmem(dest, gl_info);
3226 /* Get a pointer into the destination vbo(create one if none exists) and
3227 * write correct opengl data into it. It's cheap and allows us to run drawStridedFast
3229 if (!dest->buffer_object && gl_info->supported[ARB_VERTEX_BUFFER_OBJECT])
3231 dest->flags |= WINED3D_BUFFER_CREATEBO;
3232 wined3d_buffer_preload(dest);
3235 if (dest->buffer_object)
3237 unsigned char extrabytes = 0;
3238 /* If the destination vertex buffer has D3DFVF_XYZ position(non-rhw), native d3d writes RHW position, where the RHW
3239 * gets written into the 4 bytes after the Z position. In the case of a dest buffer that only has D3DFVF_XYZ data,
3240 * this may write 4 extra bytes beyond the area that should be written
3242 if(DestFVF == WINED3DFVF_XYZ) extrabytes = 4;
3243 dest_conv_addr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCount * get_flexible_vertex_size(DestFVF) + extrabytes);
3244 if(!dest_conv_addr) {
3245 ERR("Out of memory\n");
3246 /* Continue without storing converted vertices */
3248 dest_conv = dest_conv_addr;
3251 if (device->stateBlock->state.render_states[WINED3DRS_CLIPPING])
3253 static BOOL warned = FALSE;
3255 * The clipping code is not quite correct. Some things need
3256 * to be checked against IDirect3DDevice3 (!), d3d8 and d3d9,
3257 * so disable clipping for now.
3258 * (The graphics in Half-Life are broken, and my processvertices
3259 * test crashes with IDirect3DDevice3)
3260 doClip = TRUE;
3262 doClip = FALSE;
3263 if(!warned) {
3264 warned = TRUE;
3265 FIXME("Clipping is broken and disabled for now\n");
3267 } else doClip = FALSE;
3268 dest_ptr = ((char *)buffer_get_sysmem(dest, gl_info)) + dwDestIndex * get_flexible_vertex_size(DestFVF);
3270 wined3d_device_get_transform(device, WINED3DTS_VIEW, &view_mat);
3271 wined3d_device_get_transform(device, WINED3DTS_PROJECTION, &proj_mat);
3272 wined3d_device_get_transform(device, WINED3DTS_WORLDMATRIX(0), &world_mat);
3274 TRACE("View mat:\n");
3275 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);
3276 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);
3277 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);
3278 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);
3280 TRACE("Proj mat:\n");
3281 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);
3282 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);
3283 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);
3284 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);
3286 TRACE("World mat:\n");
3287 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);
3288 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);
3289 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);
3290 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);
3292 /* Get the viewport */
3293 wined3d_device_get_viewport(device, &vp);
3294 TRACE("viewport x %u, y %u, width %u, height %u, min_z %.8e, max_z %.8e.\n",
3295 vp.x, vp.y, vp.width, vp.height, vp.min_z, vp.max_z);
3297 multiply_matrix(&mat,&view_mat,&world_mat);
3298 multiply_matrix(&mat,&proj_mat,&mat);
3300 numTextures = (DestFVF & WINED3DFVF_TEXCOUNT_MASK) >> WINED3DFVF_TEXCOUNT_SHIFT;
3302 for (i = 0; i < dwCount; i+= 1) {
3303 unsigned int tex_index;
3305 if ( ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZ ) ||
3306 ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW ) ) {
3307 /* The position first */
3308 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_POSITION];
3309 const float *p = (const float *)(element->data.addr + i * element->stride);
3310 float x, y, z, rhw;
3311 TRACE("In: ( %06.2f %06.2f %06.2f )\n", p[0], p[1], p[2]);
3313 /* Multiplication with world, view and projection matrix */
3314 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);
3315 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);
3316 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);
3317 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);
3319 TRACE("x=%f y=%f z=%f rhw=%f\n", x, y, z, rhw);
3321 /* WARNING: The following things are taken from d3d7 and were not yet checked
3322 * against d3d8 or d3d9!
3325 /* Clipping conditions: From msdn
3327 * A vertex is clipped if it does not match the following requirements
3328 * -rhw < x <= rhw
3329 * -rhw < y <= rhw
3330 * 0 < z <= rhw
3331 * 0 < rhw ( Not in d3d7, but tested in d3d7)
3333 * If clipping is on is determined by the D3DVOP_CLIP flag in D3D7, and
3334 * by the D3DRS_CLIPPING in D3D9(according to the msdn, not checked)
3338 if( !doClip ||
3339 ( (-rhw -eps < x) && (-rhw -eps < y) && ( -eps < z) &&
3340 (x <= rhw + eps) && (y <= rhw + eps ) && (z <= rhw + eps) &&
3341 ( rhw > eps ) ) ) {
3343 /* "Normal" viewport transformation (not clipped)
3344 * 1) The values are divided by rhw
3345 * 2) The y axis is negative, so multiply it with -1
3346 * 3) Screen coordinates go from -(Width/2) to +(Width/2) and
3347 * -(Height/2) to +(Height/2). The z range is MinZ to MaxZ
3348 * 4) Multiply x with Width/2 and add Width/2
3349 * 5) The same for the height
3350 * 6) Add the viewpoint X and Y to the 2D coordinates and
3351 * The minimum Z value to z
3352 * 7) rhw = 1 / rhw Reciprocal of Homogeneous W....
3354 * Well, basically it's simply a linear transformation into viewport
3355 * coordinates
3358 x /= rhw;
3359 y /= rhw;
3360 z /= rhw;
3362 y *= -1;
3364 x *= vp.width / 2;
3365 y *= vp.height / 2;
3366 z *= vp.max_z - vp.min_z;
3368 x += vp.width / 2 + vp.x;
3369 y += vp.height / 2 + vp.y;
3370 z += vp.min_z;
3372 rhw = 1 / rhw;
3373 } else {
3374 /* That vertex got clipped
3375 * Contrary to OpenGL it is not dropped completely, it just
3376 * undergoes a different calculation.
3378 TRACE("Vertex got clipped\n");
3379 x += rhw;
3380 y += rhw;
3382 x /= 2;
3383 y /= 2;
3385 /* Msdn mentions that Direct3D9 keeps a list of clipped vertices
3386 * outside of the main vertex buffer memory. That needs some more
3387 * investigation...
3391 TRACE("Writing (%f %f %f) %f\n", x, y, z, rhw);
3394 ( (float *) dest_ptr)[0] = x;
3395 ( (float *) dest_ptr)[1] = y;
3396 ( (float *) dest_ptr)[2] = z;
3397 ( (float *) dest_ptr)[3] = rhw; /* SIC, see ddraw test! */
3399 dest_ptr += 3 * sizeof(float);
3401 if((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW) {
3402 dest_ptr += sizeof(float);
3405 if(dest_conv) {
3406 float w = 1 / rhw;
3407 ( (float *) dest_conv)[0] = x * w;
3408 ( (float *) dest_conv)[1] = y * w;
3409 ( (float *) dest_conv)[2] = z * w;
3410 ( (float *) dest_conv)[3] = w;
3412 dest_conv += 3 * sizeof(float);
3414 if((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW) {
3415 dest_conv += sizeof(float);
3419 if (DestFVF & WINED3DFVF_PSIZE) {
3420 dest_ptr += sizeof(DWORD);
3421 if(dest_conv) dest_conv += sizeof(DWORD);
3423 if (DestFVF & WINED3DFVF_NORMAL)
3425 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_NORMAL];
3426 const float *normal = (const float *)(element->data.addr + i * element->stride);
3427 /* AFAIK this should go into the lighting information */
3428 FIXME("Didn't expect the destination to have a normal\n");
3429 copy_and_next(dest_ptr, normal, 3 * sizeof(float));
3430 if(dest_conv) {
3431 copy_and_next(dest_conv, normal, 3 * sizeof(float));
3435 if (DestFVF & WINED3DFVF_DIFFUSE)
3437 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_DIFFUSE];
3438 const DWORD *color_d = (const DWORD *)(element->data.addr + i * element->stride);
3439 if (!(stream_info->use_map & (1 << WINED3D_FFP_DIFFUSE)))
3441 static BOOL warned = FALSE;
3443 if(!warned) {
3444 ERR("No diffuse color in source, but destination has one\n");
3445 warned = TRUE;
3448 *( (DWORD *) dest_ptr) = 0xffffffff;
3449 dest_ptr += sizeof(DWORD);
3451 if(dest_conv) {
3452 *( (DWORD *) dest_conv) = 0xffffffff;
3453 dest_conv += sizeof(DWORD);
3456 else {
3457 copy_and_next(dest_ptr, color_d, sizeof(DWORD));
3458 if(dest_conv) {
3459 *( (DWORD *) dest_conv) = (*color_d & 0xff00ff00) ; /* Alpha + green */
3460 *( (DWORD *) dest_conv) |= (*color_d & 0x00ff0000) >> 16; /* Red */
3461 *( (DWORD *) dest_conv) |= (*color_d & 0xff0000ff) << 16; /* Blue */
3462 dest_conv += sizeof(DWORD);
3467 if (DestFVF & WINED3DFVF_SPECULAR)
3469 /* What's the color value in the feedback buffer? */
3470 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_SPECULAR];
3471 const DWORD *color_s = (const DWORD *)(element->data.addr + i * element->stride);
3472 if (!(stream_info->use_map & (1 << WINED3D_FFP_SPECULAR)))
3474 static BOOL warned = FALSE;
3476 if(!warned) {
3477 ERR("No specular color in source, but destination has one\n");
3478 warned = TRUE;
3481 *( (DWORD *) dest_ptr) = 0xFF000000;
3482 dest_ptr += sizeof(DWORD);
3484 if(dest_conv) {
3485 *( (DWORD *) dest_conv) = 0xFF000000;
3486 dest_conv += sizeof(DWORD);
3489 else {
3490 copy_and_next(dest_ptr, color_s, sizeof(DWORD));
3491 if(dest_conv) {
3492 *( (DWORD *) dest_conv) = (*color_s & 0xff00ff00) ; /* Alpha + green */
3493 *( (DWORD *) dest_conv) |= (*color_s & 0x00ff0000) >> 16; /* Red */
3494 *( (DWORD *) dest_conv) |= (*color_s & 0xff0000ff) << 16; /* Blue */
3495 dest_conv += sizeof(DWORD);
3500 for (tex_index = 0; tex_index < numTextures; ++tex_index)
3502 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_TEXCOORD0 + tex_index];
3503 const float *tex_coord = (const float *)(element->data.addr + i * element->stride);
3504 if (!(stream_info->use_map & (1 << (WINED3D_FFP_TEXCOORD0 + tex_index))))
3506 ERR("No source texture, but destination requests one\n");
3507 dest_ptr+=GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float);
3508 if(dest_conv) dest_conv += GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float);
3510 else {
3511 copy_and_next(dest_ptr, tex_coord, GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float));
3512 if(dest_conv) {
3513 copy_and_next(dest_conv, tex_coord, GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float));
3519 if (dest_conv)
3521 ENTER_GL();
3523 GL_EXTCALL(glBindBufferARB(GL_ARRAY_BUFFER_ARB, dest->buffer_object));
3524 checkGLcall("glBindBufferARB(GL_ARRAY_BUFFER_ARB)");
3525 GL_EXTCALL(glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, dwDestIndex * get_flexible_vertex_size(DestFVF),
3526 dwCount * get_flexible_vertex_size(DestFVF),
3527 dest_conv_addr));
3528 checkGLcall("glBufferSubDataARB(GL_ARRAY_BUFFER_ARB)");
3530 LEAVE_GL();
3532 HeapFree(GetProcessHeap(), 0, dest_conv_addr);
3535 return WINED3D_OK;
3537 #undef copy_and_next
3539 /* Do not call while under the GL lock. */
3540 HRESULT CDECL wined3d_device_process_vertices(struct wined3d_device *device,
3541 UINT src_start_idx, UINT dst_idx, UINT vertex_count, struct wined3d_buffer *dst_buffer,
3542 const struct wined3d_vertex_declaration *declaration, DWORD flags, DWORD dst_fvf)
3544 struct wined3d_state *state = &device->stateBlock->state;
3545 BOOL vbo = FALSE, streamWasUP = state->user_stream;
3546 struct wined3d_stream_info stream_info;
3547 const struct wined3d_gl_info *gl_info;
3548 struct wined3d_context *context;
3549 struct wined3d_shader *vs;
3550 HRESULT hr;
3552 TRACE("device %p, src_start_idx %u, dst_idx %u, vertex_count %u, "
3553 "dst_buffer %p, declaration %p, flags %#x, dst_fvf %#x.\n",
3554 device, src_start_idx, dst_idx, vertex_count,
3555 dst_buffer, declaration, flags, dst_fvf);
3557 if (declaration)
3558 FIXME("Output vertex declaration not implemented yet.\n");
3560 /* Need any context to write to the vbo. */
3561 context = context_acquire(device, NULL);
3562 gl_info = context->gl_info;
3564 /* ProcessVertices reads from vertex buffers, which have to be assigned.
3565 * DrawPrimitive and DrawPrimitiveUP control the streamIsUP flag, thus
3566 * restore it afterwards. */
3567 vs = state->vertex_shader;
3568 state->vertex_shader = NULL;
3569 state->user_stream = FALSE;
3570 device_stream_info_from_declaration(device, &stream_info, &vbo);
3571 state->user_stream = streamWasUP;
3572 state->vertex_shader = vs;
3574 if (vbo || src_start_idx)
3576 unsigned int i;
3577 /* ProcessVertices can't convert FROM a vbo, and vertex buffers used to source into ProcessVertices are
3578 * unlikely to ever be used for drawing. Release vbos in those buffers and fix up the stream_info structure
3580 * Also get the start index in, but only loop over all elements if there's something to add at all.
3582 for (i = 0; i < (sizeof(stream_info.elements) / sizeof(*stream_info.elements)); ++i)
3584 struct wined3d_stream_info_element *e;
3586 if (!(stream_info.use_map & (1 << i))) continue;
3588 e = &stream_info.elements[i];
3589 if (e->data.buffer_object)
3591 struct wined3d_buffer *vb = state->streams[e->stream_idx].buffer;
3592 e->data.buffer_object = 0;
3593 e->data.addr = (BYTE *)((ULONG_PTR)e->data.addr + (ULONG_PTR)buffer_get_sysmem(vb, gl_info));
3594 ENTER_GL();
3595 GL_EXTCALL(glDeleteBuffersARB(1, &vb->buffer_object));
3596 vb->buffer_object = 0;
3597 LEAVE_GL();
3599 if (e->data.addr)
3600 e->data.addr += e->stride * src_start_idx;
3604 hr = process_vertices_strided(device, dst_idx, vertex_count,
3605 &stream_info, dst_buffer, flags, dst_fvf);
3607 context_release(context);
3609 return hr;
3612 HRESULT CDECL wined3d_device_set_texture_stage_state(struct wined3d_device *device,
3613 UINT stage, WINED3DTEXTURESTAGESTATETYPE state, DWORD value)
3615 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3616 DWORD old_value;
3618 TRACE("device %p, stage %u, state %s, value %#x.\n",
3619 device, stage, debug_d3dtexturestate(state), value);
3621 if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3623 WARN("Invalid state %#x passed.\n", state);
3624 return WINED3D_OK;
3627 if (stage >= gl_info->limits.texture_stages)
3629 WARN("Attempting to set stage %u which is higher than the max stage %u, ignoring.\n",
3630 stage, gl_info->limits.texture_stages - 1);
3631 return WINED3D_OK;
3634 old_value = device->updateStateBlock->state.texture_states[stage][state];
3635 device->updateStateBlock->changed.textureState[stage] |= 1 << state;
3636 device->updateStateBlock->state.texture_states[stage][state] = value;
3638 if (device->isRecordingState)
3640 TRACE("Recording... not performing anything.\n");
3641 return WINED3D_OK;
3644 /* Checked after the assignments to allow proper stateblock recording. */
3645 if (old_value == value)
3647 TRACE("Application is setting the old value over, nothing to do.\n");
3648 return WINED3D_OK;
3651 if (stage > device->stateBlock->state.lowest_disabled_stage
3652 && device->StateTable[STATE_TEXTURESTAGE(0, state)].representative
3653 == STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP))
3655 /* Colorop change above lowest disabled stage? That won't change
3656 * anything in the GL setup. Changes in other states are important on
3657 * disabled stages too. */
3658 return WINED3D_OK;
3661 if (state == WINED3DTSS_COLOROP)
3663 unsigned int i;
3665 if (value == WINED3DTOP_DISABLE && old_value != WINED3DTOP_DISABLE)
3667 /* Previously enabled stage disabled now. Make sure to dirtify
3668 * all enabled stages above stage, they have to be disabled.
3670 * The current stage is dirtified below. */
3671 for (i = stage + 1; i < device->stateBlock->state.lowest_disabled_stage; ++i)
3673 TRACE("Additionally dirtifying stage %u.\n", i);
3674 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP));
3676 device->stateBlock->state.lowest_disabled_stage = stage;
3677 TRACE("New lowest disabled: %u.\n", stage);
3679 else if (value != WINED3DTOP_DISABLE && old_value == WINED3DTOP_DISABLE)
3681 /* Previously disabled stage enabled. Stages above it may need
3682 * enabling. Stage must be lowest_disabled_stage here, if it's
3683 * bigger success is returned above, and stages below the lowest
3684 * disabled stage can't be enabled (because they are enabled
3685 * already).
3687 * Again stage stage doesn't need to be dirtified here, it is
3688 * handled below. */
3689 for (i = stage + 1; i < gl_info->limits.texture_stages; ++i)
3691 if (device->updateStateBlock->state.texture_states[i][WINED3DTSS_COLOROP] == WINED3DTOP_DISABLE)
3692 break;
3693 TRACE("Additionally dirtifying stage %u due to enable.\n", i);
3694 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP));
3696 device->stateBlock->state.lowest_disabled_stage = i;
3697 TRACE("New lowest disabled: %u.\n", i);
3701 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, state));
3703 return WINED3D_OK;
3706 HRESULT CDECL wined3d_device_get_texture_stage_state(const struct wined3d_device *device,
3707 UINT stage, WINED3DTEXTURESTAGESTATETYPE state, DWORD *value)
3709 TRACE("device %p, stage %u, state %s, value %p.\n",
3710 device, stage, debug_d3dtexturestate(state), value);
3712 if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3714 WARN("Invalid state %#x passed.\n", state);
3715 return WINED3D_OK;
3718 *value = device->updateStateBlock->state.texture_states[stage][state];
3719 TRACE("Returning %#x.\n", *value);
3721 return WINED3D_OK;
3724 HRESULT CDECL wined3d_device_set_texture(struct wined3d_device *device,
3725 UINT stage, struct wined3d_texture *texture)
3727 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3728 struct wined3d_texture *prev;
3730 TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3732 if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3733 stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3735 /* Windows accepts overflowing this array... we do not. */
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;
3742 /* SetTexture isn't allowed on textures in WINED3DPOOL_SCRATCH */
3743 if (texture && texture->resource.pool == WINED3DPOOL_SCRATCH)
3745 WARN("Rejecting attempt to set scratch texture.\n");
3746 return WINED3DERR_INVALIDCALL;
3749 device->updateStateBlock->changed.textures |= 1 << stage;
3751 prev = device->updateStateBlock->state.textures[stage];
3752 TRACE("Previous texture %p.\n", prev);
3754 if (texture == prev)
3756 TRACE("App is setting the same texture again, nothing to do.\n");
3757 return WINED3D_OK;
3760 TRACE("Setting new texture to %p.\n", texture);
3761 device->updateStateBlock->state.textures[stage] = texture;
3763 if (device->isRecordingState)
3765 TRACE("Recording... not performing anything\n");
3767 if (texture) wined3d_texture_incref(texture);
3768 if (prev) wined3d_texture_decref(prev);
3770 return WINED3D_OK;
3773 if (texture)
3775 LONG bind_count = InterlockedIncrement(&texture->bind_count);
3777 wined3d_texture_incref(texture);
3779 if (!prev || texture->target != prev->target)
3780 device_invalidate_state(device, STATE_PIXELSHADER);
3782 if (!prev && stage < gl_info->limits.texture_stages)
3784 /* The source arguments for color and alpha ops have different
3785 * meanings when a NULL texture is bound, so the COLOROP and
3786 * ALPHAOP have to be dirtified. */
3787 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3DTSS_COLOROP));
3788 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3DTSS_ALPHAOP));
3791 if (bind_count == 1)
3792 texture->sampler = stage;
3795 if (prev)
3797 LONG bind_count = InterlockedDecrement(&prev->bind_count);
3799 wined3d_texture_decref(prev);
3801 if (!texture && stage < gl_info->limits.texture_stages)
3803 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3DTSS_COLOROP));
3804 device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3DTSS_ALPHAOP));
3807 if (bind_count && prev->sampler == stage)
3809 unsigned int i;
3811 /* Search for other stages the texture is bound to. Shouldn't
3812 * happen if applications bind textures to a single stage only. */
3813 TRACE("Searching for other stages the texture is bound to.\n");
3814 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
3816 if (device->updateStateBlock->state.textures[i] == prev)
3818 TRACE("Texture is also bound to stage %u.\n", i);
3819 prev->sampler = i;
3820 break;
3826 device_invalidate_state(device, STATE_SAMPLER(stage));
3828 return WINED3D_OK;
3831 HRESULT CDECL wined3d_device_get_texture(const struct wined3d_device *device,
3832 UINT stage, struct wined3d_texture **texture)
3834 TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3836 if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3837 stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3839 if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3841 WARN("Ignoring invalid stage %u.\n", stage);
3842 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
3845 *texture = device->stateBlock->state.textures[stage];
3846 if (*texture)
3847 wined3d_texture_incref(*texture);
3849 TRACE("Returning %p.\n", *texture);
3851 return WINED3D_OK;
3854 HRESULT CDECL wined3d_device_get_back_buffer(const struct wined3d_device *device, UINT swapchain_idx,
3855 UINT backbuffer_idx, WINED3DBACKBUFFER_TYPE backbuffer_type, struct wined3d_surface **backbuffer)
3857 struct wined3d_swapchain *swapchain;
3858 HRESULT hr;
3860 TRACE("device %p, swapchain_idx %u, backbuffer_idx %u, backbuffer_type %#x, backbuffer %p.\n",
3861 device, swapchain_idx, backbuffer_idx, backbuffer_type, backbuffer);
3863 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
3864 if (FAILED(hr))
3866 WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
3867 return hr;
3870 hr = wined3d_swapchain_get_back_buffer(swapchain, backbuffer_idx, backbuffer_type, backbuffer);
3871 wined3d_swapchain_decref(swapchain);
3872 if (FAILED(hr))
3874 WARN("Failed to get backbuffer %u, hr %#x.\n", backbuffer_idx, hr);
3875 return hr;
3878 return WINED3D_OK;
3881 HRESULT CDECL wined3d_device_get_device_caps(const struct wined3d_device *device, WINED3DCAPS *caps)
3883 TRACE("device %p, caps %p.\n", device, caps);
3885 return wined3d_get_device_caps(device->wined3d, device->adapter->ordinal,
3886 device->create_parms.device_type, caps);
3889 HRESULT CDECL wined3d_device_get_display_mode(const struct wined3d_device *device,
3890 UINT swapchain_idx, struct wined3d_display_mode *mode)
3892 struct wined3d_swapchain *swapchain;
3893 HRESULT hr;
3895 TRACE("device %p, swapchain_idx %u, mode %p.\n", device, swapchain_idx, mode);
3897 if (swapchain_idx)
3899 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
3900 if (SUCCEEDED(hr))
3902 hr = wined3d_swapchain_get_display_mode(swapchain, mode);
3903 wined3d_swapchain_decref(swapchain);
3906 else
3908 const struct wined3d_adapter *adapter = device->adapter;
3910 /* Don't read the real display mode, but return the stored mode
3911 * instead. X11 can't change the color depth, and some apps are
3912 * pretty angry if they SetDisplayMode from 24 to 16 bpp and find out
3913 * that GetDisplayMode still returns 24 bpp.
3915 * Also don't relay to the swapchain because with ddraw it's possible
3916 * that there isn't a swapchain at all. */
3917 mode->width = adapter->screen_size.cx;
3918 mode->height = adapter->screen_size.cy;
3919 mode->format_id = adapter->screen_format;
3920 mode->refresh_rate = 0;
3921 hr = WINED3D_OK;
3924 return hr;
3927 HRESULT CDECL wined3d_device_begin_stateblock(struct wined3d_device *device)
3929 struct wined3d_stateblock *stateblock;
3930 HRESULT hr;
3932 TRACE("device %p.\n", device);
3934 if (device->isRecordingState)
3935 return WINED3DERR_INVALIDCALL;
3937 hr = wined3d_stateblock_create(device, WINED3DSBT_RECORDED, &stateblock);
3938 if (FAILED(hr))
3939 return hr;
3941 wined3d_stateblock_decref(device->updateStateBlock);
3942 device->updateStateBlock = stateblock;
3943 device->isRecordingState = TRUE;
3945 TRACE("Recording stateblock %p.\n", stateblock);
3947 return WINED3D_OK;
3950 HRESULT CDECL wined3d_device_end_stateblock(struct wined3d_device *device,
3951 struct wined3d_stateblock **stateblock)
3953 struct wined3d_stateblock *object = device->updateStateBlock;
3955 TRACE("device %p, stateblock %p.\n", device, stateblock);
3957 if (!device->isRecordingState)
3959 WARN("Not recording.\n");
3960 *stateblock = NULL;
3961 return WINED3DERR_INVALIDCALL;
3964 stateblock_init_contained_states(object);
3966 *stateblock = object;
3967 device->isRecordingState = FALSE;
3968 device->updateStateBlock = device->stateBlock;
3969 wined3d_stateblock_incref(device->updateStateBlock);
3971 TRACE("Returning stateblock %p.\n", *stateblock);
3973 return WINED3D_OK;
3976 HRESULT CDECL wined3d_device_begin_scene(struct wined3d_device *device)
3978 /* At the moment we have no need for any functionality at the beginning
3979 * of a scene. */
3980 TRACE("device %p.\n", device);
3982 if (device->inScene)
3984 WARN("Already in scene, returning WINED3DERR_INVALIDCALL.\n");
3985 return WINED3DERR_INVALIDCALL;
3987 device->inScene = TRUE;
3988 return WINED3D_OK;
3991 HRESULT CDECL wined3d_device_end_scene(struct wined3d_device *device)
3993 struct wined3d_context *context;
3995 TRACE("device %p.\n", device);
3997 if (!device->inScene)
3999 WARN("Not in scene, returning WINED3DERR_INVALIDCALL.\n");
4000 return WINED3DERR_INVALIDCALL;
4003 context = context_acquire(device, NULL);
4004 /* We only have to do this if we need to read the, swapbuffers performs a flush for us */
4005 wglFlush();
4006 /* No checkGLcall here to avoid locking the lock just for checking a call that hardly ever
4007 * fails. */
4008 context_release(context);
4010 device->inScene = FALSE;
4011 return WINED3D_OK;
4014 HRESULT CDECL wined3d_device_present(const struct wined3d_device *device, const RECT *src_rect,
4015 const RECT *dst_rect, HWND dst_window_override, const RGNDATA *dirty_region)
4017 UINT i;
4019 TRACE("device %p, src_rect %s, dst_rect %s, dst_window_override %p, dirty_region %p.\n",
4020 device, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect),
4021 dst_window_override, dirty_region);
4023 for (i = 0; i < device->swapchain_count; ++i)
4025 wined3d_swapchain_present(device->swapchains[i], src_rect,
4026 dst_rect, dst_window_override, dirty_region, 0);
4029 return WINED3D_OK;
4032 /* Do not call while under the GL lock. */
4033 HRESULT CDECL wined3d_device_clear(struct wined3d_device *device, DWORD rect_count,
4034 const RECT *rects, DWORD flags, const struct wined3d_color *color, float depth, DWORD stencil)
4036 RECT draw_rect;
4038 TRACE("device %p, rect_count %u, rects %p, flags %#x, color {%.8e, %.8e, %.8e, %.8e}, depth %.8e, stencil %u.\n",
4039 device, rect_count, rects, flags, color->r, color->g, color->b, color->a, depth, stencil);
4041 if (flags & (WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL))
4043 struct wined3d_surface *ds = device->fb.depth_stencil;
4044 if (!ds)
4046 WARN("Clearing depth and/or stencil without a depth stencil buffer attached, returning WINED3DERR_INVALIDCALL\n");
4047 /* TODO: What about depth stencil buffers without stencil bits? */
4048 return WINED3DERR_INVALIDCALL;
4050 else if (flags & WINED3DCLEAR_TARGET)
4052 if (ds->resource.width < device->fb.render_targets[0]->resource.width
4053 || ds->resource.height < device->fb.render_targets[0]->resource.height)
4055 WARN("Silently ignoring depth and target clear with mismatching sizes\n");
4056 return WINED3D_OK;
4061 wined3d_get_draw_rect(&device->stateBlock->state, &draw_rect);
4063 return device_clear_render_targets(device, device->adapter->gl_info.limits.buffers,
4064 &device->fb, rect_count, rects,
4065 &draw_rect, flags, color, depth, stencil);
4068 void CDECL wined3d_device_set_primitive_type(struct wined3d_device *device,
4069 WINED3DPRIMITIVETYPE primitive_type)
4071 TRACE("device %p, primitive_type %s\n", device, debug_d3dprimitivetype(primitive_type));
4073 device->updateStateBlock->changed.primitive_type = TRUE;
4074 device->updateStateBlock->state.gl_primitive_type = gl_primitive_type_from_d3d(primitive_type);
4077 void CDECL wined3d_device_get_primitive_type(const struct wined3d_device *device,
4078 WINED3DPRIMITIVETYPE *primitive_type)
4080 TRACE("device %p, primitive_type %p\n", device, primitive_type);
4082 *primitive_type = d3d_primitive_type_from_gl(device->stateBlock->state.gl_primitive_type);
4084 TRACE("Returning %s\n", debug_d3dprimitivetype(*primitive_type));
4087 HRESULT CDECL wined3d_device_draw_primitive(struct wined3d_device *device, UINT start_vertex, UINT vertex_count)
4089 TRACE("device %p, start_vertex %u, vertex_count %u.\n", device, start_vertex, vertex_count);
4091 if (!device->stateBlock->state.vertex_declaration)
4093 WARN("Called without a valid vertex declaration set.\n");
4094 return WINED3DERR_INVALIDCALL;
4097 /* The index buffer is not needed here, but restore it, otherwise it is hell to keep track of */
4098 if (device->stateBlock->state.user_stream)
4100 device_invalidate_state(device, STATE_INDEXBUFFER);
4101 device->stateBlock->state.user_stream = FALSE;
4104 if (device->stateBlock->state.load_base_vertex_index)
4106 device->stateBlock->state.load_base_vertex_index = 0;
4107 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4110 /* Account for the loading offset due to index buffers. Instead of
4111 * reloading all sources correct it with the startvertex parameter. */
4112 drawPrimitive(device, vertex_count, start_vertex, 0, NULL);
4113 return WINED3D_OK;
4116 HRESULT CDECL wined3d_device_draw_indexed_primitive(struct wined3d_device *device, UINT start_idx, UINT index_count)
4118 struct wined3d_buffer *index_buffer;
4119 UINT index_size = 2;
4120 GLuint vbo;
4121 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4123 TRACE("device %p, start_idx %u, index_count %u.\n", device, start_idx, index_count);
4125 index_buffer = device->stateBlock->state.index_buffer;
4126 if (!index_buffer)
4128 /* D3D9 returns D3DERR_INVALIDCALL when DrawIndexedPrimitive is called
4129 * without an index buffer set. (The first time at least...)
4130 * D3D8 simply dies, but I doubt it can do much harm to return
4131 * D3DERR_INVALIDCALL there as well. */
4132 WARN("Called without a valid index buffer set, returning WINED3DERR_INVALIDCALL.\n");
4133 return WINED3DERR_INVALIDCALL;
4136 if (!device->stateBlock->state.vertex_declaration)
4138 WARN("Called without a valid vertex declaration set.\n");
4139 return WINED3DERR_INVALIDCALL;
4142 if (device->stateBlock->state.user_stream)
4144 device_invalidate_state(device, STATE_INDEXBUFFER);
4145 device->stateBlock->state.user_stream = FALSE;
4147 vbo = index_buffer->buffer_object;
4149 if (device->stateBlock->state.index_format == WINED3DFMT_R16_UINT)
4150 index_size = 2;
4151 else
4152 index_size = 4;
4154 if (!gl_info->supported[ARB_DRAW_ELEMENTS_BASE_VERTEX] &&
4155 device->stateBlock->state.load_base_vertex_index != device->stateBlock->state.base_vertex_index)
4157 device->stateBlock->state.load_base_vertex_index = device->stateBlock->state.base_vertex_index;
4158 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4161 drawPrimitive(device, index_count, start_idx, index_size,
4162 vbo ? NULL : index_buffer->resource.allocatedMemory);
4164 return WINED3D_OK;
4167 HRESULT CDECL wined3d_device_draw_primitive_up(struct wined3d_device *device, UINT vertex_count,
4168 const void *stream_data, UINT stream_stride)
4170 struct wined3d_stream_state *stream;
4171 struct wined3d_buffer *vb;
4173 TRACE("device %p, vertex count %u, stream_data %p, stream_stride %u.\n",
4174 device, vertex_count, stream_data, stream_stride);
4176 if (!device->stateBlock->state.vertex_declaration)
4178 WARN("Called without a valid vertex declaration set.\n");
4179 return WINED3DERR_INVALIDCALL;
4182 /* Note in the following, it's not this type, but that's the purpose of streamIsUP */
4183 stream = &device->stateBlock->state.streams[0];
4184 vb = stream->buffer;
4185 stream->buffer = (struct wined3d_buffer *)stream_data;
4186 if (vb)
4187 wined3d_buffer_decref(vb);
4188 stream->offset = 0;
4189 stream->stride = stream_stride;
4190 device->stateBlock->state.user_stream = TRUE;
4191 if (device->stateBlock->state.load_base_vertex_index)
4193 device->stateBlock->state.load_base_vertex_index = 0;
4194 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4197 /* TODO: Only mark dirty if drawing from a different UP address */
4198 device_invalidate_state(device, STATE_STREAMSRC);
4200 drawPrimitive(device, vertex_count, 0, 0, NULL);
4202 /* MSDN specifies stream zero settings must be set to NULL */
4203 stream->buffer = NULL;
4204 stream->stride = 0;
4206 /* stream zero settings set to null at end, as per the msdn. No need to
4207 * mark dirty here, the app has to set the new stream sources or use UP
4208 * drawing again. */
4209 return WINED3D_OK;
4212 HRESULT CDECL wined3d_device_draw_indexed_primitive_up(struct wined3d_device *device,
4213 UINT index_count, const void *index_data, enum wined3d_format_id index_data_format_id,
4214 const void *stream_data, UINT stream_stride)
4216 struct wined3d_stream_state *stream;
4217 struct wined3d_buffer *vb, *ib;
4218 UINT index_size;
4220 TRACE("device %p, index_count %u, index_data %p, index_data_format %s, stream_data %p, stream_stride %u.\n",
4221 device, index_count, index_data, debug_d3dformat(index_data_format_id), stream_data, stream_stride);
4223 if (!device->stateBlock->state.vertex_declaration)
4225 WARN("(%p) : Called without a valid vertex declaration set\n", device);
4226 return WINED3DERR_INVALIDCALL;
4229 if (index_data_format_id == WINED3DFMT_R16_UINT)
4230 index_size = 2;
4231 else
4232 index_size = 4;
4234 stream = &device->stateBlock->state.streams[0];
4235 vb = stream->buffer;
4236 stream->buffer = (struct wined3d_buffer *)stream_data;
4237 if (vb)
4238 wined3d_buffer_decref(vb);
4239 stream->offset = 0;
4240 stream->stride = stream_stride;
4241 device->stateBlock->state.user_stream = TRUE;
4243 /* Set to 0 as per msdn. Do it now due to the stream source loading during drawPrimitive */
4244 device->stateBlock->state.base_vertex_index = 0;
4245 if (device->stateBlock->state.load_base_vertex_index)
4247 device->stateBlock->state.load_base_vertex_index = 0;
4248 device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4250 /* Invalidate the state until we have nicer tracking of the stream source pointers */
4251 device_invalidate_state(device, STATE_STREAMSRC);
4252 device_invalidate_state(device, STATE_INDEXBUFFER);
4254 drawPrimitive(device, index_count, 0, index_size, index_data);
4256 /* MSDN specifies stream zero settings and index buffer must be set to NULL */
4257 stream->buffer = NULL;
4258 stream->stride = 0;
4259 ib = device->stateBlock->state.index_buffer;
4260 if (ib)
4262 wined3d_buffer_decref(ib);
4263 device->stateBlock->state.index_buffer = NULL;
4265 /* No need to mark the stream source state dirty here. Either the app calls UP drawing again, or it has to call
4266 * SetStreamSource to specify a vertex buffer
4269 return WINED3D_OK;
4272 HRESULT CDECL wined3d_device_draw_primitive_strided(struct wined3d_device *device,
4273 UINT vertex_count, const WineDirect3DVertexStridedData *strided_data)
4275 /* Mark the state dirty until we have nicer tracking. It's fine to change
4276 * baseVertexIndex because that call is only called by ddraw which does
4277 * not need that value. */
4278 device_invalidate_state(device, STATE_VDECL);
4279 device_invalidate_state(device, STATE_STREAMSRC);
4280 device_invalidate_state(device, STATE_INDEXBUFFER);
4282 device->stateBlock->state.base_vertex_index = 0;
4283 device->up_strided = strided_data;
4284 drawPrimitive(device, vertex_count, 0, 0, NULL);
4285 device->up_strided = NULL;
4287 /* Invalidate the states again to make sure the values from the stateblock
4288 * are properly applied in the next regular draw. Note that the application-
4289 * provided strided data has ovwritten pretty much the entire vertex and
4290 * and index stream related states */
4291 device_invalidate_state(device, STATE_VDECL);
4292 device_invalidate_state(device, STATE_STREAMSRC);
4293 device_invalidate_state(device, STATE_INDEXBUFFER);
4294 return WINED3D_OK;
4297 HRESULT CDECL wined3d_device_draw_indexed_primitive_strided(struct wined3d_device *device,
4298 UINT index_count, const WineDirect3DVertexStridedData *strided_data,
4299 UINT vertex_count, const void *index_data, enum wined3d_format_id index_data_format_id)
4301 UINT index_size = index_data_format_id == WINED3DFMT_R32_UINT ? 4 : 2;
4303 /* Mark the state dirty until we have nicer tracking
4304 * its fine to change baseVertexIndex because that call is only called by ddraw which does not need
4305 * that value.
4307 device_invalidate_state(device, STATE_VDECL);
4308 device_invalidate_state(device, STATE_STREAMSRC);
4309 device_invalidate_state(device, STATE_INDEXBUFFER);
4311 device->stateBlock->state.user_stream = TRUE;
4312 device->stateBlock->state.base_vertex_index = 0;
4313 device->up_strided = strided_data;
4314 drawPrimitive(device, index_count, 0, index_size, index_data);
4315 device->up_strided = NULL;
4317 device_invalidate_state(device, STATE_VDECL);
4318 device_invalidate_state(device, STATE_STREAMSRC);
4319 device_invalidate_state(device, STATE_INDEXBUFFER);
4320 return WINED3D_OK;
4323 /* This is a helper function for UpdateTexture, there is no UpdateVolume method in D3D. */
4324 static HRESULT device_update_volume(struct wined3d_device *device,
4325 struct wined3d_volume *src_volume, struct wined3d_volume *dst_volume)
4327 WINED3DLOCKED_BOX src;
4328 WINED3DLOCKED_BOX dst;
4329 HRESULT hr;
4331 TRACE("device %p, src_volume %p, dst_volume %p.\n",
4332 device, src_volume, dst_volume);
4334 /* TODO: Implement direct loading into the gl volume instead of using
4335 * memcpy and dirtification to improve loading performance. */
4336 hr = wined3d_volume_map(src_volume, &src, NULL, WINED3DLOCK_READONLY);
4337 if (FAILED(hr)) return hr;
4338 hr = wined3d_volume_map(dst_volume, &dst, NULL, WINED3DLOCK_DISCARD);
4339 if (FAILED(hr))
4341 wined3d_volume_unmap(src_volume);
4342 return hr;
4345 memcpy(dst.pBits, src.pBits, dst_volume->resource.size);
4347 hr = wined3d_volume_unmap(dst_volume);
4348 if (FAILED(hr))
4349 wined3d_volume_unmap(src_volume);
4350 else
4351 hr = wined3d_volume_unmap(src_volume);
4353 return hr;
4356 HRESULT CDECL wined3d_device_update_texture(struct wined3d_device *device,
4357 struct wined3d_texture *src_texture, struct wined3d_texture *dst_texture)
4359 unsigned int level_count, i;
4360 WINED3DRESOURCETYPE type;
4361 HRESULT hr;
4363 TRACE("device %p, src_texture %p, dst_texture %p.\n", device, src_texture, dst_texture);
4365 /* Verify that the source and destination textures are non-NULL. */
4366 if (!src_texture || !dst_texture)
4368 WARN("Source and destination textures must be non-NULL, returning WINED3DERR_INVALIDCALL.\n");
4369 return WINED3DERR_INVALIDCALL;
4372 if (src_texture == dst_texture)
4374 WARN("Source and destination are the same object, returning WINED3DERR_INVALIDCALL.\n");
4375 return WINED3DERR_INVALIDCALL;
4378 /* Verify that the source and destination textures are the same type. */
4379 type = src_texture->resource.resourceType;
4380 if (dst_texture->resource.resourceType != type)
4382 WARN("Source and destination have different types, returning WINED3DERR_INVALIDCALL.\n");
4383 return WINED3DERR_INVALIDCALL;
4386 /* Check that both textures have the identical numbers of levels. */
4387 level_count = wined3d_texture_get_level_count(src_texture);
4388 if (wined3d_texture_get_level_count(dst_texture) != level_count)
4390 WARN("Source and destination have different level counts, returning WINED3DERR_INVALIDCALL.\n");
4391 return WINED3DERR_INVALIDCALL;
4394 /* Make sure that the destination texture is loaded. */
4395 dst_texture->texture_ops->texture_preload(dst_texture, SRGB_RGB);
4397 /* Update every surface level of the texture. */
4398 switch (type)
4400 case WINED3DRTYPE_TEXTURE:
4402 struct wined3d_surface *src_surface;
4403 struct wined3d_surface *dst_surface;
4405 for (i = 0; i < level_count; ++i)
4407 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4408 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4409 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4410 if (FAILED(hr))
4412 WARN("Failed to update surface, hr %#x.\n", hr);
4413 return hr;
4416 break;
4419 case WINED3DRTYPE_CUBETEXTURE:
4421 struct wined3d_surface *src_surface;
4422 struct wined3d_surface *dst_surface;
4424 for (i = 0; i < level_count * 6; ++i)
4426 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4427 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4428 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4429 if (FAILED(hr))
4431 WARN("Failed to update surface, hr %#x.\n", hr);
4432 return hr;
4435 break;
4438 case WINED3DRTYPE_VOLUMETEXTURE:
4440 for (i = 0; i < level_count; ++i)
4442 hr = device_update_volume(device,
4443 volume_from_resource(wined3d_texture_get_sub_resource(src_texture, i)),
4444 volume_from_resource(wined3d_texture_get_sub_resource(dst_texture, i)));
4445 if (FAILED(hr))
4447 WARN("Failed to update volume, hr %#x.\n", hr);
4448 return hr;
4451 break;
4454 default:
4455 FIXME("Unsupported texture type %#x.\n", type);
4456 return WINED3DERR_INVALIDCALL;
4459 return WINED3D_OK;
4462 HRESULT CDECL wined3d_device_get_front_buffer_data(const struct wined3d_device *device,
4463 UINT swapchain_idx, struct wined3d_surface *dst_surface)
4465 struct wined3d_swapchain *swapchain;
4466 HRESULT hr;
4468 TRACE("device %p, swapchain_idx %u, dst_surface %p.\n", device, swapchain_idx, dst_surface);
4470 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
4471 if (FAILED(hr)) return hr;
4473 hr = wined3d_swapchain_get_front_buffer_data(swapchain, dst_surface);
4474 wined3d_swapchain_decref(swapchain);
4476 return hr;
4479 HRESULT CDECL wined3d_device_validate_device(const struct wined3d_device *device, DWORD *num_passes)
4481 const struct wined3d_state *state = &device->stateBlock->state;
4482 struct wined3d_texture *texture;
4483 DWORD i;
4485 TRACE("device %p, num_passes %p.\n", device, num_passes);
4487 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
4489 if (state->sampler_states[i][WINED3DSAMP_MINFILTER] == WINED3DTEXF_NONE)
4491 WARN("Sampler state %u has minfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4492 return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4494 if (state->sampler_states[i][WINED3DSAMP_MAGFILTER] == WINED3DTEXF_NONE)
4496 WARN("Sampler state %u has magfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4497 return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4500 texture = state->textures[i];
4501 if (!texture || texture->resource.format->flags & WINED3DFMT_FLAG_FILTERING) continue;
4503 if (state->sampler_states[i][WINED3DSAMP_MAGFILTER] != WINED3DTEXF_POINT)
4505 WARN("Non-filterable texture and mag filter enabled on samper %u, returning E_FAIL\n", i);
4506 return E_FAIL;
4508 if (state->sampler_states[i][WINED3DSAMP_MINFILTER] != WINED3DTEXF_POINT)
4510 WARN("Non-filterable texture and min filter enabled on samper %u, returning E_FAIL\n", i);
4511 return E_FAIL;
4513 if (state->sampler_states[i][WINED3DSAMP_MIPFILTER] != WINED3DTEXF_NONE
4514 && state->sampler_states[i][WINED3DSAMP_MIPFILTER] != WINED3DTEXF_POINT)
4516 WARN("Non-filterable texture and mip filter enabled on samper %u, returning E_FAIL\n", i);
4517 return E_FAIL;
4521 if (state->render_states[WINED3DRS_ZENABLE] || state->render_states[WINED3DRS_ZWRITEENABLE] ||
4522 state->render_states[WINED3DRS_STENCILENABLE])
4524 struct wined3d_surface *ds = device->fb.depth_stencil;
4525 struct wined3d_surface *target = device->fb.render_targets[0];
4527 if(ds && target
4528 && (ds->resource.width < target->resource.width || ds->resource.height < target->resource.height))
4530 WARN("Depth stencil is smaller than the color buffer, returning D3DERR_CONFLICTINGRENDERSTATE\n");
4531 return WINED3DERR_CONFLICTINGRENDERSTATE;
4535 /* return a sensible default */
4536 *num_passes = 1;
4538 TRACE("returning D3D_OK\n");
4539 return WINED3D_OK;
4542 HRESULT CDECL wined3d_device_set_software_vertex_processing(struct wined3d_device *device, BOOL software)
4544 static BOOL warned;
4546 TRACE("device %p, software %#x.\n", device, software);
4548 if (!warned)
4550 FIXME("device %p, software %#x stub!\n", device, software);
4551 warned = TRUE;
4554 device->softwareVertexProcessing = software;
4556 return WINED3D_OK;
4559 BOOL CDECL wined3d_device_get_software_vertex_processing(const struct wined3d_device *device)
4561 static BOOL warned;
4563 TRACE("device %p.\n", device);
4565 if (!warned)
4567 TRACE("device %p stub!\n", device);
4568 warned = TRUE;
4571 return device->softwareVertexProcessing;
4574 HRESULT CDECL wined3d_device_get_raster_status(const struct wined3d_device *device,
4575 UINT swapchain_idx, WINED3DRASTER_STATUS *raster_status)
4577 struct wined3d_swapchain *swapchain;
4578 HRESULT hr;
4580 TRACE("device %p, swapchain_idx %u, raster_status %p.\n",
4581 device, swapchain_idx, raster_status);
4583 hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
4584 if (FAILED(hr))
4586 WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
4587 return hr;
4590 hr = wined3d_swapchain_get_raster_status(swapchain, raster_status);
4591 wined3d_swapchain_decref(swapchain);
4592 if (FAILED(hr))
4594 WARN("Failed to get raster status, hr %#x.\n", hr);
4595 return hr;
4598 return WINED3D_OK;
4601 HRESULT CDECL wined3d_device_set_npatch_mode(struct wined3d_device *device, float segments)
4603 static BOOL warned;
4605 TRACE("device %p, segments %.8e.\n", device, segments);
4607 if (segments != 0.0f)
4609 if (!warned)
4611 FIXME("device %p, segments %.8e stub!\n", device, segments);
4612 warned = TRUE;
4616 return WINED3D_OK;
4619 float CDECL wined3d_device_get_npatch_mode(const struct wined3d_device *device)
4621 static BOOL warned;
4623 TRACE("device %p.\n", device);
4625 if (!warned)
4627 FIXME("device %p stub!\n", device);
4628 warned = TRUE;
4631 return 0.0f;
4634 HRESULT CDECL wined3d_device_update_surface(struct wined3d_device *device,
4635 struct wined3d_surface *src_surface, const RECT *src_rect,
4636 struct wined3d_surface *dst_surface, const POINT *dst_point)
4638 TRACE("device %p, src_surface %p, src_rect %s, dst_surface %p, dst_point %s.\n",
4639 device, src_surface, wine_dbgstr_rect(src_rect),
4640 dst_surface, wine_dbgstr_point(dst_point));
4642 if (src_surface->resource.pool != WINED3DPOOL_SYSTEMMEM || dst_surface->resource.pool != WINED3DPOOL_DEFAULT)
4644 WARN("source %p must be SYSTEMMEM and dest %p must be DEFAULT, returning WINED3DERR_INVALIDCALL\n",
4645 src_surface, dst_surface);
4646 return WINED3DERR_INVALIDCALL;
4649 return surface_upload_from_surface(dst_surface, dst_point, src_surface, src_rect);
4652 HRESULT CDECL wined3d_device_draw_rect_patch(struct wined3d_device *device, UINT handle,
4653 const float *num_segs, const struct wined3d_rect_patch_info *rect_patch_info)
4655 struct WineD3DRectPatch *patch;
4656 GLenum old_primitive_type;
4657 unsigned int i;
4658 struct list *e;
4659 BOOL found;
4661 TRACE("device %p, handle %#x, num_segs %p, rect_patch_info %p.\n",
4662 device, handle, num_segs, rect_patch_info);
4664 if (!(handle || rect_patch_info))
4666 /* TODO: Write a test for the return value, thus the FIXME */
4667 FIXME("Both handle and rect_patch_info are NULL.\n");
4668 return WINED3DERR_INVALIDCALL;
4671 if (handle)
4673 i = PATCHMAP_HASHFUNC(handle);
4674 found = FALSE;
4675 LIST_FOR_EACH(e, &device->patches[i])
4677 patch = LIST_ENTRY(e, struct WineD3DRectPatch, entry);
4678 if (patch->Handle == handle)
4680 found = TRUE;
4681 break;
4685 if (!found)
4687 TRACE("Patch does not exist. Creating a new one\n");
4688 patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4689 patch->Handle = handle;
4690 list_add_head(&device->patches[i], &patch->entry);
4691 } else {
4692 TRACE("Found existing patch %p\n", patch);
4695 else
4697 /* Since opengl does not load tesselated vertex attributes into numbered vertex
4698 * attributes we have to tesselate, read back, and draw. This needs a patch
4699 * management structure instance. Create one.
4701 * A possible improvement is to check if a vertex shader is used, and if not directly
4702 * draw the patch.
4704 FIXME("Drawing an uncached patch. This is slow\n");
4705 patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4708 if (num_segs[0] != patch->numSegs[0] || num_segs[1] != patch->numSegs[1]
4709 || num_segs[2] != patch->numSegs[2] || num_segs[3] != patch->numSegs[3]
4710 || (rect_patch_info && memcmp(rect_patch_info, &patch->rect_patch_info, sizeof(*rect_patch_info))))
4712 HRESULT hr;
4713 TRACE("Tesselation density or patch info changed, retesselating\n");
4715 if (rect_patch_info)
4716 patch->rect_patch_info = *rect_patch_info;
4718 patch->numSegs[0] = num_segs[0];
4719 patch->numSegs[1] = num_segs[1];
4720 patch->numSegs[2] = num_segs[2];
4721 patch->numSegs[3] = num_segs[3];
4723 hr = tesselate_rectpatch(device, patch);
4724 if (FAILED(hr))
4726 WARN("Patch tesselation failed.\n");
4728 /* Do not release the handle to store the params of the patch */
4729 if (!handle)
4730 HeapFree(GetProcessHeap(), 0, patch);
4732 return hr;
4736 old_primitive_type = device->stateBlock->state.gl_primitive_type;
4737 device->stateBlock->state.gl_primitive_type = GL_TRIANGLES;
4738 wined3d_device_draw_primitive_strided(device, patch->numSegs[0] * patch->numSegs[1] * 2 * 3, &patch->strided);
4739 device->stateBlock->state.gl_primitive_type = old_primitive_type;
4741 /* Destroy uncached patches */
4742 if (!handle)
4744 HeapFree(GetProcessHeap(), 0, patch->mem);
4745 HeapFree(GetProcessHeap(), 0, patch);
4747 return WINED3D_OK;
4750 HRESULT CDECL wined3d_device_draw_tri_patch(struct wined3d_device *device, UINT handle,
4751 const float *segment_count, const struct wined3d_tri_patch_info *patch_info)
4753 FIXME("device %p, handle %#x, segment_count %p, patch_info %p stub!\n",
4754 device, handle, segment_count, patch_info);
4756 return WINED3D_OK;
4759 HRESULT CDECL wined3d_device_delete_patch(struct wined3d_device *device, UINT handle)
4761 struct WineD3DRectPatch *patch;
4762 struct list *e;
4763 int i;
4765 TRACE("device %p, handle %#x.\n", device, handle);
4767 i = PATCHMAP_HASHFUNC(handle);
4768 LIST_FOR_EACH(e, &device->patches[i])
4770 patch = LIST_ENTRY(e, struct WineD3DRectPatch, entry);
4771 if (patch->Handle == handle)
4773 TRACE("Deleting patch %p\n", patch);
4774 list_remove(&patch->entry);
4775 HeapFree(GetProcessHeap(), 0, patch->mem);
4776 HeapFree(GetProcessHeap(), 0, patch);
4777 return WINED3D_OK;
4781 /* TODO: Write a test for the return value */
4782 FIXME("Attempt to destroy nonexistent patch\n");
4783 return WINED3DERR_INVALIDCALL;
4786 /* Do not call while under the GL lock. */
4787 HRESULT CDECL wined3d_device_color_fill(struct wined3d_device *device,
4788 struct wined3d_surface *surface, const RECT *rect, const struct wined3d_color *color)
4790 RECT r;
4792 TRACE("device %p, surface %p, rect %s, color {%.8e, %.8e, %.8e, %.8e}.\n",
4793 device, surface, wine_dbgstr_rect(rect),
4794 color->r, color->g, color->b, color->a);
4796 if (surface->resource.pool != WINED3DPOOL_DEFAULT && surface->resource.pool != WINED3DPOOL_SYSTEMMEM)
4798 FIXME("call to colorfill with non WINED3DPOOL_DEFAULT or WINED3DPOOL_SYSTEMMEM surface\n");
4799 return WINED3DERR_INVALIDCALL;
4802 if (!rect)
4804 SetRect(&r, 0, 0, surface->resource.width, surface->resource.height);
4805 rect = &r;
4808 return surface_color_fill(surface, rect, color);
4811 /* Do not call while under the GL lock. */
4812 void CDECL wined3d_device_clear_rendertarget_view(struct wined3d_device *device,
4813 struct wined3d_rendertarget_view *rendertarget_view, const struct wined3d_color *color)
4815 struct wined3d_resource *resource;
4816 HRESULT hr;
4817 RECT rect;
4819 resource = rendertarget_view->resource;
4820 if (resource->resourceType != WINED3DRTYPE_SURFACE)
4822 FIXME("Only supported on surface resources\n");
4823 return;
4826 SetRect(&rect, 0, 0, resource->width, resource->height);
4827 hr = surface_color_fill(surface_from_resource(resource), &rect, color);
4828 if (FAILED(hr)) ERR("Color fill failed, hr %#x.\n", hr);
4831 HRESULT CDECL wined3d_device_get_render_target(const struct wined3d_device *device,
4832 UINT render_target_idx, struct wined3d_surface **render_target)
4834 TRACE("device %p, render_target_idx %u, render_target %p.\n",
4835 device, render_target_idx, render_target);
4837 if (render_target_idx >= device->adapter->gl_info.limits.buffers)
4839 WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
4840 return WINED3DERR_INVALIDCALL;
4843 *render_target = device->fb.render_targets[render_target_idx];
4844 TRACE("Returning render target %p.\n", *render_target);
4846 if (!*render_target)
4847 return WINED3DERR_NOTFOUND;
4849 wined3d_surface_incref(*render_target);
4851 return WINED3D_OK;
4854 HRESULT CDECL wined3d_device_get_depth_stencil(const struct wined3d_device *device,
4855 struct wined3d_surface **depth_stencil)
4857 TRACE("device %p, depth_stencil %p.\n", device, depth_stencil);
4859 *depth_stencil = device->fb.depth_stencil;
4860 TRACE("Returning depth/stencil surface %p.\n", *depth_stencil);
4862 if (!*depth_stencil)
4863 return WINED3DERR_NOTFOUND;
4865 wined3d_surface_incref(*depth_stencil);
4867 return WINED3D_OK;
4870 HRESULT CDECL wined3d_device_set_render_target(struct wined3d_device *device,
4871 UINT render_target_idx, struct wined3d_surface *render_target, BOOL set_viewport)
4873 struct wined3d_surface *prev;
4875 TRACE("device %p, render_target_idx %u, render_target %p, set_viewport %#x.\n",
4876 device, render_target_idx, render_target, set_viewport);
4878 if (render_target_idx >= device->adapter->gl_info.limits.buffers)
4880 WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
4881 return WINED3DERR_INVALIDCALL;
4884 prev = device->fb.render_targets[render_target_idx];
4885 if (render_target == prev)
4887 TRACE("Trying to do a NOP SetRenderTarget operation.\n");
4888 return WINED3D_OK;
4891 /* Render target 0 can't be set to NULL. */
4892 if (!render_target && !render_target_idx)
4894 WARN("Trying to set render target 0 to NULL.\n");
4895 return WINED3DERR_INVALIDCALL;
4898 if (render_target && !(render_target->resource.usage & WINED3DUSAGE_RENDERTARGET))
4900 FIXME("Surface %p doesn't have render target usage.\n", render_target);
4901 return WINED3DERR_INVALIDCALL;
4904 if (render_target)
4905 wined3d_surface_incref(render_target);
4906 device->fb.render_targets[render_target_idx] = render_target;
4907 /* Release after the assignment, to prevent device_resource_released()
4908 * from seeing the surface as still in use. */
4909 if (prev)
4910 wined3d_surface_decref(prev);
4912 /* Render target 0 is special. */
4913 if (!render_target_idx && set_viewport)
4915 /* Set the viewport and scissor rectangles, if requested. Tests show
4916 * that stateblock recording is ignored, the change goes directly
4917 * into the primary stateblock. */
4918 device->stateBlock->state.viewport.height = device->fb.render_targets[0]->resource.height;
4919 device->stateBlock->state.viewport.width = device->fb.render_targets[0]->resource.width;
4920 device->stateBlock->state.viewport.x = 0;
4921 device->stateBlock->state.viewport.y = 0;
4922 device->stateBlock->state.viewport.max_z = 1.0f;
4923 device->stateBlock->state.viewport.min_z = 0.0f;
4924 device_invalidate_state(device, STATE_VIEWPORT);
4926 device->stateBlock->state.scissor_rect.top = 0;
4927 device->stateBlock->state.scissor_rect.left = 0;
4928 device->stateBlock->state.scissor_rect.right = device->stateBlock->state.viewport.width;
4929 device->stateBlock->state.scissor_rect.bottom = device->stateBlock->state.viewport.height;
4930 device_invalidate_state(device, STATE_SCISSORRECT);
4933 device_invalidate_state(device, STATE_FRAMEBUFFER);
4935 return WINED3D_OK;
4938 HRESULT CDECL wined3d_device_set_depth_stencil(struct wined3d_device *device, struct wined3d_surface *depth_stencil)
4940 struct wined3d_surface *prev = device->fb.depth_stencil;
4942 TRACE("device %p, depth_stencil %p, old depth_stencil %p.\n",
4943 device, depth_stencil, prev);
4945 if (prev == depth_stencil)
4947 TRACE("Trying to do a NOP SetRenderTarget operation.\n");
4948 return WINED3D_OK;
4951 if (prev)
4953 if (device->swapchains[0]->presentParms.Flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
4954 || prev->flags & SFLAG_DISCARD)
4956 surface_modify_ds_location(prev, SFLAG_DS_DISCARDED,
4957 prev->resource.width, prev->resource.height);
4958 if (prev == device->onscreen_depth_stencil)
4960 wined3d_surface_decref(device->onscreen_depth_stencil);
4961 device->onscreen_depth_stencil = NULL;
4966 device->fb.depth_stencil = depth_stencil;
4967 if (depth_stencil)
4968 wined3d_surface_incref(depth_stencil);
4970 if (!prev != !depth_stencil)
4972 /* Swapping NULL / non NULL depth stencil affects the depth and tests */
4973 device_invalidate_state(device, STATE_RENDER(WINED3DRS_ZENABLE));
4974 device_invalidate_state(device, STATE_RENDER(WINED3DRS_STENCILENABLE));
4975 device_invalidate_state(device, STATE_RENDER(WINED3DRS_STENCILWRITEMASK));
4976 device_invalidate_state(device, STATE_RENDER(WINED3DRS_DEPTHBIAS));
4978 else if (prev && prev->resource.format->depth_size != depth_stencil->resource.format->depth_size)
4980 device_invalidate_state(device, STATE_RENDER(WINED3DRS_DEPTHBIAS));
4982 if (prev)
4983 wined3d_surface_decref(prev);
4985 device_invalidate_state(device, STATE_FRAMEBUFFER);
4987 return WINED3D_OK;
4990 HRESULT CDECL wined3d_device_set_cursor_properties(struct wined3d_device *device,
4991 UINT x_hotspot, UINT y_hotspot, struct wined3d_surface *cursor_image)
4993 WINED3DLOCKED_RECT lockedRect;
4995 TRACE("device %p, x_hotspot %u, y_hotspot %u, cursor_image %p.\n",
4996 device, x_hotspot, y_hotspot, cursor_image);
4998 /* some basic validation checks */
4999 if (device->cursorTexture)
5001 struct wined3d_context *context = context_acquire(device, NULL);
5002 ENTER_GL();
5003 glDeleteTextures(1, &device->cursorTexture);
5004 LEAVE_GL();
5005 context_release(context);
5006 device->cursorTexture = 0;
5009 if (cursor_image)
5011 WINED3DLOCKED_RECT rect;
5013 /* MSDN: Cursor must be A8R8G8B8 */
5014 if (cursor_image->resource.format->id != WINED3DFMT_B8G8R8A8_UNORM)
5016 WARN("surface %p has an invalid format.\n", cursor_image);
5017 return WINED3DERR_INVALIDCALL;
5020 /* MSDN: Cursor must be smaller than the display mode */
5021 if (cursor_image->resource.width > device->adapter->screen_size.cx
5022 || cursor_image->resource.height > device->adapter->screen_size.cy)
5024 WARN("Surface %p dimensions are %ux%u, but screen dimensions are %ux%u.\n",
5025 cursor_image, cursor_image->resource.width, cursor_image->resource.height,
5026 device->adapter->screen_size.cx, device->adapter->screen_size.cy);
5027 return WINED3DERR_INVALIDCALL;
5030 /* TODO: MSDN: Cursor sizes must be a power of 2 */
5032 /* Do not store the surface's pointer because the application may
5033 * release it after setting the cursor image. Windows doesn't
5034 * addref the set surface, so we can't do this either without
5035 * creating circular refcount dependencies. Copy out the gl texture
5036 * instead. */
5037 device->cursorWidth = cursor_image->resource.width;
5038 device->cursorHeight = cursor_image->resource.height;
5039 if (SUCCEEDED(wined3d_surface_map(cursor_image, &rect, NULL, WINED3DLOCK_READONLY)))
5041 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
5042 const struct wined3d_format *format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
5043 struct wined3d_context *context;
5044 char *mem, *bits = rect.pBits;
5045 GLint intfmt = format->glInternal;
5046 GLint gl_format = format->glFormat;
5047 GLint type = format->glType;
5048 INT height = device->cursorHeight;
5049 INT width = device->cursorWidth;
5050 INT bpp = format->byte_count;
5051 INT i;
5053 /* Reformat the texture memory (pitch and width can be
5054 * different) */
5055 mem = HeapAlloc(GetProcessHeap(), 0, width * height * bpp);
5056 for(i = 0; i < height; i++)
5057 memcpy(&mem[width * bpp * i], &bits[rect.Pitch * i], width * bpp);
5058 wined3d_surface_unmap(cursor_image);
5060 context = context_acquire(device, NULL);
5062 ENTER_GL();
5064 if (gl_info->supported[APPLE_CLIENT_STORAGE])
5066 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
5067 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
5070 invalidate_active_texture(device, context);
5071 /* Create a new cursor texture */
5072 glGenTextures(1, &device->cursorTexture);
5073 checkGLcall("glGenTextures");
5074 context_bind_texture(context, GL_TEXTURE_2D, device->cursorTexture);
5075 /* Copy the bitmap memory into the cursor texture */
5076 glTexImage2D(GL_TEXTURE_2D, 0, intfmt, width, height, 0, gl_format, type, mem);
5077 checkGLcall("glTexImage2D");
5078 HeapFree(GetProcessHeap(), 0, mem);
5080 if (gl_info->supported[APPLE_CLIENT_STORAGE])
5082 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
5083 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
5086 LEAVE_GL();
5088 context_release(context);
5090 else
5092 FIXME("A cursor texture was not returned.\n");
5093 device->cursorTexture = 0;
5096 if (cursor_image->resource.width == 32 && cursor_image->resource.height == 32)
5098 /* Draw a hardware cursor */
5099 ICONINFO cursorInfo;
5100 HCURSOR cursor;
5101 /* Create and clear maskBits because it is not needed for
5102 * 32-bit cursors. 32x32 bits split into 32-bit chunks == 32
5103 * chunks. */
5104 DWORD *maskBits = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
5105 (cursor_image->resource.width * cursor_image->resource.height / 8));
5106 wined3d_surface_map(cursor_image, &lockedRect, NULL,
5107 WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY);
5108 TRACE("width: %u height: %u.\n", cursor_image->resource.width, cursor_image->resource.height);
5110 cursorInfo.fIcon = FALSE;
5111 cursorInfo.xHotspot = x_hotspot;
5112 cursorInfo.yHotspot = y_hotspot;
5113 cursorInfo.hbmMask = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
5114 1, 1, maskBits);
5115 cursorInfo.hbmColor = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
5116 1, 32, lockedRect.pBits);
5117 wined3d_surface_unmap(cursor_image);
5118 /* Create our cursor and clean up. */
5119 cursor = CreateIconIndirect(&cursorInfo);
5120 if (cursorInfo.hbmMask) DeleteObject(cursorInfo.hbmMask);
5121 if (cursorInfo.hbmColor) DeleteObject(cursorInfo.hbmColor);
5122 if (device->hardwareCursor) DestroyCursor(device->hardwareCursor);
5123 device->hardwareCursor = cursor;
5124 if (device->bCursorVisible) SetCursor( cursor );
5125 HeapFree(GetProcessHeap(), 0, maskBits);
5129 device->xHotSpot = x_hotspot;
5130 device->yHotSpot = y_hotspot;
5131 return WINED3D_OK;
5134 void CDECL wined3d_device_set_cursor_position(struct wined3d_device *device,
5135 int x_screen_space, int y_screen_space, DWORD flags)
5137 TRACE("device %p, x %d, y %d, flags %#x.\n",
5138 device, x_screen_space, y_screen_space, flags);
5140 device->xScreenSpace = x_screen_space;
5141 device->yScreenSpace = y_screen_space;
5143 if (device->hardwareCursor)
5145 POINT pt;
5147 GetCursorPos( &pt );
5148 if (x_screen_space == pt.x && y_screen_space == pt.y)
5149 return;
5150 SetCursorPos( x_screen_space, y_screen_space );
5152 /* Switch to the software cursor if position diverges from the hardware one. */
5153 GetCursorPos( &pt );
5154 if (x_screen_space != pt.x || y_screen_space != pt.y)
5156 if (device->bCursorVisible) SetCursor( NULL );
5157 DestroyCursor( device->hardwareCursor );
5158 device->hardwareCursor = 0;
5163 BOOL CDECL wined3d_device_show_cursor(struct wined3d_device *device, BOOL show)
5165 BOOL oldVisible = device->bCursorVisible;
5167 TRACE("device %p, show %#x.\n", device, show);
5170 * When ShowCursor is first called it should make the cursor appear at the OS's last
5171 * known cursor position.
5173 if (show && !oldVisible)
5175 POINT pt;
5176 GetCursorPos(&pt);
5177 device->xScreenSpace = pt.x;
5178 device->yScreenSpace = pt.y;
5181 if (device->hardwareCursor)
5183 device->bCursorVisible = show;
5184 if (show)
5185 SetCursor(device->hardwareCursor);
5186 else
5187 SetCursor(NULL);
5189 else
5191 if (device->cursorTexture)
5192 device->bCursorVisible = show;
5195 return oldVisible;
5198 void CDECL wined3d_device_evict_managed_resources(struct wined3d_device *device)
5200 struct wined3d_resource *resource, *cursor;
5202 TRACE("device %p.\n", device);
5204 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5206 TRACE("Checking resource %p for eviction.\n", resource);
5208 if (resource->pool == WINED3DPOOL_MANAGED)
5210 TRACE("Evicting %p.\n", resource);
5211 resource->resource_ops->resource_unload(resource);
5215 /* Invalidate stream sources, the buffer(s) may have been evicted. */
5216 device_invalidate_state(device, STATE_STREAMSRC);
5219 static HRESULT updateSurfaceDesc(struct wined3d_surface *surface,
5220 const WINED3DPRESENT_PARAMETERS *pPresentationParameters)
5222 struct wined3d_device *device = surface->resource.device;
5223 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
5225 /* Reallocate proper memory for the front and back buffer and adjust their sizes */
5226 if (surface->flags & SFLAG_DIBSECTION)
5228 DeleteDC(surface->hDC);
5229 DeleteObject(surface->dib.DIBsection);
5230 surface->dib.bitmap_data = NULL;
5231 surface->resource.allocatedMemory = NULL;
5232 surface->flags &= ~SFLAG_DIBSECTION;
5234 surface->resource.width = pPresentationParameters->BackBufferWidth;
5235 surface->resource.height = pPresentationParameters->BackBufferHeight;
5236 if (gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] || gl_info->supported[ARB_TEXTURE_RECTANGLE]
5237 || gl_info->supported[WINED3D_GL_NORMALIZED_TEXRECT])
5239 surface->pow2Width = pPresentationParameters->BackBufferWidth;
5240 surface->pow2Height = pPresentationParameters->BackBufferHeight;
5241 } else {
5242 surface->pow2Width = surface->pow2Height = 1;
5243 while (surface->pow2Width < pPresentationParameters->BackBufferWidth) surface->pow2Width <<= 1;
5244 while (surface->pow2Height < pPresentationParameters->BackBufferHeight) surface->pow2Height <<= 1;
5247 if (!(surface->resource.usage & WINED3DUSAGE_DEPTHSTENCIL))
5248 surface->resource.format = wined3d_get_format(gl_info, pPresentationParameters->BackBufferFormat);
5249 surface->resource.multisample_type = pPresentationParameters->MultiSampleType;
5250 surface->resource.multisample_quality = pPresentationParameters->MultiSampleQuality;
5252 surface->resource.resource_ops->resource_unload(&surface->resource);
5254 if (surface->pow2Width != pPresentationParameters->BackBufferWidth
5255 || surface->pow2Height != pPresentationParameters->BackBufferHeight)
5257 surface->flags |= SFLAG_NONPOW2;
5259 else
5261 surface->flags &= ~SFLAG_NONPOW2;
5263 HeapFree(GetProcessHeap(), 0, surface->resource.heapMemory);
5264 surface->resource.allocatedMemory = NULL;
5265 surface->resource.heapMemory = NULL;
5266 surface->resource.size = wined3d_surface_get_pitch(surface) * surface->pow2Width;
5268 /* Put all surfaces into sysmem - the drawable might disappear if the backbuffer was rendered
5269 * to a FBO */
5270 if (!surface_init_sysmem(surface))
5272 return E_OUTOFMEMORY;
5274 return WINED3D_OK;
5277 static BOOL is_display_mode_supported(const struct wined3d_device *device, const WINED3DPRESENT_PARAMETERS *pp)
5279 struct wined3d_display_mode m;
5280 UINT i, count;
5281 HRESULT hr;
5283 /* All Windowed modes are supported, as is leaving the current mode */
5284 if(pp->Windowed) return TRUE;
5285 if(!pp->BackBufferWidth) return TRUE;
5286 if(!pp->BackBufferHeight) return TRUE;
5288 count = wined3d_get_adapter_mode_count(device->wined3d, device->adapter->ordinal, WINED3DFMT_UNKNOWN);
5289 for (i = 0; i < count; ++i)
5291 memset(&m, 0, sizeof(m));
5292 hr = wined3d_enum_adapter_modes(device->wined3d, device->adapter->ordinal, WINED3DFMT_UNKNOWN, i, &m);
5293 if (FAILED(hr))
5294 ERR("Failed to enumerate adapter mode.\n");
5295 if (m.width == pp->BackBufferWidth && m.height == pp->BackBufferHeight)
5296 /* Mode found, it is supported. */
5297 return TRUE;
5299 /* Mode not found -> not supported */
5300 return FALSE;
5303 /* Do not call while under the GL lock. */
5304 static void delete_opengl_contexts(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
5306 struct wined3d_resource *resource, *cursor;
5307 const struct wined3d_gl_info *gl_info;
5308 struct wined3d_context *context;
5309 struct wined3d_shader *shader;
5311 context = context_acquire(device, NULL);
5312 gl_info = context->gl_info;
5314 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5316 TRACE("Unloading resource %p.\n", resource);
5318 resource->resource_ops->resource_unload(resource);
5321 LIST_FOR_EACH_ENTRY(shader, &device->shaders, struct wined3d_shader, shader_list_entry)
5323 device->shader_backend->shader_destroy(shader);
5326 ENTER_GL();
5327 if (device->depth_blt_texture)
5329 glDeleteTextures(1, &device->depth_blt_texture);
5330 device->depth_blt_texture = 0;
5332 if (device->cursorTexture)
5334 glDeleteTextures(1, &device->cursorTexture);
5335 device->cursorTexture = 0;
5337 LEAVE_GL();
5339 device->blitter->free_private(device);
5340 device->frag_pipe->free_private(device);
5341 device->shader_backend->shader_free_private(device);
5342 destroy_dummy_textures(device, gl_info);
5344 context_release(context);
5346 while (device->context_count)
5348 swapchain_destroy_contexts(device->contexts[0]->swapchain);
5351 HeapFree(GetProcessHeap(), 0, swapchain->context);
5352 swapchain->context = NULL;
5355 /* Do not call while under the GL lock. */
5356 static HRESULT create_primary_opengl_context(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
5358 struct wined3d_context *context;
5359 struct wined3d_surface *target;
5360 HRESULT hr;
5362 /* Recreate the primary swapchain's context */
5363 swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(*swapchain->context));
5364 if (!swapchain->context)
5366 ERR("Failed to allocate memory for swapchain context array.\n");
5367 return E_OUTOFMEMORY;
5370 target = swapchain->back_buffers ? swapchain->back_buffers[0] : swapchain->front_buffer;
5371 if (!(context = context_create(swapchain, target, swapchain->ds_format)))
5373 WARN("Failed to create context.\n");
5374 HeapFree(GetProcessHeap(), 0, swapchain->context);
5375 return E_FAIL;
5378 swapchain->context[0] = context;
5379 swapchain->num_contexts = 1;
5380 create_dummy_textures(device, context);
5381 context_release(context);
5383 hr = device->shader_backend->shader_alloc_private(device);
5384 if (FAILED(hr))
5386 ERR("Failed to allocate shader private data, hr %#x.\n", hr);
5387 goto err;
5390 hr = device->frag_pipe->alloc_private(device);
5391 if (FAILED(hr))
5393 ERR("Failed to allocate fragment pipe private data, hr %#x.\n", hr);
5394 device->shader_backend->shader_free_private(device);
5395 goto err;
5398 hr = device->blitter->alloc_private(device);
5399 if (FAILED(hr))
5401 ERR("Failed to allocate blitter private data, hr %#x.\n", hr);
5402 device->frag_pipe->free_private(device);
5403 device->shader_backend->shader_free_private(device);
5404 goto err;
5407 return WINED3D_OK;
5409 err:
5410 context_acquire(device, NULL);
5411 destroy_dummy_textures(device, context->gl_info);
5412 context_release(context);
5413 context_destroy(device, context);
5414 HeapFree(GetProcessHeap(), 0, swapchain->context);
5415 swapchain->num_contexts = 0;
5416 return hr;
5419 /* Do not call while under the GL lock. */
5420 HRESULT CDECL wined3d_device_reset(struct wined3d_device *device,
5421 const WINED3DPRESENT_PARAMETERS *present_parameters,
5422 wined3d_device_reset_cb callback)
5424 struct wined3d_resource *resource, *cursor;
5425 struct wined3d_swapchain *swapchain;
5426 struct wined3d_display_mode mode;
5427 BOOL DisplayModeChanged = FALSE;
5428 BOOL update_desc = FALSE;
5429 unsigned int i;
5430 HRESULT hr;
5432 TRACE("device %p, present_parameters %p.\n", device, present_parameters);
5434 wined3d_device_set_index_buffer(device, NULL, WINED3DFMT_UNKNOWN);
5435 for (i = 0; i < MAX_STREAMS; ++i)
5437 wined3d_device_set_stream_source(device, i, NULL, 0, 0);
5439 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
5441 wined3d_device_set_texture(device, i, NULL);
5443 if (device->onscreen_depth_stencil)
5445 wined3d_surface_decref(device->onscreen_depth_stencil);
5446 device->onscreen_depth_stencil = NULL;
5449 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5451 TRACE("Enumerating resource %p.\n", resource);
5452 if (FAILED(hr = callback(resource)))
5453 return hr;
5456 hr = wined3d_device_get_swapchain(device, 0, &swapchain);
5457 if (FAILED(hr))
5459 ERR("Failed to get the first implicit swapchain\n");
5460 return hr;
5463 if (!is_display_mode_supported(device, present_parameters))
5465 WARN("Rejecting Reset() call because the requested display mode is not supported\n");
5466 WARN("Requested mode: %d, %d.\n",
5467 present_parameters->BackBufferWidth,
5468 present_parameters->BackBufferHeight);
5469 wined3d_swapchain_decref(swapchain);
5470 return WINED3DERR_INVALIDCALL;
5473 /* Is it necessary to recreate the gl context? Actually every setting can be changed
5474 * on an existing gl context, so there's no real need for recreation.
5476 * TODO: Figure out how Reset influences resources in D3DPOOL_DEFAULT, D3DPOOL_SYSTEMMEMORY and D3DPOOL_MANAGED
5478 * TODO: Figure out what happens to explicit swapchains, or if we have more than one implicit swapchain
5480 TRACE("New params:\n");
5481 TRACE("BackBufferWidth = %d\n", present_parameters->BackBufferWidth);
5482 TRACE("BackBufferHeight = %d\n", present_parameters->BackBufferHeight);
5483 TRACE("BackBufferFormat = %s\n", debug_d3dformat(present_parameters->BackBufferFormat));
5484 TRACE("BackBufferCount = %d\n", present_parameters->BackBufferCount);
5485 TRACE("MultiSampleType = %d\n", present_parameters->MultiSampleType);
5486 TRACE("MultiSampleQuality = %d\n", present_parameters->MultiSampleQuality);
5487 TRACE("SwapEffect = %d\n", present_parameters->SwapEffect);
5488 TRACE("hDeviceWindow = %p\n", present_parameters->hDeviceWindow);
5489 TRACE("Windowed = %s\n", present_parameters->Windowed ? "true" : "false");
5490 TRACE("EnableAutoDepthStencil = %s\n", present_parameters->EnableAutoDepthStencil ? "true" : "false");
5491 TRACE("Flags = %08x\n", present_parameters->Flags);
5492 TRACE("FullScreen_RefreshRateInHz = %d\n", present_parameters->FullScreen_RefreshRateInHz);
5493 TRACE("PresentationInterval = %d\n", present_parameters->PresentationInterval);
5495 /* No special treatment of these parameters. Just store them */
5496 swapchain->presentParms.SwapEffect = present_parameters->SwapEffect;
5497 swapchain->presentParms.Flags = present_parameters->Flags;
5498 swapchain->presentParms.PresentationInterval = present_parameters->PresentationInterval;
5499 swapchain->presentParms.FullScreen_RefreshRateInHz = present_parameters->FullScreen_RefreshRateInHz;
5501 /* What to do about these? */
5502 if (present_parameters->BackBufferCount
5503 && present_parameters->BackBufferCount != swapchain->presentParms.BackBufferCount)
5504 FIXME("Cannot change the back buffer count yet.\n");
5506 if (present_parameters->hDeviceWindow
5507 && present_parameters->hDeviceWindow != swapchain->presentParms.hDeviceWindow)
5508 FIXME("Cannot change the device window yet.\n");
5510 if (present_parameters->EnableAutoDepthStencil && !device->auto_depth_stencil)
5512 HRESULT hrc;
5514 TRACE("Creating the depth stencil buffer\n");
5516 hrc = device->device_parent->ops->create_depth_stencil(device->device_parent,
5517 present_parameters->BackBufferWidth,
5518 present_parameters->BackBufferHeight,
5519 present_parameters->AutoDepthStencilFormat,
5520 present_parameters->MultiSampleType,
5521 present_parameters->MultiSampleQuality,
5522 FALSE,
5523 &device->auto_depth_stencil);
5524 if (FAILED(hrc))
5526 ERR("Failed to create the depth stencil buffer.\n");
5527 wined3d_swapchain_decref(swapchain);
5528 return WINED3DERR_INVALIDCALL;
5532 if (device->onscreen_depth_stencil)
5534 wined3d_surface_decref(device->onscreen_depth_stencil);
5535 device->onscreen_depth_stencil = NULL;
5538 /* Reset the depth stencil */
5539 if (present_parameters->EnableAutoDepthStencil)
5540 wined3d_device_set_depth_stencil(device, device->auto_depth_stencil);
5541 else
5542 wined3d_device_set_depth_stencil(device, NULL);
5544 TRACE("Resetting stateblock\n");
5545 wined3d_stateblock_decref(device->updateStateBlock);
5546 wined3d_stateblock_decref(device->stateBlock);
5548 if (present_parameters->Windowed)
5550 mode.width = swapchain->orig_width;
5551 mode.height = swapchain->orig_height;
5552 mode.refresh_rate = 0;
5553 mode.format_id = swapchain->presentParms.BackBufferFormat;
5555 else
5557 mode.width = present_parameters->BackBufferWidth;
5558 mode.height = present_parameters->BackBufferHeight;
5559 mode.refresh_rate = present_parameters->FullScreen_RefreshRateInHz;
5560 mode.format_id = present_parameters->BackBufferFormat;
5563 /* Should Width == 800 && Height == 0 set 800x600? */
5564 if (present_parameters->BackBufferWidth && present_parameters->BackBufferHeight
5565 && (present_parameters->BackBufferWidth != swapchain->presentParms.BackBufferWidth
5566 || present_parameters->BackBufferHeight != swapchain->presentParms.BackBufferHeight))
5568 if (!present_parameters->Windowed)
5569 DisplayModeChanged = TRUE;
5571 swapchain->presentParms.BackBufferWidth = present_parameters->BackBufferWidth;
5572 swapchain->presentParms.BackBufferHeight = present_parameters->BackBufferHeight;
5573 update_desc = TRUE;
5576 if (present_parameters->BackBufferFormat != WINED3DFMT_UNKNOWN
5577 && present_parameters->BackBufferFormat != swapchain->presentParms.BackBufferFormat)
5579 swapchain->presentParms.BackBufferFormat = present_parameters->BackBufferFormat;
5580 update_desc = TRUE;
5583 if (present_parameters->MultiSampleType != swapchain->presentParms.MultiSampleType
5584 || present_parameters->MultiSampleQuality != swapchain->presentParms.MultiSampleQuality)
5586 swapchain->presentParms.MultiSampleType = present_parameters->MultiSampleType;
5587 swapchain->presentParms.MultiSampleQuality = present_parameters->MultiSampleQuality;
5588 update_desc = TRUE;
5591 if (update_desc)
5593 UINT i;
5595 hr = updateSurfaceDesc(swapchain->front_buffer, &swapchain->presentParms);
5596 if (FAILED(hr))
5598 wined3d_swapchain_decref(swapchain);
5599 return hr;
5602 for (i = 0; i < swapchain->presentParms.BackBufferCount; ++i)
5604 hr = updateSurfaceDesc(swapchain->back_buffers[i], &swapchain->presentParms);
5605 if (FAILED(hr))
5607 wined3d_swapchain_decref(swapchain);
5608 return hr;
5611 if (device->auto_depth_stencil)
5613 hr = updateSurfaceDesc(device->auto_depth_stencil, &swapchain->presentParms);
5614 if (FAILED(hr))
5616 wined3d_swapchain_decref(swapchain);
5617 return hr;
5622 delete_opengl_contexts(device, swapchain);
5624 if (!present_parameters->Windowed != !swapchain->presentParms.Windowed
5625 || DisplayModeChanged)
5627 wined3d_device_set_display_mode(device, 0, &mode);
5629 if (!present_parameters->Windowed)
5631 if (swapchain->presentParms.Windowed)
5633 HWND focus_window = device->create_parms.focus_window;
5634 if (!focus_window)
5635 focus_window = present_parameters->hDeviceWindow;
5636 if (FAILED(hr = wined3d_device_acquire_focus_window(device, focus_window)))
5638 ERR("Failed to acquire focus window, hr %#x.\n", hr);
5639 wined3d_swapchain_decref(swapchain);
5640 return hr;
5643 /* switch from windowed to fs */
5644 wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5645 present_parameters->BackBufferWidth,
5646 present_parameters->BackBufferHeight);
5648 else
5650 /* Fullscreen -> fullscreen mode change */
5651 MoveWindow(swapchain->device_window, 0, 0,
5652 present_parameters->BackBufferWidth, present_parameters->BackBufferHeight,
5653 TRUE);
5656 else if (!swapchain->presentParms.Windowed)
5658 /* Fullscreen -> windowed switch */
5659 wined3d_device_restore_fullscreen_window(device, swapchain->device_window);
5660 wined3d_device_release_focus_window(device);
5662 swapchain->presentParms.Windowed = present_parameters->Windowed;
5664 else if (!present_parameters->Windowed)
5666 DWORD style = device->style;
5667 DWORD exStyle = device->exStyle;
5668 /* If we're in fullscreen, and the mode wasn't changed, we have to get the window back into
5669 * the right position. Some applications(Battlefield 2, Guild Wars) move it and then call
5670 * Reset to clear up their mess. Guild Wars also loses the device during that.
5672 device->style = 0;
5673 device->exStyle = 0;
5674 wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5675 present_parameters->BackBufferWidth,
5676 present_parameters->BackBufferHeight);
5677 device->style = style;
5678 device->exStyle = exStyle;
5681 /* Note: No parent needed for initial internal stateblock */
5682 hr = wined3d_stateblock_create(device, WINED3DSBT_INIT, &device->stateBlock);
5683 if (FAILED(hr))
5684 ERR("Resetting the stateblock failed with error %#x.\n", hr);
5685 else
5686 TRACE("Created stateblock %p.\n", device->stateBlock);
5687 device->updateStateBlock = device->stateBlock;
5688 wined3d_stateblock_incref(device->updateStateBlock);
5690 stateblock_init_default_state(device->stateBlock);
5692 swapchain_update_render_to_fbo(swapchain);
5693 swapchain_update_draw_bindings(swapchain);
5695 hr = create_primary_opengl_context(device, swapchain);
5696 wined3d_swapchain_decref(swapchain);
5698 /* All done. There is no need to reload resources or shaders, this will happen automatically on the
5699 * first use
5701 return hr;
5704 HRESULT CDECL wined3d_device_set_dialog_box_mode(struct wined3d_device *device, BOOL enable_dialogs)
5706 TRACE("device %p, enable_dialogs %#x.\n", device, enable_dialogs);
5708 if (!enable_dialogs) FIXME("Dialogs cannot be disabled yet.\n");
5710 return WINED3D_OK;
5714 HRESULT CDECL wined3d_device_get_creation_parameters(const struct wined3d_device *device,
5715 struct wined3d_device_creation_parameters *parameters)
5717 TRACE("device %p, parameters %p.\n", device, parameters);
5719 *parameters = device->create_parms;
5720 return WINED3D_OK;
5723 void CDECL wined3d_device_set_gamma_ramp(const struct wined3d_device *device,
5724 UINT swapchain_idx, DWORD flags, const struct wined3d_gamma_ramp *ramp)
5726 struct wined3d_swapchain *swapchain;
5728 TRACE("device %p, swapchain_idx %u, flags %#x, ramp %p.\n",
5729 device, swapchain_idx, flags, ramp);
5731 if (SUCCEEDED(wined3d_device_get_swapchain(device, swapchain_idx, &swapchain)))
5733 wined3d_swapchain_set_gamma_ramp(swapchain, flags, ramp);
5734 wined3d_swapchain_decref(swapchain);
5738 void CDECL wined3d_device_get_gamma_ramp(const struct wined3d_device *device,
5739 UINT swapchain_idx, struct wined3d_gamma_ramp *ramp)
5741 struct wined3d_swapchain *swapchain;
5743 TRACE("device %p, swapchain_idx %u, ramp %p.\n",
5744 device, swapchain_idx, ramp);
5746 if (SUCCEEDED(wined3d_device_get_swapchain(device, swapchain_idx, &swapchain)))
5748 wined3d_swapchain_get_gamma_ramp(swapchain, ramp);
5749 wined3d_swapchain_decref(swapchain);
5753 void device_resource_add(struct wined3d_device *device, struct wined3d_resource *resource)
5755 TRACE("device %p, resource %p.\n", device, resource);
5757 list_add_head(&device->resources, &resource->resource_list_entry);
5760 static void device_resource_remove(struct wined3d_device *device, struct wined3d_resource *resource)
5762 TRACE("device %p, resource %p.\n", device, resource);
5764 list_remove(&resource->resource_list_entry);
5767 void device_resource_released(struct wined3d_device *device, struct wined3d_resource *resource)
5769 WINED3DRESOURCETYPE type = resource->resourceType;
5770 unsigned int i;
5772 TRACE("device %p, resource %p, type %s.\n", device, resource, debug_d3dresourcetype(type));
5774 context_resource_released(device, resource, type);
5776 switch (type)
5778 case WINED3DRTYPE_SURFACE:
5780 struct wined3d_surface *surface = surface_from_resource(resource);
5782 if (!device->d3d_initialized) break;
5784 for (i = 0; i < device->adapter->gl_info.limits.buffers; ++i)
5786 if (device->fb.render_targets[i] == surface)
5788 ERR("Surface %p is still in use as render target %u.\n", surface, i);
5789 device->fb.render_targets[i] = NULL;
5793 if (device->fb.depth_stencil == surface)
5795 ERR("Surface %p is still in use as depth/stencil buffer.\n", surface);
5796 device->fb.depth_stencil = NULL;
5799 break;
5801 case WINED3DRTYPE_TEXTURE:
5802 case WINED3DRTYPE_CUBETEXTURE:
5803 case WINED3DRTYPE_VOLUMETEXTURE:
5804 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
5806 struct wined3d_texture *texture = wined3d_texture_from_resource(resource);
5808 if (device->stateBlock && device->stateBlock->state.textures[i] == texture)
5810 ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
5811 texture, device->stateBlock, i);
5812 device->stateBlock->state.textures[i] = NULL;
5815 if (device->updateStateBlock != device->stateBlock
5816 && device->updateStateBlock->state.textures[i] == texture)
5818 ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
5819 texture, device->updateStateBlock, i);
5820 device->updateStateBlock->state.textures[i] = NULL;
5823 break;
5825 case WINED3DRTYPE_BUFFER:
5827 struct wined3d_buffer *buffer = buffer_from_resource(resource);
5829 for (i = 0; i < MAX_STREAMS; ++i)
5831 if (device->stateBlock && device->stateBlock->state.streams[i].buffer == buffer)
5833 ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
5834 buffer, device->stateBlock, i);
5835 device->stateBlock->state.streams[i].buffer = NULL;
5838 if (device->updateStateBlock != device->stateBlock
5839 && device->updateStateBlock->state.streams[i].buffer == buffer)
5841 ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
5842 buffer, device->updateStateBlock, i);
5843 device->updateStateBlock->state.streams[i].buffer = NULL;
5848 if (device->stateBlock && device->stateBlock->state.index_buffer == buffer)
5850 ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
5851 buffer, device->stateBlock);
5852 device->stateBlock->state.index_buffer = NULL;
5855 if (device->updateStateBlock != device->stateBlock
5856 && device->updateStateBlock->state.index_buffer == buffer)
5858 ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
5859 buffer, device->updateStateBlock);
5860 device->updateStateBlock->state.index_buffer = NULL;
5863 break;
5865 default:
5866 break;
5869 /* Remove the resource from the resourceStore */
5870 device_resource_remove(device, resource);
5872 TRACE("Resource released.\n");
5875 HRESULT CDECL wined3d_device_get_surface_from_dc(const struct wined3d_device *device,
5876 HDC dc, struct wined3d_surface **surface)
5878 struct wined3d_resource *resource;
5880 TRACE("device %p, dc %p, surface %p.\n", device, dc, surface);
5882 if (!dc)
5883 return WINED3DERR_INVALIDCALL;
5885 LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
5887 if (resource->resourceType == WINED3DRTYPE_SURFACE)
5889 struct wined3d_surface *s = surface_from_resource(resource);
5891 if (s->hDC == dc)
5893 TRACE("Found surface %p for dc %p.\n", s, dc);
5894 *surface = s;
5895 return WINED3D_OK;
5900 return WINED3DERR_INVALIDCALL;
5903 HRESULT device_init(struct wined3d_device *device, struct wined3d *wined3d,
5904 UINT adapter_idx, WINED3DDEVTYPE device_type, HWND focus_window, DWORD flags,
5905 BYTE surface_alignment, struct wined3d_device_parent *device_parent)
5907 struct wined3d_adapter *adapter = &wined3d->adapters[adapter_idx];
5908 const struct fragment_pipeline *fragment_pipeline;
5909 struct wined3d_display_mode mode;
5910 struct shader_caps shader_caps;
5911 struct fragment_caps ffp_caps;
5912 unsigned int i;
5913 HRESULT hr;
5915 device->ref = 1;
5916 device->wined3d = wined3d;
5917 wined3d_incref(device->wined3d);
5918 device->adapter = wined3d->adapter_count ? adapter : NULL;
5919 device->device_parent = device_parent;
5920 list_init(&device->resources);
5921 list_init(&device->shaders);
5922 device->surface_alignment = surface_alignment;
5924 /* Get the initial screen setup for ddraw. */
5925 hr = wined3d_get_adapter_display_mode(wined3d, adapter_idx, &mode);
5926 if (FAILED(hr))
5928 ERR("Failed to get the adapter's display mode, hr %#x.\n", hr);
5929 wined3d_decref(device->wined3d);
5930 return hr;
5932 adapter->screen_size.cx = mode.width;
5933 adapter->screen_size.cy = mode.height;
5934 adapter->screen_format = mode.format_id;
5936 /* Save the creation parameters. */
5937 device->create_parms.adapter_idx = adapter_idx;
5938 device->create_parms.device_type = device_type;
5939 device->create_parms.focus_window = focus_window;
5940 device->create_parms.flags = flags;
5942 for (i = 0; i < PATCHMAP_SIZE; ++i) list_init(&device->patches[i]);
5944 select_shader_mode(&adapter->gl_info, &device->ps_selected_mode, &device->vs_selected_mode);
5945 device->shader_backend = adapter->shader_backend;
5947 if (device->shader_backend)
5949 device->shader_backend->shader_get_caps(&adapter->gl_info, &shader_caps);
5950 device->vshader_version = shader_caps.VertexShaderVersion;
5951 device->pshader_version = shader_caps.PixelShaderVersion;
5952 device->d3d_vshader_constantF = shader_caps.MaxVertexShaderConst;
5953 device->d3d_pshader_constantF = shader_caps.MaxPixelShaderConst;
5954 device->vs_clipping = shader_caps.VSClipping;
5956 fragment_pipeline = adapter->fragment_pipe;
5957 device->frag_pipe = fragment_pipeline;
5958 if (fragment_pipeline)
5960 fragment_pipeline->get_caps(&adapter->gl_info, &ffp_caps);
5961 device->max_ffp_textures = ffp_caps.MaxSimultaneousTextures;
5963 hr = compile_state_table(device->StateTable, device->multistate_funcs, &adapter->gl_info,
5964 ffp_vertexstate_template, fragment_pipeline, misc_state_template);
5965 if (FAILED(hr))
5967 ERR("Failed to compile state table, hr %#x.\n", hr);
5968 wined3d_decref(device->wined3d);
5969 return hr;
5972 device->blitter = adapter->blitter;
5974 return WINED3D_OK;
5978 void device_invalidate_state(const struct wined3d_device *device, DWORD state)
5980 DWORD rep = device->StateTable[state].representative;
5981 struct wined3d_context *context;
5982 DWORD idx;
5983 BYTE shift;
5984 UINT i;
5986 for (i = 0; i < device->context_count; ++i)
5988 context = device->contexts[i];
5989 if(isStateDirty(context, rep)) continue;
5991 context->dirtyArray[context->numDirtyEntries++] = rep;
5992 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
5993 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
5994 context->isStateDirty[idx] |= (1 << shift);
5998 void get_drawable_size_fbo(const struct wined3d_context *context, UINT *width, UINT *height)
6000 /* The drawable size of a fbo target is the opengl texture size, which is the power of two size. */
6001 *width = context->current_rt->pow2Width;
6002 *height = context->current_rt->pow2Height;
6005 void get_drawable_size_backbuffer(const struct wined3d_context *context, UINT *width, UINT *height)
6007 const struct wined3d_swapchain *swapchain = context->swapchain;
6008 /* The drawable size of a backbuffer / aux buffer offscreen target is the size of the
6009 * current context's drawable, which is the size of the back buffer of the swapchain
6010 * the active context belongs to. */
6011 *width = swapchain->presentParms.BackBufferWidth;
6012 *height = swapchain->presentParms.BackBufferHeight;
6015 LRESULT device_process_message(struct wined3d_device *device, HWND window, BOOL unicode,
6016 UINT message, WPARAM wparam, LPARAM lparam, WNDPROC proc)
6018 if (device->filter_messages)
6020 TRACE("Filtering message: window %p, message %#x, wparam %#lx, lparam %#lx.\n",
6021 window, message, wparam, lparam);
6022 if (unicode)
6023 return DefWindowProcW(window, message, wparam, lparam);
6024 else
6025 return DefWindowProcA(window, message, wparam, lparam);
6028 if (message == WM_DESTROY)
6030 TRACE("unregister window %p.\n", window);
6031 wined3d_unregister_window(window);
6033 if (device->focus_window == window) device->focus_window = NULL;
6034 else ERR("Window %p is not the focus window for device %p.\n", window, device);
6036 else if (message == WM_DISPLAYCHANGE)
6038 device->device_parent->ops->mode_changed(device->device_parent);
6041 if (unicode)
6042 return CallWindowProcW(proc, window, message, wparam, lparam);
6043 else
6044 return CallWindowProcA(proc, window, message, wparam, lparam);