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