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