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