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