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