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