d3drm: Implement IDirect3DRMMesh_AddGroup.
[wine] / dlls / wined3d / device.c
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
11  *
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.
16  *
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.
21  *
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
25  */
26
27 #include "config.h"
28 #include <stdio.h>
29 #ifdef HAVE_FLOAT_H
30 # include <float.h>
31 #endif
32 #include "wined3d_private.h"
33
34 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
35
36 /* Define the default light parameters as specified by MSDN. */
37 const struct wined3d_light WINED3D_default_light =
38 {
39     WINED3D_LIGHT_DIRECTIONAL,  /* Type */
40     { 1.0f, 1.0f, 1.0f, 0.0f }, /* Diffuse r,g,b,a */
41     { 0.0f, 0.0f, 0.0f, 0.0f }, /* Specular r,g,b,a */
42     { 0.0f, 0.0f, 0.0f, 0.0f }, /* Ambient r,g,b,a, */
43     { 0.0f, 0.0f, 0.0f },       /* Position x,y,z */
44     { 0.0f, 0.0f, 1.0f },       /* Direction x,y,z */
45     0.0f,                       /* Range */
46     0.0f,                       /* Falloff */
47     0.0f, 0.0f, 0.0f,           /* Attenuation 0,1,2 */
48     0.0f,                       /* Theta */
49     0.0f                        /* Phi */
50 };
51
52 /**********************************************************
53  * Global variable / Constants follow
54  **********************************************************/
55 const struct wined3d_matrix identity =
56 {{{
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 */
62
63 /* Note that except for WINED3DPT_POINTLIST and WINED3DPT_LINELIST these
64  * actually have the same values in GL and D3D. */
65 static GLenum gl_primitive_type_from_d3d(enum wined3d_primitive_type primitive_type)
66 {
67     switch(primitive_type)
68     {
69         case WINED3D_PT_POINTLIST:
70             return GL_POINTS;
71
72         case WINED3D_PT_LINELIST:
73             return GL_LINES;
74
75         case WINED3D_PT_LINESTRIP:
76             return GL_LINE_STRIP;
77
78         case WINED3D_PT_TRIANGLELIST:
79             return GL_TRIANGLES;
80
81         case WINED3D_PT_TRIANGLESTRIP:
82             return GL_TRIANGLE_STRIP;
83
84         case WINED3D_PT_TRIANGLEFAN:
85             return GL_TRIANGLE_FAN;
86
87         case WINED3D_PT_LINELIST_ADJ:
88             return GL_LINES_ADJACENCY_ARB;
89
90         case WINED3D_PT_LINESTRIP_ADJ:
91             return GL_LINE_STRIP_ADJACENCY_ARB;
92
93         case WINED3D_PT_TRIANGLELIST_ADJ:
94             return GL_TRIANGLES_ADJACENCY_ARB;
95
96         case WINED3D_PT_TRIANGLESTRIP_ADJ:
97             return GL_TRIANGLE_STRIP_ADJACENCY_ARB;
98
99         default:
100             FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
101             return GL_NONE;
102     }
103 }
104
105 static enum wined3d_primitive_type d3d_primitive_type_from_gl(GLenum primitive_type)
106 {
107     switch(primitive_type)
108     {
109         case GL_POINTS:
110             return WINED3D_PT_POINTLIST;
111
112         case GL_LINES:
113             return WINED3D_PT_LINELIST;
114
115         case GL_LINE_STRIP:
116             return WINED3D_PT_LINESTRIP;
117
118         case GL_TRIANGLES:
119             return WINED3D_PT_TRIANGLELIST;
120
121         case GL_TRIANGLE_STRIP:
122             return WINED3D_PT_TRIANGLESTRIP;
123
124         case GL_TRIANGLE_FAN:
125             return WINED3D_PT_TRIANGLEFAN;
126
127         case GL_LINES_ADJACENCY_ARB:
128             return WINED3D_PT_LINELIST_ADJ;
129
130         case GL_LINE_STRIP_ADJACENCY_ARB:
131             return WINED3D_PT_LINESTRIP_ADJ;
132
133         case GL_TRIANGLES_ADJACENCY_ARB:
134             return WINED3D_PT_TRIANGLELIST_ADJ;
135
136         case GL_TRIANGLE_STRIP_ADJACENCY_ARB:
137             return WINED3D_PT_TRIANGLESTRIP_ADJ;
138
139         default:
140             FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
141             return WINED3D_PT_UNDEFINED;
142     }
143 }
144
145 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
146 {
147     if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
148         *regnum = WINED3D_FFP_POSITION;
149     else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
150         *regnum = WINED3D_FFP_BLENDWEIGHT;
151     else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
152         *regnum = WINED3D_FFP_BLENDINDICES;
153     else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
154         *regnum = WINED3D_FFP_NORMAL;
155     else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
156         *regnum = WINED3D_FFP_PSIZE;
157     else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
158         *regnum = WINED3D_FFP_DIFFUSE;
159     else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
160         *regnum = WINED3D_FFP_SPECULAR;
161     else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
162         *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
163     else
164     {
165         FIXME("Unsupported input stream [usage=%s, usage_idx=%u]\n", debug_d3ddeclusage(usage), usage_idx);
166         *regnum = ~0U;
167         return FALSE;
168     }
169
170     return TRUE;
171 }
172
173 /* Context activation is done by the caller. */
174 void device_stream_info_from_declaration(struct wined3d_device *device, struct wined3d_stream_info *stream_info)
175 {
176     const struct wined3d_state *state = &device->stateBlock->state;
177     /* We need to deal with frequency data! */
178     struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
179     BOOL use_vshader;
180     unsigned int i;
181
182     stream_info->use_map = 0;
183     stream_info->swizzle_map = 0;
184
185     /* Check for transformed vertices, disable vertex shader if present. */
186     stream_info->position_transformed = declaration->position_transformed;
187     use_vshader = state->vertex_shader && !declaration->position_transformed;
188
189     /* Translate the declaration into strided data. */
190     for (i = 0; i < declaration->element_count; ++i)
191     {
192         const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
193         const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
194         struct wined3d_buffer *buffer = stream->buffer;
195         struct wined3d_bo_address data;
196         BOOL stride_used;
197         unsigned int idx;
198         DWORD stride;
199
200         TRACE("%p Element %p (%u of %u)\n", declaration->elements,
201                 element, i + 1, declaration->element_count);
202
203         if (!buffer) continue;
204
205         data.buffer_object = 0;
206         data.addr = NULL;
207
208         stride = stream->stride;
209         if (state->user_stream)
210         {
211             TRACE("Stream %u is UP, %p\n", element->input_slot, buffer);
212             data.buffer_object = 0;
213             data.addr = (BYTE *)buffer;
214         }
215         else
216         {
217             TRACE("Stream %u isn't UP, %p\n", element->input_slot, buffer);
218             buffer_get_memory(buffer, &device->adapter->gl_info, &data);
219
220             /* Can't use vbo's if the base vertex index is negative. OpenGL doesn't accept negative offsets
221              * (or rather offsets bigger than the vbo, because the pointer is unsigned), so use system memory
222              * sources. In most sane cases the pointer - offset will still be > 0, otherwise it will wrap
223              * around to some big value. Hope that with the indices, the driver wraps it back internally. If
224              * not, drawStridedSlow is needed, including a vertex buffer path. */
225             if (state->load_base_vertex_index < 0)
226             {
227                 WARN("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
228                         state->load_base_vertex_index);
229                 data.buffer_object = 0;
230                 data.addr = buffer_get_sysmem(buffer, &device->adapter->gl_info);
231                 if ((UINT_PTR)data.addr < -state->load_base_vertex_index * stride)
232                 {
233                     FIXME("System memory vertex data load offset is negative!\n");
234                 }
235             }
236         }
237         data.addr += element->offset;
238
239         TRACE("offset %u input_slot %u usage_idx %d\n", element->offset, element->input_slot, element->usage_idx);
240
241         if (use_vshader)
242         {
243             if (element->output_slot == ~0U)
244             {
245                 /* TODO: Assuming vertexdeclarations are usually used with the
246                  * same or a similar shader, it might be worth it to store the
247                  * last used output slot and try that one first. */
248                 stride_used = vshader_get_input(state->vertex_shader,
249                         element->usage, element->usage_idx, &idx);
250             }
251             else
252             {
253                 idx = element->output_slot;
254                 stride_used = TRUE;
255             }
256         }
257         else
258         {
259             if (!element->ffp_valid)
260             {
261                 WARN("Skipping unsupported fixed function element of format %s and usage %s\n",
262                         debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
263                 stride_used = FALSE;
264             }
265             else
266             {
267                 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
268             }
269         }
270
271         if (stride_used)
272         {
273             TRACE("Load %s array %u [usage %s, usage_idx %u, "
274                     "input_slot %u, offset %u, stride %u, format %s, buffer_object %u]\n",
275                     use_vshader ? "shader": "fixed function", idx,
276                     debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
277                     element->offset, stride, debug_d3dformat(element->format->id), data.buffer_object);
278
279             data.addr += stream->offset;
280
281             stream_info->elements[idx].format = element->format;
282             stream_info->elements[idx].data = data;
283             stream_info->elements[idx].stride = stride;
284             stream_info->elements[idx].stream_idx = element->input_slot;
285
286             if (!device->adapter->gl_info.supported[ARB_VERTEX_ARRAY_BGRA]
287                     && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
288             {
289                 stream_info->swizzle_map |= 1 << idx;
290             }
291             stream_info->use_map |= 1 << idx;
292         }
293     }
294
295     device->num_buffer_queries = 0;
296     if (!state->user_stream)
297     {
298         WORD map = stream_info->use_map;
299         stream_info->all_vbo = 1;
300
301         /* PreLoad all the vertex buffers. */
302         for (i = 0; map; map >>= 1, ++i)
303         {
304             struct wined3d_stream_info_element *element;
305             struct wined3d_buffer *buffer;
306
307             if (!(map & 1)) continue;
308
309             element = &stream_info->elements[i];
310             buffer = state->streams[element->stream_idx].buffer;
311             wined3d_buffer_preload(buffer);
312
313             /* If the preload dropped the buffer object, update the stream info. */
314             if (buffer->buffer_object != element->data.buffer_object)
315             {
316                 element->data.buffer_object = 0;
317                 element->data.addr = buffer_get_sysmem(buffer, &device->adapter->gl_info)
318                         + (ptrdiff_t)element->data.addr;
319             }
320
321             if (!buffer->buffer_object)
322                 stream_info->all_vbo = 0;
323
324             if (buffer->query)
325                 device->buffer_queries[device->num_buffer_queries++] = buffer->query;
326         }
327     }
328     else
329     {
330         stream_info->all_vbo = 0;
331     }
332 }
333
334 static void stream_info_element_from_strided(const struct wined3d_gl_info *gl_info,
335         const struct wined3d_strided_element *strided, struct wined3d_stream_info_element *e)
336 {
337     e->data.addr = strided->data;
338     e->data.buffer_object = 0;
339     e->format = wined3d_get_format(gl_info, strided->format);
340     e->stride = strided->stride;
341     e->stream_idx = 0;
342 }
343
344 static void device_stream_info_from_strided(const struct wined3d_gl_info *gl_info,
345         const struct wined3d_strided_data *strided, struct wined3d_stream_info *stream_info)
346 {
347     unsigned int i;
348
349     memset(stream_info, 0, sizeof(*stream_info));
350
351     if (strided->position.data)
352         stream_info_element_from_strided(gl_info, &strided->position, &stream_info->elements[WINED3D_FFP_POSITION]);
353     if (strided->normal.data)
354         stream_info_element_from_strided(gl_info, &strided->normal, &stream_info->elements[WINED3D_FFP_NORMAL]);
355     if (strided->diffuse.data)
356         stream_info_element_from_strided(gl_info, &strided->diffuse, &stream_info->elements[WINED3D_FFP_DIFFUSE]);
357     if (strided->specular.data)
358         stream_info_element_from_strided(gl_info, &strided->specular, &stream_info->elements[WINED3D_FFP_SPECULAR]);
359
360     for (i = 0; i < WINED3DDP_MAXTEXCOORD; ++i)
361     {
362         if (strided->tex_coords[i].data)
363             stream_info_element_from_strided(gl_info, &strided->tex_coords[i],
364                     &stream_info->elements[WINED3D_FFP_TEXCOORD0 + i]);
365     }
366
367     stream_info->position_transformed = strided->position_transformed;
368
369     for (i = 0; i < sizeof(stream_info->elements) / sizeof(*stream_info->elements); ++i)
370     {
371         if (!stream_info->elements[i].format) continue;
372
373         if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
374                 && stream_info->elements[i].format->id == WINED3DFMT_B8G8R8A8_UNORM)
375         {
376             stream_info->swizzle_map |= 1 << i;
377         }
378         stream_info->use_map |= 1 << i;
379     }
380 }
381
382 static void device_trace_strided_stream_info(const struct wined3d_stream_info *stream_info)
383 {
384     TRACE("Strided Data:\n");
385     TRACE_STRIDED(stream_info, WINED3D_FFP_POSITION);
386     TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDWEIGHT);
387     TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDINDICES);
388     TRACE_STRIDED(stream_info, WINED3D_FFP_NORMAL);
389     TRACE_STRIDED(stream_info, WINED3D_FFP_PSIZE);
390     TRACE_STRIDED(stream_info, WINED3D_FFP_DIFFUSE);
391     TRACE_STRIDED(stream_info, WINED3D_FFP_SPECULAR);
392     TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD0);
393     TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD1);
394     TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD2);
395     TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD3);
396     TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD4);
397     TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD5);
398     TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD6);
399     TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD7);
400 }
401
402 /* Context activation is done by the caller. */
403 void device_update_stream_info(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
404 {
405     struct wined3d_stream_info *stream_info = &device->strided_streams;
406     const struct wined3d_state *state = &device->stateBlock->state;
407     DWORD prev_all_vbo = stream_info->all_vbo;
408
409     if (device->up_strided)
410     {
411         /* Note: this is a ddraw fixed-function code path. */
412         TRACE("=============================== Strided Input ================================\n");
413         device_stream_info_from_strided(gl_info, device->up_strided, stream_info);
414         if (TRACE_ON(d3d)) device_trace_strided_stream_info(stream_info);
415     }
416     else
417     {
418         TRACE("============================= Vertex Declaration =============================\n");
419         device_stream_info_from_declaration(device, stream_info);
420     }
421
422     if (state->vertex_shader && !stream_info->position_transformed)
423     {
424         if (state->vertex_declaration->half_float_conv_needed && !stream_info->all_vbo)
425         {
426             TRACE("Using drawStridedSlow with vertex shaders for FLOAT16 conversion.\n");
427             device->useDrawStridedSlow = TRUE;
428         }
429         else
430         {
431             device->useDrawStridedSlow = FALSE;
432         }
433     }
434     else
435     {
436         WORD slow_mask = (1 << WINED3D_FFP_PSIZE);
437         slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
438                 & ((1 << WINED3D_FFP_DIFFUSE) | (1 << WINED3D_FFP_SPECULAR));
439
440         if ((stream_info->position_transformed || (stream_info->use_map & slow_mask)) && !stream_info->all_vbo)
441         {
442             device->useDrawStridedSlow = TRUE;
443         }
444         else
445         {
446             device->useDrawStridedSlow = FALSE;
447         }
448     }
449
450     if (state->index_buffer && !state->user_stream)
451     {
452         if (prev_all_vbo != stream_info->all_vbo)
453             device_invalidate_state(device, STATE_INDEXBUFFER);
454         if (stream_info->all_vbo)
455             wined3d_buffer_preload(state->index_buffer);
456         else
457             buffer_get_sysmem(state->index_buffer, gl_info);
458     }
459 }
460
461 static void device_preload_texture(const struct wined3d_state *state, unsigned int idx)
462 {
463     struct wined3d_texture *texture;
464     enum WINED3DSRGB srgb;
465
466     if (!(texture = state->textures[idx])) return;
467     srgb = state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE] ? SRGB_SRGB : SRGB_RGB;
468     texture->texture_ops->texture_preload(texture, srgb);
469 }
470
471 void device_preload_textures(const struct wined3d_device *device)
472 {
473     const struct wined3d_state *state = &device->stateBlock->state;
474     unsigned int i;
475
476     if (use_vs(state))
477     {
478         for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
479         {
480             if (state->vertex_shader->reg_maps.sampler_type[i])
481                 device_preload_texture(state, MAX_FRAGMENT_SAMPLERS + i);
482         }
483     }
484
485     if (use_ps(state))
486     {
487         for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
488         {
489             if (state->pixel_shader->reg_maps.sampler_type[i])
490                 device_preload_texture(state, i);
491         }
492     }
493     else
494     {
495         WORD ffu_map = device->fixed_function_usage_map;
496
497         for (i = 0; ffu_map; ffu_map >>= 1, ++i)
498         {
499             if (ffu_map & 1)
500                 device_preload_texture(state, i);
501         }
502     }
503 }
504
505 BOOL device_context_add(struct wined3d_device *device, struct wined3d_context *context)
506 {
507     struct wined3d_context **new_array;
508
509     TRACE("Adding context %p.\n", context);
510
511     if (!device->contexts) new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_array));
512     else new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts,
513             sizeof(*new_array) * (device->context_count + 1));
514
515     if (!new_array)
516     {
517         ERR("Failed to grow the context array.\n");
518         return FALSE;
519     }
520
521     new_array[device->context_count++] = context;
522     device->contexts = new_array;
523     return TRUE;
524 }
525
526 void device_context_remove(struct wined3d_device *device, struct wined3d_context *context)
527 {
528     struct wined3d_context **new_array;
529     BOOL found = FALSE;
530     UINT i;
531
532     TRACE("Removing context %p.\n", context);
533
534     for (i = 0; i < device->context_count; ++i)
535     {
536         if (device->contexts[i] == context)
537         {
538             found = TRUE;
539             break;
540         }
541     }
542
543     if (!found)
544     {
545         ERR("Context %p doesn't exist in context array.\n", context);
546         return;
547     }
548
549     if (!--device->context_count)
550     {
551         HeapFree(GetProcessHeap(), 0, device->contexts);
552         device->contexts = NULL;
553         return;
554     }
555
556     memmove(&device->contexts[i], &device->contexts[i + 1], (device->context_count - i) * sizeof(*device->contexts));
557     new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts, device->context_count * sizeof(*device->contexts));
558     if (!new_array)
559     {
560         ERR("Failed to shrink context array. Oh well.\n");
561         return;
562     }
563
564     device->contexts = new_array;
565 }
566
567 /* Do not call while under the GL lock. */
568 void device_switch_onscreen_ds(struct wined3d_device *device,
569         struct wined3d_context *context, struct wined3d_surface *depth_stencil)
570 {
571     if (device->onscreen_depth_stencil)
572     {
573         surface_load_ds_location(device->onscreen_depth_stencil, context, SFLAG_INTEXTURE);
574
575         surface_modify_ds_location(device->onscreen_depth_stencil, SFLAG_INTEXTURE,
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);
579     }
580     device->onscreen_depth_stencil = depth_stencil;
581     wined3d_surface_incref(device->onscreen_depth_stencil);
582 }
583
584 static BOOL is_full_clear(const struct wined3d_surface *target, const RECT *draw_rect, const RECT *clear_rect)
585 {
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;
591
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;
597
598     return TRUE;
599 }
600
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, RECT *out_rect)
603 {
604     RECT current_rect, r;
605
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);
612
613     IntersectRect(&r, draw_rect, &current_rect);
614     if (EqualRect(&r, draw_rect))
615     {
616         /* current_rect âЇ draw_rect, modify only. */
617         SetRect(out_rect, 0, 0, ds->ds_current_size.cx, ds->ds_current_size.cy);
618         return;
619     }
620
621     if (EqualRect(&r, &current_rect))
622     {
623         /* draw_rect âЇ current_rect, test if we're doing a full clear. */
624
625         if (!clear_rect)
626         {
627             /* Full clear, modify only. */
628             *out_rect = *draw_rect;
629             return;
630         }
631
632         IntersectRect(&r, draw_rect, clear_rect);
633         if (EqualRect(&r, draw_rect))
634         {
635             /* clear_rect âЇ draw_rect, modify only. */
636             *out_rect = *draw_rect;
637             return;
638         }
639     }
640
641     /* Full load. */
642     surface_load_ds_location(ds, context, location);
643     SetRect(out_rect, 0, 0, ds->ds_current_size.cx, ds->ds_current_size.cy);
644 }
645
646 /* Do not call while under the GL lock. */
647 void 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)
650 {
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;
658     RECT ds_rect;
659
660     /* When we're clearing parts of the drawable, make sure that the target surface is well up to date in the
661      * drawable. After the clear we'll mark the drawable up to date, so we have to make sure that this is true
662      * for the cleared parts, and the untouched parts.
663      *
664      * If we're clearing the whole target there is no need to copy it into the drawable, it will be overwritten
665      * anyway. If we're not clearing the color buffer we don't have to copy either since we're not going to set
666      * the drawable up to date. We have to check all settings that limit the clear area though. Do not bother
667      * checking all this if the dest surface is in the drawable anyway. */
668     if (flags & WINED3DCLEAR_TARGET && !is_full_clear(target, draw_rect, clear_rect))
669     {
670         for (i = 0; i < rt_count; ++i)
671         {
672             struct wined3d_surface *rt = fb->render_targets[i];
673             if (rt)
674                 surface_load_location(rt, rt->draw_binding, NULL);
675         }
676     }
677
678     context = context_acquire(device, target);
679     if (!context->valid)
680     {
681         context_release(context);
682         WARN("Invalid context, skipping clear.\n");
683         return;
684     }
685
686     if (target)
687     {
688         render_offscreen = context->render_offscreen;
689         target->get_drawable_size(context, &drawable_width, &drawable_height);
690     }
691     else
692     {
693         render_offscreen = TRUE;
694         drawable_width = fb->depth_stencil->pow2Width;
695         drawable_height = fb->depth_stencil->pow2Height;
696     }
697
698     if (flags & WINED3DCLEAR_ZBUFFER)
699     {
700         DWORD location = render_offscreen ? fb->depth_stencil->draw_binding : SFLAG_INDRAWABLE;
701
702         if (!render_offscreen && fb->depth_stencil != device->onscreen_depth_stencil)
703             device_switch_onscreen_ds(device, context, fb->depth_stencil);
704         prepare_ds_clear(fb->depth_stencil, context, location,
705                 draw_rect, rect_count, clear_rect, &ds_rect);
706     }
707
708     if (!context_apply_clear_state(context, device, rt_count, fb))
709     {
710         context_release(context);
711         WARN("Failed to apply clear state, skipping clear.\n");
712         return;
713     }
714
715     ENTER_GL();
716
717     /* Only set the values up once, as they are not changing. */
718     if (flags & WINED3DCLEAR_STENCIL)
719     {
720         if (context->gl_info->supported[EXT_STENCIL_TWO_SIDE])
721         {
722             glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
723             context_invalidate_state(context, STATE_RENDER(WINED3D_RS_TWOSIDEDSTENCILMODE));
724         }
725         glStencilMask(~0U);
726         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILWRITEMASK));
727         glClearStencil(stencil);
728         checkGLcall("glClearStencil");
729         clear_mask = clear_mask | GL_STENCIL_BUFFER_BIT;
730     }
731
732     if (flags & WINED3DCLEAR_ZBUFFER)
733     {
734         DWORD location = render_offscreen ? fb->depth_stencil->draw_binding : SFLAG_INDRAWABLE;
735
736         surface_modify_ds_location(fb->depth_stencil, location, ds_rect.right, ds_rect.bottom);
737
738         glDepthMask(GL_TRUE);
739         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZWRITEENABLE));
740         glClearDepth(depth);
741         checkGLcall("glClearDepth");
742         clear_mask = clear_mask | GL_DEPTH_BUFFER_BIT;
743     }
744
745     if (flags & WINED3DCLEAR_TARGET)
746     {
747         for (i = 0; i < rt_count; ++i)
748         {
749             struct wined3d_surface *rt = fb->render_targets[i];
750
751             if (rt)
752                 surface_modify_location(rt, rt->draw_binding, TRUE);
753         }
754
755         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
756         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
757         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
758         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
759         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
760         glClearColor(color->r, color->g, color->b, color->a);
761         checkGLcall("glClearColor");
762         clear_mask = clear_mask | GL_COLOR_BUFFER_BIT;
763     }
764
765     if (!clear_rect)
766     {
767         if (render_offscreen)
768         {
769             glScissor(draw_rect->left, draw_rect->top,
770                     draw_rect->right - draw_rect->left, draw_rect->bottom - draw_rect->top);
771         }
772         else
773         {
774             glScissor(draw_rect->left, drawable_height - draw_rect->bottom,
775                         draw_rect->right - draw_rect->left, draw_rect->bottom - draw_rect->top);
776         }
777         checkGLcall("glScissor");
778         glClear(clear_mask);
779         checkGLcall("glClear");
780     }
781     else
782     {
783         RECT current_rect;
784
785         /* Now process each rect in turn. */
786         for (i = 0; i < rect_count; ++i)
787         {
788             /* Note that GL uses lower left, width/height. */
789             IntersectRect(&current_rect, draw_rect, &clear_rect[i]);
790
791             TRACE("clear_rect[%u] %s, current_rect %s.\n", i,
792                     wine_dbgstr_rect(&clear_rect[i]),
793                     wine_dbgstr_rect(&current_rect));
794
795             /* Tests show that rectangles where x1 > x2 or y1 > y2 are ignored silently.
796              * The rectangle is not cleared, no error is returned, but further rectangles are
797              * still cleared if they are valid. */
798             if (current_rect.left > current_rect.right || current_rect.top > current_rect.bottom)
799             {
800                 TRACE("Rectangle with negative dimensions, ignoring.\n");
801                 continue;
802             }
803
804             if (render_offscreen)
805             {
806                 glScissor(current_rect.left, current_rect.top,
807                         current_rect.right - current_rect.left, current_rect.bottom - current_rect.top);
808             }
809             else
810             {
811                 glScissor(current_rect.left, drawable_height - current_rect.bottom,
812                           current_rect.right - current_rect.left, current_rect.bottom - current_rect.top);
813             }
814             checkGLcall("glScissor");
815
816             glClear(clear_mask);
817             checkGLcall("glClear");
818         }
819     }
820
821     LEAVE_GL();
822
823     if (wined3d_settings.strict_draw_ordering || (flags & WINED3DCLEAR_TARGET
824             && target->container.type == WINED3D_CONTAINER_SWAPCHAIN
825             && target->container.u.swapchain->front_buffer == target))
826         wglFlush(); /* Flush to ensure ordering across contexts. */
827
828     context_release(context);
829 }
830
831 ULONG CDECL wined3d_device_incref(struct wined3d_device *device)
832 {
833     ULONG refcount = InterlockedIncrement(&device->ref);
834
835     TRACE("%p increasing refcount to %u.\n", device, refcount);
836
837     return refcount;
838 }
839
840 ULONG CDECL wined3d_device_decref(struct wined3d_device *device)
841 {
842     ULONG refcount = InterlockedDecrement(&device->ref);
843
844     TRACE("%p decreasing refcount to %u.\n", device, refcount);
845
846     if (!refcount)
847     {
848         struct wined3d_stateblock *stateblock;
849         UINT i;
850
851         if (wined3d_stateblock_decref(device->updateStateBlock)
852                 && device->updateStateBlock != device->stateBlock)
853             FIXME("Something's still holding the update stateblock.\n");
854         device->updateStateBlock = NULL;
855
856         stateblock = device->stateBlock;
857         device->stateBlock = NULL;
858         if (wined3d_stateblock_decref(stateblock))
859             FIXME("Something's still holding the stateblock.\n");
860
861         for (i = 0; i < sizeof(device->multistate_funcs) / sizeof(device->multistate_funcs[0]); ++i)
862         {
863             HeapFree(GetProcessHeap(), 0, device->multistate_funcs[i]);
864             device->multistate_funcs[i] = NULL;
865         }
866
867         if (!list_empty(&device->resources))
868         {
869             struct wined3d_resource *resource;
870
871             FIXME("Device released with resources still bound, acceptable but unexpected.\n");
872
873             LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
874             {
875                 FIXME("Leftover resource %p with type %s (%#x).\n",
876                         resource, debug_d3dresourcetype(resource->type), resource->type);
877             }
878         }
879
880         if (device->contexts)
881             ERR("Context array not freed!\n");
882         if (device->hardwareCursor)
883             DestroyCursor(device->hardwareCursor);
884         device->hardwareCursor = 0;
885
886         wined3d_decref(device->wined3d);
887         device->wined3d = NULL;
888         HeapFree(GetProcessHeap(), 0, device);
889         TRACE("Freed device %p.\n", device);
890     }
891
892     return refcount;
893 }
894
895 UINT CDECL wined3d_device_get_swapchain_count(const struct wined3d_device *device)
896 {
897     TRACE("device %p.\n", device);
898
899     return device->swapchain_count;
900 }
901
902 HRESULT CDECL wined3d_device_get_swapchain(const struct wined3d_device *device,
903         UINT swapchain_idx, struct wined3d_swapchain **swapchain)
904 {
905     TRACE("device %p, swapchain_idx %u, swapchain %p.\n",
906             device, swapchain_idx, swapchain);
907
908     if (swapchain_idx >= device->swapchain_count)
909     {
910         WARN("swapchain_idx %u >= swapchain_count %u.\n",
911                 swapchain_idx, device->swapchain_count);
912         *swapchain = NULL;
913
914         return WINED3DERR_INVALIDCALL;
915     }
916
917     *swapchain = device->swapchains[swapchain_idx];
918     wined3d_swapchain_incref(*swapchain);
919     TRACE("Returning %p.\n", *swapchain);
920
921     return WINED3D_OK;
922 }
923
924 static void device_load_logo(struct wined3d_device *device, const char *filename)
925 {
926     struct wined3d_color_key color_key;
927     HBITMAP hbm;
928     BITMAP bm;
929     HRESULT hr;
930     HDC dcb = NULL, dcs = NULL;
931
932     hbm = LoadImageA(NULL, filename, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
933     if(hbm)
934     {
935         GetObjectA(hbm, sizeof(BITMAP), &bm);
936         dcb = CreateCompatibleDC(NULL);
937         if(!dcb) goto out;
938         SelectObject(dcb, hbm);
939     }
940     else
941     {
942         /* Create a 32x32 white surface to indicate that wined3d is used, but the specified image
943          * couldn't be loaded
944          */
945         memset(&bm, 0, sizeof(bm));
946         bm.bmWidth = 32;
947         bm.bmHeight = 32;
948     }
949
950     hr = wined3d_surface_create(device, bm.bmWidth, bm.bmHeight, WINED3DFMT_B5G6R5_UNORM, 0, 0,
951             WINED3D_POOL_DEFAULT, WINED3D_MULTISAMPLE_NONE, 0, WINED3D_SURFACE_TYPE_OPENGL, WINED3D_SURFACE_MAPPABLE,
952             NULL, &wined3d_null_parent_ops, &device->logo_surface);
953     if (FAILED(hr))
954     {
955         ERR("Wine logo requested, but failed to create surface, hr %#x.\n", hr);
956         goto out;
957     }
958
959     if (dcb)
960     {
961         if (FAILED(hr = wined3d_surface_getdc(device->logo_surface, &dcs)))
962             goto out;
963         BitBlt(dcs, 0, 0, bm.bmWidth, bm.bmHeight, dcb, 0, 0, SRCCOPY);
964         wined3d_surface_releasedc(device->logo_surface, dcs);
965
966         color_key.color_space_low_value = 0;
967         color_key.color_space_high_value = 0;
968         wined3d_surface_set_color_key(device->logo_surface, WINEDDCKEY_SRCBLT, &color_key);
969     }
970     else
971     {
972         const struct wined3d_color c = {1.0f, 1.0f, 1.0f, 1.0f};
973         /* Fill the surface with a white color to show that wined3d is there */
974         wined3d_device_color_fill(device, device->logo_surface, NULL, &c);
975     }
976
977 out:
978     if (dcb) DeleteDC(dcb);
979     if (hbm) DeleteObject(hbm);
980 }
981
982 /* Context activation is done by the caller. */
983 static void create_dummy_textures(struct wined3d_device *device, struct wined3d_context *context)
984 {
985     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
986     unsigned int i, j, count;
987     /* Under DirectX you can sample even if no texture is bound, whereas
988      * OpenGL will only allow that when a valid texture is bound.
989      * We emulate this by creating dummy textures and binding them
990      * to each texture stage when the currently set D3D texture is NULL. */
991     ENTER_GL();
992
993     if (gl_info->supported[APPLE_CLIENT_STORAGE])
994     {
995         /* The dummy texture does not have client storage backing */
996         glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
997         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
998     }
999
1000     count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1001     for (i = 0; i < count; ++i)
1002     {
1003         DWORD color = 0x000000ff;
1004
1005         /* Make appropriate texture active */
1006         context_active_texture(context, gl_info, i);
1007
1008         glGenTextures(1, &device->dummy_texture_2d[i]);
1009         checkGLcall("glGenTextures");
1010         TRACE("Dummy 2D texture %u given name %u.\n", i, device->dummy_texture_2d[i]);
1011
1012         glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1013         checkGLcall("glBindTexture");
1014
1015         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1016         checkGLcall("glTexImage2D");
1017
1018         if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1019         {
1020             glGenTextures(1, &device->dummy_texture_rect[i]);
1021             checkGLcall("glGenTextures");
1022             TRACE("Dummy rectangle texture %u given name %u.\n", i, device->dummy_texture_rect[i]);
1023
1024             glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1025             checkGLcall("glBindTexture");
1026
1027             glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1028             checkGLcall("glTexImage2D");
1029         }
1030
1031         if (gl_info->supported[EXT_TEXTURE3D])
1032         {
1033             glGenTextures(1, &device->dummy_texture_3d[i]);
1034             checkGLcall("glGenTextures");
1035             TRACE("Dummy 3D texture %u given name %u.\n", i, device->dummy_texture_3d[i]);
1036
1037             glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1038             checkGLcall("glBindTexture");
1039
1040             GL_EXTCALL(glTexImage3DEXT(GL_TEXTURE_3D, 0, GL_RGBA8, 1, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color));
1041             checkGLcall("glTexImage3D");
1042         }
1043
1044         if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1045         {
1046             glGenTextures(1, &device->dummy_texture_cube[i]);
1047             checkGLcall("glGenTextures");
1048             TRACE("Dummy cube texture %u given name %u.\n", i, device->dummy_texture_cube[i]);
1049
1050             glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1051             checkGLcall("glBindTexture");
1052
1053             for (j = GL_TEXTURE_CUBE_MAP_POSITIVE_X; j <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; ++j)
1054             {
1055                 glTexImage2D(j, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &color);
1056                 checkGLcall("glTexImage2D");
1057             }
1058         }
1059     }
1060
1061     if (gl_info->supported[APPLE_CLIENT_STORAGE])
1062     {
1063         /* Re-enable because if supported it is enabled by default */
1064         glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1065         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1066     }
1067
1068     LEAVE_GL();
1069 }
1070
1071 /* Context activation is done by the caller. */
1072 static void destroy_dummy_textures(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
1073 {
1074     unsigned int count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1075
1076     ENTER_GL();
1077     if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1078     {
1079         glDeleteTextures(count, device->dummy_texture_cube);
1080         checkGLcall("glDeleteTextures(count, device->dummy_texture_cube)");
1081     }
1082
1083     if (gl_info->supported[EXT_TEXTURE3D])
1084     {
1085         glDeleteTextures(count, device->dummy_texture_3d);
1086         checkGLcall("glDeleteTextures(count, device->dummy_texture_3d)");
1087     }
1088
1089     if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1090     {
1091         glDeleteTextures(count, device->dummy_texture_rect);
1092         checkGLcall("glDeleteTextures(count, device->dummy_texture_rect)");
1093     }
1094
1095     glDeleteTextures(count, device->dummy_texture_2d);
1096     checkGLcall("glDeleteTextures(count, device->dummy_texture_2d)");
1097     LEAVE_GL();
1098
1099     memset(device->dummy_texture_cube, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_cube));
1100     memset(device->dummy_texture_3d, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_3d));
1101     memset(device->dummy_texture_rect, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_rect));
1102     memset(device->dummy_texture_2d, 0, gl_info->limits.textures * sizeof(*device->dummy_texture_2d));
1103 }
1104
1105 static LONG fullscreen_style(LONG style)
1106 {
1107     /* Make sure the window is managed, otherwise we won't get keyboard input. */
1108     style |= WS_POPUP | WS_SYSMENU;
1109     style &= ~(WS_CAPTION | WS_THICKFRAME);
1110
1111     return style;
1112 }
1113
1114 static LONG fullscreen_exstyle(LONG exstyle)
1115 {
1116     /* Filter out window decorations. */
1117     exstyle &= ~(WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);
1118
1119     return exstyle;
1120 }
1121
1122 void CDECL wined3d_device_setup_fullscreen_window(struct wined3d_device *device, HWND window, UINT w, UINT h)
1123 {
1124     BOOL filter_messages;
1125     LONG style, exstyle;
1126
1127     TRACE("Setting up window %p for fullscreen mode.\n", window);
1128
1129     if (device->style || device->exStyle)
1130     {
1131         ERR("Changing the window style for window %p, but another style (%08x, %08x) is already stored.\n",
1132                 window, device->style, device->exStyle);
1133     }
1134
1135     device->style = GetWindowLongW(window, GWL_STYLE);
1136     device->exStyle = GetWindowLongW(window, GWL_EXSTYLE);
1137
1138     style = fullscreen_style(device->style);
1139     exstyle = fullscreen_exstyle(device->exStyle);
1140
1141     TRACE("Old style was %08x, %08x, setting to %08x, %08x.\n",
1142             device->style, device->exStyle, style, exstyle);
1143
1144     filter_messages = device->filter_messages;
1145     device->filter_messages = TRUE;
1146
1147     SetWindowLongW(window, GWL_STYLE, style);
1148     SetWindowLongW(window, GWL_EXSTYLE, exstyle);
1149     SetWindowPos(window, HWND_TOP, 0, 0, w, h, SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOACTIVATE);
1150
1151     device->filter_messages = filter_messages;
1152 }
1153
1154 void CDECL wined3d_device_restore_fullscreen_window(struct wined3d_device *device, HWND window)
1155 {
1156     BOOL filter_messages;
1157     LONG style, exstyle;
1158
1159     if (!device->style && !device->exStyle) return;
1160
1161     TRACE("Restoring window style of window %p to %08x, %08x.\n",
1162             window, device->style, device->exStyle);
1163
1164     style = GetWindowLongW(window, GWL_STYLE);
1165     exstyle = GetWindowLongW(window, GWL_EXSTYLE);
1166
1167     filter_messages = device->filter_messages;
1168     device->filter_messages = TRUE;
1169
1170     /* Only restore the style if the application didn't modify it during the
1171      * fullscreen phase. Some applications change it before calling Reset()
1172      * when switching between windowed and fullscreen modes (HL2), some
1173      * depend on the original style (Eve Online). */
1174     if (style == fullscreen_style(device->style) && exstyle == fullscreen_exstyle(device->exStyle))
1175     {
1176         SetWindowLongW(window, GWL_STYLE, device->style);
1177         SetWindowLongW(window, GWL_EXSTYLE, device->exStyle);
1178     }
1179     SetWindowPos(window, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
1180
1181     device->filter_messages = filter_messages;
1182
1183     /* Delete the old values. */
1184     device->style = 0;
1185     device->exStyle = 0;
1186 }
1187
1188 HRESULT CDECL wined3d_device_acquire_focus_window(struct wined3d_device *device, HWND window)
1189 {
1190     TRACE("device %p, window %p.\n", device, window);
1191
1192     if (!wined3d_register_window(window, device))
1193     {
1194         ERR("Failed to register window %p.\n", window);
1195         return E_FAIL;
1196     }
1197
1198     InterlockedExchangePointer((void **)&device->focus_window, window);
1199     SetWindowPos(window, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
1200
1201     return WINED3D_OK;
1202 }
1203
1204 void CDECL wined3d_device_release_focus_window(struct wined3d_device *device)
1205 {
1206     TRACE("device %p.\n", device);
1207
1208     if (device->focus_window) wined3d_unregister_window(device->focus_window);
1209     InterlockedExchangePointer((void **)&device->focus_window, NULL);
1210 }
1211
1212 HRESULT CDECL wined3d_device_init_3d(struct wined3d_device *device,
1213         struct wined3d_swapchain_desc *swapchain_desc)
1214 {
1215     static const struct wined3d_color black = {0.0f, 0.0f, 0.0f, 0.0f};
1216     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1217     struct wined3d_swapchain *swapchain = NULL;
1218     struct wined3d_context *context;
1219     HRESULT hr;
1220     DWORD state;
1221     unsigned int i;
1222
1223     TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
1224
1225     if (device->d3d_initialized)
1226         return WINED3DERR_INVALIDCALL;
1227     if (!device->adapter->opengl)
1228         return WINED3DERR_INVALIDCALL;
1229
1230     device->valid_rt_mask = 0;
1231     for (i = 0; i < gl_info->limits.buffers; ++i)
1232         device->valid_rt_mask |= (1 << i);
1233     device->fb.render_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1234             sizeof(*device->fb.render_targets) * gl_info->limits.buffers);
1235
1236     /* Initialize the texture unit mapping to a 1:1 mapping */
1237     for (state = 0; state < MAX_COMBINED_SAMPLERS; ++state)
1238     {
1239         if (state < gl_info->limits.fragment_samplers)
1240         {
1241             device->texUnitMap[state] = state;
1242             device->rev_tex_unit_map[state] = state;
1243         }
1244         else
1245         {
1246             device->texUnitMap[state] = WINED3D_UNMAPPED_STAGE;
1247             device->rev_tex_unit_map[state] = WINED3D_UNMAPPED_STAGE;
1248         }
1249     }
1250
1251     /* Setup the implicit swapchain. This also initializes a context. */
1252     TRACE("Creating implicit swapchain\n");
1253     hr = device->device_parent->ops->create_swapchain(device->device_parent,
1254             swapchain_desc, &swapchain);
1255     if (FAILED(hr))
1256     {
1257         WARN("Failed to create implicit swapchain\n");
1258         goto err_out;
1259     }
1260
1261     device->swapchain_count = 1;
1262     device->swapchains = HeapAlloc(GetProcessHeap(), 0, device->swapchain_count * sizeof(*device->swapchains));
1263     if (!device->swapchains)
1264     {
1265         ERR("Out of memory!\n");
1266         goto err_out;
1267     }
1268     device->swapchains[0] = swapchain;
1269
1270     if (swapchain->back_buffers && swapchain->back_buffers[0])
1271     {
1272         TRACE("Setting rendertarget to %p.\n", swapchain->back_buffers);
1273         device->fb.render_targets[0] = swapchain->back_buffers[0];
1274     }
1275     else
1276     {
1277         TRACE("Setting rendertarget to %p.\n", swapchain->front_buffer);
1278         device->fb.render_targets[0] = swapchain->front_buffer;
1279     }
1280     wined3d_surface_incref(device->fb.render_targets[0]);
1281
1282     /* Depth Stencil support */
1283     device->fb.depth_stencil = device->auto_depth_stencil;
1284     if (device->fb.depth_stencil)
1285         wined3d_surface_incref(device->fb.depth_stencil);
1286
1287     hr = device->shader_backend->shader_alloc_private(device);
1288     if (FAILED(hr))
1289     {
1290         TRACE("Shader private data couldn't be allocated\n");
1291         goto err_out;
1292     }
1293     hr = device->frag_pipe->alloc_private(device);
1294     if (FAILED(hr))
1295     {
1296         TRACE("Fragment pipeline private data couldn't be allocated\n");
1297         goto err_out;
1298     }
1299     hr = device->blitter->alloc_private(device);
1300     if (FAILED(hr))
1301     {
1302         TRACE("Blitter private data couldn't be allocated\n");
1303         goto err_out;
1304     }
1305
1306     /* Set up some starting GL setup */
1307
1308     /* Setup all the devices defaults */
1309     stateblock_init_default_state(device->stateBlock);
1310
1311     context = context_acquire(device, swapchain->front_buffer);
1312
1313     create_dummy_textures(device, context);
1314
1315     ENTER_GL();
1316
1317     /* Initialize the current view state */
1318     device->view_ident = 1;
1319     device->contexts[0]->last_was_rhw = 0;
1320
1321     switch (wined3d_settings.offscreen_rendering_mode)
1322     {
1323         case ORM_FBO:
1324             device->offscreenBuffer = GL_COLOR_ATTACHMENT0;
1325             break;
1326
1327         case ORM_BACKBUFFER:
1328         {
1329             if (context_get_current()->aux_buffers > 0)
1330             {
1331                 TRACE("Using auxiliary buffer for offscreen rendering\n");
1332                 device->offscreenBuffer = GL_AUX0;
1333             }
1334             else
1335             {
1336                 TRACE("Using back buffer for offscreen rendering\n");
1337                 device->offscreenBuffer = GL_BACK;
1338             }
1339         }
1340     }
1341
1342     TRACE("All defaults now set up, leaving 3D init.\n");
1343     LEAVE_GL();
1344
1345     context_release(context);
1346
1347     /* Clear the screen */
1348     wined3d_device_clear(device, 0, NULL, WINED3DCLEAR_TARGET
1349             | (swapchain_desc->enable_auto_depth_stencil ? WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL : 0),
1350             &black, 1.0f, 0);
1351
1352     device->d3d_initialized = TRUE;
1353
1354     if (wined3d_settings.logo)
1355         device_load_logo(device, wined3d_settings.logo);
1356     return WINED3D_OK;
1357
1358 err_out:
1359     HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1360     HeapFree(GetProcessHeap(), 0, device->swapchains);
1361     device->swapchain_count = 0;
1362     if (swapchain)
1363         wined3d_swapchain_decref(swapchain);
1364     if (device->blit_priv)
1365         device->blitter->free_private(device);
1366     if (device->fragment_priv)
1367         device->frag_pipe->free_private(device);
1368     if (device->shader_priv)
1369         device->shader_backend->shader_free_private(device);
1370
1371     return hr;
1372 }
1373
1374 HRESULT CDECL wined3d_device_init_gdi(struct wined3d_device *device,
1375         struct wined3d_swapchain_desc *swapchain_desc)
1376 {
1377     struct wined3d_swapchain *swapchain = NULL;
1378     HRESULT hr;
1379
1380     TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
1381
1382     /* Setup the implicit swapchain */
1383     TRACE("Creating implicit swapchain\n");
1384     hr = device->device_parent->ops->create_swapchain(device->device_parent,
1385             swapchain_desc, &swapchain);
1386     if (FAILED(hr))
1387     {
1388         WARN("Failed to create implicit swapchain\n");
1389         goto err_out;
1390     }
1391
1392     device->swapchain_count = 1;
1393     device->swapchains = HeapAlloc(GetProcessHeap(), 0, device->swapchain_count * sizeof(*device->swapchains));
1394     if (!device->swapchains)
1395     {
1396         ERR("Out of memory!\n");
1397         goto err_out;
1398     }
1399     device->swapchains[0] = swapchain;
1400     return WINED3D_OK;
1401
1402 err_out:
1403     wined3d_swapchain_decref(swapchain);
1404     return hr;
1405 }
1406
1407 HRESULT CDECL wined3d_device_uninit_3d(struct wined3d_device *device)
1408 {
1409     struct wined3d_resource *resource, *cursor;
1410     const struct wined3d_gl_info *gl_info;
1411     struct wined3d_context *context;
1412     struct wined3d_surface *surface;
1413     UINT i;
1414
1415     TRACE("device %p.\n", device);
1416
1417     if (!device->d3d_initialized)
1418         return WINED3DERR_INVALIDCALL;
1419
1420     /* Force making the context current again, to verify it is still valid
1421      * (workaround for broken drivers) */
1422     context_set_current(NULL);
1423     /* I don't think that the interface guarantees that the device is destroyed from the same thread
1424      * it was created. Thus make sure a context is active for the glDelete* calls
1425      */
1426     context = context_acquire(device, NULL);
1427     gl_info = context->gl_info;
1428
1429     if (device->logo_surface)
1430         wined3d_surface_decref(device->logo_surface);
1431
1432     stateblock_unbind_resources(device->stateBlock);
1433
1434     /* Unload resources */
1435     LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
1436     {
1437         TRACE("Unloading resource %p.\n", resource);
1438
1439         resource->resource_ops->resource_unload(resource);
1440     }
1441
1442     TRACE("Deleting high order patches\n");
1443     for (i = 0; i < PATCHMAP_SIZE; ++i)
1444     {
1445         struct wined3d_rect_patch *patch;
1446         struct list *e1, *e2;
1447
1448         LIST_FOR_EACH_SAFE(e1, e2, &device->patches[i])
1449         {
1450             patch = LIST_ENTRY(e1, struct wined3d_rect_patch, entry);
1451             wined3d_device_delete_patch(device, patch->Handle);
1452         }
1453     }
1454
1455     /* Delete the mouse cursor texture */
1456     if (device->cursorTexture)
1457     {
1458         ENTER_GL();
1459         glDeleteTextures(1, &device->cursorTexture);
1460         LEAVE_GL();
1461         device->cursorTexture = 0;
1462     }
1463
1464     /* Destroy the depth blt resources, they will be invalid after the reset. Also free shader
1465      * private data, it might contain opengl pointers
1466      */
1467     if (device->depth_blt_texture)
1468     {
1469         ENTER_GL();
1470         glDeleteTextures(1, &device->depth_blt_texture);
1471         LEAVE_GL();
1472         device->depth_blt_texture = 0;
1473     }
1474
1475     /* Destroy the shader backend. Note that this has to happen after all shaders are destroyed. */
1476     device->blitter->free_private(device);
1477     device->frag_pipe->free_private(device);
1478     device->shader_backend->shader_free_private(device);
1479
1480     /* Release the buffers (with sanity checks)*/
1481     if (device->onscreen_depth_stencil)
1482     {
1483         surface = device->onscreen_depth_stencil;
1484         device->onscreen_depth_stencil = NULL;
1485         wined3d_surface_decref(surface);
1486     }
1487
1488     if (device->fb.depth_stencil)
1489     {
1490         surface = device->fb.depth_stencil;
1491
1492         TRACE("Releasing depth/stencil buffer %p.\n", surface);
1493
1494         device->fb.depth_stencil = NULL;
1495         wined3d_surface_decref(surface);
1496     }
1497
1498     if (device->auto_depth_stencil)
1499     {
1500         surface = device->auto_depth_stencil;
1501         device->auto_depth_stencil = NULL;
1502         if (wined3d_surface_decref(surface))
1503             FIXME("Something's still holding the auto depth stencil buffer (%p).\n", surface);
1504     }
1505
1506     for (i = 1; i < gl_info->limits.buffers; ++i)
1507     {
1508         wined3d_device_set_render_target(device, i, NULL, FALSE);
1509     }
1510
1511     surface = device->fb.render_targets[0];
1512     TRACE("Setting rendertarget 0 to NULL\n");
1513     device->fb.render_targets[0] = NULL;
1514     TRACE("Releasing the render target at %p\n", surface);
1515     wined3d_surface_decref(surface);
1516
1517     context_release(context);
1518
1519     for (i = 0; i < device->swapchain_count; ++i)
1520     {
1521         TRACE("Releasing the implicit swapchain %u.\n", i);
1522         if (wined3d_swapchain_decref(device->swapchains[i]))
1523             FIXME("Something's still holding the implicit swapchain.\n");
1524     }
1525
1526     HeapFree(GetProcessHeap(), 0, device->swapchains);
1527     device->swapchains = NULL;
1528     device->swapchain_count = 0;
1529
1530     HeapFree(GetProcessHeap(), 0, device->fb.render_targets);
1531     device->fb.render_targets = NULL;
1532
1533     device->d3d_initialized = FALSE;
1534
1535     return WINED3D_OK;
1536 }
1537
1538 HRESULT CDECL wined3d_device_uninit_gdi(struct wined3d_device *device)
1539 {
1540     unsigned int i;
1541
1542     for (i = 0; i < device->swapchain_count; ++i)
1543     {
1544         TRACE("Releasing the implicit swapchain %u.\n", i);
1545         if (wined3d_swapchain_decref(device->swapchains[i]))
1546             FIXME("Something's still holding the implicit swapchain.\n");
1547     }
1548
1549     HeapFree(GetProcessHeap(), 0, device->swapchains);
1550     device->swapchains = NULL;
1551     device->swapchain_count = 0;
1552     return WINED3D_OK;
1553 }
1554
1555 /* Enables thread safety in the wined3d device and its resources. Called by DirectDraw
1556  * from SetCooperativeLevel if DDSCL_MULTITHREADED is specified, and by d3d8/9 from
1557  * CreateDevice if D3DCREATE_MULTITHREADED is passed.
1558  *
1559  * There is no way to deactivate thread safety once it is enabled.
1560  */
1561 void CDECL wined3d_device_set_multithreaded(struct wined3d_device *device)
1562 {
1563     TRACE("device %p.\n", device);
1564
1565     /* For now just store the flag (needed in case of ddraw). */
1566     device->create_parms.flags |= WINED3DCREATE_MULTITHREADED;
1567 }
1568
1569 HRESULT CDECL wined3d_device_set_display_mode(struct wined3d_device *device,
1570         UINT swapchain_idx, const struct wined3d_display_mode *mode)
1571 {
1572     struct wined3d_adapter *adapter = device->adapter;
1573     const struct wined3d_format *format = wined3d_get_format(&adapter->gl_info, mode->format_id);
1574     DEVMODEW devmode;
1575     LONG ret;
1576     RECT clip_rc;
1577
1578     TRACE("device %p, swapchain_idx %u, mode %p (%ux%u@%u %s).\n", device, swapchain_idx, mode,
1579             mode->width, mode->height, mode->refresh_rate, debug_d3dformat(mode->format_id));
1580
1581     /* Resize the screen even without a window:
1582      * The app could have unset it with SetCooperativeLevel, but not called
1583      * RestoreDisplayMode first. Then the release will call RestoreDisplayMode,
1584      * but we don't have any hwnd
1585      */
1586
1587     memset(&devmode, 0, sizeof(devmode));
1588     devmode.dmSize = sizeof(devmode);
1589     devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1590     devmode.dmBitsPerPel = format->byte_count * CHAR_BIT;
1591     devmode.dmPelsWidth = mode->width;
1592     devmode.dmPelsHeight = mode->height;
1593
1594     devmode.dmDisplayFrequency = mode->refresh_rate;
1595     if (mode->refresh_rate)
1596         devmode.dmFields |= DM_DISPLAYFREQUENCY;
1597
1598     /* Only change the mode if necessary */
1599     if (adapter->screen_size.cx == mode->width && adapter->screen_size.cy == mode->height
1600             && adapter->screen_format == mode->format_id && !mode->refresh_rate)
1601         return WINED3D_OK;
1602
1603     ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL);
1604     if (ret != DISP_CHANGE_SUCCESSFUL)
1605     {
1606         if (devmode.dmDisplayFrequency)
1607         {
1608             WARN("ChangeDisplaySettingsExW failed, trying without the refresh rate\n");
1609             devmode.dmFields &= ~DM_DISPLAYFREQUENCY;
1610             devmode.dmDisplayFrequency = 0;
1611             ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL) != DISP_CHANGE_SUCCESSFUL;
1612         }
1613         if(ret != DISP_CHANGE_SUCCESSFUL) {
1614             return WINED3DERR_NOTAVAILABLE;
1615         }
1616     }
1617
1618     /* Store the new values */
1619     adapter->screen_size.cx = mode->width;
1620     adapter->screen_size.cy = mode->height;
1621     adapter->screen_format = mode->format_id;
1622
1623     /* And finally clip mouse to our screen */
1624     SetRect(&clip_rc, 0, 0, mode->width, mode->height);
1625     ClipCursor(&clip_rc);
1626
1627     return WINED3D_OK;
1628 }
1629
1630 HRESULT CDECL wined3d_device_get_wined3d(const struct wined3d_device *device, struct wined3d **wined3d)
1631 {
1632     TRACE("device %p, wined3d %p.\n", device, wined3d);
1633
1634     *wined3d = device->wined3d;
1635     wined3d_incref(*wined3d);
1636
1637     TRACE("Returning %p.\n", *wined3d);
1638
1639     return WINED3D_OK;
1640 }
1641
1642 UINT CDECL wined3d_device_get_available_texture_mem(const struct wined3d_device *device)
1643 {
1644     TRACE("device %p.\n", device);
1645
1646     TRACE("Emulating %d MB, returning %d MB left.\n",
1647             device->adapter->TextureRam / (1024 * 1024),
1648             (device->adapter->TextureRam - device->adapter->UsedTextureRam) / (1024 * 1024));
1649
1650     return device->adapter->TextureRam - device->adapter->UsedTextureRam;
1651 }
1652
1653 HRESULT CDECL wined3d_device_set_stream_source(struct wined3d_device *device, UINT stream_idx,
1654         struct wined3d_buffer *buffer, UINT offset, UINT stride)
1655 {
1656     struct wined3d_stream_state *stream;
1657     struct wined3d_buffer *prev_buffer;
1658
1659     TRACE("device %p, stream_idx %u, buffer %p, offset %u, stride %u.\n",
1660             device, stream_idx, buffer, offset, stride);
1661
1662     if (stream_idx >= MAX_STREAMS)
1663     {
1664         WARN("Stream index %u out of range.\n", stream_idx);
1665         return WINED3DERR_INVALIDCALL;
1666     }
1667     else if (offset & 0x3)
1668     {
1669         WARN("Offset %u is not 4 byte aligned.\n", offset);
1670         return WINED3DERR_INVALIDCALL;
1671     }
1672
1673     stream = &device->updateStateBlock->state.streams[stream_idx];
1674     prev_buffer = stream->buffer;
1675
1676     device->updateStateBlock->changed.streamSource |= 1 << stream_idx;
1677
1678     if (prev_buffer == buffer
1679             && stream->stride == stride
1680             && stream->offset == offset)
1681     {
1682        TRACE("Application is setting the old values over, nothing to do.\n");
1683        return WINED3D_OK;
1684     }
1685
1686     stream->buffer = buffer;
1687     if (buffer)
1688     {
1689         stream->stride = stride;
1690         stream->offset = offset;
1691     }
1692
1693     /* Handle recording of state blocks. */
1694     if (device->isRecordingState)
1695     {
1696         TRACE("Recording... not performing anything.\n");
1697         if (buffer)
1698             wined3d_buffer_incref(buffer);
1699         if (prev_buffer)
1700             wined3d_buffer_decref(prev_buffer);
1701         return WINED3D_OK;
1702     }
1703
1704     if (buffer)
1705     {
1706         InterlockedIncrement(&buffer->resource.bind_count);
1707         wined3d_buffer_incref(buffer);
1708     }
1709     if (prev_buffer)
1710     {
1711         InterlockedDecrement(&prev_buffer->resource.bind_count);
1712         wined3d_buffer_decref(prev_buffer);
1713     }
1714
1715     device_invalidate_state(device, STATE_STREAMSRC);
1716
1717     return WINED3D_OK;
1718 }
1719
1720 HRESULT CDECL wined3d_device_get_stream_source(const struct wined3d_device *device,
1721         UINT stream_idx, struct wined3d_buffer **buffer, UINT *offset, UINT *stride)
1722 {
1723     struct wined3d_stream_state *stream;
1724
1725     TRACE("device %p, stream_idx %u, buffer %p, offset %p, stride %p.\n",
1726             device, stream_idx, buffer, offset, stride);
1727
1728     if (stream_idx >= MAX_STREAMS)
1729     {
1730         WARN("Stream index %u out of range.\n", stream_idx);
1731         return WINED3DERR_INVALIDCALL;
1732     }
1733
1734     stream = &device->stateBlock->state.streams[stream_idx];
1735     *buffer = stream->buffer;
1736     if (*buffer)
1737         wined3d_buffer_incref(*buffer);
1738     if (offset)
1739         *offset = stream->offset;
1740     *stride = stream->stride;
1741
1742     return WINED3D_OK;
1743 }
1744
1745 HRESULT CDECL wined3d_device_set_stream_source_freq(struct wined3d_device *device, UINT stream_idx, UINT divider)
1746 {
1747     struct wined3d_stream_state *stream;
1748     UINT old_flags, old_freq;
1749
1750     TRACE("device %p, stream_idx %u, divider %#x.\n", device, stream_idx, divider);
1751
1752     /* Verify input. At least in d3d9 this is invalid. */
1753     if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && (divider & WINED3DSTREAMSOURCE_INDEXEDDATA))
1754     {
1755         WARN("INSTANCEDATA and INDEXEDDATA were set, returning D3DERR_INVALIDCALL.\n");
1756         return WINED3DERR_INVALIDCALL;
1757     }
1758     if ((divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && !stream_idx)
1759     {
1760         WARN("INSTANCEDATA used on stream 0, returning D3DERR_INVALIDCALL.\n");
1761         return WINED3DERR_INVALIDCALL;
1762     }
1763     if (!divider)
1764     {
1765         WARN("Divider is 0, returning D3DERR_INVALIDCALL.\n");
1766         return WINED3DERR_INVALIDCALL;
1767     }
1768
1769     stream = &device->updateStateBlock->state.streams[stream_idx];
1770     old_flags = stream->flags;
1771     old_freq = stream->frequency;
1772
1773     stream->flags = divider & (WINED3DSTREAMSOURCE_INSTANCEDATA | WINED3DSTREAMSOURCE_INDEXEDDATA);
1774     stream->frequency = divider & 0x7fffff;
1775
1776     device->updateStateBlock->changed.streamFreq |= 1 << stream_idx;
1777
1778     if (stream->frequency != old_freq || stream->flags != old_flags)
1779         device_invalidate_state(device, STATE_STREAMSRC);
1780
1781     return WINED3D_OK;
1782 }
1783
1784 HRESULT CDECL wined3d_device_get_stream_source_freq(const struct wined3d_device *device,
1785         UINT stream_idx, UINT *divider)
1786 {
1787     struct wined3d_stream_state *stream;
1788
1789     TRACE("device %p, stream_idx %u, divider %p.\n", device, stream_idx, divider);
1790
1791     stream = &device->updateStateBlock->state.streams[stream_idx];
1792     *divider = stream->flags | stream->frequency;
1793
1794     TRACE("Returning %#x.\n", *divider);
1795
1796     return WINED3D_OK;
1797 }
1798
1799 HRESULT CDECL wined3d_device_set_transform(struct wined3d_device *device,
1800         enum wined3d_transform_state d3dts, const struct wined3d_matrix *matrix)
1801 {
1802     TRACE("device %p, state %s, matrix %p.\n",
1803             device, debug_d3dtstype(d3dts), matrix);
1804
1805     /* Handle recording of state blocks. */
1806     if (device->isRecordingState)
1807     {
1808         TRACE("Recording... not performing anything.\n");
1809         device->updateStateBlock->changed.transform[d3dts >> 5] |= 1 << (d3dts & 0x1f);
1810         device->updateStateBlock->state.transforms[d3dts] = *matrix;
1811         return WINED3D_OK;
1812     }
1813
1814     /* If the new matrix is the same as the current one,
1815      * we cut off any further processing. this seems to be a reasonable
1816      * optimization because as was noticed, some apps (warcraft3 for example)
1817      * tend towards setting the same matrix repeatedly for some reason.
1818      *
1819      * From here on we assume that the new matrix is different, wherever it matters. */
1820     if (!memcmp(&device->stateBlock->state.transforms[d3dts].u.m[0][0], matrix, sizeof(*matrix)))
1821     {
1822         TRACE("The application is setting the same matrix over again.\n");
1823         return WINED3D_OK;
1824     }
1825
1826     conv_mat(matrix, &device->stateBlock->state.transforms[d3dts].u.m[0][0]);
1827
1828     /* ScreenCoord = ProjectionMat * ViewMat * WorldMat * ObjectCoord
1829      * where ViewMat = Camera space, WorldMat = world space.
1830      *
1831      * In OpenGL, camera and world space is combined into GL_MODELVIEW
1832      * matrix.  The Projection matrix stay projection matrix. */
1833
1834     if (d3dts == WINED3D_TS_VIEW)
1835         device->view_ident = !memcmp(matrix, &identity, sizeof(identity));
1836
1837     if (d3dts < WINED3D_TS_WORLD_MATRIX(device->adapter->gl_info.limits.blends))
1838         device_invalidate_state(device, STATE_TRANSFORM(d3dts));
1839
1840     return WINED3D_OK;
1841
1842 }
1843
1844 HRESULT CDECL wined3d_device_get_transform(const struct wined3d_device *device,
1845         enum wined3d_transform_state state, struct wined3d_matrix *matrix)
1846 {
1847     TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1848
1849     *matrix = device->stateBlock->state.transforms[state];
1850
1851     return WINED3D_OK;
1852 }
1853
1854 HRESULT CDECL wined3d_device_multiply_transform(struct wined3d_device *device,
1855         enum wined3d_transform_state state, const struct wined3d_matrix *matrix)
1856 {
1857     const struct wined3d_matrix *mat = NULL;
1858     struct wined3d_matrix temp;
1859
1860     TRACE("device %p, state %s, matrix %p.\n", device, debug_d3dtstype(state), matrix);
1861
1862     /* Note: Using 'updateStateBlock' rather than 'stateblock' in the code
1863      * below means it will be recorded in a state block change, but it
1864      * works regardless where it is recorded.
1865      * If this is found to be wrong, change to StateBlock. */
1866     if (state > HIGHEST_TRANSFORMSTATE)
1867     {
1868         WARN("Unhandled transform state %#x.\n", state);
1869         return WINED3D_OK;
1870     }
1871
1872     mat = &device->updateStateBlock->state.transforms[state];
1873     multiply_matrix(&temp, mat, matrix);
1874
1875     /* Apply change via set transform - will reapply to eg. lights this way. */
1876     return wined3d_device_set_transform(device, state, &temp);
1877 }
1878
1879 /* Note lights are real special cases. Although the device caps state only
1880  * e.g. 8 are supported, you can reference any indexes you want as long as
1881  * that number max are enabled at any one point in time. Therefore since the
1882  * indices can be anything, we need a hashmap of them. However, this causes
1883  * stateblock problems. When capturing the state block, I duplicate the
1884  * hashmap, but when recording, just build a chain pretty much of commands to
1885  * be replayed. */
1886 HRESULT CDECL wined3d_device_set_light(struct wined3d_device *device,
1887         UINT light_idx, const struct wined3d_light *light)
1888 {
1889     UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
1890     struct wined3d_light_info *object = NULL;
1891     struct list *e;
1892     float rho;
1893
1894     TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
1895
1896     /* Check the parameter range. Need for speed most wanted sets junk lights
1897      * which confuse the GL driver. */
1898     if (!light)
1899         return WINED3DERR_INVALIDCALL;
1900
1901     switch (light->type)
1902     {
1903         case WINED3D_LIGHT_POINT:
1904         case WINED3D_LIGHT_SPOT:
1905         case WINED3D_LIGHT_PARALLELPOINT:
1906         case WINED3D_LIGHT_GLSPOT:
1907             /* Incorrect attenuation values can cause the gl driver to crash.
1908              * Happens with Need for speed most wanted. */
1909             if (light->attenuation0 < 0.0f || light->attenuation1 < 0.0f || light->attenuation2 < 0.0f)
1910             {
1911                 WARN("Attenuation is negative, returning WINED3DERR_INVALIDCALL.\n");
1912                 return WINED3DERR_INVALIDCALL;
1913             }
1914             break;
1915
1916         case WINED3D_LIGHT_DIRECTIONAL:
1917             /* Ignores attenuation */
1918             break;
1919
1920         default:
1921         WARN("Light type out of range, returning WINED3DERR_INVALIDCALL\n");
1922         return WINED3DERR_INVALIDCALL;
1923     }
1924
1925     LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
1926     {
1927         object = LIST_ENTRY(e, struct wined3d_light_info, entry);
1928         if (object->OriginalIndex == light_idx)
1929             break;
1930         object = NULL;
1931     }
1932
1933     if (!object)
1934     {
1935         TRACE("Adding new light\n");
1936         object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1937         if (!object)
1938         {
1939             ERR("Out of memory error when allocating a light\n");
1940             return E_OUTOFMEMORY;
1941         }
1942         list_add_head(&device->updateStateBlock->state.light_map[hash_idx], &object->entry);
1943         object->glIndex = -1;
1944         object->OriginalIndex = light_idx;
1945     }
1946
1947     /* Initialize the object. */
1948     TRACE("Light %d setting to type %d, Diffuse(%f,%f,%f,%f), Specular(%f,%f,%f,%f), Ambient(%f,%f,%f,%f)\n",
1949             light_idx, light->type,
1950             light->diffuse.r, light->diffuse.g, light->diffuse.b, light->diffuse.a,
1951             light->specular.r, light->specular.g, light->specular.b, light->specular.a,
1952             light->ambient.r, light->ambient.g, light->ambient.b, light->ambient.a);
1953     TRACE("... Pos(%f,%f,%f), Dir(%f,%f,%f)\n", light->position.x, light->position.y, light->position.z,
1954             light->direction.x, light->direction.y, light->direction.z);
1955     TRACE("... Range(%f), Falloff(%f), Theta(%f), Phi(%f)\n",
1956             light->range, light->falloff, light->theta, light->phi);
1957
1958     /* Save away the information. */
1959     object->OriginalParms = *light;
1960
1961     switch (light->type)
1962     {
1963         case WINED3D_LIGHT_POINT:
1964             /* Position */
1965             object->lightPosn[0] = light->position.x;
1966             object->lightPosn[1] = light->position.y;
1967             object->lightPosn[2] = light->position.z;
1968             object->lightPosn[3] = 1.0f;
1969             object->cutoff = 180.0f;
1970             /* FIXME: Range */
1971             break;
1972
1973         case WINED3D_LIGHT_DIRECTIONAL:
1974             /* Direction */
1975             object->lightPosn[0] = -light->direction.x;
1976             object->lightPosn[1] = -light->direction.y;
1977             object->lightPosn[2] = -light->direction.z;
1978             object->lightPosn[3] = 0.0f;
1979             object->exponent = 0.0f;
1980             object->cutoff = 180.0f;
1981             break;
1982
1983         case WINED3D_LIGHT_SPOT:
1984             /* Position */
1985             object->lightPosn[0] = light->position.x;
1986             object->lightPosn[1] = light->position.y;
1987             object->lightPosn[2] = light->position.z;
1988             object->lightPosn[3] = 1.0f;
1989
1990             /* Direction */
1991             object->lightDirn[0] = light->direction.x;
1992             object->lightDirn[1] = light->direction.y;
1993             object->lightDirn[2] = light->direction.z;
1994             object->lightDirn[3] = 1.0f;
1995
1996             /* opengl-ish and d3d-ish spot lights use too different models
1997              * for the light "intensity" as a function of the angle towards
1998              * the main light direction, so we only can approximate very
1999              * roughly. However, spot lights are rather rarely used in games
2000              * (if ever used at all). Furthermore if still used, probably
2001              * nobody pays attention to such details. */
2002             if (!light->falloff)
2003             {
2004                 /* Falloff = 0 is easy, because d3d's and opengl's spot light
2005                  * equations have the falloff resp. exponent parameter as an
2006                  * exponent, so the spot light lighting will always be 1.0 for
2007                  * both of them, and we don't have to care for the rest of the
2008                  * rather complex calculation. */
2009                 object->exponent = 0.0f;
2010             }
2011             else
2012             {
2013                 rho = light->theta + (light->phi - light->theta) / (2 * light->falloff);
2014                 if (rho < 0.0001f)
2015                     rho = 0.0001f;
2016                 object->exponent = -0.3f / logf(cosf(rho / 2));
2017             }
2018
2019             if (object->exponent > 128.0f)
2020                 object->exponent = 128.0f;
2021
2022             object->cutoff = (float)(light->phi * 90 / M_PI);
2023             /* FIXME: Range */
2024             break;
2025
2026         default:
2027             FIXME("Unrecognized light type %#x.\n", light->type);
2028     }
2029
2030     /* Update the live definitions if the light is currently assigned a glIndex. */
2031     if (object->glIndex != -1 && !device->isRecordingState)
2032         device_invalidate_state(device, STATE_ACTIVELIGHT(object->glIndex));
2033
2034     return WINED3D_OK;
2035 }
2036
2037 HRESULT CDECL wined3d_device_get_light(const struct wined3d_device *device,
2038         UINT light_idx, struct wined3d_light *light)
2039 {
2040     UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2041     struct wined3d_light_info *light_info = NULL;
2042     struct list *e;
2043
2044     TRACE("device %p, light_idx %u, light %p.\n", device, light_idx, light);
2045
2046     LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
2047     {
2048         light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2049         if (light_info->OriginalIndex == light_idx)
2050             break;
2051         light_info = NULL;
2052     }
2053
2054     if (!light_info)
2055     {
2056         TRACE("Light information requested but light not defined\n");
2057         return WINED3DERR_INVALIDCALL;
2058     }
2059
2060     *light = light_info->OriginalParms;
2061     return WINED3D_OK;
2062 }
2063
2064 HRESULT CDECL wined3d_device_set_light_enable(struct wined3d_device *device, UINT light_idx, BOOL enable)
2065 {
2066     UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2067     struct wined3d_light_info *light_info = NULL;
2068     struct list *e;
2069
2070     TRACE("device %p, light_idx %u, enable %#x.\n", device, light_idx, enable);
2071
2072     LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2073     {
2074         light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2075         if (light_info->OriginalIndex == light_idx)
2076             break;
2077         light_info = NULL;
2078     }
2079     TRACE("Found light %p.\n", light_info);
2080
2081     /* Special case - enabling an undefined light creates one with a strict set of parameters. */
2082     if (!light_info)
2083     {
2084         TRACE("Light enabled requested but light not defined, so defining one!\n");
2085         wined3d_device_set_light(device, light_idx, &WINED3D_default_light);
2086
2087         /* Search for it again! Should be fairly quick as near head of list. */
2088         LIST_FOR_EACH(e, &device->updateStateBlock->state.light_map[hash_idx])
2089         {
2090             light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2091             if (light_info->OriginalIndex == light_idx)
2092                 break;
2093             light_info = NULL;
2094         }
2095         if (!light_info)
2096         {
2097             FIXME("Adding default lights has failed dismally\n");
2098             return WINED3DERR_INVALIDCALL;
2099         }
2100     }
2101
2102     if (!enable)
2103     {
2104         if (light_info->glIndex != -1)
2105         {
2106             if (!device->isRecordingState)
2107                 device_invalidate_state(device, STATE_ACTIVELIGHT(light_info->glIndex));
2108
2109             device->updateStateBlock->state.lights[light_info->glIndex] = NULL;
2110             light_info->glIndex = -1;
2111         }
2112         else
2113         {
2114             TRACE("Light already disabled, nothing to do\n");
2115         }
2116         light_info->enabled = FALSE;
2117     }
2118     else
2119     {
2120         light_info->enabled = TRUE;
2121         if (light_info->glIndex != -1)
2122         {
2123             TRACE("Nothing to do as light was enabled\n");
2124         }
2125         else
2126         {
2127             unsigned int i;
2128             const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2129             /* Find a free GL light. */
2130             for (i = 0; i < gl_info->limits.lights; ++i)
2131             {
2132                 if (!device->updateStateBlock->state.lights[i])
2133                 {
2134                     device->updateStateBlock->state.lights[i] = light_info;
2135                     light_info->glIndex = i;
2136                     break;
2137                 }
2138             }
2139             if (light_info->glIndex == -1)
2140             {
2141                 /* Our tests show that Windows returns D3D_OK in this situation, even with
2142                  * D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE devices. This
2143                  * is consistent among ddraw, d3d8 and d3d9. GetLightEnable returns TRUE
2144                  * as well for those lights.
2145                  *
2146                  * TODO: Test how this affects rendering. */
2147                 WARN("Too many concurrently active lights\n");
2148                 return WINED3D_OK;
2149             }
2150
2151             /* i == light_info->glIndex */
2152             if (!device->isRecordingState)
2153                 device_invalidate_state(device, STATE_ACTIVELIGHT(i));
2154         }
2155     }
2156
2157     return WINED3D_OK;
2158 }
2159
2160 HRESULT CDECL wined3d_device_get_light_enable(const struct wined3d_device *device, UINT light_idx, BOOL *enable)
2161 {
2162     UINT hash_idx = LIGHTMAP_HASHFUNC(light_idx);
2163     struct wined3d_light_info *light_info = NULL;
2164     struct list *e;
2165
2166     TRACE("device %p, light_idx %u, enable %p.\n", device, light_idx, enable);
2167
2168     LIST_FOR_EACH(e, &device->stateBlock->state.light_map[hash_idx])
2169     {
2170         light_info = LIST_ENTRY(e, struct wined3d_light_info, entry);
2171         if (light_info->OriginalIndex == light_idx)
2172             break;
2173         light_info = NULL;
2174     }
2175
2176     if (!light_info)
2177     {
2178         TRACE("Light enabled state requested but light not defined.\n");
2179         return WINED3DERR_INVALIDCALL;
2180     }
2181     /* true is 128 according to SetLightEnable */
2182     *enable = light_info->enabled ? 128 : 0;
2183     return WINED3D_OK;
2184 }
2185
2186 HRESULT CDECL wined3d_device_set_clip_plane(struct wined3d_device *device, UINT plane_idx, const float *plane)
2187 {
2188     TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2189
2190     /* Validate plane_idx. */
2191     if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2192     {
2193         TRACE("Application has requested clipplane this device doesn't support.\n");
2194         return WINED3DERR_INVALIDCALL;
2195     }
2196
2197     device->updateStateBlock->changed.clipplane |= 1 << plane_idx;
2198
2199     if (device->updateStateBlock->state.clip_planes[plane_idx][0] == plane[0]
2200             && device->updateStateBlock->state.clip_planes[plane_idx][1] == plane[1]
2201             && device->updateStateBlock->state.clip_planes[plane_idx][2] == plane[2]
2202             && device->updateStateBlock->state.clip_planes[plane_idx][3] == plane[3])
2203     {
2204         TRACE("Application is setting old values over, nothing to do.\n");
2205         return WINED3D_OK;
2206     }
2207
2208     device->updateStateBlock->state.clip_planes[plane_idx][0] = plane[0];
2209     device->updateStateBlock->state.clip_planes[plane_idx][1] = plane[1];
2210     device->updateStateBlock->state.clip_planes[plane_idx][2] = plane[2];
2211     device->updateStateBlock->state.clip_planes[plane_idx][3] = plane[3];
2212
2213     /* Handle recording of state blocks. */
2214     if (device->isRecordingState)
2215     {
2216         TRACE("Recording... not performing anything.\n");
2217         return WINED3D_OK;
2218     }
2219
2220     device_invalidate_state(device, STATE_CLIPPLANE(plane_idx));
2221
2222     return WINED3D_OK;
2223 }
2224
2225 HRESULT CDECL wined3d_device_get_clip_plane(const struct wined3d_device *device, UINT plane_idx, float *plane)
2226 {
2227     TRACE("device %p, plane_idx %u, plane %p.\n", device, plane_idx, plane);
2228
2229     /* Validate plane_idx. */
2230     if (plane_idx >= device->adapter->gl_info.limits.clipplanes)
2231     {
2232         TRACE("Application has requested clipplane this device doesn't support.\n");
2233         return WINED3DERR_INVALIDCALL;
2234     }
2235
2236     plane[0] = (float)device->stateBlock->state.clip_planes[plane_idx][0];
2237     plane[1] = (float)device->stateBlock->state.clip_planes[plane_idx][1];
2238     plane[2] = (float)device->stateBlock->state.clip_planes[plane_idx][2];
2239     plane[3] = (float)device->stateBlock->state.clip_planes[plane_idx][3];
2240
2241     return WINED3D_OK;
2242 }
2243
2244 HRESULT CDECL wined3d_device_set_clip_status(struct wined3d_device *device,
2245         const struct wined3d_clip_status *clip_status)
2246 {
2247     FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2248
2249     if (!clip_status)
2250         return WINED3DERR_INVALIDCALL;
2251
2252     return WINED3D_OK;
2253 }
2254
2255 HRESULT CDECL wined3d_device_get_clip_status(const struct wined3d_device *device,
2256         struct wined3d_clip_status *clip_status)
2257 {
2258     FIXME("device %p, clip_status %p stub!\n", device, clip_status);
2259
2260     if (!clip_status)
2261         return WINED3DERR_INVALIDCALL;
2262
2263     return WINED3D_OK;
2264 }
2265
2266 HRESULT CDECL wined3d_device_set_material(struct wined3d_device *device, const struct wined3d_material *material)
2267 {
2268     TRACE("device %p, material %p.\n", device, material);
2269
2270     device->updateStateBlock->changed.material = TRUE;
2271     device->updateStateBlock->state.material = *material;
2272
2273     /* Handle recording of state blocks */
2274     if (device->isRecordingState)
2275     {
2276         TRACE("Recording... not performing anything.\n");
2277         return WINED3D_OK;
2278     }
2279
2280     device_invalidate_state(device, STATE_MATERIAL);
2281
2282     return WINED3D_OK;
2283 }
2284
2285 HRESULT CDECL wined3d_device_get_material(const struct wined3d_device *device, struct wined3d_material *material)
2286 {
2287     TRACE("device %p, material %p.\n", device, material);
2288
2289     *material = device->updateStateBlock->state.material;
2290
2291     TRACE("diffuse {%.8e, %.8e, %.8e, %.8e}\n",
2292             material->diffuse.r, material->diffuse.g,
2293             material->diffuse.b, material->diffuse.a);
2294     TRACE("ambient {%.8e, %.8e, %.8e, %.8e}\n",
2295             material->ambient.r, material->ambient.g,
2296             material->ambient.b, material->ambient.a);
2297     TRACE("specular {%.8e, %.8e, %.8e, %.8e}\n",
2298             material->specular.r, material->specular.g,
2299             material->specular.b, material->specular.a);
2300     TRACE("emissive {%.8e, %.8e, %.8e, %.8e}\n",
2301             material->emissive.r, material->emissive.g,
2302             material->emissive.b, material->emissive.a);
2303     TRACE("power %.8e.\n", material->power);
2304
2305     return WINED3D_OK;
2306 }
2307
2308 HRESULT CDECL wined3d_device_set_index_buffer(struct wined3d_device *device,
2309         struct wined3d_buffer *buffer, enum wined3d_format_id format_id)
2310 {
2311     struct wined3d_buffer *prev_buffer;
2312
2313     TRACE("device %p, buffer %p, format %s.\n",
2314             device, buffer, debug_d3dformat(format_id));
2315
2316     prev_buffer = device->updateStateBlock->state.index_buffer;
2317
2318     device->updateStateBlock->changed.indices = TRUE;
2319     device->updateStateBlock->state.index_buffer = buffer;
2320     device->updateStateBlock->state.index_format = format_id;
2321
2322     /* Handle recording of state blocks. */
2323     if (device->isRecordingState)
2324     {
2325         TRACE("Recording... not performing anything.\n");
2326         if (buffer)
2327             wined3d_buffer_incref(buffer);
2328         if (prev_buffer)
2329             wined3d_buffer_decref(prev_buffer);
2330         return WINED3D_OK;
2331     }
2332
2333     if (prev_buffer != buffer)
2334     {
2335         device_invalidate_state(device, STATE_INDEXBUFFER);
2336         if (buffer)
2337         {
2338             InterlockedIncrement(&buffer->resource.bind_count);
2339             wined3d_buffer_incref(buffer);
2340         }
2341         if (prev_buffer)
2342         {
2343             InterlockedDecrement(&prev_buffer->resource.bind_count);
2344             wined3d_buffer_decref(prev_buffer);
2345         }
2346     }
2347
2348     return WINED3D_OK;
2349 }
2350
2351 HRESULT CDECL wined3d_device_get_index_buffer(const struct wined3d_device *device, struct wined3d_buffer **buffer)
2352 {
2353     TRACE("device %p, buffer %p.\n", device, buffer);
2354
2355     *buffer = device->stateBlock->state.index_buffer;
2356
2357     if (*buffer)
2358         wined3d_buffer_incref(*buffer);
2359
2360     TRACE("Returning %p.\n", *buffer);
2361
2362     return WINED3D_OK;
2363 }
2364
2365 /* Method to offer d3d9 a simple way to set the base vertex index without messing with the index buffer */
2366 HRESULT CDECL wined3d_device_set_base_vertex_index(struct wined3d_device *device, INT base_index)
2367 {
2368     TRACE("device %p, base_index %d.\n", device, base_index);
2369
2370     if (device->updateStateBlock->state.base_vertex_index == base_index)
2371     {
2372         TRACE("Application is setting the old value over, nothing to do\n");
2373         return WINED3D_OK;
2374     }
2375
2376     device->updateStateBlock->state.base_vertex_index = base_index;
2377
2378     if (device->isRecordingState)
2379     {
2380         TRACE("Recording... not performing anything\n");
2381         return WINED3D_OK;
2382     }
2383     return WINED3D_OK;
2384 }
2385
2386 INT CDECL wined3d_device_get_base_vertex_index(const struct wined3d_device *device)
2387 {
2388     TRACE("device %p.\n", device);
2389
2390     return device->stateBlock->state.base_vertex_index;
2391 }
2392
2393 HRESULT CDECL wined3d_device_set_viewport(struct wined3d_device *device, const struct wined3d_viewport *viewport)
2394 {
2395     TRACE("device %p, viewport %p.\n", device, viewport);
2396     TRACE("x %u, y %u, w %u, h %u, min_z %.8e, max_z %.8e.\n",
2397           viewport->x, viewport->y, viewport->width, viewport->height, viewport->min_z, viewport->max_z);
2398
2399     device->updateStateBlock->changed.viewport = TRUE;
2400     device->updateStateBlock->state.viewport = *viewport;
2401
2402     /* Handle recording of state blocks */
2403     if (device->isRecordingState)
2404     {
2405         TRACE("Recording... not performing anything\n");
2406         return WINED3D_OK;
2407     }
2408
2409     device_invalidate_state(device, STATE_VIEWPORT);
2410
2411     return WINED3D_OK;
2412 }
2413
2414 HRESULT CDECL wined3d_device_get_viewport(const struct wined3d_device *device, struct wined3d_viewport *viewport)
2415 {
2416     TRACE("device %p, viewport %p.\n", device, viewport);
2417
2418     *viewport = device->stateBlock->state.viewport;
2419
2420     return WINED3D_OK;
2421 }
2422
2423 HRESULT CDECL wined3d_device_set_render_state(struct wined3d_device *device,
2424         enum wined3d_render_state state, DWORD value)
2425 {
2426     DWORD old_value = device->stateBlock->state.render_states[state];
2427
2428     TRACE("device %p, state %s (%#x), value %#x.\n", device, debug_d3drenderstate(state), state, value);
2429
2430     device->updateStateBlock->changed.renderState[state >> 5] |= 1 << (state & 0x1f);
2431     device->updateStateBlock->state.render_states[state] = value;
2432
2433     /* Handle recording of state blocks. */
2434     if (device->isRecordingState)
2435     {
2436         TRACE("Recording... not performing anything.\n");
2437         return WINED3D_OK;
2438     }
2439
2440     /* Compared here and not before the assignment to allow proper stateblock recording. */
2441     if (value == old_value)
2442         TRACE("Application is setting the old value over, nothing to do.\n");
2443     else
2444         device_invalidate_state(device, STATE_RENDER(state));
2445
2446     return WINED3D_OK;
2447 }
2448
2449 HRESULT CDECL wined3d_device_get_render_state(const struct wined3d_device *device,
2450         enum wined3d_render_state state, DWORD *value)
2451 {
2452     TRACE("device %p, state %s (%#x), value %p.\n", device, debug_d3drenderstate(state), state, value);
2453
2454     *value = device->stateBlock->state.render_states[state];
2455
2456     return WINED3D_OK;
2457 }
2458
2459 HRESULT CDECL wined3d_device_set_sampler_state(struct wined3d_device *device,
2460         UINT sampler_idx, enum wined3d_sampler_state state, DWORD value)
2461 {
2462     DWORD old_value;
2463
2464     TRACE("device %p, sampler_idx %u, state %s, value %#x.\n",
2465             device, sampler_idx, debug_d3dsamplerstate(state), value);
2466
2467     if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2468         sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2469
2470     if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2471             / sizeof(*device->stateBlock->state.sampler_states))
2472     {
2473         WARN("Invalid sampler %u.\n", sampler_idx);
2474         return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2475     }
2476
2477     old_value = device->stateBlock->state.sampler_states[sampler_idx][state];
2478     device->updateStateBlock->state.sampler_states[sampler_idx][state] = value;
2479     device->updateStateBlock->changed.samplerState[sampler_idx] |= 1 << state;
2480
2481     /* Handle recording of state blocks. */
2482     if (device->isRecordingState)
2483     {
2484         TRACE("Recording... not performing anything.\n");
2485         return WINED3D_OK;
2486     }
2487
2488     if (old_value == value)
2489     {
2490         TRACE("Application is setting the old value over, nothing to do.\n");
2491         return WINED3D_OK;
2492     }
2493
2494     device_invalidate_state(device, STATE_SAMPLER(sampler_idx));
2495
2496     return WINED3D_OK;
2497 }
2498
2499 HRESULT CDECL wined3d_device_get_sampler_state(const struct wined3d_device *device,
2500         UINT sampler_idx, enum wined3d_sampler_state state, DWORD *value)
2501 {
2502     TRACE("device %p, sampler_idx %u, state %s, value %p.\n",
2503             device, sampler_idx, debug_d3dsamplerstate(state), value);
2504
2505     if (sampler_idx >= WINED3DVERTEXTEXTURESAMPLER0 && sampler_idx <= WINED3DVERTEXTEXTURESAMPLER3)
2506         sampler_idx -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2507
2508     if (sampler_idx >= sizeof(device->stateBlock->state.sampler_states)
2509             / sizeof(*device->stateBlock->state.sampler_states))
2510     {
2511         WARN("Invalid sampler %u.\n", sampler_idx);
2512         return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2513     }
2514
2515     *value = device->stateBlock->state.sampler_states[sampler_idx][state];
2516     TRACE("Returning %#x.\n", *value);
2517
2518     return WINED3D_OK;
2519 }
2520
2521 HRESULT CDECL wined3d_device_set_scissor_rect(struct wined3d_device *device, const RECT *rect)
2522 {
2523     TRACE("device %p, rect %s.\n", device, wine_dbgstr_rect(rect));
2524
2525     device->updateStateBlock->changed.scissorRect = TRUE;
2526     if (EqualRect(&device->updateStateBlock->state.scissor_rect, rect))
2527     {
2528         TRACE("App is setting the old scissor rectangle over, nothing to do.\n");
2529         return WINED3D_OK;
2530     }
2531     CopyRect(&device->updateStateBlock->state.scissor_rect, rect);
2532
2533     if (device->isRecordingState)
2534     {
2535         TRACE("Recording... not performing anything.\n");
2536         return WINED3D_OK;
2537     }
2538
2539     device_invalidate_state(device, STATE_SCISSORRECT);
2540
2541     return WINED3D_OK;
2542 }
2543
2544 HRESULT CDECL wined3d_device_get_scissor_rect(const struct wined3d_device *device, RECT *rect)
2545 {
2546     TRACE("device %p, rect %p.\n", device, rect);
2547
2548     *rect = device->updateStateBlock->state.scissor_rect;
2549     TRACE("Returning rect %s.\n", wine_dbgstr_rect(rect));
2550
2551     return WINED3D_OK;
2552 }
2553
2554 HRESULT CDECL wined3d_device_set_vertex_declaration(struct wined3d_device *device,
2555         struct wined3d_vertex_declaration *declaration)
2556 {
2557     struct wined3d_vertex_declaration *prev = device->updateStateBlock->state.vertex_declaration;
2558
2559     TRACE("device %p, declaration %p.\n", device, declaration);
2560
2561     if (declaration)
2562         wined3d_vertex_declaration_incref(declaration);
2563     if (prev)
2564         wined3d_vertex_declaration_decref(prev);
2565
2566     device->updateStateBlock->state.vertex_declaration = declaration;
2567     device->updateStateBlock->changed.vertexDecl = TRUE;
2568
2569     if (device->isRecordingState)
2570     {
2571         TRACE("Recording... not performing anything.\n");
2572         return WINED3D_OK;
2573     }
2574     else if (declaration == prev)
2575     {
2576         /* Checked after the assignment to allow proper stateblock recording. */
2577         TRACE("Application is setting the old declaration over, nothing to do.\n");
2578         return WINED3D_OK;
2579     }
2580
2581     device_invalidate_state(device, STATE_VDECL);
2582     return WINED3D_OK;
2583 }
2584
2585 HRESULT CDECL wined3d_device_get_vertex_declaration(const struct wined3d_device *device,
2586         struct wined3d_vertex_declaration **declaration)
2587 {
2588     TRACE("device %p, declaration %p.\n", device, declaration);
2589
2590     *declaration = device->stateBlock->state.vertex_declaration;
2591     if (*declaration)
2592         wined3d_vertex_declaration_incref(*declaration);
2593
2594     return WINED3D_OK;
2595 }
2596
2597 HRESULT CDECL wined3d_device_set_vertex_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2598 {
2599     struct wined3d_shader *prev = device->updateStateBlock->state.vertex_shader;
2600
2601     TRACE("device %p, shader %p.\n", device, shader);
2602
2603     device->updateStateBlock->state.vertex_shader = shader;
2604     device->updateStateBlock->changed.vertexShader = TRUE;
2605
2606     if (device->isRecordingState)
2607     {
2608         if (shader)
2609             wined3d_shader_incref(shader);
2610         if (prev)
2611             wined3d_shader_decref(prev);
2612         TRACE("Recording... not performing anything.\n");
2613         return WINED3D_OK;
2614     }
2615
2616     if (shader == prev)
2617     {
2618         TRACE("Application is setting the old shader over, nothing to do.\n");
2619         return WINED3D_OK;
2620     }
2621
2622     if (shader)
2623         wined3d_shader_incref(shader);
2624     if (prev)
2625         wined3d_shader_decref(prev);
2626
2627     device_invalidate_state(device, STATE_VSHADER);
2628
2629     return WINED3D_OK;
2630 }
2631
2632 struct wined3d_shader * CDECL wined3d_device_get_vertex_shader(const struct wined3d_device *device)
2633 {
2634     struct wined3d_shader *shader;
2635
2636     TRACE("device %p.\n", device);
2637
2638     shader = device->stateBlock->state.vertex_shader;
2639     if (shader)
2640         wined3d_shader_incref(shader);
2641
2642     TRACE("Returning %p.\n", shader);
2643     return shader;
2644 }
2645
2646 HRESULT CDECL wined3d_device_set_vs_consts_b(struct wined3d_device *device,
2647         UINT start_register, const BOOL *constants, UINT bool_count)
2648 {
2649     UINT count = min(bool_count, MAX_CONST_B - start_register);
2650     UINT i;
2651
2652     TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2653             device, start_register, constants, bool_count);
2654
2655     if (!constants || start_register >= MAX_CONST_B)
2656         return WINED3DERR_INVALIDCALL;
2657
2658     memcpy(&device->updateStateBlock->state.vs_consts_b[start_register], constants, count * sizeof(BOOL));
2659     for (i = 0; i < count; ++i)
2660         TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
2661
2662     for (i = start_register; i < count + start_register; ++i)
2663         device->updateStateBlock->changed.vertexShaderConstantsB |= (1 << i);
2664
2665     if (!device->isRecordingState)
2666         device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2667
2668     return WINED3D_OK;
2669 }
2670
2671 HRESULT CDECL wined3d_device_get_vs_consts_b(const struct wined3d_device *device,
2672         UINT start_register, BOOL *constants, UINT bool_count)
2673 {
2674     UINT count = min(bool_count, MAX_CONST_B - start_register);
2675
2676     TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
2677             device, start_register, constants, bool_count);
2678
2679     if (!constants || start_register >= MAX_CONST_B)
2680         return WINED3DERR_INVALIDCALL;
2681
2682     memcpy(constants, &device->stateBlock->state.vs_consts_b[start_register], count * sizeof(BOOL));
2683
2684     return WINED3D_OK;
2685 }
2686
2687 HRESULT CDECL wined3d_device_set_vs_consts_i(struct wined3d_device *device,
2688         UINT start_register, const int *constants, UINT vector4i_count)
2689 {
2690     UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2691     UINT i;
2692
2693     TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2694             device, start_register, constants, vector4i_count);
2695
2696     if (!constants || start_register >= MAX_CONST_I)
2697         return WINED3DERR_INVALIDCALL;
2698
2699     memcpy(&device->updateStateBlock->state.vs_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
2700     for (i = 0; i < count; ++i)
2701         TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
2702                 constants[i * 4], constants[i * 4 + 1],
2703                 constants[i * 4 + 2], constants[i * 4 + 3]);
2704
2705     for (i = start_register; i < count + start_register; ++i)
2706         device->updateStateBlock->changed.vertexShaderConstantsI |= (1 << i);
2707
2708     if (!device->isRecordingState)
2709         device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2710
2711     return WINED3D_OK;
2712 }
2713
2714 HRESULT CDECL wined3d_device_get_vs_consts_i(const struct wined3d_device *device,
2715         UINT start_register, int *constants, UINT vector4i_count)
2716 {
2717     UINT count = min(vector4i_count, MAX_CONST_I - start_register);
2718
2719     TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
2720             device, start_register, constants, vector4i_count);
2721
2722     if (!constants || start_register >= MAX_CONST_I)
2723         return WINED3DERR_INVALIDCALL;
2724
2725     memcpy(constants, &device->stateBlock->state.vs_consts_i[start_register * 4], count * sizeof(int) * 4);
2726     return WINED3D_OK;
2727 }
2728
2729 HRESULT CDECL wined3d_device_set_vs_consts_f(struct wined3d_device *device,
2730         UINT start_register, const float *constants, UINT vector4f_count)
2731 {
2732     UINT i;
2733
2734     TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2735             device, start_register, constants, vector4f_count);
2736
2737     /* Specifically test start_register > limit to catch MAX_UINT overflows
2738      * when adding start_register + vector4f_count. */
2739     if (!constants
2740             || start_register + vector4f_count > device->d3d_vshader_constantF
2741             || start_register > device->d3d_vshader_constantF)
2742         return WINED3DERR_INVALIDCALL;
2743
2744     memcpy(&device->updateStateBlock->state.vs_consts_f[start_register * 4],
2745             constants, vector4f_count * sizeof(float) * 4);
2746     if (TRACE_ON(d3d))
2747     {
2748         for (i = 0; i < vector4f_count; ++i)
2749             TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
2750                     constants[i * 4], constants[i * 4 + 1],
2751                     constants[i * 4 + 2], constants[i * 4 + 3]);
2752     }
2753
2754     if (!device->isRecordingState)
2755     {
2756         device->shader_backend->shader_update_float_vertex_constants(device, start_register, vector4f_count);
2757         device_invalidate_state(device, STATE_VERTEXSHADERCONSTANT);
2758     }
2759
2760     memset(device->updateStateBlock->changed.vertexShaderConstantsF + start_register, 1,
2761             sizeof(*device->updateStateBlock->changed.vertexShaderConstantsF) * vector4f_count);
2762
2763     return WINED3D_OK;
2764 }
2765
2766 HRESULT CDECL wined3d_device_get_vs_consts_f(const struct wined3d_device *device,
2767         UINT start_register, float *constants, UINT vector4f_count)
2768 {
2769     int count = min(vector4f_count, device->d3d_vshader_constantF - start_register);
2770
2771     TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
2772             device, start_register, constants, vector4f_count);
2773
2774     if (!constants || count < 0)
2775         return WINED3DERR_INVALIDCALL;
2776
2777     memcpy(constants, &device->stateBlock->state.vs_consts_f[start_register * 4], count * sizeof(float) * 4);
2778
2779     return WINED3D_OK;
2780 }
2781
2782 static void device_invalidate_texture_stage(const struct wined3d_device *device, DWORD stage)
2783 {
2784     DWORD i;
2785
2786     for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2787     {
2788         device_invalidate_state(device, STATE_TEXTURESTAGE(stage, i));
2789     }
2790 }
2791
2792 static void device_map_stage(struct wined3d_device *device, DWORD stage, DWORD unit)
2793 {
2794     DWORD i = device->rev_tex_unit_map[unit];
2795     DWORD j = device->texUnitMap[stage];
2796
2797     device->texUnitMap[stage] = unit;
2798     if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2799         device->texUnitMap[i] = WINED3D_UNMAPPED_STAGE;
2800
2801     device->rev_tex_unit_map[unit] = stage;
2802     if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2803         device->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2804 }
2805
2806 static void device_update_fixed_function_usage_map(struct wined3d_device *device)
2807 {
2808     UINT i;
2809
2810     device->fixed_function_usage_map = 0;
2811     for (i = 0; i < MAX_TEXTURES; ++i)
2812     {
2813         const struct wined3d_state *state = &device->stateBlock->state;
2814         enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2815         enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2816         DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2817         DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2818         DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2819         DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2820         DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2821         DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2822
2823         /* Not used, and disable higher stages. */
2824         if (color_op == WINED3D_TOP_DISABLE)
2825             break;
2826
2827         if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2828                 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2829                 || ((color_arg3 == WINED3DTA_TEXTURE)
2830                     && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2831                 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2832                 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2833                 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2834                     && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2835             device->fixed_function_usage_map |= (1 << i);
2836
2837         if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2838                 && i < MAX_TEXTURES - 1)
2839             device->fixed_function_usage_map |= (1 << (i + 1));
2840     }
2841 }
2842
2843 static void device_map_fixed_function_samplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2844 {
2845     unsigned int i, tex;
2846     WORD ffu_map;
2847
2848     device_update_fixed_function_usage_map(device);
2849     ffu_map = device->fixed_function_usage_map;
2850
2851     if (device->max_ffp_textures == gl_info->limits.texture_stages
2852             || device->stateBlock->state.lowest_disabled_stage <= device->max_ffp_textures)
2853     {
2854         for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2855         {
2856             if (!(ffu_map & 1)) continue;
2857
2858             if (device->texUnitMap[i] != i)
2859             {
2860                 device_map_stage(device, i, i);
2861                 device_invalidate_state(device, STATE_SAMPLER(i));
2862                 device_invalidate_texture_stage(device, i);
2863             }
2864         }
2865         return;
2866     }
2867
2868     /* Now work out the mapping */
2869     tex = 0;
2870     for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2871     {
2872         if (!(ffu_map & 1)) continue;
2873
2874         if (device->texUnitMap[i] != tex)
2875         {
2876             device_map_stage(device, i, tex);
2877             device_invalidate_state(device, STATE_SAMPLER(i));
2878             device_invalidate_texture_stage(device, i);
2879         }
2880
2881         ++tex;
2882     }
2883 }
2884
2885 static void device_map_psamplers(struct wined3d_device *device, const struct wined3d_gl_info *gl_info)
2886 {
2887     const enum wined3d_sampler_texture_type *sampler_type =
2888             device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2889     unsigned int i;
2890
2891     for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2892     {
2893         if (sampler_type[i] && device->texUnitMap[i] != i)
2894         {
2895             device_map_stage(device, i, i);
2896             device_invalidate_state(device, STATE_SAMPLER(i));
2897             if (i < gl_info->limits.texture_stages)
2898                 device_invalidate_texture_stage(device, i);
2899         }
2900     }
2901 }
2902
2903 static BOOL device_unit_free_for_vs(const struct wined3d_device *device,
2904         const enum wined3d_sampler_texture_type *pshader_sampler_tokens,
2905         const enum wined3d_sampler_texture_type *vshader_sampler_tokens, DWORD unit)
2906 {
2907     DWORD current_mapping = device->rev_tex_unit_map[unit];
2908
2909     /* Not currently used */
2910     if (current_mapping == WINED3D_UNMAPPED_STAGE) return TRUE;
2911
2912     if (current_mapping < MAX_FRAGMENT_SAMPLERS) {
2913         /* Used by a fragment sampler */
2914
2915         if (!pshader_sampler_tokens) {
2916             /* No pixel shader, check fixed function */
2917             return current_mapping >= MAX_TEXTURES || !(device->fixed_function_usage_map & (1 << current_mapping));
2918         }
2919
2920         /* Pixel shader, check the shader's sampler map */
2921         return !pshader_sampler_tokens[current_mapping];
2922     }
2923
2924     /* Used by a vertex sampler */
2925     return !vshader_sampler_tokens[current_mapping - MAX_FRAGMENT_SAMPLERS];
2926 }
2927
2928 static void device_map_vsamplers(struct wined3d_device *device, BOOL ps, const struct wined3d_gl_info *gl_info)
2929 {
2930     const enum wined3d_sampler_texture_type *vshader_sampler_type =
2931             device->stateBlock->state.vertex_shader->reg_maps.sampler_type;
2932     const enum wined3d_sampler_texture_type *pshader_sampler_type = NULL;
2933     int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2934     int i;
2935
2936     if (ps)
2937     {
2938         /* Note that we only care if a sampler is sampled or not, not the sampler's specific type.
2939          * Otherwise we'd need to call shader_update_samplers() here for 1.x pixelshaders. */
2940         pshader_sampler_type = device->stateBlock->state.pixel_shader->reg_maps.sampler_type;
2941     }
2942
2943     for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
2944         DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2945         if (vshader_sampler_type[i])
2946         {
2947             if (device->texUnitMap[vsampler_idx] != WINED3D_UNMAPPED_STAGE)
2948             {
2949                 /* Already mapped somewhere */
2950                 continue;
2951             }
2952
2953             while (start >= 0)
2954             {
2955                 if (device_unit_free_for_vs(device, pshader_sampler_type, vshader_sampler_type, start))
2956                 {
2957                     device_map_stage(device, vsampler_idx, start);
2958                     device_invalidate_state(device, STATE_SAMPLER(vsampler_idx));
2959
2960                     --start;
2961                     break;
2962                 }
2963
2964                 --start;
2965             }
2966         }
2967     }
2968 }
2969
2970 void device_update_tex_unit_map(struct wined3d_device *device)
2971 {
2972     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2973     const struct wined3d_state *state = &device->stateBlock->state;
2974     BOOL vs = use_vs(state);
2975     BOOL ps = use_ps(state);
2976     /*
2977      * Rules are:
2978      * -> Pixel shaders need a 1:1 map. In theory the shader input could be mapped too, but
2979      * that would be really messy and require shader recompilation
2980      * -> When the mapping of a stage is changed, sampler and ALL texture stage states have
2981      * to be reset. Because of that try to work with a 1:1 mapping as much as possible
2982      */
2983     if (ps)
2984         device_map_psamplers(device, gl_info);
2985     else
2986         device_map_fixed_function_samplers(device, gl_info);
2987
2988     if (vs)
2989         device_map_vsamplers(device, ps, gl_info);
2990 }
2991
2992 HRESULT CDECL wined3d_device_set_pixel_shader(struct wined3d_device *device, struct wined3d_shader *shader)
2993 {
2994     struct wined3d_shader *prev = device->updateStateBlock->state.pixel_shader;
2995
2996     TRACE("device %p, shader %p.\n", device, shader);
2997
2998     device->updateStateBlock->state.pixel_shader = shader;
2999     device->updateStateBlock->changed.pixelShader = TRUE;
3000
3001     if (device->isRecordingState)
3002     {
3003         if (shader)
3004             wined3d_shader_incref(shader);
3005         if (prev)
3006             wined3d_shader_decref(prev);
3007         TRACE("Recording... not performing anything.\n");
3008         return WINED3D_OK;
3009     }
3010
3011     if (shader == prev)
3012     {
3013         TRACE("Application is setting the old shader over, nothing to do.\n");
3014         return WINED3D_OK;
3015     }
3016
3017     if (shader)
3018         wined3d_shader_incref(shader);
3019     if (prev)
3020         wined3d_shader_decref(prev);
3021
3022     device_invalidate_state(device, STATE_PIXELSHADER);
3023
3024     return WINED3D_OK;
3025 }
3026
3027 struct wined3d_shader * CDECL wined3d_device_get_pixel_shader(const struct wined3d_device *device)
3028 {
3029     struct wined3d_shader *shader;
3030
3031     TRACE("device %p.\n", device);
3032
3033     shader = device->stateBlock->state.pixel_shader;
3034     if (shader)
3035         wined3d_shader_incref(shader);
3036
3037     TRACE("Returning %p.\n", shader);
3038     return shader;
3039 }
3040
3041 HRESULT CDECL wined3d_device_set_ps_consts_b(struct wined3d_device *device,
3042         UINT start_register, const BOOL *constants, UINT bool_count)
3043 {
3044     UINT count = min(bool_count, MAX_CONST_B - start_register);
3045     UINT i;
3046
3047     TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
3048             device, start_register, constants, bool_count);
3049
3050     if (!constants || start_register >= MAX_CONST_B)
3051         return WINED3DERR_INVALIDCALL;
3052
3053     memcpy(&device->updateStateBlock->state.ps_consts_b[start_register], constants, count * sizeof(BOOL));
3054     for (i = 0; i < count; ++i)
3055         TRACE("Set BOOL constant %u to %s.\n", start_register + i, constants[i] ? "true" : "false");
3056
3057     for (i = start_register; i < count + start_register; ++i)
3058         device->updateStateBlock->changed.pixelShaderConstantsB |= (1 << i);
3059
3060     if (!device->isRecordingState)
3061         device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3062
3063     return WINED3D_OK;
3064 }
3065
3066 HRESULT CDECL wined3d_device_get_ps_consts_b(const struct wined3d_device *device,
3067         UINT start_register, BOOL *constants, UINT bool_count)
3068 {
3069     UINT count = min(bool_count, MAX_CONST_B - start_register);
3070
3071     TRACE("device %p, start_register %u, constants %p, bool_count %u.\n",
3072             device, start_register, constants, bool_count);
3073
3074     if (!constants || start_register >= MAX_CONST_B)
3075         return WINED3DERR_INVALIDCALL;
3076
3077     memcpy(constants, &device->stateBlock->state.ps_consts_b[start_register], count * sizeof(BOOL));
3078
3079     return WINED3D_OK;
3080 }
3081
3082 HRESULT CDECL wined3d_device_set_ps_consts_i(struct wined3d_device *device,
3083         UINT start_register, const int *constants, UINT vector4i_count)
3084 {
3085     UINT count = min(vector4i_count, MAX_CONST_I - start_register);
3086     UINT i;
3087
3088     TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
3089             device, start_register, constants, vector4i_count);
3090
3091     if (!constants || start_register >= MAX_CONST_I)
3092         return WINED3DERR_INVALIDCALL;
3093
3094     memcpy(&device->updateStateBlock->state.ps_consts_i[start_register * 4], constants, count * sizeof(int) * 4);
3095     for (i = 0; i < count; ++i)
3096         TRACE("Set INT constant %u to {%d, %d, %d, %d}.\n", start_register + i,
3097                 constants[i * 4], constants[i * 4 + 1],
3098                 constants[i * 4 + 2], constants[i * 4 + 3]);
3099
3100     for (i = start_register; i < count + start_register; ++i)
3101         device->updateStateBlock->changed.pixelShaderConstantsI |= (1 << i);
3102
3103     if (!device->isRecordingState)
3104         device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3105
3106     return WINED3D_OK;
3107 }
3108
3109 HRESULT CDECL wined3d_device_get_ps_consts_i(const struct wined3d_device *device,
3110         UINT start_register, int *constants, UINT vector4i_count)
3111 {
3112     UINT count = min(vector4i_count, MAX_CONST_I - start_register);
3113
3114     TRACE("device %p, start_register %u, constants %p, vector4i_count %u.\n",
3115             device, start_register, constants, vector4i_count);
3116
3117     if (!constants || start_register >= MAX_CONST_I)
3118         return WINED3DERR_INVALIDCALL;
3119
3120     memcpy(constants, &device->stateBlock->state.ps_consts_i[start_register * 4], count * sizeof(int) * 4);
3121
3122     return WINED3D_OK;
3123 }
3124
3125 HRESULT CDECL wined3d_device_set_ps_consts_f(struct wined3d_device *device,
3126         UINT start_register, const float *constants, UINT vector4f_count)
3127 {
3128     UINT i;
3129
3130     TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3131             device, start_register, constants, vector4f_count);
3132
3133     /* Specifically test start_register > limit to catch MAX_UINT overflows
3134      * when adding start_register + vector4f_count. */
3135     if (!constants
3136             || start_register + vector4f_count > device->d3d_pshader_constantF
3137             || start_register > device->d3d_pshader_constantF)
3138         return WINED3DERR_INVALIDCALL;
3139
3140     memcpy(&device->updateStateBlock->state.ps_consts_f[start_register * 4],
3141             constants, vector4f_count * sizeof(float) * 4);
3142     if (TRACE_ON(d3d))
3143     {
3144         for (i = 0; i < vector4f_count; ++i)
3145             TRACE("Set FLOAT constant %u to {%.8e, %.8e, %.8e, %.8e}.\n", start_register + i,
3146                     constants[i * 4], constants[i * 4 + 1],
3147                     constants[i * 4 + 2], constants[i * 4 + 3]);
3148     }
3149
3150     if (!device->isRecordingState)
3151     {
3152         device->shader_backend->shader_update_float_pixel_constants(device, start_register, vector4f_count);
3153         device_invalidate_state(device, STATE_PIXELSHADERCONSTANT);
3154     }
3155
3156     memset(device->updateStateBlock->changed.pixelShaderConstantsF + start_register, 1,
3157             sizeof(*device->updateStateBlock->changed.pixelShaderConstantsF) * vector4f_count);
3158
3159     return WINED3D_OK;
3160 }
3161
3162 HRESULT CDECL wined3d_device_get_ps_consts_f(const struct wined3d_device *device,
3163         UINT start_register, float *constants, UINT vector4f_count)
3164 {
3165     int count = min(vector4f_count, device->d3d_pshader_constantF - start_register);
3166
3167     TRACE("device %p, start_register %u, constants %p, vector4f_count %u.\n",
3168             device, start_register, constants, vector4f_count);
3169
3170     if (!constants || count < 0)
3171         return WINED3DERR_INVALIDCALL;
3172
3173     memcpy(constants, &device->stateBlock->state.ps_consts_f[start_register * 4], count * sizeof(float) * 4);
3174
3175     return WINED3D_OK;
3176 }
3177
3178 /* Context activation is done by the caller. */
3179 /* Do not call while under the GL lock. */
3180 #define copy_and_next(dest, src, size) memcpy(dest, src, size); dest += (size)
3181 static HRESULT process_vertices_strided(const struct wined3d_device *device, DWORD dwDestIndex, DWORD dwCount,
3182         const struct wined3d_stream_info *stream_info, struct wined3d_buffer *dest, DWORD flags,
3183         DWORD DestFVF)
3184 {
3185     struct wined3d_matrix mat, proj_mat, view_mat, world_mat;
3186     struct wined3d_viewport vp;
3187     UINT vertex_size;
3188     unsigned int i;
3189     BYTE *dest_ptr;
3190     BOOL doClip;
3191     DWORD numTextures;
3192     HRESULT hr;
3193
3194     if (stream_info->use_map & (1 << WINED3D_FFP_NORMAL))
3195     {
3196         WARN(" lighting state not saved yet... Some strange stuff may happen !\n");
3197     }
3198
3199     if (!(stream_info->use_map & (1 << WINED3D_FFP_POSITION)))
3200     {
3201         ERR("Source has no position mask\n");
3202         return WINED3DERR_INVALIDCALL;
3203     }
3204
3205     if (device->stateBlock->state.render_states[WINED3D_RS_CLIPPING])
3206     {
3207         static BOOL warned = FALSE;
3208         /*
3209          * The clipping code is not quite correct. Some things need
3210          * to be checked against IDirect3DDevice3 (!), d3d8 and d3d9,
3211          * so disable clipping for now.
3212          * (The graphics in Half-Life are broken, and my processvertices
3213          *  test crashes with IDirect3DDevice3)
3214         doClip = TRUE;
3215          */
3216         doClip = FALSE;
3217         if(!warned) {
3218            warned = TRUE;
3219            FIXME("Clipping is broken and disabled for now\n");
3220         }
3221     }
3222     else
3223         doClip = FALSE;
3224
3225     vertex_size = get_flexible_vertex_size(DestFVF);
3226     if (FAILED(hr = wined3d_buffer_map(dest, dwDestIndex * vertex_size, dwCount * vertex_size, &dest_ptr, 0)))
3227     {
3228         WARN("Failed to map buffer, hr %#x.\n", hr);
3229         return hr;
3230     }
3231
3232     wined3d_device_get_transform(device, WINED3D_TS_VIEW, &view_mat);
3233     wined3d_device_get_transform(device, WINED3D_TS_PROJECTION, &proj_mat);
3234     wined3d_device_get_transform(device, WINED3D_TS_WORLD_MATRIX(0), &world_mat);
3235
3236     TRACE("View mat:\n");
3237     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);
3238     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);
3239     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);
3240     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);
3241
3242     TRACE("Proj mat:\n");
3243     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);
3244     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);
3245     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);
3246     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);
3247
3248     TRACE("World mat:\n");
3249     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);
3250     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);
3251     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);
3252     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);
3253
3254     /* Get the viewport */
3255     wined3d_device_get_viewport(device, &vp);
3256     TRACE("viewport  x %u, y %u, width %u, height %u, min_z %.8e, max_z %.8e.\n",
3257           vp.x, vp.y, vp.width, vp.height, vp.min_z, vp.max_z);
3258
3259     multiply_matrix(&mat,&view_mat,&world_mat);
3260     multiply_matrix(&mat,&proj_mat,&mat);
3261
3262     numTextures = (DestFVF & WINED3DFVF_TEXCOUNT_MASK) >> WINED3DFVF_TEXCOUNT_SHIFT;
3263
3264     for (i = 0; i < dwCount; i+= 1) {
3265         unsigned int tex_index;
3266
3267         if ( ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZ ) ||
3268              ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW ) ) {
3269             /* The position first */
3270             const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_POSITION];
3271             const float *p = (const float *)(element->data.addr + i * element->stride);
3272             float x, y, z, rhw;
3273             TRACE("In: ( %06.2f %06.2f %06.2f )\n", p[0], p[1], p[2]);
3274
3275             /* Multiplication with world, view and projection matrix */
3276             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);
3277             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);
3278             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);
3279             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);
3280
3281             TRACE("x=%f y=%f z=%f rhw=%f\n", x, y, z, rhw);
3282
3283             /* WARNING: The following things are taken from d3d7 and were not yet checked
3284              * against d3d8 or d3d9!
3285              */
3286
3287             /* Clipping conditions: From msdn
3288              *
3289              * A vertex is clipped if it does not match the following requirements
3290              * -rhw < x <= rhw
3291              * -rhw < y <= rhw
3292              *    0 < z <= rhw
3293              *    0 < rhw ( Not in d3d7, but tested in d3d7)
3294              *
3295              * If clipping is on is determined by the D3DVOP_CLIP flag in D3D7, and
3296              * by the D3DRS_CLIPPING in D3D9(according to the msdn, not checked)
3297              *
3298              */
3299
3300             if( !doClip ||
3301                 ( (-rhw -eps < x) && (-rhw -eps < y) && ( -eps < z) &&
3302                   (x <= rhw + eps) && (y <= rhw + eps ) && (z <= rhw + eps) &&
3303                   ( rhw > eps ) ) ) {
3304
3305                 /* "Normal" viewport transformation (not clipped)
3306                  * 1) The values are divided by rhw
3307                  * 2) The y axis is negative, so multiply it with -1
3308                  * 3) Screen coordinates go from -(Width/2) to +(Width/2) and
3309                  *    -(Height/2) to +(Height/2). The z range is MinZ to MaxZ
3310                  * 4) Multiply x with Width/2 and add Width/2
3311                  * 5) The same for the height
3312                  * 6) Add the viewpoint X and Y to the 2D coordinates and
3313                  *    The minimum Z value to z
3314                  * 7) rhw = 1 / rhw Reciprocal of Homogeneous W....
3315                  *
3316                  * Well, basically it's simply a linear transformation into viewport
3317                  * coordinates
3318                  */
3319
3320                 x /= rhw;
3321                 y /= rhw;
3322                 z /= rhw;
3323
3324                 y *= -1;
3325
3326                 x *= vp.width / 2;
3327                 y *= vp.height / 2;
3328                 z *= vp.max_z - vp.min_z;
3329
3330                 x += vp.width / 2 + vp.x;
3331                 y += vp.height / 2 + vp.y;
3332                 z += vp.min_z;
3333
3334                 rhw = 1 / rhw;
3335             } else {
3336                 /* That vertex got clipped
3337                  * Contrary to OpenGL it is not dropped completely, it just
3338                  * undergoes a different calculation.
3339                  */
3340                 TRACE("Vertex got clipped\n");
3341                 x += rhw;
3342                 y += rhw;
3343
3344                 x  /= 2;
3345                 y  /= 2;
3346
3347                 /* Msdn mentions that Direct3D9 keeps a list of clipped vertices
3348                  * outside of the main vertex buffer memory. That needs some more
3349                  * investigation...
3350                  */
3351             }
3352
3353             TRACE("Writing (%f %f %f) %f\n", x, y, z, rhw);
3354
3355
3356             ( (float *) dest_ptr)[0] = x;
3357             ( (float *) dest_ptr)[1] = y;
3358             ( (float *) dest_ptr)[2] = z;
3359             ( (float *) dest_ptr)[3] = rhw; /* SIC, see ddraw test! */
3360
3361             dest_ptr += 3 * sizeof(float);
3362
3363             if ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW)
3364                 dest_ptr += sizeof(float);
3365         }
3366
3367         if (DestFVF & WINED3DFVF_PSIZE)
3368             dest_ptr += sizeof(DWORD);
3369
3370         if (DestFVF & WINED3DFVF_NORMAL)
3371         {
3372             const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_NORMAL];
3373             const float *normal = (const float *)(element->data.addr + i * element->stride);
3374             /* AFAIK this should go into the lighting information */
3375             FIXME("Didn't expect the destination to have a normal\n");
3376             copy_and_next(dest_ptr, normal, 3 * sizeof(float));
3377         }
3378
3379         if (DestFVF & WINED3DFVF_DIFFUSE)
3380         {
3381             const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_DIFFUSE];
3382             const DWORD *color_d = (const DWORD *)(element->data.addr + i * element->stride);
3383             if (!(stream_info->use_map & (1 << WINED3D_FFP_DIFFUSE)))
3384             {
3385                 static BOOL warned = FALSE;
3386
3387                 if(!warned) {
3388                     ERR("No diffuse color in source, but destination has one\n");
3389                     warned = TRUE;
3390                 }
3391
3392                 *( (DWORD *) dest_ptr) = 0xffffffff;
3393                 dest_ptr += sizeof(DWORD);
3394             }
3395             else
3396             {
3397                 copy_and_next(dest_ptr, color_d, sizeof(DWORD));
3398             }
3399         }
3400
3401         if (DestFVF & WINED3DFVF_SPECULAR)
3402         {
3403             /* What's the color value in the feedback buffer? */
3404             const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_SPECULAR];
3405             const DWORD *color_s = (const DWORD *)(element->data.addr + i * element->stride);
3406             if (!(stream_info->use_map & (1 << WINED3D_FFP_SPECULAR)))
3407             {
3408                 static BOOL warned = FALSE;
3409
3410                 if(!warned) {
3411                     ERR("No specular color in source, but destination has one\n");
3412                     warned = TRUE;
3413                 }
3414
3415                 *( (DWORD *) dest_ptr) = 0xFF000000;
3416                 dest_ptr += sizeof(DWORD);
3417             }
3418             else
3419             {
3420                 copy_and_next(dest_ptr, color_s, sizeof(DWORD));
3421             }
3422         }
3423
3424         for (tex_index = 0; tex_index < numTextures; ++tex_index)
3425         {
3426             const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_TEXCOORD0 + tex_index];
3427             const float *tex_coord = (const float *)(element->data.addr + i * element->stride);
3428             if (!(stream_info->use_map & (1 << (WINED3D_FFP_TEXCOORD0 + tex_index))))
3429             {
3430                 ERR("No source texture, but destination requests one\n");
3431                 dest_ptr += GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float);
3432             }
3433             else
3434             {
3435                 copy_and_next(dest_ptr, tex_coord, GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float));
3436             }
3437         }
3438     }
3439
3440     wined3d_buffer_unmap(dest);
3441
3442     return WINED3D_OK;
3443 }
3444 #undef copy_and_next
3445
3446 /* Do not call while under the GL lock. */
3447 HRESULT CDECL wined3d_device_process_vertices(struct wined3d_device *device,
3448         UINT src_start_idx, UINT dst_idx, UINT vertex_count, struct wined3d_buffer *dst_buffer,
3449         const struct wined3d_vertex_declaration *declaration, DWORD flags, DWORD dst_fvf)
3450 {
3451     struct wined3d_state *state = &device->stateBlock->state;
3452     struct wined3d_stream_info stream_info;
3453     const struct wined3d_gl_info *gl_info;
3454     BOOL streamWasUP = state->user_stream;
3455     struct wined3d_context *context;
3456     struct wined3d_shader *vs;
3457     unsigned int i;
3458     HRESULT hr;
3459
3460     TRACE("device %p, src_start_idx %u, dst_idx %u, vertex_count %u, "
3461             "dst_buffer %p, declaration %p, flags %#x, dst_fvf %#x.\n",
3462             device, src_start_idx, dst_idx, vertex_count,
3463             dst_buffer, declaration, flags, dst_fvf);
3464
3465     if (declaration)
3466         FIXME("Output vertex declaration not implemented yet.\n");
3467
3468     /* Need any context to write to the vbo. */
3469     context = context_acquire(device, NULL);
3470     gl_info = context->gl_info;
3471
3472     /* ProcessVertices reads from vertex buffers, which have to be assigned.
3473      * DrawPrimitive and DrawPrimitiveUP control the streamIsUP flag, thus
3474      * restore it afterwards. */
3475     vs = state->vertex_shader;
3476     state->vertex_shader = NULL;
3477     state->user_stream = FALSE;
3478     device_stream_info_from_declaration(device, &stream_info);
3479     state->user_stream = streamWasUP;
3480     state->vertex_shader = vs;
3481
3482     /* We can't convert FROM a VBO, and vertex buffers used to source into
3483      * process_vertices() are unlikely to ever be used for drawing. Release
3484      * VBOs in those buffers and fix up the stream_info structure.
3485      *
3486      * Also apply the start index. */
3487     for (i = 0; i < (sizeof(stream_info.elements) / sizeof(*stream_info.elements)); ++i)
3488     {
3489         struct wined3d_stream_info_element *e;
3490
3491         if (!(stream_info.use_map & (1 << i)))
3492             continue;
3493
3494         e = &stream_info.elements[i];
3495         if (e->data.buffer_object)
3496         {
3497             struct wined3d_buffer *vb = state->streams[e->stream_idx].buffer;
3498             e->data.buffer_object = 0;
3499             e->data.addr = (BYTE *)((ULONG_PTR)e->data.addr + (ULONG_PTR)buffer_get_sysmem(vb, gl_info));
3500             ENTER_GL();
3501             GL_EXTCALL(glDeleteBuffersARB(1, &vb->buffer_object));
3502             vb->buffer_object = 0;
3503             LEAVE_GL();
3504         }
3505         if (e->data.addr)
3506             e->data.addr += e->stride * src_start_idx;
3507     }
3508
3509     hr = process_vertices_strided(device, dst_idx, vertex_count,
3510             &stream_info, dst_buffer, flags, dst_fvf);
3511
3512     context_release(context);
3513
3514     return hr;
3515 }
3516
3517 HRESULT CDECL wined3d_device_set_texture_stage_state(struct wined3d_device *device,
3518         UINT stage, enum wined3d_texture_stage_state state, DWORD value)
3519 {
3520     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3521     DWORD old_value;
3522
3523     TRACE("device %p, stage %u, state %s, value %#x.\n",
3524             device, stage, debug_d3dtexturestate(state), value);
3525
3526     if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3527     {
3528         WARN("Invalid state %#x passed.\n", state);
3529         return WINED3D_OK;
3530     }
3531
3532     if (stage >= gl_info->limits.texture_stages)
3533     {
3534         WARN("Attempting to set stage %u which is higher than the max stage %u, ignoring.\n",
3535                 stage, gl_info->limits.texture_stages - 1);
3536         return WINED3D_OK;
3537     }
3538
3539     old_value = device->updateStateBlock->state.texture_states[stage][state];
3540     device->updateStateBlock->changed.textureState[stage] |= 1 << state;
3541     device->updateStateBlock->state.texture_states[stage][state] = value;
3542
3543     if (device->isRecordingState)
3544     {
3545         TRACE("Recording... not performing anything.\n");
3546         return WINED3D_OK;
3547     }
3548
3549     /* Checked after the assignments to allow proper stateblock recording. */
3550     if (old_value == value)
3551     {
3552         TRACE("Application is setting the old value over, nothing to do.\n");
3553         return WINED3D_OK;
3554     }
3555
3556     if (stage > device->stateBlock->state.lowest_disabled_stage
3557             && device->StateTable[STATE_TEXTURESTAGE(0, state)].representative
3558             == STATE_TEXTURESTAGE(0, WINED3D_TSS_COLOR_OP))
3559     {
3560         /* Colorop change above lowest disabled stage? That won't change
3561          * anything in the GL setup. Changes in other states are important on
3562          * disabled stages too. */
3563         return WINED3D_OK;
3564     }
3565
3566     if (state == WINED3D_TSS_COLOR_OP)
3567     {
3568         unsigned int i;
3569
3570         if (value == WINED3D_TOP_DISABLE && old_value != WINED3D_TOP_DISABLE)
3571         {
3572             /* Previously enabled stage disabled now. Make sure to dirtify
3573              * all enabled stages above stage, they have to be disabled.
3574              *
3575              * The current stage is dirtified below. */
3576             for (i = stage + 1; i < device->stateBlock->state.lowest_disabled_stage; ++i)
3577             {
3578                 TRACE("Additionally dirtifying stage %u.\n", i);
3579                 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
3580             }
3581             device->stateBlock->state.lowest_disabled_stage = stage;
3582             TRACE("New lowest disabled: %u.\n", stage);
3583         }
3584         else if (value != WINED3D_TOP_DISABLE && old_value == WINED3D_TOP_DISABLE)
3585         {
3586             /* Previously disabled stage enabled. Stages above it may need
3587              * enabling. Stage must be lowest_disabled_stage here, if it's
3588              * bigger success is returned above, and stages below the lowest
3589              * disabled stage can't be enabled (because they are enabled
3590              * already).
3591              *
3592              * Again stage stage doesn't need to be dirtified here, it is
3593              * handled below. */
3594             for (i = stage + 1; i < gl_info->limits.texture_stages; ++i)
3595             {
3596                 if (device->updateStateBlock->state.texture_states[i][WINED3D_TSS_COLOR_OP] == WINED3D_TOP_DISABLE)
3597                     break;
3598                 TRACE("Additionally dirtifying stage %u due to enable.\n", i);
3599                 device_invalidate_state(device, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
3600             }
3601             device->stateBlock->state.lowest_disabled_stage = i;
3602             TRACE("New lowest disabled: %u.\n", i);
3603         }
3604     }
3605
3606     device_invalidate_state(device, STATE_TEXTURESTAGE(stage, state));
3607
3608     return WINED3D_OK;
3609 }
3610
3611 HRESULT CDECL wined3d_device_get_texture_stage_state(const struct wined3d_device *device,
3612         UINT stage, enum wined3d_texture_stage_state state, DWORD *value)
3613 {
3614     TRACE("device %p, stage %u, state %s, value %p.\n",
3615             device, stage, debug_d3dtexturestate(state), value);
3616
3617     if (state > WINED3D_HIGHEST_TEXTURE_STATE)
3618     {
3619         WARN("Invalid state %#x passed.\n", state);
3620         return WINED3D_OK;
3621     }
3622
3623     *value = device->updateStateBlock->state.texture_states[stage][state];
3624     TRACE("Returning %#x.\n", *value);
3625
3626     return WINED3D_OK;
3627 }
3628
3629 HRESULT CDECL wined3d_device_set_texture(struct wined3d_device *device,
3630         UINT stage, struct wined3d_texture *texture)
3631 {
3632     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3633     struct wined3d_texture *prev;
3634
3635     TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3636
3637     if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3638         stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3639
3640     /* Windows accepts overflowing this array... we do not. */
3641     if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3642     {
3643         WARN("Ignoring invalid stage %u.\n", stage);
3644         return WINED3D_OK;
3645     }
3646
3647     if (texture && texture->resource.pool == WINED3D_POOL_SCRATCH)
3648     {
3649         WARN("Rejecting attempt to set scratch texture.\n");
3650         return WINED3DERR_INVALIDCALL;
3651     }
3652
3653     device->updateStateBlock->changed.textures |= 1 << stage;
3654
3655     prev = device->updateStateBlock->state.textures[stage];
3656     TRACE("Previous texture %p.\n", prev);
3657
3658     if (texture == prev)
3659     {
3660         TRACE("App is setting the same texture again, nothing to do.\n");
3661         return WINED3D_OK;
3662     }
3663
3664     TRACE("Setting new texture to %p.\n", texture);
3665     device->updateStateBlock->state.textures[stage] = texture;
3666
3667     if (device->isRecordingState)
3668     {
3669         TRACE("Recording... not performing anything\n");
3670
3671         if (texture) wined3d_texture_incref(texture);
3672         if (prev) wined3d_texture_decref(prev);
3673
3674         return WINED3D_OK;
3675     }
3676
3677     if (texture)
3678     {
3679         LONG bind_count = InterlockedIncrement(&texture->resource.bind_count);
3680
3681         wined3d_texture_incref(texture);
3682
3683         if (!prev || texture->target != prev->target)
3684             device_invalidate_state(device, STATE_PIXELSHADER);
3685
3686         if (!prev && stage < gl_info->limits.texture_stages)
3687         {
3688             /* The source arguments for color and alpha ops have different
3689              * meanings when a NULL texture is bound, so the COLOR_OP and
3690              * ALPHA_OP have to be dirtified. */
3691             device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_COLOR_OP));
3692             device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_ALPHA_OP));
3693         }
3694
3695         if (bind_count == 1)
3696             texture->sampler = stage;
3697     }
3698
3699     if (prev)
3700     {
3701         LONG bind_count = InterlockedDecrement(&prev->resource.bind_count);
3702
3703         wined3d_texture_decref(prev);
3704
3705         if (!texture && stage < gl_info->limits.texture_stages)
3706         {
3707             device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_COLOR_OP));
3708             device_invalidate_state(device, STATE_TEXTURESTAGE(stage, WINED3D_TSS_ALPHA_OP));
3709         }
3710
3711         if (bind_count && prev->sampler == stage)
3712         {
3713             unsigned int i;
3714
3715             /* Search for other stages the texture is bound to. Shouldn't
3716              * happen if applications bind textures to a single stage only. */
3717             TRACE("Searching for other stages the texture is bound to.\n");
3718             for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
3719             {
3720                 if (device->updateStateBlock->state.textures[i] == prev)
3721                 {
3722                     TRACE("Texture is also bound to stage %u.\n", i);
3723                     prev->sampler = i;
3724                     break;
3725                 }
3726             }
3727         }
3728     }
3729
3730     device_invalidate_state(device, STATE_SAMPLER(stage));
3731
3732     return WINED3D_OK;
3733 }
3734
3735 HRESULT CDECL wined3d_device_get_texture(const struct wined3d_device *device,
3736         UINT stage, struct wined3d_texture **texture)
3737 {
3738     TRACE("device %p, stage %u, texture %p.\n", device, stage, texture);
3739
3740     if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
3741         stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
3742
3743     if (stage >= sizeof(device->stateBlock->state.textures) / sizeof(*device->stateBlock->state.textures))
3744     {
3745         WARN("Ignoring invalid stage %u.\n", stage);
3746         return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
3747     }
3748
3749     *texture = device->stateBlock->state.textures[stage];
3750     if (*texture)
3751         wined3d_texture_incref(*texture);
3752
3753     TRACE("Returning %p.\n", *texture);
3754
3755     return WINED3D_OK;
3756 }
3757
3758 HRESULT CDECL wined3d_device_get_back_buffer(const struct wined3d_device *device, UINT swapchain_idx,
3759         UINT backbuffer_idx, enum wined3d_backbuffer_type backbuffer_type, struct wined3d_surface **backbuffer)
3760 {
3761     struct wined3d_swapchain *swapchain;
3762     HRESULT hr;
3763
3764     TRACE("device %p, swapchain_idx %u, backbuffer_idx %u, backbuffer_type %#x, backbuffer %p.\n",
3765             device, swapchain_idx, backbuffer_idx, backbuffer_type, backbuffer);
3766
3767     hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
3768     if (FAILED(hr))
3769     {
3770         WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
3771         return hr;
3772     }
3773
3774     hr = wined3d_swapchain_get_back_buffer(swapchain, backbuffer_idx, backbuffer_type, backbuffer);
3775     wined3d_swapchain_decref(swapchain);
3776     if (FAILED(hr))
3777     {
3778         WARN("Failed to get backbuffer %u, hr %#x.\n", backbuffer_idx, hr);
3779         return hr;
3780     }
3781
3782     return WINED3D_OK;
3783 }
3784
3785 HRESULT CDECL wined3d_device_get_device_caps(const struct wined3d_device *device, WINED3DCAPS *caps)
3786 {
3787     TRACE("device %p, caps %p.\n", device, caps);
3788
3789     return wined3d_get_device_caps(device->wined3d, device->adapter->ordinal,
3790             device->create_parms.device_type, caps);
3791 }
3792
3793 HRESULT CDECL wined3d_device_get_display_mode(const struct wined3d_device *device,
3794         UINT swapchain_idx, struct wined3d_display_mode *mode)
3795 {
3796     struct wined3d_swapchain *swapchain;
3797     HRESULT hr;
3798
3799     TRACE("device %p, swapchain_idx %u, mode %p.\n", device, swapchain_idx, mode);
3800
3801     if (swapchain_idx)
3802     {
3803         hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
3804         if (SUCCEEDED(hr))
3805         {
3806             hr = wined3d_swapchain_get_display_mode(swapchain, mode);
3807             wined3d_swapchain_decref(swapchain);
3808         }
3809     }
3810     else
3811     {
3812         const struct wined3d_adapter *adapter = device->adapter;
3813
3814         /* Don't read the real display mode, but return the stored mode
3815          * instead. X11 can't change the color depth, and some apps are
3816          * pretty angry if they SetDisplayMode from 24 to 16 bpp and find out
3817          * that GetDisplayMode still returns 24 bpp.
3818          *
3819          * Also don't relay to the swapchain because with ddraw it's possible
3820          * that there isn't a swapchain at all. */
3821         mode->width = adapter->screen_size.cx;
3822         mode->height = adapter->screen_size.cy;
3823         mode->format_id = adapter->screen_format;
3824         mode->refresh_rate = 0;
3825         hr = WINED3D_OK;
3826     }
3827
3828     return hr;
3829 }
3830
3831 HRESULT CDECL wined3d_device_begin_stateblock(struct wined3d_device *device)
3832 {
3833     struct wined3d_stateblock *stateblock;
3834     HRESULT hr;
3835
3836     TRACE("device %p.\n", device);
3837
3838     if (device->isRecordingState)
3839         return WINED3DERR_INVALIDCALL;
3840
3841     hr = wined3d_stateblock_create(device, WINED3D_SBT_RECORDED, &stateblock);
3842     if (FAILED(hr))
3843         return hr;
3844
3845     wined3d_stateblock_decref(device->updateStateBlock);
3846     device->updateStateBlock = stateblock;
3847     device->isRecordingState = TRUE;
3848
3849     TRACE("Recording stateblock %p.\n", stateblock);
3850
3851     return WINED3D_OK;
3852 }
3853
3854 HRESULT CDECL wined3d_device_end_stateblock(struct wined3d_device *device,
3855         struct wined3d_stateblock **stateblock)
3856 {
3857     struct wined3d_stateblock *object = device->updateStateBlock;
3858
3859     TRACE("device %p, stateblock %p.\n", device, stateblock);
3860
3861     if (!device->isRecordingState)
3862     {
3863         WARN("Not recording.\n");
3864         *stateblock = NULL;
3865         return WINED3DERR_INVALIDCALL;
3866     }
3867
3868     stateblock_init_contained_states(object);
3869
3870     *stateblock = object;
3871     device->isRecordingState = FALSE;
3872     device->updateStateBlock = device->stateBlock;
3873     wined3d_stateblock_incref(device->updateStateBlock);
3874
3875     TRACE("Returning stateblock %p.\n", *stateblock);
3876
3877     return WINED3D_OK;
3878 }
3879
3880 HRESULT CDECL wined3d_device_begin_scene(struct wined3d_device *device)
3881 {
3882     /* At the moment we have no need for any functionality at the beginning
3883      * of a scene. */
3884     TRACE("device %p.\n", device);
3885
3886     if (device->inScene)
3887     {
3888         WARN("Already in scene, returning WINED3DERR_INVALIDCALL.\n");
3889         return WINED3DERR_INVALIDCALL;
3890     }
3891     device->inScene = TRUE;
3892     return WINED3D_OK;
3893 }
3894
3895 HRESULT CDECL wined3d_device_end_scene(struct wined3d_device *device)
3896 {
3897     struct wined3d_context *context;
3898
3899     TRACE("device %p.\n", device);
3900
3901     if (!device->inScene)
3902     {
3903         WARN("Not in scene, returning WINED3DERR_INVALIDCALL.\n");
3904         return WINED3DERR_INVALIDCALL;
3905     }
3906
3907     context = context_acquire(device, NULL);
3908     /* We only have to do this if we need to read the, swapbuffers performs a flush for us */
3909     wglFlush();
3910     /* No checkGLcall here to avoid locking the lock just for checking a call that hardly ever
3911      * fails. */
3912     context_release(context);
3913
3914     device->inScene = FALSE;
3915     return WINED3D_OK;
3916 }
3917
3918 HRESULT CDECL wined3d_device_present(const struct wined3d_device *device, const RECT *src_rect,
3919         const RECT *dst_rect, HWND dst_window_override, const RGNDATA *dirty_region)
3920 {
3921     UINT i;
3922
3923     TRACE("device %p, src_rect %s, dst_rect %s, dst_window_override %p, dirty_region %p.\n",
3924             device, wine_dbgstr_rect(src_rect), wine_dbgstr_rect(dst_rect),
3925             dst_window_override, dirty_region);
3926
3927     for (i = 0; i < device->swapchain_count; ++i)
3928     {
3929         wined3d_swapchain_present(device->swapchains[i], src_rect,
3930                 dst_rect, dst_window_override, dirty_region, 0);
3931     }
3932
3933     return WINED3D_OK;
3934 }
3935
3936 /* Do not call while under the GL lock. */
3937 HRESULT CDECL wined3d_device_clear(struct wined3d_device *device, DWORD rect_count,
3938         const RECT *rects, DWORD flags, const struct wined3d_color *color, float depth, DWORD stencil)
3939 {
3940     RECT draw_rect;
3941
3942     TRACE("device %p, rect_count %u, rects %p, flags %#x, color {%.8e, %.8e, %.8e, %.8e}, depth %.8e, stencil %u.\n",
3943             device, rect_count, rects, flags, color->r, color->g, color->b, color->a, depth, stencil);
3944
3945     if (flags & (WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL))
3946     {
3947         struct wined3d_surface *ds = device->fb.depth_stencil;
3948         if (!ds)
3949         {
3950             WARN("Clearing depth and/or stencil without a depth stencil buffer attached, returning WINED3DERR_INVALIDCALL\n");
3951             /* TODO: What about depth stencil buffers without stencil bits? */
3952             return WINED3DERR_INVALIDCALL;
3953         }
3954         else if (flags & WINED3DCLEAR_TARGET)
3955         {
3956             if (ds->resource.width < device->fb.render_targets[0]->resource.width
3957                     || ds->resource.height < device->fb.render_targets[0]->resource.height)
3958             {
3959                 WARN("Silently ignoring depth and target clear with mismatching sizes\n");
3960                 return WINED3D_OK;
3961             }
3962         }
3963     }
3964
3965     wined3d_get_draw_rect(&device->stateBlock->state, &draw_rect);
3966     device_clear_render_targets(device, device->adapter->gl_info.limits.buffers,
3967             &device->fb, rect_count, rects, &draw_rect, flags, color, depth, stencil);
3968
3969     return WINED3D_OK;
3970 }
3971
3972 void CDECL wined3d_device_set_primitive_type(struct wined3d_device *device,
3973         enum wined3d_primitive_type primitive_type)
3974 {
3975     TRACE("device %p, primitive_type %s\n", device, debug_d3dprimitivetype(primitive_type));
3976
3977     device->updateStateBlock->changed.primitive_type = TRUE;
3978     device->updateStateBlock->state.gl_primitive_type = gl_primitive_type_from_d3d(primitive_type);
3979 }
3980
3981 void CDECL wined3d_device_get_primitive_type(const struct wined3d_device *device,
3982         enum wined3d_primitive_type *primitive_type)
3983 {
3984     TRACE("device %p, primitive_type %p\n", device, primitive_type);
3985
3986     *primitive_type = d3d_primitive_type_from_gl(device->stateBlock->state.gl_primitive_type);
3987
3988     TRACE("Returning %s\n", debug_d3dprimitivetype(*primitive_type));
3989 }
3990
3991 HRESULT CDECL wined3d_device_draw_primitive(struct wined3d_device *device, UINT start_vertex, UINT vertex_count)
3992 {
3993     TRACE("device %p, start_vertex %u, vertex_count %u.\n", device, start_vertex, vertex_count);
3994
3995     if (!device->stateBlock->state.vertex_declaration)
3996     {
3997         WARN("Called without a valid vertex declaration set.\n");
3998         return WINED3DERR_INVALIDCALL;
3999     }
4000
4001     /* The index buffer is not needed here, but restore it, otherwise it is hell to keep track of */
4002     if (device->stateBlock->state.user_stream)
4003     {
4004         device_invalidate_state(device, STATE_INDEXBUFFER);
4005         device->stateBlock->state.user_stream = FALSE;
4006     }
4007
4008     if (device->stateBlock->state.load_base_vertex_index)
4009     {
4010         device->stateBlock->state.load_base_vertex_index = 0;
4011         device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4012     }
4013
4014     /* Account for the loading offset due to index buffers. Instead of
4015      * reloading all sources correct it with the startvertex parameter. */
4016     drawPrimitive(device, vertex_count, start_vertex, FALSE, NULL);
4017     return WINED3D_OK;
4018 }
4019
4020 HRESULT CDECL wined3d_device_draw_indexed_primitive(struct wined3d_device *device, UINT start_idx, UINT index_count)
4021 {
4022     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4023
4024     TRACE("device %p, start_idx %u, index_count %u.\n", device, start_idx, index_count);
4025
4026     if (!device->stateBlock->state.index_buffer)
4027     {
4028         /* D3D9 returns D3DERR_INVALIDCALL when DrawIndexedPrimitive is called
4029          * without an index buffer set. (The first time at least...)
4030          * D3D8 simply dies, but I doubt it can do much harm to return
4031          * D3DERR_INVALIDCALL there as well. */
4032         WARN("Called without a valid index buffer set, returning WINED3DERR_INVALIDCALL.\n");
4033         return WINED3DERR_INVALIDCALL;
4034     }
4035
4036     if (!device->stateBlock->state.vertex_declaration)
4037     {
4038         WARN("Called without a valid vertex declaration set.\n");
4039         return WINED3DERR_INVALIDCALL;
4040     }
4041
4042     if (device->stateBlock->state.user_stream)
4043     {
4044         device_invalidate_state(device, STATE_INDEXBUFFER);
4045         device->stateBlock->state.user_stream = FALSE;
4046     }
4047
4048     if (!gl_info->supported[ARB_DRAW_ELEMENTS_BASE_VERTEX] &&
4049         device->stateBlock->state.load_base_vertex_index != device->stateBlock->state.base_vertex_index)
4050     {
4051         device->stateBlock->state.load_base_vertex_index = device->stateBlock->state.base_vertex_index;
4052         device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4053     }
4054
4055     drawPrimitive(device, index_count, start_idx, TRUE, NULL);
4056
4057     return WINED3D_OK;
4058 }
4059
4060 HRESULT CDECL wined3d_device_draw_primitive_up(struct wined3d_device *device, UINT vertex_count,
4061         const void *stream_data, UINT stream_stride)
4062 {
4063     struct wined3d_stream_state *stream;
4064     struct wined3d_buffer *vb;
4065
4066     TRACE("device %p, vertex count %u, stream_data %p, stream_stride %u.\n",
4067             device, vertex_count, stream_data, stream_stride);
4068
4069     if (!device->stateBlock->state.vertex_declaration)
4070     {
4071         WARN("Called without a valid vertex declaration set.\n");
4072         return WINED3DERR_INVALIDCALL;
4073     }
4074
4075     /* Note in the following, it's not this type, but that's the purpose of streamIsUP */
4076     stream = &device->stateBlock->state.streams[0];
4077     vb = stream->buffer;
4078     stream->buffer = (struct wined3d_buffer *)stream_data;
4079     if (vb)
4080         wined3d_buffer_decref(vb);
4081     stream->offset = 0;
4082     stream->stride = stream_stride;
4083     device->stateBlock->state.user_stream = TRUE;
4084     if (device->stateBlock->state.load_base_vertex_index)
4085     {
4086         device->stateBlock->state.load_base_vertex_index = 0;
4087         device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4088     }
4089
4090     /* TODO: Only mark dirty if drawing from a different UP address */
4091     device_invalidate_state(device, STATE_STREAMSRC);
4092
4093     drawPrimitive(device, vertex_count, 0, FALSE, NULL);
4094
4095     /* MSDN specifies stream zero settings must be set to NULL */
4096     stream->buffer = NULL;
4097     stream->stride = 0;
4098
4099     /* stream zero settings set to null at end, as per the msdn. No need to
4100      * mark dirty here, the app has to set the new stream sources or use UP
4101      * drawing again. */
4102     return WINED3D_OK;
4103 }
4104
4105 HRESULT CDECL wined3d_device_draw_indexed_primitive_up(struct wined3d_device *device,
4106         UINT index_count, const void *index_data, enum wined3d_format_id index_data_format_id,
4107         const void *stream_data, UINT stream_stride)
4108 {
4109     struct wined3d_stream_state *stream;
4110     struct wined3d_buffer *vb, *ib;
4111
4112     TRACE("device %p, index_count %u, index_data %p, index_data_format %s, stream_data %p, stream_stride %u.\n",
4113             device, index_count, index_data, debug_d3dformat(index_data_format_id), stream_data, stream_stride);
4114
4115     if (!device->stateBlock->state.vertex_declaration)
4116     {
4117         WARN("(%p) : Called without a valid vertex declaration set\n", device);
4118         return WINED3DERR_INVALIDCALL;
4119     }
4120
4121     stream = &device->stateBlock->state.streams[0];
4122     vb = stream->buffer;
4123     stream->buffer = (struct wined3d_buffer *)stream_data;
4124     if (vb)
4125         wined3d_buffer_decref(vb);
4126     stream->offset = 0;
4127     stream->stride = stream_stride;
4128     device->stateBlock->state.user_stream = TRUE;
4129     device->stateBlock->state.index_format = index_data_format_id;
4130
4131     /* Set to 0 as per msdn. Do it now due to the stream source loading during drawPrimitive */
4132     device->stateBlock->state.base_vertex_index = 0;
4133     if (device->stateBlock->state.load_base_vertex_index)
4134     {
4135         device->stateBlock->state.load_base_vertex_index = 0;
4136         device_invalidate_state(device, STATE_BASEVERTEXINDEX);
4137     }
4138     /* Invalidate the state until we have nicer tracking of the stream source pointers */
4139     device_invalidate_state(device, STATE_STREAMSRC);
4140     device_invalidate_state(device, STATE_INDEXBUFFER);
4141
4142     drawPrimitive(device, index_count, 0, TRUE, index_data);
4143
4144     /* MSDN specifies stream zero settings and index buffer must be set to NULL */
4145     stream->buffer = NULL;
4146     stream->stride = 0;
4147     ib = device->stateBlock->state.index_buffer;
4148     if (ib)
4149     {
4150         wined3d_buffer_decref(ib);
4151         device->stateBlock->state.index_buffer = NULL;
4152     }
4153     /* No need to mark the stream source state dirty here. Either the app calls UP drawing again, or it has to call
4154      * SetStreamSource to specify a vertex buffer
4155      */
4156
4157     return WINED3D_OK;
4158 }
4159
4160 HRESULT CDECL wined3d_device_draw_primitive_strided(struct wined3d_device *device,
4161         UINT vertex_count, const struct wined3d_strided_data *strided_data)
4162 {
4163     /* Mark the state dirty until we have nicer tracking. It's fine to change
4164      * baseVertexIndex because that call is only called by ddraw which does
4165      * not need that value. */
4166     device_invalidate_state(device, STATE_VDECL);
4167     device_invalidate_state(device, STATE_STREAMSRC);
4168     device_invalidate_state(device, STATE_INDEXBUFFER);
4169
4170     device->stateBlock->state.base_vertex_index = 0;
4171     device->up_strided = strided_data;
4172     drawPrimitive(device, vertex_count, 0, FALSE, NULL);
4173     device->up_strided = NULL;
4174
4175     /* Invalidate the states again to make sure the values from the stateblock
4176      * are properly applied in the next regular draw. Note that the application-
4177      * provided strided data has ovwritten pretty much the entire vertex and
4178      * and index stream related states */
4179     device_invalidate_state(device, STATE_VDECL);
4180     device_invalidate_state(device, STATE_STREAMSRC);
4181     device_invalidate_state(device, STATE_INDEXBUFFER);
4182     return WINED3D_OK;
4183 }
4184
4185 HRESULT CDECL wined3d_device_draw_indexed_primitive_strided(struct wined3d_device *device,
4186         UINT index_count, const struct wined3d_strided_data *strided_data,
4187         UINT vertex_count, const void *index_data, enum wined3d_format_id index_data_format_id)
4188 {
4189     enum wined3d_format_id prev_idx_format;
4190
4191     /* Mark the state dirty until we have nicer tracking
4192      * its fine to change baseVertexIndex because that call is only called by ddraw which does not need
4193      * that value.
4194      */
4195     device_invalidate_state(device, STATE_VDECL);
4196     device_invalidate_state(device, STATE_STREAMSRC);
4197     device_invalidate_state(device, STATE_INDEXBUFFER);
4198
4199     prev_idx_format = device->stateBlock->state.index_format;
4200     device->stateBlock->state.index_format = index_data_format_id;
4201     device->stateBlock->state.user_stream = TRUE;
4202     device->stateBlock->state.base_vertex_index = 0;
4203     device->up_strided = strided_data;
4204     drawPrimitive(device, index_count, 0, TRUE, index_data);
4205     device->up_strided = NULL;
4206     device->stateBlock->state.index_format = prev_idx_format;
4207
4208     device_invalidate_state(device, STATE_VDECL);
4209     device_invalidate_state(device, STATE_STREAMSRC);
4210     device_invalidate_state(device, STATE_INDEXBUFFER);
4211     return WINED3D_OK;
4212 }
4213
4214 /* This is a helper function for UpdateTexture, there is no UpdateVolume method in D3D. */
4215 static HRESULT device_update_volume(struct wined3d_device *device,
4216         struct wined3d_volume *src_volume, struct wined3d_volume *dst_volume)
4217 {
4218     struct wined3d_map_desc src;
4219     struct wined3d_map_desc dst;
4220     HRESULT hr;
4221
4222     TRACE("device %p, src_volume %p, dst_volume %p.\n",
4223             device, src_volume, dst_volume);
4224
4225     /* TODO: Implement direct loading into the gl volume instead of using
4226      * memcpy and dirtification to improve loading performance. */
4227     hr = wined3d_volume_map(src_volume, &src, NULL, WINED3DLOCK_READONLY);
4228     if (FAILED(hr)) return hr;
4229     hr = wined3d_volume_map(dst_volume, &dst, NULL, WINED3DLOCK_DISCARD);
4230     if (FAILED(hr))
4231     {
4232         wined3d_volume_unmap(src_volume);
4233         return hr;
4234     }
4235
4236     memcpy(dst.data, src.data, dst_volume->resource.size);
4237
4238     hr = wined3d_volume_unmap(dst_volume);
4239     if (FAILED(hr))
4240         wined3d_volume_unmap(src_volume);
4241     else
4242         hr = wined3d_volume_unmap(src_volume);
4243
4244     return hr;
4245 }
4246
4247 HRESULT CDECL wined3d_device_update_texture(struct wined3d_device *device,
4248         struct wined3d_texture *src_texture, struct wined3d_texture *dst_texture)
4249 {
4250     enum wined3d_resource_type type;
4251     unsigned int level_count, i;
4252     HRESULT hr;
4253
4254     TRACE("device %p, src_texture %p, dst_texture %p.\n", device, src_texture, dst_texture);
4255
4256     /* Verify that the source and destination textures are non-NULL. */
4257     if (!src_texture || !dst_texture)
4258     {
4259         WARN("Source and destination textures must be non-NULL, returning WINED3DERR_INVALIDCALL.\n");
4260         return WINED3DERR_INVALIDCALL;
4261     }
4262
4263     if (src_texture == dst_texture)
4264     {
4265         WARN("Source and destination are the same object, returning WINED3DERR_INVALIDCALL.\n");
4266         return WINED3DERR_INVALIDCALL;
4267     }
4268
4269     /* Verify that the source and destination textures are the same type. */
4270     type = src_texture->resource.type;
4271     if (dst_texture->resource.type != type)
4272     {
4273         WARN("Source and destination have different types, returning WINED3DERR_INVALIDCALL.\n");
4274         return WINED3DERR_INVALIDCALL;
4275     }
4276
4277     /* Check that both textures have the identical numbers of levels. */
4278     level_count = wined3d_texture_get_level_count(src_texture);
4279     if (wined3d_texture_get_level_count(dst_texture) != level_count)
4280     {
4281         WARN("Source and destination have different level counts, returning WINED3DERR_INVALIDCALL.\n");
4282         return WINED3DERR_INVALIDCALL;
4283     }
4284
4285     /* Make sure that the destination texture is loaded. */
4286     dst_texture->texture_ops->texture_preload(dst_texture, SRGB_RGB);
4287
4288     /* Update every surface level of the texture. */
4289     switch (type)
4290     {
4291         case WINED3D_RTYPE_TEXTURE:
4292         {
4293             struct wined3d_surface *src_surface;
4294             struct wined3d_surface *dst_surface;
4295
4296             for (i = 0; i < level_count; ++i)
4297             {
4298                 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4299                 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4300                 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4301                 if (FAILED(hr))
4302                 {
4303                     WARN("Failed to update surface, hr %#x.\n", hr);
4304                     return hr;
4305                 }
4306             }
4307             break;
4308         }
4309
4310         case WINED3D_RTYPE_CUBE_TEXTURE:
4311         {
4312             struct wined3d_surface *src_surface;
4313             struct wined3d_surface *dst_surface;
4314
4315             for (i = 0; i < level_count * 6; ++i)
4316             {
4317                 src_surface = surface_from_resource(wined3d_texture_get_sub_resource(src_texture, i));
4318                 dst_surface = surface_from_resource(wined3d_texture_get_sub_resource(dst_texture, i));
4319                 hr = wined3d_device_update_surface(device, src_surface, NULL, dst_surface, NULL);
4320                 if (FAILED(hr))
4321                 {
4322                     WARN("Failed to update surface, hr %#x.\n", hr);
4323                     return hr;
4324                 }
4325             }
4326             break;
4327         }
4328
4329         case WINED3D_RTYPE_VOLUME_TEXTURE:
4330         {
4331             for (i = 0; i < level_count; ++i)
4332             {
4333                 hr = device_update_volume(device,
4334                         volume_from_resource(wined3d_texture_get_sub_resource(src_texture, i)),
4335                         volume_from_resource(wined3d_texture_get_sub_resource(dst_texture, i)));
4336                 if (FAILED(hr))
4337                 {
4338                     WARN("Failed to update volume, hr %#x.\n", hr);
4339                     return hr;
4340                 }
4341             }
4342             break;
4343         }
4344
4345         default:
4346             FIXME("Unsupported texture type %#x.\n", type);
4347             return WINED3DERR_INVALIDCALL;
4348     }
4349
4350     return WINED3D_OK;
4351 }
4352
4353 HRESULT CDECL wined3d_device_get_front_buffer_data(const struct wined3d_device *device,
4354         UINT swapchain_idx, struct wined3d_surface *dst_surface)
4355 {
4356     struct wined3d_swapchain *swapchain;
4357     HRESULT hr;
4358
4359     TRACE("device %p, swapchain_idx %u, dst_surface %p.\n", device, swapchain_idx, dst_surface);
4360
4361     hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
4362     if (FAILED(hr)) return hr;
4363
4364     hr = wined3d_swapchain_get_front_buffer_data(swapchain, dst_surface);
4365     wined3d_swapchain_decref(swapchain);
4366
4367     return hr;
4368 }
4369
4370 HRESULT CDECL wined3d_device_validate_device(const struct wined3d_device *device, DWORD *num_passes)
4371 {
4372     const struct wined3d_state *state = &device->stateBlock->state;
4373     struct wined3d_texture *texture;
4374     DWORD i;
4375
4376     TRACE("device %p, num_passes %p.\n", device, num_passes);
4377
4378     for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
4379     {
4380         if (state->sampler_states[i][WINED3D_SAMP_MIN_FILTER] == WINED3D_TEXF_NONE)
4381         {
4382             WARN("Sampler state %u has minfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4383             return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4384         }
4385         if (state->sampler_states[i][WINED3D_SAMP_MAG_FILTER] == WINED3D_TEXF_NONE)
4386         {
4387             WARN("Sampler state %u has magfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4388             return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4389         }
4390
4391         texture = state->textures[i];
4392         if (!texture || texture->resource.format->flags & WINED3DFMT_FLAG_FILTERING) continue;
4393
4394         if (state->sampler_states[i][WINED3D_SAMP_MAG_FILTER] != WINED3D_TEXF_POINT)
4395         {
4396             WARN("Non-filterable texture and mag filter enabled on samper %u, returning E_FAIL\n", i);
4397             return E_FAIL;
4398         }
4399         if (state->sampler_states[i][WINED3D_SAMP_MIN_FILTER] != WINED3D_TEXF_POINT)
4400         {
4401             WARN("Non-filterable texture and min filter enabled on samper %u, returning E_FAIL\n", i);
4402             return E_FAIL;
4403         }
4404         if (state->sampler_states[i][WINED3D_SAMP_MIP_FILTER] != WINED3D_TEXF_NONE
4405                 && state->sampler_states[i][WINED3D_SAMP_MIP_FILTER] != WINED3D_TEXF_POINT)
4406         {
4407             WARN("Non-filterable texture and mip filter enabled on samper %u, returning E_FAIL\n", i);
4408             return E_FAIL;
4409         }
4410     }
4411
4412     if (state->render_states[WINED3D_RS_ZENABLE] || state->render_states[WINED3D_RS_ZWRITEENABLE]
4413             || state->render_states[WINED3D_RS_STENCILENABLE])
4414     {
4415         struct wined3d_surface *ds = device->fb.depth_stencil;
4416         struct wined3d_surface *target = device->fb.render_targets[0];
4417
4418         if(ds && target
4419                 && (ds->resource.width < target->resource.width || ds->resource.height < target->resource.height))
4420         {
4421             WARN("Depth stencil is smaller than the color buffer, returning D3DERR_CONFLICTINGRENDERSTATE\n");
4422             return WINED3DERR_CONFLICTINGRENDERSTATE;
4423         }
4424     }
4425
4426     /* return a sensible default */
4427     *num_passes = 1;
4428
4429     TRACE("returning D3D_OK\n");
4430     return WINED3D_OK;
4431 }
4432
4433 HRESULT CDECL wined3d_device_set_software_vertex_processing(struct wined3d_device *device, BOOL software)
4434 {
4435     static BOOL warned;
4436
4437     TRACE("device %p, software %#x.\n", device, software);
4438
4439     if (!warned)
4440     {
4441         FIXME("device %p, software %#x stub!\n", device, software);
4442         warned = TRUE;
4443     }
4444
4445     device->softwareVertexProcessing = software;
4446
4447     return WINED3D_OK;
4448 }
4449
4450 BOOL CDECL wined3d_device_get_software_vertex_processing(const struct wined3d_device *device)
4451 {
4452     static BOOL warned;
4453
4454     TRACE("device %p.\n", device);
4455
4456     if (!warned)
4457     {
4458         TRACE("device %p stub!\n", device);
4459         warned = TRUE;
4460     }
4461
4462     return device->softwareVertexProcessing;
4463 }
4464
4465 HRESULT CDECL wined3d_device_get_raster_status(const struct wined3d_device *device,
4466         UINT swapchain_idx, struct wined3d_raster_status *raster_status)
4467 {
4468     struct wined3d_swapchain *swapchain;
4469     HRESULT hr;
4470
4471     TRACE("device %p, swapchain_idx %u, raster_status %p.\n",
4472             device, swapchain_idx, raster_status);
4473
4474     hr = wined3d_device_get_swapchain(device, swapchain_idx, &swapchain);
4475     if (FAILED(hr))
4476     {
4477         WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
4478         return hr;
4479     }
4480
4481     hr = wined3d_swapchain_get_raster_status(swapchain, raster_status);
4482     wined3d_swapchain_decref(swapchain);
4483     if (FAILED(hr))
4484     {
4485         WARN("Failed to get raster status, hr %#x.\n", hr);
4486         return hr;
4487     }
4488
4489     return WINED3D_OK;
4490 }
4491
4492 HRESULT CDECL wined3d_device_set_npatch_mode(struct wined3d_device *device, float segments)
4493 {
4494     static BOOL warned;
4495
4496     TRACE("device %p, segments %.8e.\n", device, segments);
4497
4498     if (segments != 0.0f)
4499     {
4500         if (!warned)
4501         {
4502             FIXME("device %p, segments %.8e stub!\n", device, segments);
4503             warned = TRUE;
4504         }
4505     }
4506
4507     return WINED3D_OK;
4508 }
4509
4510 float CDECL wined3d_device_get_npatch_mode(const struct wined3d_device *device)
4511 {
4512     static BOOL warned;
4513
4514     TRACE("device %p.\n", device);
4515
4516     if (!warned)
4517     {
4518         FIXME("device %p stub!\n", device);
4519         warned = TRUE;
4520     }
4521
4522     return 0.0f;
4523 }
4524
4525 HRESULT CDECL wined3d_device_update_surface(struct wined3d_device *device,
4526         struct wined3d_surface *src_surface, const RECT *src_rect,
4527         struct wined3d_surface *dst_surface, const POINT *dst_point)
4528 {
4529     TRACE("device %p, src_surface %p, src_rect %s, dst_surface %p, dst_point %s.\n",
4530             device, src_surface, wine_dbgstr_rect(src_rect),
4531             dst_surface, wine_dbgstr_point(dst_point));
4532
4533     if (src_surface->resource.pool != WINED3D_POOL_SYSTEM_MEM || dst_surface->resource.pool != WINED3D_POOL_DEFAULT)
4534     {
4535         WARN("source %p must be SYSTEMMEM and dest %p must be DEFAULT, returning WINED3DERR_INVALIDCALL\n",
4536                 src_surface, dst_surface);
4537         return WINED3DERR_INVALIDCALL;
4538     }
4539
4540     return surface_upload_from_surface(dst_surface, dst_point, src_surface, src_rect);
4541 }
4542
4543 HRESULT CDECL wined3d_device_draw_rect_patch(struct wined3d_device *device, UINT handle,
4544         const float *num_segs, const struct wined3d_rect_patch_info *rect_patch_info)
4545 {
4546     struct wined3d_rect_patch *patch;
4547     GLenum old_primitive_type;
4548     unsigned int i;
4549     struct list *e;
4550     BOOL found;
4551
4552     TRACE("device %p, handle %#x, num_segs %p, rect_patch_info %p.\n",
4553             device, handle, num_segs, rect_patch_info);
4554
4555     if (!(handle || rect_patch_info))
4556     {
4557         /* TODO: Write a test for the return value, thus the FIXME */
4558         FIXME("Both handle and rect_patch_info are NULL.\n");
4559         return WINED3DERR_INVALIDCALL;
4560     }
4561
4562     if (handle)
4563     {
4564         i = PATCHMAP_HASHFUNC(handle);
4565         found = FALSE;
4566         LIST_FOR_EACH(e, &device->patches[i])
4567         {
4568             patch = LIST_ENTRY(e, struct wined3d_rect_patch, entry);
4569             if (patch->Handle == handle)
4570             {
4571                 found = TRUE;
4572                 break;
4573             }
4574         }
4575
4576         if (!found)
4577         {
4578             TRACE("Patch does not exist. Creating a new one\n");
4579             patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4580             patch->Handle = handle;
4581             list_add_head(&device->patches[i], &patch->entry);
4582         } else {
4583             TRACE("Found existing patch %p\n", patch);
4584         }
4585     }
4586     else
4587     {
4588         /* Since opengl does not load tesselated vertex attributes into numbered vertex
4589          * attributes we have to tesselate, read back, and draw. This needs a patch
4590          * management structure instance. Create one.
4591          *
4592          * A possible improvement is to check if a vertex shader is used, and if not directly
4593          * draw the patch.
4594          */
4595         FIXME("Drawing an uncached patch. This is slow\n");
4596         patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
4597     }
4598
4599     if (num_segs[0] != patch->numSegs[0] || num_segs[1] != patch->numSegs[1]
4600             || num_segs[2] != patch->numSegs[2] || num_segs[3] != patch->numSegs[3]
4601             || (rect_patch_info && memcmp(rect_patch_info, &patch->rect_patch_info, sizeof(*rect_patch_info))))
4602     {
4603         HRESULT hr;
4604         TRACE("Tesselation density or patch info changed, retesselating\n");
4605
4606         if (rect_patch_info)
4607             patch->rect_patch_info = *rect_patch_info;
4608
4609         patch->numSegs[0] = num_segs[0];
4610         patch->numSegs[1] = num_segs[1];
4611         patch->numSegs[2] = num_segs[2];
4612         patch->numSegs[3] = num_segs[3];
4613
4614         hr = tesselate_rectpatch(device, patch);
4615         if (FAILED(hr))
4616         {
4617             WARN("Patch tesselation failed.\n");
4618
4619             /* Do not release the handle to store the params of the patch */
4620             if (!handle)
4621                 HeapFree(GetProcessHeap(), 0, patch);
4622
4623             return hr;
4624         }
4625     }
4626
4627     old_primitive_type = device->stateBlock->state.gl_primitive_type;
4628     device->stateBlock->state.gl_primitive_type = GL_TRIANGLES;
4629     wined3d_device_draw_primitive_strided(device, patch->numSegs[0] * patch->numSegs[1] * 2 * 3, &patch->strided);
4630     device->stateBlock->state.gl_primitive_type = old_primitive_type;
4631
4632     /* Destroy uncached patches */
4633     if (!handle)
4634     {
4635         HeapFree(GetProcessHeap(), 0, patch->mem);
4636         HeapFree(GetProcessHeap(), 0, patch);
4637     }
4638     return WINED3D_OK;
4639 }
4640
4641 HRESULT CDECL wined3d_device_draw_tri_patch(struct wined3d_device *device, UINT handle,
4642         const float *segment_count, const struct wined3d_tri_patch_info *patch_info)
4643 {
4644     FIXME("device %p, handle %#x, segment_count %p, patch_info %p stub!\n",
4645             device, handle, segment_count, patch_info);
4646
4647     return WINED3D_OK;
4648 }
4649
4650 HRESULT CDECL wined3d_device_delete_patch(struct wined3d_device *device, UINT handle)
4651 {
4652     struct wined3d_rect_patch *patch;
4653     struct list *e;
4654     int i;
4655
4656     TRACE("device %p, handle %#x.\n", device, handle);
4657
4658     i = PATCHMAP_HASHFUNC(handle);
4659     LIST_FOR_EACH(e, &device->patches[i])
4660     {
4661         patch = LIST_ENTRY(e, struct wined3d_rect_patch, entry);
4662         if (patch->Handle == handle)
4663         {
4664             TRACE("Deleting patch %p\n", patch);
4665             list_remove(&patch->entry);
4666             HeapFree(GetProcessHeap(), 0, patch->mem);
4667             HeapFree(GetProcessHeap(), 0, patch);
4668             return WINED3D_OK;
4669         }
4670     }
4671
4672     /* TODO: Write a test for the return value */
4673     FIXME("Attempt to destroy nonexistent patch\n");
4674     return WINED3DERR_INVALIDCALL;
4675 }
4676
4677 /* Do not call while under the GL lock. */
4678 HRESULT CDECL wined3d_device_color_fill(struct wined3d_device *device,
4679         struct wined3d_surface *surface, const RECT *rect, const struct wined3d_color *color)
4680 {
4681     RECT r;
4682
4683     TRACE("device %p, surface %p, rect %s, color {%.8e, %.8e, %.8e, %.8e}.\n",
4684             device, surface, wine_dbgstr_rect(rect),
4685             color->r, color->g, color->b, color->a);
4686
4687     if (surface->resource.pool != WINED3D_POOL_DEFAULT && surface->resource.pool != WINED3D_POOL_SYSTEM_MEM)
4688     {
4689         WARN("Color-fill not allowed on %s surfaces.\n", debug_d3dpool(surface->resource.pool));
4690         return WINED3DERR_INVALIDCALL;
4691     }
4692
4693     if (!rect)
4694     {
4695         SetRect(&r, 0, 0, surface->resource.width, surface->resource.height);
4696         rect = &r;
4697     }
4698
4699     return surface_color_fill(surface, rect, color);
4700 }
4701
4702 /* Do not call while under the GL lock. */
4703 void CDECL wined3d_device_clear_rendertarget_view(struct wined3d_device *device,
4704         struct wined3d_rendertarget_view *rendertarget_view, const struct wined3d_color *color)
4705 {
4706     struct wined3d_resource *resource;
4707     HRESULT hr;
4708     RECT rect;
4709
4710     resource = rendertarget_view->resource;
4711     if (resource->type != WINED3D_RTYPE_SURFACE)
4712     {
4713         FIXME("Only supported on surface resources\n");
4714         return;
4715     }
4716
4717     SetRect(&rect, 0, 0, resource->width, resource->height);
4718     hr = surface_color_fill(surface_from_resource(resource), &rect, color);
4719     if (FAILED(hr)) ERR("Color fill failed, hr %#x.\n", hr);
4720 }
4721
4722 HRESULT CDECL wined3d_device_get_render_target(const struct wined3d_device *device,
4723         UINT render_target_idx, struct wined3d_surface **render_target)
4724 {
4725     TRACE("device %p, render_target_idx %u, render_target %p.\n",
4726             device, render_target_idx, render_target);
4727
4728     if (render_target_idx >= device->adapter->gl_info.limits.buffers)
4729     {
4730         WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
4731         return WINED3DERR_INVALIDCALL;
4732     }
4733
4734     *render_target = device->fb.render_targets[render_target_idx];
4735     TRACE("Returning render target %p.\n", *render_target);
4736
4737     if (!*render_target)
4738         return WINED3DERR_NOTFOUND;
4739
4740     wined3d_surface_incref(*render_target);
4741
4742     return WINED3D_OK;
4743 }
4744
4745 HRESULT CDECL wined3d_device_get_depth_stencil(const struct wined3d_device *device,
4746         struct wined3d_surface **depth_stencil)
4747 {
4748     TRACE("device %p, depth_stencil %p.\n", device, depth_stencil);
4749
4750     *depth_stencil = device->fb.depth_stencil;
4751     TRACE("Returning depth/stencil surface %p.\n", *depth_stencil);
4752
4753     if (!*depth_stencil)
4754         return WINED3DERR_NOTFOUND;
4755
4756     wined3d_surface_incref(*depth_stencil);
4757
4758     return WINED3D_OK;
4759 }
4760
4761 HRESULT CDECL wined3d_device_set_render_target(struct wined3d_device *device,
4762         UINT render_target_idx, struct wined3d_surface *render_target, BOOL set_viewport)
4763 {
4764     struct wined3d_surface *prev;
4765
4766     TRACE("device %p, render_target_idx %u, render_target %p, set_viewport %#x.\n",
4767             device, render_target_idx, render_target, set_viewport);
4768
4769     if (render_target_idx >= device->adapter->gl_info.limits.buffers)
4770     {
4771         WARN("Only %u render targets are supported.\n", device->adapter->gl_info.limits.buffers);
4772         return WINED3DERR_INVALIDCALL;
4773     }
4774
4775     prev = device->fb.render_targets[render_target_idx];
4776     if (render_target == prev)
4777     {
4778         TRACE("Trying to do a NOP SetRenderTarget operation.\n");
4779         return WINED3D_OK;
4780     }
4781
4782     /* Render target 0 can't be set to NULL. */
4783     if (!render_target && !render_target_idx)
4784     {
4785         WARN("Trying to set render target 0 to NULL.\n");
4786         return WINED3DERR_INVALIDCALL;
4787     }
4788
4789     if (render_target && !(render_target->resource.usage & WINED3DUSAGE_RENDERTARGET))
4790     {
4791         FIXME("Surface %p doesn't have render target usage.\n", render_target);
4792         return WINED3DERR_INVALIDCALL;
4793     }
4794
4795     if (render_target)
4796         wined3d_surface_incref(render_target);
4797     device->fb.render_targets[render_target_idx] = render_target;
4798     /* Release after the assignment, to prevent device_resource_released()
4799      * from seeing the surface as still in use. */
4800     if (prev)
4801         wined3d_surface_decref(prev);
4802
4803     /* Render target 0 is special. */
4804     if (!render_target_idx && set_viewport)
4805     {
4806         /* Set the viewport and scissor rectangles, if requested. Tests show
4807          * that stateblock recording is ignored, the change goes directly
4808          * into the primary stateblock. */
4809         device->stateBlock->state.viewport.height = device->fb.render_targets[0]->resource.height;
4810         device->stateBlock->state.viewport.width  = device->fb.render_targets[0]->resource.width;
4811         device->stateBlock->state.viewport.x      = 0;
4812         device->stateBlock->state.viewport.y      = 0;
4813         device->stateBlock->state.viewport.max_z  = 1.0f;
4814         device->stateBlock->state.viewport.min_z  = 0.0f;
4815         device_invalidate_state(device, STATE_VIEWPORT);
4816
4817         device->stateBlock->state.scissor_rect.top = 0;
4818         device->stateBlock->state.scissor_rect.left = 0;
4819         device->stateBlock->state.scissor_rect.right = device->stateBlock->state.viewport.width;
4820         device->stateBlock->state.scissor_rect.bottom = device->stateBlock->state.viewport.height;
4821         device_invalidate_state(device, STATE_SCISSORRECT);
4822     }
4823
4824     device_invalidate_state(device, STATE_FRAMEBUFFER);
4825
4826     return WINED3D_OK;
4827 }
4828
4829 HRESULT CDECL wined3d_device_set_depth_stencil(struct wined3d_device *device, struct wined3d_surface *depth_stencil)
4830 {
4831     struct wined3d_surface *prev = device->fb.depth_stencil;
4832
4833     TRACE("device %p, depth_stencil %p, old depth_stencil %p.\n",
4834             device, depth_stencil, prev);
4835
4836     if (prev == depth_stencil)
4837     {
4838         TRACE("Trying to do a NOP SetRenderTarget operation.\n");
4839         return WINED3D_OK;
4840     }
4841
4842     if (prev)
4843     {
4844         if (device->swapchains[0]->desc.flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
4845                 || prev->flags & SFLAG_DISCARD)
4846         {
4847             surface_modify_ds_location(prev, SFLAG_DISCARDED,
4848                     prev->resource.width, prev->resource.height);
4849             if (prev == device->onscreen_depth_stencil)
4850             {
4851                 wined3d_surface_decref(device->onscreen_depth_stencil);
4852                 device->onscreen_depth_stencil = NULL;
4853             }
4854         }
4855     }
4856
4857     device->fb.depth_stencil = depth_stencil;
4858     if (depth_stencil)
4859         wined3d_surface_incref(depth_stencil);
4860
4861     if (!prev != !depth_stencil)
4862     {
4863         /* Swapping NULL / non NULL depth stencil affects the depth and tests */
4864         device_invalidate_state(device, STATE_RENDER(WINED3D_RS_ZENABLE));
4865         device_invalidate_state(device, STATE_RENDER(WINED3D_RS_STENCILENABLE));
4866         device_invalidate_state(device, STATE_RENDER(WINED3D_RS_STENCILWRITEMASK));
4867         device_invalidate_state(device, STATE_RENDER(WINED3D_RS_DEPTHBIAS));
4868     }
4869     else if (prev && prev->resource.format->depth_size != depth_stencil->resource.format->depth_size)
4870     {
4871         device_invalidate_state(device, STATE_RENDER(WINED3D_RS_DEPTHBIAS));
4872     }
4873     if (prev)
4874         wined3d_surface_decref(prev);
4875
4876     device_invalidate_state(device, STATE_FRAMEBUFFER);
4877
4878     return WINED3D_OK;
4879 }
4880
4881 HRESULT CDECL wined3d_device_set_cursor_properties(struct wined3d_device *device,
4882         UINT x_hotspot, UINT y_hotspot, struct wined3d_surface *cursor_image)
4883 {
4884     TRACE("device %p, x_hotspot %u, y_hotspot %u, cursor_image %p.\n",
4885             device, x_hotspot, y_hotspot, cursor_image);
4886
4887     /* some basic validation checks */
4888     if (device->cursorTexture)
4889     {
4890         struct wined3d_context *context = context_acquire(device, NULL);
4891         ENTER_GL();
4892         glDeleteTextures(1, &device->cursorTexture);
4893         LEAVE_GL();
4894         context_release(context);
4895         device->cursorTexture = 0;
4896     }
4897
4898     if (cursor_image)
4899     {
4900         struct wined3d_map_desc map_desc;
4901
4902         /* MSDN: Cursor must be A8R8G8B8 */
4903         if (cursor_image->resource.format->id != WINED3DFMT_B8G8R8A8_UNORM)
4904         {
4905             WARN("surface %p has an invalid format.\n", cursor_image);
4906             return WINED3DERR_INVALIDCALL;
4907         }
4908
4909         /* MSDN: Cursor must be smaller than the display mode */
4910         if (cursor_image->resource.width > device->adapter->screen_size.cx
4911                 || cursor_image->resource.height > device->adapter->screen_size.cy)
4912         {
4913             WARN("Surface %p dimensions are %ux%u, but screen dimensions are %ux%u.\n",
4914                     cursor_image, cursor_image->resource.width, cursor_image->resource.height,
4915                     device->adapter->screen_size.cx, device->adapter->screen_size.cy);
4916             return WINED3DERR_INVALIDCALL;
4917         }
4918
4919         /* TODO: MSDN: Cursor sizes must be a power of 2 */
4920
4921         /* Do not store the surface's pointer because the application may
4922          * release it after setting the cursor image. Windows doesn't
4923          * addref the set surface, so we can't do this either without
4924          * creating circular refcount dependencies. Copy out the gl texture
4925          * instead. */
4926         device->cursorWidth = cursor_image->resource.width;
4927         device->cursorHeight = cursor_image->resource.height;
4928         if (SUCCEEDED(wined3d_surface_map(cursor_image, &map_desc, NULL, WINED3DLOCK_READONLY)))
4929         {
4930             const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4931             const struct wined3d_format *format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
4932             struct wined3d_context *context;
4933             char *mem, *bits = map_desc.data;
4934             GLint intfmt = format->glInternal;
4935             GLint gl_format = format->glFormat;
4936             GLint type = format->glType;
4937             INT height = device->cursorHeight;
4938             INT width = device->cursorWidth;
4939             INT bpp = format->byte_count;
4940             INT i;
4941
4942             /* Reformat the texture memory (pitch and width can be
4943              * different) */
4944             mem = HeapAlloc(GetProcessHeap(), 0, width * height * bpp);
4945             for (i = 0; i < height; ++i)
4946                 memcpy(&mem[width * bpp * i], &bits[map_desc.row_pitch * i], width * bpp);
4947             wined3d_surface_unmap(cursor_image);
4948
4949             context = context_acquire(device, NULL);
4950
4951             ENTER_GL();
4952
4953             if (gl_info->supported[APPLE_CLIENT_STORAGE])
4954             {
4955                 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
4956                 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
4957             }
4958
4959             invalidate_active_texture(device, context);
4960             /* Create a new cursor texture */
4961             glGenTextures(1, &device->cursorTexture);
4962             checkGLcall("glGenTextures");
4963             context_bind_texture(context, GL_TEXTURE_2D, device->cursorTexture);
4964             /* Copy the bitmap memory into the cursor texture */
4965             glTexImage2D(GL_TEXTURE_2D, 0, intfmt, width, height, 0, gl_format, type, mem);
4966             checkGLcall("glTexImage2D");
4967             HeapFree(GetProcessHeap(), 0, mem);
4968
4969             if (gl_info->supported[APPLE_CLIENT_STORAGE])
4970             {
4971                 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
4972                 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
4973             }
4974
4975             LEAVE_GL();
4976
4977             context_release(context);
4978         }
4979         else
4980         {
4981             FIXME("A cursor texture was not returned.\n");
4982             device->cursorTexture = 0;
4983         }
4984
4985         if (cursor_image->resource.width == 32 && cursor_image->resource.height == 32)
4986         {
4987             UINT mask_size = cursor_image->resource.width * cursor_image->resource.height / 8;
4988             ICONINFO cursorInfo;
4989             DWORD *maskBits;
4990             HCURSOR cursor;
4991
4992             /* 32-bit user32 cursors ignore the alpha channel if it's all
4993              * zeroes, and use the mask instead. Fill the mask with all ones
4994              * to ensure we still get a fully transparent cursor. */
4995             maskBits = HeapAlloc(GetProcessHeap(), 0, mask_size);
4996             memset(maskBits, 0xff, mask_size);
4997             wined3d_surface_map(cursor_image, &map_desc, NULL,
4998                     WINED3DLOCK_NO_DIRTY_UPDATE | WINED3DLOCK_READONLY);
4999             TRACE("width: %u height: %u.\n", cursor_image->resource.width, cursor_image->resource.height);
5000
5001             cursorInfo.fIcon = FALSE;
5002             cursorInfo.xHotspot = x_hotspot;
5003             cursorInfo.yHotspot = y_hotspot;
5004             cursorInfo.hbmMask = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
5005                     1, 1, maskBits);
5006             cursorInfo.hbmColor = CreateBitmap(cursor_image->resource.width, cursor_image->resource.height,
5007                     1, 32, map_desc.data);
5008             wined3d_surface_unmap(cursor_image);
5009             /* Create our cursor and clean up. */
5010             cursor = CreateIconIndirect(&cursorInfo);
5011             if (cursorInfo.hbmMask) DeleteObject(cursorInfo.hbmMask);
5012             if (cursorInfo.hbmColor) DeleteObject(cursorInfo.hbmColor);
5013             if (device->hardwareCursor) DestroyCursor(device->hardwareCursor);
5014             device->hardwareCursor = cursor;
5015             if (device->bCursorVisible) SetCursor( cursor );
5016             HeapFree(GetProcessHeap(), 0, maskBits);
5017         }
5018     }
5019
5020     device->xHotSpot = x_hotspot;
5021     device->yHotSpot = y_hotspot;
5022     return WINED3D_OK;
5023 }
5024
5025 void CDECL wined3d_device_set_cursor_position(struct wined3d_device *device,
5026         int x_screen_space, int y_screen_space, DWORD flags)
5027 {
5028     TRACE("device %p, x %d, y %d, flags %#x.\n",
5029             device, x_screen_space, y_screen_space, flags);
5030
5031     device->xScreenSpace = x_screen_space;
5032     device->yScreenSpace = y_screen_space;
5033
5034     if (device->hardwareCursor)
5035     {
5036         POINT pt;
5037
5038         GetCursorPos( &pt );
5039         if (x_screen_space == pt.x && y_screen_space == pt.y)
5040             return;
5041         SetCursorPos( x_screen_space, y_screen_space );
5042
5043         /* Switch to the software cursor if position diverges from the hardware one. */
5044         GetCursorPos( &pt );
5045         if (x_screen_space != pt.x || y_screen_space != pt.y)
5046         {
5047             if (device->bCursorVisible) SetCursor( NULL );
5048             DestroyCursor( device->hardwareCursor );
5049             device->hardwareCursor = 0;
5050         }
5051     }
5052 }
5053
5054 BOOL CDECL wined3d_device_show_cursor(struct wined3d_device *device, BOOL show)
5055 {
5056     BOOL oldVisible = device->bCursorVisible;
5057
5058     TRACE("device %p, show %#x.\n", device, show);
5059
5060     /*
5061      * When ShowCursor is first called it should make the cursor appear at the OS's last
5062      * known cursor position.
5063      */
5064     if (show && !oldVisible)
5065     {
5066         POINT pt;
5067         GetCursorPos(&pt);
5068         device->xScreenSpace = pt.x;
5069         device->yScreenSpace = pt.y;
5070     }
5071
5072     if (device->hardwareCursor)
5073     {
5074         device->bCursorVisible = show;
5075         if (show)
5076             SetCursor(device->hardwareCursor);
5077         else
5078             SetCursor(NULL);
5079     }
5080     else
5081     {
5082         if (device->cursorTexture)
5083             device->bCursorVisible = show;
5084     }
5085
5086     return oldVisible;
5087 }
5088
5089 void CDECL wined3d_device_evict_managed_resources(struct wined3d_device *device)
5090 {
5091     struct wined3d_resource *resource, *cursor;
5092
5093     TRACE("device %p.\n", device);
5094
5095     LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5096     {
5097         TRACE("Checking resource %p for eviction.\n", resource);
5098
5099         if (resource->pool == WINED3D_POOL_MANAGED)
5100         {
5101             TRACE("Evicting %p.\n", resource);
5102             resource->resource_ops->resource_unload(resource);
5103         }
5104     }
5105
5106     /* Invalidate stream sources, the buffer(s) may have been evicted. */
5107     device_invalidate_state(device, STATE_STREAMSRC);
5108 }
5109
5110 static BOOL is_display_mode_supported(const struct wined3d_device *device,
5111         const struct wined3d_swapchain_desc *swapchain_desc)
5112 {
5113     struct wined3d_display_mode m;
5114     UINT i, count;
5115     HRESULT hr;
5116
5117     /* All Windowed modes are supported, as is leaving the current mode */
5118     if (swapchain_desc->windowed)
5119         return TRUE;
5120     if (!swapchain_desc->backbuffer_width)
5121         return TRUE;
5122     if (!swapchain_desc->backbuffer_height)
5123         return TRUE;
5124
5125     count = wined3d_get_adapter_mode_count(device->wined3d, device->adapter->ordinal, WINED3DFMT_UNKNOWN);
5126     for (i = 0; i < count; ++i)
5127     {
5128         memset(&m, 0, sizeof(m));
5129         hr = wined3d_enum_adapter_modes(device->wined3d, device->adapter->ordinal, WINED3DFMT_UNKNOWN, i, &m);
5130         if (FAILED(hr))
5131             ERR("Failed to enumerate adapter mode.\n");
5132         if (m.width == swapchain_desc->backbuffer_width && m.height == swapchain_desc->backbuffer_height)
5133             /* Mode found, it is supported. */
5134             return TRUE;
5135     }
5136     /* Mode not found -> not supported */
5137     return FALSE;
5138 }
5139
5140 /* Do not call while under the GL lock. */
5141 static void delete_opengl_contexts(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
5142 {
5143     struct wined3d_resource *resource, *cursor;
5144     const struct wined3d_gl_info *gl_info;
5145     struct wined3d_context *context;
5146     struct wined3d_shader *shader;
5147
5148     context = context_acquire(device, NULL);
5149     gl_info = context->gl_info;
5150
5151     LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5152     {
5153         TRACE("Unloading resource %p.\n", resource);
5154
5155         resource->resource_ops->resource_unload(resource);
5156     }
5157
5158     LIST_FOR_EACH_ENTRY(shader, &device->shaders, struct wined3d_shader, shader_list_entry)
5159     {
5160         device->shader_backend->shader_destroy(shader);
5161     }
5162
5163     ENTER_GL();
5164     if (device->depth_blt_texture)
5165     {
5166         glDeleteTextures(1, &device->depth_blt_texture);
5167         device->depth_blt_texture = 0;
5168     }
5169     if (device->cursorTexture)
5170     {
5171         glDeleteTextures(1, &device->cursorTexture);
5172         device->cursorTexture = 0;
5173     }
5174     LEAVE_GL();
5175
5176     device->blitter->free_private(device);
5177     device->frag_pipe->free_private(device);
5178     device->shader_backend->shader_free_private(device);
5179     destroy_dummy_textures(device, gl_info);
5180
5181     context_release(context);
5182
5183     while (device->context_count)
5184     {
5185         swapchain_destroy_contexts(device->contexts[0]->swapchain);
5186     }
5187
5188     HeapFree(GetProcessHeap(), 0, swapchain->context);
5189     swapchain->context = NULL;
5190 }
5191
5192 /* Do not call while under the GL lock. */
5193 static HRESULT create_primary_opengl_context(struct wined3d_device *device, struct wined3d_swapchain *swapchain)
5194 {
5195     struct wined3d_context *context;
5196     struct wined3d_surface *target;
5197     HRESULT hr;
5198
5199     /* Recreate the primary swapchain's context */
5200     swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(*swapchain->context));
5201     if (!swapchain->context)
5202     {
5203         ERR("Failed to allocate memory for swapchain context array.\n");
5204         return E_OUTOFMEMORY;
5205     }
5206
5207     target = swapchain->back_buffers ? swapchain->back_buffers[0] : swapchain->front_buffer;
5208     if (!(context = context_create(swapchain, target, swapchain->ds_format)))
5209     {
5210         WARN("Failed to create context.\n");
5211         HeapFree(GetProcessHeap(), 0, swapchain->context);
5212         return E_FAIL;
5213     }
5214
5215     swapchain->context[0] = context;
5216     swapchain->num_contexts = 1;
5217     create_dummy_textures(device, context);
5218     context_release(context);
5219
5220     hr = device->shader_backend->shader_alloc_private(device);
5221     if (FAILED(hr))
5222     {
5223         ERR("Failed to allocate shader private data, hr %#x.\n", hr);
5224         goto err;
5225     }
5226
5227     hr = device->frag_pipe->alloc_private(device);
5228     if (FAILED(hr))
5229     {
5230         ERR("Failed to allocate fragment pipe private data, hr %#x.\n", hr);
5231         device->shader_backend->shader_free_private(device);
5232         goto err;
5233     }
5234
5235     hr = device->blitter->alloc_private(device);
5236     if (FAILED(hr))
5237     {
5238         ERR("Failed to allocate blitter private data, hr %#x.\n", hr);
5239         device->frag_pipe->free_private(device);
5240         device->shader_backend->shader_free_private(device);
5241         goto err;
5242     }
5243
5244     return WINED3D_OK;
5245
5246 err:
5247     context_acquire(device, NULL);
5248     destroy_dummy_textures(device, context->gl_info);
5249     context_release(context);
5250     context_destroy(device, context);
5251     HeapFree(GetProcessHeap(), 0, swapchain->context);
5252     swapchain->num_contexts = 0;
5253     return hr;
5254 }
5255
5256 /* Do not call while under the GL lock. */
5257 HRESULT CDECL wined3d_device_reset(struct wined3d_device *device,
5258         const struct wined3d_swapchain_desc *swapchain_desc,
5259         wined3d_device_reset_cb callback)
5260 {
5261     struct wined3d_resource *resource, *cursor;
5262     struct wined3d_swapchain *swapchain;
5263     struct wined3d_display_mode mode;
5264     BOOL DisplayModeChanged = FALSE;
5265     BOOL update_desc = FALSE;
5266     HRESULT hr;
5267
5268     TRACE("device %p, swapchain_desc %p.\n", device, swapchain_desc);
5269
5270     stateblock_unbind_resources(device->stateBlock);
5271
5272     if (device->onscreen_depth_stencil)
5273     {
5274         wined3d_surface_decref(device->onscreen_depth_stencil);
5275         device->onscreen_depth_stencil = NULL;
5276     }
5277
5278     LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &device->resources, struct wined3d_resource, resource_list_entry)
5279     {
5280         TRACE("Enumerating resource %p.\n", resource);
5281         if (FAILED(hr = callback(resource)))
5282             return hr;
5283     }
5284
5285     hr = wined3d_device_get_swapchain(device, 0, &swapchain);
5286     if (FAILED(hr))
5287     {
5288         ERR("Failed to get the first implicit swapchain\n");
5289         return hr;
5290     }
5291
5292     if (!is_display_mode_supported(device, swapchain_desc))
5293     {
5294         WARN("Rejecting reset() call because the requested display mode is not supported.\n");
5295         WARN("Requested mode: %ux%u.\n",
5296                 swapchain_desc->backbuffer_width,
5297                 swapchain_desc->backbuffer_height);
5298         wined3d_swapchain_decref(swapchain);
5299         return WINED3DERR_INVALIDCALL;
5300     }
5301
5302     /* Is it necessary to recreate the gl context? Actually every setting can be changed
5303      * on an existing gl context, so there's no real need for recreation.
5304      *
5305      * TODO: Figure out how Reset influences resources in D3DPOOL_DEFAULT, D3DPOOL_SYSTEMMEMORY and D3DPOOL_MANAGED
5306      *
5307      * TODO: Figure out what happens to explicit swapchains, or if we have more than one implicit swapchain
5308      */
5309     TRACE("New params:\n");
5310     TRACE("backbuffer_width %u\n", swapchain_desc->backbuffer_width);
5311     TRACE("backbuffer_height %u\n", swapchain_desc->backbuffer_height);
5312     TRACE("backbuffer_format %s\n", debug_d3dformat(swapchain_desc->backbuffer_format));
5313     TRACE("backbuffer_count %u\n", swapchain_desc->backbuffer_count);
5314     TRACE("multisample_type %#x\n", swapchain_desc->multisample_type);
5315     TRACE("multisample_quality %u\n", swapchain_desc->multisample_quality);
5316     TRACE("swap_effect %#x\n", swapchain_desc->swap_effect);
5317     TRACE("device_window %p\n", swapchain_desc->device_window);
5318     TRACE("windowed %#x\n", swapchain_desc->windowed);
5319     TRACE("enable_auto_depth_stencil %#x\n", swapchain_desc->enable_auto_depth_stencil);
5320     if (swapchain_desc->enable_auto_depth_stencil)
5321         TRACE("auto_depth_stencil_format %s\n", debug_d3dformat(swapchain_desc->auto_depth_stencil_format));
5322     TRACE("flags %#x\n", swapchain_desc->flags);
5323     TRACE("refresh_rate %u\n", swapchain_desc->refresh_rate);
5324     TRACE("swap_interval %u\n", swapchain_desc->swap_interval);
5325     TRACE("auto_restore_display_mode %#x\n", swapchain_desc->auto_restore_display_mode);
5326
5327     /* No special treatment of these parameters. Just store them */
5328     swapchain->desc.swap_effect = swapchain_desc->swap_effect;
5329     swapchain->desc.flags = swapchain_desc->flags;
5330     swapchain->desc.swap_interval = swapchain_desc->swap_interval;
5331     swapchain->desc.refresh_rate = swapchain_desc->refresh_rate;
5332
5333     /* What to do about these? */
5334     if (swapchain_desc->backbuffer_count
5335             && swapchain_desc->backbuffer_count != swapchain->desc.backbuffer_count)
5336         FIXME("Cannot change the back buffer count yet.\n");
5337
5338     if (swapchain_desc->device_window
5339             && swapchain_desc->device_window != swapchain->desc.device_window)
5340     {
5341         TRACE("Changing the device window from %p to %p.\n",
5342                 swapchain->desc.device_window, swapchain_desc->device_window);
5343         swapchain->desc.device_window = swapchain_desc->device_window;
5344         swapchain->device_window = swapchain_desc->device_window;
5345         wined3d_swapchain_set_window(swapchain, NULL);
5346     }
5347
5348     if (swapchain_desc->enable_auto_depth_stencil && !device->auto_depth_stencil)
5349     {
5350         HRESULT hrc;
5351
5352         TRACE("Creating the depth stencil buffer\n");
5353
5354         hrc = device->device_parent->ops->create_depth_stencil(device->device_parent,
5355                 swapchain_desc->backbuffer_width,
5356                 swapchain_desc->backbuffer_height,
5357                 swapchain_desc->auto_depth_stencil_format,
5358                 swapchain_desc->multisample_type,
5359                 swapchain_desc->multisample_quality,
5360                 FALSE,
5361                 &device->auto_depth_stencil);
5362         if (FAILED(hrc))
5363         {
5364             ERR("Failed to create the depth stencil buffer.\n");
5365             wined3d_swapchain_decref(swapchain);
5366             return WINED3DERR_INVALIDCALL;
5367         }
5368     }
5369
5370     if (device->onscreen_depth_stencil)
5371     {
5372         wined3d_surface_decref(device->onscreen_depth_stencil);
5373         device->onscreen_depth_stencil = NULL;
5374     }
5375
5376     /* Reset the depth stencil */
5377     if (swapchain_desc->enable_auto_depth_stencil)
5378         wined3d_device_set_depth_stencil(device, device->auto_depth_stencil);
5379     else
5380         wined3d_device_set_depth_stencil(device, NULL);
5381
5382     TRACE("Resetting stateblock\n");
5383     wined3d_stateblock_decref(device->updateStateBlock);
5384     wined3d_stateblock_decref(device->stateBlock);
5385
5386     if (swapchain_desc->windowed)
5387     {
5388         mode.width = swapchain->orig_width;
5389         mode.height = swapchain->orig_height;
5390         mode.refresh_rate = 0;
5391         mode.format_id = swapchain->desc.backbuffer_format;
5392     }
5393     else
5394     {
5395         mode.width = swapchain_desc->backbuffer_width;
5396         mode.height = swapchain_desc->backbuffer_height;
5397         mode.refresh_rate = swapchain_desc->refresh_rate;
5398         mode.format_id = swapchain_desc->backbuffer_format;
5399     }
5400
5401     /* Should Width == 800 && Height == 0 set 800x600? */
5402     if (swapchain_desc->backbuffer_width && swapchain_desc->backbuffer_height
5403             && (swapchain_desc->backbuffer_width != swapchain->desc.backbuffer_width
5404             || swapchain_desc->backbuffer_height != swapchain->desc.backbuffer_height))
5405     {
5406         if (!swapchain_desc->windowed)
5407             DisplayModeChanged = TRUE;
5408
5409         swapchain->desc.backbuffer_width = swapchain_desc->backbuffer_width;
5410         swapchain->desc.backbuffer_height = swapchain_desc->backbuffer_height;
5411         update_desc = TRUE;
5412     }
5413
5414     if (swapchain_desc->backbuffer_format != WINED3DFMT_UNKNOWN
5415             && swapchain_desc->backbuffer_format != swapchain->desc.backbuffer_format)
5416     {
5417         swapchain->desc.backbuffer_format = swapchain_desc->backbuffer_format;
5418         update_desc = TRUE;
5419     }
5420
5421     if (swapchain_desc->multisample_type != swapchain->desc.multisample_type
5422             || swapchain_desc->multisample_quality != swapchain->desc.multisample_quality)
5423     {
5424         swapchain->desc.multisample_type = swapchain_desc->multisample_type;
5425         swapchain->desc.multisample_quality = swapchain_desc->multisample_quality;
5426         update_desc = TRUE;
5427     }
5428
5429     if (update_desc)
5430     {
5431         UINT i;
5432
5433         hr = wined3d_surface_update_desc(swapchain->front_buffer, swapchain->desc.backbuffer_width,
5434                 swapchain->desc.backbuffer_height, swapchain->desc.backbuffer_format,
5435                 swapchain->desc.multisample_type, swapchain->desc.multisample_quality);
5436         if (FAILED(hr))
5437         {
5438             wined3d_swapchain_decref(swapchain);
5439             return hr;
5440         }
5441
5442         for (i = 0; i < swapchain->desc.backbuffer_count; ++i)
5443         {
5444             hr = wined3d_surface_update_desc(swapchain->back_buffers[i], swapchain->desc.backbuffer_width,
5445                     swapchain->desc.backbuffer_height, swapchain->desc.backbuffer_format,
5446                     swapchain->desc.multisample_type, swapchain->desc.multisample_quality);
5447             if (FAILED(hr))
5448             {
5449                 wined3d_swapchain_decref(swapchain);
5450                 return hr;
5451             }
5452         }
5453         if (device->auto_depth_stencil)
5454         {
5455             hr = wined3d_surface_update_desc(device->auto_depth_stencil, swapchain->desc.backbuffer_width,
5456                     swapchain->desc.backbuffer_height, device->auto_depth_stencil->resource.format->id,
5457                     swapchain->desc.multisample_type, swapchain->desc.multisample_quality);
5458             if (FAILED(hr))
5459             {
5460                 wined3d_swapchain_decref(swapchain);
5461                 return hr;
5462             }
5463         }
5464     }
5465
5466     if (device->d3d_initialized)
5467         delete_opengl_contexts(device, swapchain);
5468
5469     if (!swapchain_desc->windowed != !swapchain->desc.windowed
5470             || DisplayModeChanged)
5471     {
5472         wined3d_device_set_display_mode(device, 0, &mode);
5473
5474         if (!swapchain_desc->windowed)
5475         {
5476             if (swapchain->desc.windowed)
5477             {
5478                 HWND focus_window = device->create_parms.focus_window;
5479                 if (!focus_window)
5480                     focus_window = swapchain_desc->device_window;
5481                 if (FAILED(hr = wined3d_device_acquire_focus_window(device, focus_window)))
5482                 {
5483                     ERR("Failed to acquire focus window, hr %#x.\n", hr);
5484                     wined3d_swapchain_decref(swapchain);
5485                     return hr;
5486                 }
5487
5488                 /* switch from windowed to fs */
5489                 wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5490                         swapchain_desc->backbuffer_width,
5491                         swapchain_desc->backbuffer_height);
5492             }
5493             else
5494             {
5495                 /* Fullscreen -> fullscreen mode change */
5496                 MoveWindow(swapchain->device_window, 0, 0,
5497                         swapchain_desc->backbuffer_width,
5498                         swapchain_desc->backbuffer_height,
5499                         TRUE);
5500             }
5501         }
5502         else if (!swapchain->desc.windowed)
5503         {
5504             /* Fullscreen -> windowed switch */
5505             wined3d_device_restore_fullscreen_window(device, swapchain->device_window);
5506             wined3d_device_release_focus_window(device);
5507         }
5508         swapchain->desc.windowed = swapchain_desc->windowed;
5509     }
5510     else if (!swapchain_desc->windowed)
5511     {
5512         DWORD style = device->style;
5513         DWORD exStyle = device->exStyle;
5514         /* If we're in fullscreen, and the mode wasn't changed, we have to get the window back into
5515          * the right position. Some applications(Battlefield 2, Guild Wars) move it and then call
5516          * Reset to clear up their mess. Guild Wars also loses the device during that.
5517          */
5518         device->style = 0;
5519         device->exStyle = 0;
5520         wined3d_device_setup_fullscreen_window(device, swapchain->device_window,
5521                 swapchain_desc->backbuffer_width,
5522                 swapchain_desc->backbuffer_height);
5523         device->style = style;
5524         device->exStyle = exStyle;
5525     }
5526
5527     /* Note: No parent needed for initial internal stateblock */
5528     hr = wined3d_stateblock_create(device, WINED3D_SBT_INIT, &device->stateBlock);
5529     if (FAILED(hr))
5530         ERR("Resetting the stateblock failed with error %#x.\n", hr);
5531     else
5532         TRACE("Created stateblock %p.\n", device->stateBlock);
5533     device->updateStateBlock = device->stateBlock;
5534     wined3d_stateblock_incref(device->updateStateBlock);
5535
5536     stateblock_init_default_state(device->stateBlock);
5537
5538     swapchain_update_render_to_fbo(swapchain);
5539     swapchain_update_draw_bindings(swapchain);
5540
5541     if (device->d3d_initialized)
5542         hr = create_primary_opengl_context(device, swapchain);
5543     wined3d_swapchain_decref(swapchain);
5544
5545     /* All done. There is no need to reload resources or shaders, this will happen automatically on the
5546      * first use
5547      */
5548     return hr;
5549 }
5550
5551 HRESULT CDECL wined3d_device_set_dialog_box_mode(struct wined3d_device *device, BOOL enable_dialogs)
5552 {
5553     TRACE("device %p, enable_dialogs %#x.\n", device, enable_dialogs);
5554
5555     if (!enable_dialogs) FIXME("Dialogs cannot be disabled yet.\n");
5556
5557     return WINED3D_OK;
5558 }
5559
5560
5561 HRESULT CDECL wined3d_device_get_creation_parameters(const struct wined3d_device *device,
5562         struct wined3d_device_creation_parameters *parameters)
5563 {
5564     TRACE("device %p, parameters %p.\n", device, parameters);
5565
5566     *parameters = device->create_parms;
5567     return WINED3D_OK;
5568 }
5569
5570 void CDECL wined3d_device_set_gamma_ramp(const struct wined3d_device *device,
5571         UINT swapchain_idx, DWORD flags, const struct wined3d_gamma_ramp *ramp)
5572 {
5573     struct wined3d_swapchain *swapchain;
5574
5575     TRACE("device %p, swapchain_idx %u, flags %#x, ramp %p.\n",
5576             device, swapchain_idx, flags, ramp);
5577
5578     if (SUCCEEDED(wined3d_device_get_swapchain(device, swapchain_idx, &swapchain)))
5579     {
5580         wined3d_swapchain_set_gamma_ramp(swapchain, flags, ramp);
5581         wined3d_swapchain_decref(swapchain);
5582     }
5583 }
5584
5585 void CDECL wined3d_device_get_gamma_ramp(const struct wined3d_device *device,
5586         UINT swapchain_idx, struct wined3d_gamma_ramp *ramp)
5587 {
5588     struct wined3d_swapchain *swapchain;
5589
5590     TRACE("device %p, swapchain_idx %u, ramp %p.\n",
5591             device, swapchain_idx, ramp);
5592
5593     if (SUCCEEDED(wined3d_device_get_swapchain(device, swapchain_idx, &swapchain)))
5594     {
5595         wined3d_swapchain_get_gamma_ramp(swapchain, ramp);
5596         wined3d_swapchain_decref(swapchain);
5597     }
5598 }
5599
5600 void device_resource_add(struct wined3d_device *device, struct wined3d_resource *resource)
5601 {
5602     TRACE("device %p, resource %p.\n", device, resource);
5603
5604     list_add_head(&device->resources, &resource->resource_list_entry);
5605 }
5606
5607 static void device_resource_remove(struct wined3d_device *device, struct wined3d_resource *resource)
5608 {
5609     TRACE("device %p, resource %p.\n", device, resource);
5610
5611     list_remove(&resource->resource_list_entry);
5612 }
5613
5614 void device_resource_released(struct wined3d_device *device, struct wined3d_resource *resource)
5615 {
5616     enum wined3d_resource_type type = resource->type;
5617     unsigned int i;
5618
5619     TRACE("device %p, resource %p, type %s.\n", device, resource, debug_d3dresourcetype(type));
5620
5621     context_resource_released(device, resource, type);
5622
5623     switch (type)
5624     {
5625         case WINED3D_RTYPE_SURFACE:
5626             {
5627                 struct wined3d_surface *surface = surface_from_resource(resource);
5628
5629                 if (!device->d3d_initialized) break;
5630
5631                 for (i = 0; i < device->adapter->gl_info.limits.buffers; ++i)
5632                 {
5633                     if (device->fb.render_targets[i] == surface)
5634                     {
5635                         ERR("Surface %p is still in use as render target %u.\n", surface, i);
5636                         device->fb.render_targets[i] = NULL;
5637                     }
5638                 }
5639
5640                 if (device->fb.depth_stencil == surface)
5641                 {
5642                     ERR("Surface %p is still in use as depth/stencil buffer.\n", surface);
5643                     device->fb.depth_stencil = NULL;
5644                 }
5645             }
5646             break;
5647
5648         case WINED3D_RTYPE_TEXTURE:
5649         case WINED3D_RTYPE_CUBE_TEXTURE:
5650         case WINED3D_RTYPE_VOLUME_TEXTURE:
5651             for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
5652             {
5653                 struct wined3d_texture *texture = wined3d_texture_from_resource(resource);
5654
5655                 if (device->stateBlock && device->stateBlock->state.textures[i] == texture)
5656                 {
5657                     ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
5658                             texture, device->stateBlock, i);
5659                     device->stateBlock->state.textures[i] = NULL;
5660                 }
5661
5662                 if (device->updateStateBlock != device->stateBlock
5663                         && device->updateStateBlock->state.textures[i] == texture)
5664                 {
5665                     ERR("Texture %p is still in use by stateblock %p, stage %u.\n",
5666                             texture, device->updateStateBlock, i);
5667                     device->updateStateBlock->state.textures[i] = NULL;
5668                 }
5669             }
5670             break;
5671
5672         case WINED3D_RTYPE_BUFFER:
5673             {
5674                 struct wined3d_buffer *buffer = buffer_from_resource(resource);
5675
5676                 for (i = 0; i < MAX_STREAMS; ++i)
5677                 {
5678                     if (device->stateBlock && device->stateBlock->state.streams[i].buffer == buffer)
5679                     {
5680                         ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
5681                                 buffer, device->stateBlock, i);
5682                         device->stateBlock->state.streams[i].buffer = NULL;
5683                     }
5684
5685                     if (device->updateStateBlock != device->stateBlock
5686                             && device->updateStateBlock->state.streams[i].buffer == buffer)
5687                     {
5688                         ERR("Buffer %p is still in use by stateblock %p, stream %u.\n",
5689                                 buffer, device->updateStateBlock, i);
5690                         device->updateStateBlock->state.streams[i].buffer = NULL;
5691                     }
5692
5693                 }
5694
5695                 if (device->stateBlock && device->stateBlock->state.index_buffer == buffer)
5696                 {
5697                     ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
5698                             buffer, device->stateBlock);
5699                     device->stateBlock->state.index_buffer =  NULL;
5700                 }
5701
5702                 if (device->updateStateBlock != device->stateBlock
5703                         && device->updateStateBlock->state.index_buffer == buffer)
5704                 {
5705                     ERR("Buffer %p is still in use by stateblock %p as index buffer.\n",
5706                             buffer, device->updateStateBlock);
5707                     device->updateStateBlock->state.index_buffer =  NULL;
5708                 }
5709             }
5710             break;
5711
5712         default:
5713             break;
5714     }
5715
5716     /* Remove the resource from the resourceStore */
5717     device_resource_remove(device, resource);
5718
5719     TRACE("Resource released.\n");
5720 }
5721
5722 HRESULT CDECL wined3d_device_get_surface_from_dc(const struct wined3d_device *device,
5723         HDC dc, struct wined3d_surface **surface)
5724 {
5725     struct wined3d_resource *resource;
5726
5727     TRACE("device %p, dc %p, surface %p.\n", device, dc, surface);
5728
5729     if (!dc)
5730         return WINED3DERR_INVALIDCALL;
5731
5732     LIST_FOR_EACH_ENTRY(resource, &device->resources, struct wined3d_resource, resource_list_entry)
5733     {
5734         if (resource->type == WINED3D_RTYPE_SURFACE)
5735         {
5736             struct wined3d_surface *s = surface_from_resource(resource);
5737
5738             if (s->hDC == dc)
5739             {
5740                 TRACE("Found surface %p for dc %p.\n", s, dc);
5741                 *surface = s;
5742                 return WINED3D_OK;
5743             }
5744         }
5745     }
5746
5747     return WINED3DERR_INVALIDCALL;
5748 }
5749
5750 HRESULT device_init(struct wined3d_device *device, struct wined3d *wined3d,
5751         UINT adapter_idx, enum wined3d_device_type device_type, HWND focus_window, DWORD flags,
5752         BYTE surface_alignment, struct wined3d_device_parent *device_parent)
5753 {
5754     struct wined3d_adapter *adapter = &wined3d->adapters[adapter_idx];
5755     const struct fragment_pipeline *fragment_pipeline;
5756     struct wined3d_display_mode mode;
5757     struct shader_caps shader_caps;
5758     struct fragment_caps ffp_caps;
5759     unsigned int i;
5760     HRESULT hr;
5761
5762     device->ref = 1;
5763     device->wined3d = wined3d;
5764     wined3d_incref(device->wined3d);
5765     device->adapter = wined3d->adapter_count ? adapter : NULL;
5766     device->device_parent = device_parent;
5767     list_init(&device->resources);
5768     list_init(&device->shaders);
5769     device->surface_alignment = surface_alignment;
5770
5771     /* Get the initial screen setup for ddraw. */
5772     hr = wined3d_get_adapter_display_mode(wined3d, adapter_idx, &mode);
5773     if (FAILED(hr))
5774     {
5775         ERR("Failed to get the adapter's display mode, hr %#x.\n", hr);
5776         wined3d_decref(device->wined3d);
5777         return hr;
5778     }
5779     adapter->screen_size.cx = mode.width;
5780     adapter->screen_size.cy = mode.height;
5781     adapter->screen_format = mode.format_id;
5782
5783     /* Save the creation parameters. */
5784     device->create_parms.adapter_idx = adapter_idx;
5785     device->create_parms.device_type = device_type;
5786     device->create_parms.focus_window = focus_window;
5787     device->create_parms.flags = flags;
5788
5789     for (i = 0; i < PATCHMAP_SIZE; ++i) list_init(&device->patches[i]);
5790
5791     select_shader_mode(&adapter->gl_info, &device->ps_selected_mode, &device->vs_selected_mode);
5792     device->shader_backend = adapter->shader_backend;
5793
5794     if (device->shader_backend)
5795     {
5796         device->shader_backend->shader_get_caps(&adapter->gl_info, &shader_caps);
5797         device->vshader_version = shader_caps.VertexShaderVersion;
5798         device->pshader_version = shader_caps.PixelShaderVersion;
5799         device->d3d_vshader_constantF = shader_caps.MaxVertexShaderConst;
5800         device->d3d_pshader_constantF = shader_caps.MaxPixelShaderConst;
5801         device->vs_clipping = shader_caps.VSClipping;
5802     }
5803     fragment_pipeline = adapter->fragment_pipe;
5804     device->frag_pipe = fragment_pipeline;
5805     if (fragment_pipeline)
5806     {
5807         fragment_pipeline->get_caps(&adapter->gl_info, &ffp_caps);
5808         device->max_ffp_textures = ffp_caps.MaxSimultaneousTextures;
5809
5810         hr = compile_state_table(device->StateTable, device->multistate_funcs, &adapter->gl_info,
5811                                  ffp_vertexstate_template, fragment_pipeline, misc_state_template);
5812         if (FAILED(hr))
5813         {
5814             ERR("Failed to compile state table, hr %#x.\n", hr);
5815             wined3d_decref(device->wined3d);
5816             return hr;
5817         }
5818     }
5819     device->blitter = adapter->blitter;
5820
5821     hr = wined3d_stateblock_create(device, WINED3D_SBT_INIT, &device->stateBlock);
5822     if (FAILED(hr))
5823     {
5824         WARN("Failed to create stateblock.\n");
5825         for (i = 0; i < sizeof(device->multistate_funcs) / sizeof(device->multistate_funcs[0]); ++i)
5826         {
5827             HeapFree(GetProcessHeap(), 0, device->multistate_funcs[i]);
5828         }
5829         wined3d_decref(device->wined3d);
5830         return hr;
5831     }
5832
5833     TRACE("Created stateblock %p.\n", device->stateBlock);
5834     device->updateStateBlock = device->stateBlock;
5835     wined3d_stateblock_incref(device->updateStateBlock);
5836
5837     return WINED3D_OK;
5838 }
5839
5840
5841 void device_invalidate_state(const struct wined3d_device *device, DWORD state)
5842 {
5843     DWORD rep = device->StateTable[state].representative;
5844     struct wined3d_context *context;
5845     DWORD idx;
5846     BYTE shift;
5847     UINT i;
5848
5849     for (i = 0; i < device->context_count; ++i)
5850     {
5851         context = device->contexts[i];
5852         if(isStateDirty(context, rep)) continue;
5853
5854         context->dirtyArray[context->numDirtyEntries++] = rep;
5855         idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
5856         shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
5857         context->isStateDirty[idx] |= (1 << shift);
5858     }
5859 }
5860
5861 void get_drawable_size_fbo(const struct wined3d_context *context, UINT *width, UINT *height)
5862 {
5863     /* The drawable size of a fbo target is the opengl texture size, which is the power of two size. */
5864     *width = context->current_rt->pow2Width;
5865     *height = context->current_rt->pow2Height;
5866 }
5867
5868 void get_drawable_size_backbuffer(const struct wined3d_context *context, UINT *width, UINT *height)
5869 {
5870     const struct wined3d_swapchain *swapchain = context->swapchain;
5871     /* The drawable size of a backbuffer / aux buffer offscreen target is the size of the
5872      * current context's drawable, which is the size of the back buffer of the swapchain
5873      * the active context belongs to. */
5874     *width = swapchain->desc.backbuffer_width;
5875     *height = swapchain->desc.backbuffer_height;
5876 }
5877
5878 LRESULT device_process_message(struct wined3d_device *device, HWND window, BOOL unicode,
5879         UINT message, WPARAM wparam, LPARAM lparam, WNDPROC proc)
5880 {
5881     if (device->filter_messages)
5882     {
5883         TRACE("Filtering message: window %p, message %#x, wparam %#lx, lparam %#lx.\n",
5884                 window, message, wparam, lparam);
5885         if (unicode)
5886             return DefWindowProcW(window, message, wparam, lparam);
5887         else
5888             return DefWindowProcA(window, message, wparam, lparam);
5889     }
5890
5891     if (message == WM_DESTROY)
5892     {
5893         TRACE("unregister window %p.\n", window);
5894         wined3d_unregister_window(window);
5895
5896         if (InterlockedCompareExchangePointer((void **)&device->focus_window, NULL, window) != window)
5897             ERR("Window %p is not the focus window for device %p.\n", window, device);
5898     }
5899     else if (message == WM_DISPLAYCHANGE)
5900     {
5901         device->device_parent->ops->mode_changed(device->device_parent);
5902     }
5903
5904     if (unicode)
5905         return CallWindowProcW(proc, window, message, wparam, lparam);
5906     else
5907         return CallWindowProcA(proc, window, message, wparam, lparam);
5908 }