shell32: Replaced drive.ico with a Tango compliant icon.
[wine.git] / dlls / wined3d / device.c
blob6cd2831ef45e856b60376f8abe23dd820ce077c7
1 /*
2 * IWineD3DDevice implementation
4 * Copyright 2002 Lionel Ulmer
5 * Copyright 2002-2005 Jason Edmeades
6 * Copyright 2003-2004 Raphael Junqueira
7 * Copyright 2004 Christian Costa
8 * Copyright 2005 Oliver Stieber
9 * Copyright 2006-2008 Stefan Dösinger for CodeWeavers
10 * Copyright 2006-2008 Henri Verbeet
11 * Copyright 2007 Andrew Riedi
12 * Copyright 2009 Henri Verbeet for CodeWeavers
14 * This library is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Lesser General Public
16 * License as published by the Free Software Foundation; either
17 * version 2.1 of the License, or (at your option) any later version.
19 * This library is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 * Lesser General Public License for more details.
24 * You should have received a copy of the GNU Lesser General Public
25 * License along with this library; if not, write to the Free Software
26 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
29 #include "config.h"
30 #include <stdio.h>
31 #ifdef HAVE_FLOAT_H
32 # include <float.h>
33 #endif
34 #include "wined3d_private.h"
36 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
37 #define GLINFO_LOCATION This->adapter->gl_info
39 /* Define the default light parameters as specified by MSDN */
40 const WINED3DLIGHT WINED3D_default_light = {
42 WINED3DLIGHT_DIRECTIONAL, /* Type */
43 { 1.0f, 1.0f, 1.0f, 0.0f }, /* Diffuse r,g,b,a */
44 { 0.0f, 0.0f, 0.0f, 0.0f }, /* Specular r,g,b,a */
45 { 0.0f, 0.0f, 0.0f, 0.0f }, /* Ambient r,g,b,a, */
46 { 0.0f, 0.0f, 0.0f }, /* Position x,y,z */
47 { 0.0f, 0.0f, 1.0f }, /* Direction x,y,z */
48 0.0f, /* Range */
49 0.0f, /* Falloff */
50 0.0f, 0.0f, 0.0f, /* Attenuation 0,1,2 */
51 0.0f, /* Theta */
52 0.0f /* Phi */
55 /**********************************************************
56 * Global variable / Constants follow
57 **********************************************************/
58 const float identity[] =
60 1.0f, 0.0f, 0.0f, 0.0f,
61 0.0f, 1.0f, 0.0f, 0.0f,
62 0.0f, 0.0f, 1.0f, 0.0f,
63 0.0f, 0.0f, 0.0f, 1.0f,
64 }; /* When needed for comparisons */
66 /* Note that except for WINED3DPT_POINTLIST and WINED3DPT_LINELIST these
67 * actually have the same values in GL and D3D. */
68 static GLenum gl_primitive_type_from_d3d(WINED3DPRIMITIVETYPE primitive_type)
70 switch(primitive_type)
72 case WINED3DPT_POINTLIST:
73 return GL_POINTS;
75 case WINED3DPT_LINELIST:
76 return GL_LINES;
78 case WINED3DPT_LINESTRIP:
79 return GL_LINE_STRIP;
81 case WINED3DPT_TRIANGLELIST:
82 return GL_TRIANGLES;
84 case WINED3DPT_TRIANGLESTRIP:
85 return GL_TRIANGLE_STRIP;
87 case WINED3DPT_TRIANGLEFAN:
88 return GL_TRIANGLE_FAN;
90 case WINED3DPT_LINELIST_ADJ:
91 return GL_LINES_ADJACENCY_ARB;
93 case WINED3DPT_LINESTRIP_ADJ:
94 return GL_LINE_STRIP_ADJACENCY_ARB;
96 case WINED3DPT_TRIANGLELIST_ADJ:
97 return GL_TRIANGLES_ADJACENCY_ARB;
99 case WINED3DPT_TRIANGLESTRIP_ADJ:
100 return GL_TRIANGLE_STRIP_ADJACENCY_ARB;
102 default:
103 FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
104 return GL_NONE;
108 static WINED3DPRIMITIVETYPE d3d_primitive_type_from_gl(GLenum primitive_type)
110 switch(primitive_type)
112 case GL_POINTS:
113 return WINED3DPT_POINTLIST;
115 case GL_LINES:
116 return WINED3DPT_LINELIST;
118 case GL_LINE_STRIP:
119 return WINED3DPT_LINESTRIP;
121 case GL_TRIANGLES:
122 return WINED3DPT_TRIANGLELIST;
124 case GL_TRIANGLE_STRIP:
125 return WINED3DPT_TRIANGLESTRIP;
127 case GL_TRIANGLE_FAN:
128 return WINED3DPT_TRIANGLEFAN;
130 case GL_LINES_ADJACENCY_ARB:
131 return WINED3DPT_LINELIST_ADJ;
133 case GL_LINE_STRIP_ADJACENCY_ARB:
134 return WINED3DPT_LINESTRIP_ADJ;
136 case GL_TRIANGLES_ADJACENCY_ARB:
137 return WINED3DPT_TRIANGLELIST_ADJ;
139 case GL_TRIANGLE_STRIP_ADJACENCY_ARB:
140 return WINED3DPT_TRIANGLESTRIP_ADJ;
142 default:
143 FIXME("Unhandled primitive type %s\n", debug_d3dprimitivetype(primitive_type));
144 return WINED3DPT_UNDEFINED;
148 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
150 if ((usage == WINED3DDECLUSAGE_POSITION || usage == WINED3DDECLUSAGE_POSITIONT) && usage_idx == 0)
151 *regnum = WINED3D_FFP_POSITION;
152 else if (usage == WINED3DDECLUSAGE_BLENDWEIGHT && usage_idx == 0)
153 *regnum = WINED3D_FFP_BLENDWEIGHT;
154 else if (usage == WINED3DDECLUSAGE_BLENDINDICES && usage_idx == 0)
155 *regnum = WINED3D_FFP_BLENDINDICES;
156 else if (usage == WINED3DDECLUSAGE_NORMAL && usage_idx == 0)
157 *regnum = WINED3D_FFP_NORMAL;
158 else if (usage == WINED3DDECLUSAGE_PSIZE && usage_idx == 0)
159 *regnum = WINED3D_FFP_PSIZE;
160 else if (usage == WINED3DDECLUSAGE_COLOR && usage_idx == 0)
161 *regnum = WINED3D_FFP_DIFFUSE;
162 else if (usage == WINED3DDECLUSAGE_COLOR && usage_idx == 1)
163 *regnum = WINED3D_FFP_SPECULAR;
164 else if (usage == WINED3DDECLUSAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
165 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
166 else
168 FIXME("Unsupported input stream [usage=%s, usage_idx=%u]\n", debug_d3ddeclusage(usage), usage_idx);
169 *regnum = ~0U;
170 return FALSE;
173 return TRUE;
176 /* Context activation is done by the caller. */
177 void device_stream_info_from_declaration(IWineD3DDeviceImpl *This,
178 BOOL use_vshader, struct wined3d_stream_info *stream_info, BOOL *fixup)
180 /* We need to deal with frequency data! */
181 IWineD3DVertexDeclarationImpl *declaration = (IWineD3DVertexDeclarationImpl *)This->stateBlock->vertexDecl;
182 unsigned int i;
184 stream_info->use_map = 0;
185 stream_info->swizzle_map = 0;
187 /* Check for transformed vertices, disable vertex shader if present. */
188 stream_info->position_transformed = declaration->position_transformed;
189 if (declaration->position_transformed) use_vshader = FALSE;
191 /* Translate the declaration into strided data. */
192 for (i = 0; i < declaration->element_count; ++i)
194 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
195 GLuint buffer_object = 0;
196 const BYTE *data = NULL;
197 BOOL stride_used;
198 unsigned int idx;
199 DWORD stride;
201 TRACE("%p Element %p (%u of %u)\n", declaration->elements,
202 element, i + 1, declaration->element_count);
204 if (!This->stateBlock->streamSource[element->input_slot]) continue;
206 stride = This->stateBlock->streamStride[element->input_slot];
207 if (This->stateBlock->streamIsUP)
209 TRACE("Stream %u is UP, %p\n", element->input_slot, This->stateBlock->streamSource[element->input_slot]);
210 buffer_object = 0;
211 data = (BYTE *)This->stateBlock->streamSource[element->input_slot];
213 else
215 TRACE("Stream %u isn't UP, %p\n", element->input_slot, This->stateBlock->streamSource[element->input_slot]);
216 data = buffer_get_memory(This->stateBlock->streamSource[element->input_slot], &buffer_object);
218 /* Can't use vbo's if the base vertex index is negative. OpenGL doesn't accept negative offsets
219 * (or rather offsets bigger than the vbo, because the pointer is unsigned), so use system memory
220 * sources. In most sane cases the pointer - offset will still be > 0, otherwise it will wrap
221 * around to some big value. Hope that with the indices, the driver wraps it back internally. If
222 * not, drawStridedSlow is needed, including a vertex buffer path. */
223 if (This->stateBlock->loadBaseVertexIndex < 0)
225 WARN("loadBaseVertexIndex is < 0 (%d), not using vbos\n", This->stateBlock->loadBaseVertexIndex);
226 buffer_object = 0;
227 data = buffer_get_sysmem((struct wined3d_buffer *)This->stateBlock->streamSource[element->input_slot]);
228 if ((UINT_PTR)data < -This->stateBlock->loadBaseVertexIndex * stride)
230 FIXME("System memory vertex data load offset is negative!\n");
234 if (fixup)
236 if (buffer_object) *fixup = TRUE;
237 else if (*fixup && !use_vshader
238 && (element->usage == WINED3DDECLUSAGE_COLOR
239 || element->usage == WINED3DDECLUSAGE_POSITIONT))
241 static BOOL warned = FALSE;
242 if (!warned)
244 /* This may be bad with the fixed function pipeline. */
245 FIXME("Missing vbo streams with unfixed colors or transformed position, expect problems\n");
246 warned = TRUE;
251 data += element->offset;
253 TRACE("offset %u input_slot %u usage_idx %d\n", element->offset, element->input_slot, element->usage_idx);
255 if (use_vshader)
257 if (element->output_slot == ~0U)
259 /* TODO: Assuming vertexdeclarations are usually used with the
260 * same or a similar shader, it might be worth it to store the
261 * last used output slot and try that one first. */
262 stride_used = vshader_get_input(This->stateBlock->vertexShader,
263 element->usage, element->usage_idx, &idx);
265 else
267 idx = element->output_slot;
268 stride_used = TRUE;
271 else
273 if (!element->ffp_valid)
275 WARN("Skipping unsupported fixed function element of format %s and usage %s\n",
276 debug_d3dformat(element->format_desc->format), debug_d3ddeclusage(element->usage));
277 stride_used = FALSE;
279 else
281 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
285 if (stride_used)
287 TRACE("Load %s array %u [usage %s, usage_idx %u, "
288 "input_slot %u, offset %u, stride %u, format %s, buffer_object %u]\n",
289 use_vshader ? "shader": "fixed function", idx,
290 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
291 element->offset, stride, debug_d3dformat(element->format_desc->format), buffer_object);
293 stream_info->elements[idx].format_desc = element->format_desc;
294 stream_info->elements[idx].stride = stride;
295 stream_info->elements[idx].data = data;
296 stream_info->elements[idx].stream_idx = element->input_slot;
297 stream_info->elements[idx].buffer_object = buffer_object;
299 if (!This->adapter->gl_info.supported[ARB_VERTEX_ARRAY_BGRA]
300 && element->format_desc->format == WINED3DFMT_B8G8R8A8_UNORM)
302 stream_info->swizzle_map |= 1 << idx;
304 stream_info->use_map |= 1 << idx;
308 This->num_buffer_queries = 0;
309 if (!This->stateBlock->streamIsUP)
311 WORD map = stream_info->use_map;
313 /* PreLoad all the vertex buffers. */
314 for (i = 0; map; map >>= 1, ++i)
316 struct wined3d_stream_info_element *element;
317 struct wined3d_buffer *buffer;
318 struct wined3d_event_query *query;
320 if (!(map & 1)) continue;
322 element = &stream_info->elements[i];
323 buffer = (struct wined3d_buffer *)This->stateBlock->streamSource[element->stream_idx];
324 IWineD3DBuffer_PreLoad((IWineD3DBuffer *)buffer);
326 /* If PreLoad dropped the buffer object, update the stream info. */
327 if (buffer->buffer_object != element->buffer_object)
329 element->buffer_object = 0;
330 element->data = buffer_get_sysmem(buffer) + (ptrdiff_t)element->data;
333 query = ((struct wined3d_buffer *) buffer)->query;
334 if(query)
336 This->buffer_queries[This->num_buffer_queries++] = query;
342 static void stream_info_element_from_strided(const struct wined3d_gl_info *gl_info,
343 const struct WineDirect3DStridedData *strided, struct wined3d_stream_info_element *e)
345 const struct wined3d_format_desc *format_desc = getFormatDescEntry(strided->format, gl_info);
346 e->format_desc = format_desc;
347 e->stride = strided->dwStride;
348 e->data = strided->lpData;
349 e->stream_idx = 0;
350 e->buffer_object = 0;
353 static void device_stream_info_from_strided(const struct wined3d_gl_info *gl_info,
354 const struct WineDirect3DVertexStridedData *strided, struct wined3d_stream_info *stream_info)
356 unsigned int i;
358 memset(stream_info, 0, sizeof(*stream_info));
360 if (strided->position.lpData)
361 stream_info_element_from_strided(gl_info, &strided->position, &stream_info->elements[WINED3D_FFP_POSITION]);
362 if (strided->normal.lpData)
363 stream_info_element_from_strided(gl_info, &strided->normal, &stream_info->elements[WINED3D_FFP_NORMAL]);
364 if (strided->diffuse.lpData)
365 stream_info_element_from_strided(gl_info, &strided->diffuse, &stream_info->elements[WINED3D_FFP_DIFFUSE]);
366 if (strided->specular.lpData)
367 stream_info_element_from_strided(gl_info, &strided->specular, &stream_info->elements[WINED3D_FFP_SPECULAR]);
369 for (i = 0; i < WINED3DDP_MAXTEXCOORD; ++i)
371 if (strided->texCoords[i].lpData)
372 stream_info_element_from_strided(gl_info, &strided->texCoords[i],
373 &stream_info->elements[WINED3D_FFP_TEXCOORD0 + i]);
376 stream_info->position_transformed = strided->position_transformed;
378 for (i = 0; i < sizeof(stream_info->elements) / sizeof(*stream_info->elements); ++i)
380 if (!stream_info->elements[i].format_desc) continue;
382 if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
383 && stream_info->elements[i].format_desc->format == WINED3DFMT_B8G8R8A8_UNORM)
385 stream_info->swizzle_map |= 1 << i;
387 stream_info->use_map |= 1 << i;
391 static void device_trace_strided_stream_info(const struct wined3d_stream_info *stream_info)
393 TRACE("Strided Data:\n");
394 TRACE_STRIDED(stream_info, WINED3D_FFP_POSITION);
395 TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDWEIGHT);
396 TRACE_STRIDED(stream_info, WINED3D_FFP_BLENDINDICES);
397 TRACE_STRIDED(stream_info, WINED3D_FFP_NORMAL);
398 TRACE_STRIDED(stream_info, WINED3D_FFP_PSIZE);
399 TRACE_STRIDED(stream_info, WINED3D_FFP_DIFFUSE);
400 TRACE_STRIDED(stream_info, WINED3D_FFP_SPECULAR);
401 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD0);
402 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD1);
403 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD2);
404 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD3);
405 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD4);
406 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD5);
407 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD6);
408 TRACE_STRIDED(stream_info, WINED3D_FFP_TEXCOORD7);
411 /* Context activation is done by the caller. */
412 void device_update_stream_info(IWineD3DDeviceImpl *device, const struct wined3d_gl_info *gl_info)
414 struct wined3d_stream_info *stream_info = &device->strided_streams;
415 IWineD3DStateBlockImpl *stateblock = device->stateBlock;
416 BOOL vs = stateblock->vertexShader && device->vs_selected_mode != SHADER_NONE;
417 BOOL fixup = FALSE;
419 if (device->up_strided)
421 /* Note: this is a ddraw fixed-function code path. */
422 TRACE("=============================== Strided Input ================================\n");
423 device_stream_info_from_strided(gl_info, device->up_strided, stream_info);
424 if (TRACE_ON(d3d)) device_trace_strided_stream_info(stream_info);
426 else
428 TRACE("============================= Vertex Declaration =============================\n");
429 device_stream_info_from_declaration(device, vs, stream_info, &fixup);
432 if (vs && !stream_info->position_transformed)
434 if (((IWineD3DVertexDeclarationImpl *)stateblock->vertexDecl)->half_float_conv_needed && !fixup)
436 TRACE("Using drawStridedSlow with vertex shaders for FLOAT16 conversion.\n");
437 device->useDrawStridedSlow = TRUE;
439 else
441 device->useDrawStridedSlow = FALSE;
444 else
446 WORD slow_mask = (1 << WINED3D_FFP_PSIZE);
447 slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
448 & ((1 << WINED3D_FFP_DIFFUSE) | (1 << WINED3D_FFP_SPECULAR));
450 if ((stream_info->position_transformed || (stream_info->use_map & slow_mask)) && !fixup)
452 device->useDrawStridedSlow = TRUE;
454 else
456 device->useDrawStridedSlow = FALSE;
461 static void device_preload_texture(IWineD3DStateBlockImpl *stateblock, unsigned int idx)
463 IWineD3DBaseTextureImpl *texture;
464 enum WINED3DSRGB srgb;
466 if (!(texture = (IWineD3DBaseTextureImpl *)stateblock->textures[idx])) return;
467 srgb = stateblock->samplerState[idx][WINED3DSAMP_SRGBTEXTURE] ? SRGB_SRGB : SRGB_RGB;
468 texture->baseTexture.internal_preload((IWineD3DBaseTexture *)texture, srgb);
471 void device_preload_textures(IWineD3DDeviceImpl *device)
473 IWineD3DStateBlockImpl *stateblock = device->stateBlock;
474 unsigned int i;
476 if (use_vs(stateblock))
478 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
480 if (((IWineD3DBaseShaderImpl *)stateblock->vertexShader)->baseShader.reg_maps.sampler_type[i])
481 device_preload_texture(stateblock, MAX_FRAGMENT_SAMPLERS + i);
485 if (use_ps(stateblock))
487 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
489 if (((IWineD3DBaseShaderImpl *)stateblock->pixelShader)->baseShader.reg_maps.sampler_type[i])
490 device_preload_texture(stateblock, i);
493 else
495 WORD ffu_map = device->fixed_function_usage_map;
497 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
499 if (ffu_map & 1)
500 device_preload_texture(stateblock, i);
505 BOOL device_context_add(IWineD3DDeviceImpl *device, struct wined3d_context *context)
507 struct wined3d_context **new_array;
509 TRACE("Adding context %p.\n", context);
511 if (!device->contexts) new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_array));
512 else new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts, sizeof(*new_array) * (device->numContexts + 1));
514 if (!new_array)
516 ERR("Failed to grow the context array.\n");
517 return FALSE;
520 new_array[device->numContexts++] = context;
521 device->contexts = new_array;
522 return TRUE;
525 void device_context_remove(IWineD3DDeviceImpl *device, struct wined3d_context *context)
527 struct wined3d_context **new_array;
528 BOOL found = FALSE;
529 UINT i;
531 TRACE("Removing context %p.\n", context);
533 for (i = 0; i < device->numContexts; ++i)
535 if (device->contexts[i] == context)
537 found = TRUE;
538 break;
542 if (!found)
544 ERR("Context %p doesn't exist in context array.\n", context);
545 return;
548 if (!--device->numContexts)
550 HeapFree(GetProcessHeap(), 0, device->contexts);
551 device->contexts = NULL;
552 return;
555 memmove(&device->contexts[i], &device->contexts[i + 1], (device->numContexts - i) * sizeof(*device->contexts));
556 new_array = HeapReAlloc(GetProcessHeap(), 0, device->contexts, device->numContexts * sizeof(*device->contexts));
557 if (!new_array)
559 ERR("Failed to shrink context array. Oh well.\n");
560 return;
563 device->contexts = new_array;
567 /**********************************************************
568 * IUnknown parts follows
569 **********************************************************/
571 static HRESULT WINAPI IWineD3DDeviceImpl_QueryInterface(IWineD3DDevice *iface,REFIID riid,LPVOID *ppobj)
573 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
575 TRACE("(%p)->(%s,%p)\n",This,debugstr_guid(riid),ppobj);
576 if (IsEqualGUID(riid, &IID_IUnknown)
577 || IsEqualGUID(riid, &IID_IWineD3DBase)
578 || IsEqualGUID(riid, &IID_IWineD3DDevice)) {
579 IUnknown_AddRef(iface);
580 *ppobj = This;
581 return S_OK;
583 *ppobj = NULL;
584 return E_NOINTERFACE;
587 static ULONG WINAPI IWineD3DDeviceImpl_AddRef(IWineD3DDevice *iface) {
588 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
589 ULONG refCount = InterlockedIncrement(&This->ref);
591 TRACE("(%p) : AddRef increasing from %d\n", This, refCount - 1);
592 return refCount;
595 static ULONG WINAPI IWineD3DDeviceImpl_Release(IWineD3DDevice *iface) {
596 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
597 ULONG refCount = InterlockedDecrement(&This->ref);
599 TRACE("(%p) : Releasing from %d\n", This, refCount + 1);
601 if (!refCount) {
602 UINT i;
604 for (i = 0; i < sizeof(This->multistate_funcs)/sizeof(This->multistate_funcs[0]); ++i) {
605 HeapFree(GetProcessHeap(), 0, This->multistate_funcs[i]);
606 This->multistate_funcs[i] = NULL;
609 /* TODO: Clean up all the surfaces and textures! */
610 /* NOTE: You must release the parent if the object was created via a callback
611 ** ***************************/
613 if (!list_empty(&This->resources))
615 IWineD3DResourceImpl *resource;
616 FIXME("(%p) Device released with resources still bound, acceptable but unexpected\n", This);
618 LIST_FOR_EACH_ENTRY(resource, &This->resources, IWineD3DResourceImpl, resource.resource_list_entry)
620 WINED3DRESOURCETYPE type = IWineD3DResource_GetType((IWineD3DResource *)resource);
621 FIXME("Leftover resource %p with type %s (%#x).\n",
622 resource, debug_d3dresourcetype(type), type);
626 if(This->contexts) ERR("Context array not freed!\n");
627 if (This->hardwareCursor) DestroyCursor(This->hardwareCursor);
628 This->haveHardwareCursor = FALSE;
630 IWineD3D_Release(This->wined3d);
631 This->wined3d = NULL;
632 HeapFree(GetProcessHeap(), 0, This);
633 TRACE("Freed device %p\n", This);
634 This = NULL;
636 return refCount;
639 /**********************************************************
640 * IWineD3DDevice implementation follows
641 **********************************************************/
642 static HRESULT WINAPI IWineD3DDeviceImpl_GetParent(IWineD3DDevice *iface, IUnknown **pParent) {
643 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
644 *pParent = This->parent;
645 IUnknown_AddRef(This->parent);
646 return WINED3D_OK;
649 static HRESULT WINAPI IWineD3DDeviceImpl_CreateBuffer(IWineD3DDevice *iface, struct wined3d_buffer_desc *desc,
650 const void *data, IUnknown *parent, const struct wined3d_parent_ops *parent_ops, IWineD3DBuffer **buffer)
652 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
653 struct wined3d_buffer *object;
654 HRESULT hr;
656 TRACE("iface %p, desc %p, data %p, parent %p, buffer %p\n", iface, desc, data, parent, buffer);
658 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
659 if (!object)
661 ERR("Failed to allocate memory\n");
662 return E_OUTOFMEMORY;
665 FIXME("Ignoring access flags (pool)\n");
667 hr = buffer_init(object, This, desc->byte_width, desc->usage, WINED3DFMT_UNKNOWN,
668 WINED3DPOOL_MANAGED, GL_ARRAY_BUFFER_ARB, data, parent, parent_ops);
669 if (FAILED(hr))
671 WARN("Failed to initialize buffer, hr %#x.\n", hr);
672 HeapFree(GetProcessHeap(), 0, object);
673 return hr;
675 object->desc = *desc;
677 TRACE("Created buffer %p.\n", object);
679 *buffer = (IWineD3DBuffer *)object;
681 return WINED3D_OK;
684 static HRESULT WINAPI IWineD3DDeviceImpl_CreateVertexBuffer(IWineD3DDevice *iface,
685 UINT Size, DWORD Usage, WINED3DPOOL Pool, IWineD3DBuffer **ppVertexBuffer,
686 IUnknown *parent, const struct wined3d_parent_ops *parent_ops)
688 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
689 struct wined3d_buffer *object;
690 HRESULT hr;
692 TRACE("iface %p, size %u, usage %#x, pool %#x, buffer %p, parent %p, parent_ops %p.\n",
693 iface, Size, Usage, Pool, ppVertexBuffer, parent, parent_ops);
695 if (Pool == WINED3DPOOL_SCRATCH)
697 /* The d3d9 testsuit shows that this is not allowed. It doesn't make much sense
698 * anyway, SCRATCH vertex buffers aren't usable anywhere
700 WARN("Vertex buffer in D3DPOOL_SCRATCH requested, returning WINED3DERR_INVALIDCALL\n");
701 *ppVertexBuffer = NULL;
702 return WINED3DERR_INVALIDCALL;
705 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
706 if (!object)
708 ERR("Out of memory\n");
709 *ppVertexBuffer = NULL;
710 return WINED3DERR_OUTOFVIDEOMEMORY;
713 hr = buffer_init(object, This, Size, Usage, WINED3DFMT_VERTEXDATA,
714 Pool, GL_ARRAY_BUFFER_ARB, NULL, parent, parent_ops);
715 if (FAILED(hr))
717 WARN("Failed to initialize buffer, hr %#x.\n", hr);
718 HeapFree(GetProcessHeap(), 0, object);
719 return hr;
722 TRACE("Created buffer %p.\n", object);
723 *ppVertexBuffer = (IWineD3DBuffer *)object;
725 return WINED3D_OK;
728 static HRESULT WINAPI IWineD3DDeviceImpl_CreateIndexBuffer(IWineD3DDevice *iface,
729 UINT Length, DWORD Usage, WINED3DPOOL Pool, IWineD3DBuffer **ppIndexBuffer,
730 IUnknown *parent, const struct wined3d_parent_ops *parent_ops)
732 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
733 struct wined3d_buffer *object;
734 HRESULT hr;
736 TRACE("(%p) Creating index buffer\n", This);
738 /* Allocate the storage for the device */
739 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
740 if (!object)
742 ERR("Out of memory\n");
743 *ppIndexBuffer = NULL;
744 return WINED3DERR_OUTOFVIDEOMEMORY;
747 hr = buffer_init(object, This, Length, Usage | WINED3DUSAGE_STATICDECL,
748 WINED3DFMT_UNKNOWN, Pool, GL_ELEMENT_ARRAY_BUFFER_ARB, NULL,
749 parent, parent_ops);
750 if (FAILED(hr))
752 WARN("Failed to initialize buffer, hr %#x\n", hr);
753 HeapFree(GetProcessHeap(), 0, object);
754 return hr;
757 TRACE("Created buffer %p.\n", object);
759 *ppIndexBuffer = (IWineD3DBuffer *) object;
761 return WINED3D_OK;
764 static HRESULT WINAPI IWineD3DDeviceImpl_CreateStateBlock(IWineD3DDevice *iface,
765 WINED3DSTATEBLOCKTYPE type, IWineD3DStateBlock **stateblock, IUnknown *parent)
767 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
768 IWineD3DStateBlockImpl *object;
769 HRESULT hr;
771 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
772 if(!object)
774 ERR("Failed to allocate stateblock memory.\n");
775 return E_OUTOFMEMORY;
778 hr = stateblock_init(object, This, type);
779 if (FAILED(hr))
781 WARN("Failed to initialize stateblock, hr %#x.\n", hr);
782 HeapFree(GetProcessHeap(), 0, object);
783 return hr;
786 TRACE("Created stateblock %p.\n", object);
787 *stateblock = (IWineD3DStateBlock *)object;
789 return WINED3D_OK;
792 static HRESULT WINAPI IWineD3DDeviceImpl_CreateSurface(IWineD3DDevice *iface, UINT Width, UINT Height,
793 WINED3DFORMAT Format, BOOL Lockable, BOOL Discard, UINT Level, IWineD3DSurface **ppSurface,
794 DWORD Usage, WINED3DPOOL Pool, WINED3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality,
795 WINED3DSURFTYPE Impl, IUnknown *parent, const struct wined3d_parent_ops *parent_ops)
797 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
798 IWineD3DSurfaceImpl *object;
799 HRESULT hr;
801 TRACE("iface %p, width %u, height %u, format %s (%#x), lockable %#x, discard %#x, level %u\n",
802 iface, Width, Height, debug_d3dformat(Format), Format, Lockable, Discard, Level);
803 TRACE("surface %p, usage %s (%#x), pool %s (%#x), multisample_type %#x, multisample_quality %u\n",
804 ppSurface, debug_d3dusage(Usage), Usage, debug_d3dpool(Pool), Pool, MultiSample, MultisampleQuality);
805 TRACE("surface_type %#x, parent %p, parent_ops %p.\n", Impl, parent, parent_ops);
807 if (Impl == SURFACE_OPENGL && !This->adapter)
809 ERR("OpenGL surfaces are not available without OpenGL.\n");
810 return WINED3DERR_NOTAVAILABLE;
813 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
814 if (!object)
816 ERR("Failed to allocate surface memory.\n");
817 return WINED3DERR_OUTOFVIDEOMEMORY;
820 hr = surface_init(object, Impl, This->surface_alignment, Width, Height, Level, Lockable,
821 Discard, MultiSample, MultisampleQuality, This, Usage, Format, Pool, parent, parent_ops);
822 if (FAILED(hr))
824 WARN("Failed to initialize surface, returning %#x.\n", hr);
825 HeapFree(GetProcessHeap(), 0, object);
826 return hr;
829 TRACE("(%p) : Created surface %p\n", This, object);
831 *ppSurface = (IWineD3DSurface *)object;
833 return hr;
836 static HRESULT WINAPI IWineD3DDeviceImpl_CreateRendertargetView(IWineD3DDevice *iface,
837 IWineD3DResource *resource, IUnknown *parent, IWineD3DRendertargetView **rendertarget_view)
839 struct wined3d_rendertarget_view *object;
841 TRACE("iface %p, resource %p, parent %p, rendertarget_view %p.\n",
842 iface, resource, parent, rendertarget_view);
844 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
845 if (!object)
847 ERR("Failed to allocate memory\n");
848 return E_OUTOFMEMORY;
851 wined3d_rendertarget_view_init(object, resource, parent);
853 TRACE("Created render target view %p.\n", object);
854 *rendertarget_view = (IWineD3DRendertargetView *)object;
856 return WINED3D_OK;
859 static HRESULT WINAPI IWineD3DDeviceImpl_CreateTexture(IWineD3DDevice *iface,
860 UINT Width, UINT Height, UINT Levels, DWORD Usage, WINED3DFORMAT Format, WINED3DPOOL Pool,
861 IWineD3DTexture **ppTexture, IUnknown *parent, const struct wined3d_parent_ops *parent_ops)
863 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
864 IWineD3DTextureImpl *object;
865 HRESULT hr;
867 TRACE("(%p) : Width %d, Height %d, Levels %d, Usage %#x\n", This, Width, Height, Levels, Usage);
868 TRACE("Format %#x (%s), Pool %#x, ppTexture %p, parent %p\n",
869 Format, debug_d3dformat(Format), Pool, ppTexture, parent);
871 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
872 if (!object)
874 ERR("Out of memory\n");
875 *ppTexture = NULL;
876 return WINED3DERR_OUTOFVIDEOMEMORY;
879 hr = texture_init(object, Width, Height, Levels, This, Usage, Format, Pool, parent, parent_ops);
880 if (FAILED(hr))
882 WARN("Failed to initialize texture, returning %#x\n", hr);
883 HeapFree(GetProcessHeap(), 0, object);
884 *ppTexture = NULL;
885 return hr;
888 *ppTexture = (IWineD3DTexture *)object;
890 TRACE("(%p) : Created texture %p\n", This, object);
892 return WINED3D_OK;
895 static HRESULT WINAPI IWineD3DDeviceImpl_CreateVolumeTexture(IWineD3DDevice *iface,
896 UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, WINED3DFORMAT Format, WINED3DPOOL Pool,
897 IWineD3DVolumeTexture **ppVolumeTexture, IUnknown *parent, const struct wined3d_parent_ops *parent_ops)
899 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
900 IWineD3DVolumeTextureImpl *object;
901 HRESULT hr;
903 TRACE("(%p) : W(%u) H(%u) D(%u), Lvl(%u) Usage(%#x), Fmt(%u,%s), Pool(%s)\n", This, Width, Height,
904 Depth, Levels, Usage, Format, debug_d3dformat(Format), debug_d3dpool(Pool));
906 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
907 if (!object)
909 ERR("Out of memory\n");
910 *ppVolumeTexture = NULL;
911 return WINED3DERR_OUTOFVIDEOMEMORY;
914 hr = volumetexture_init(object, Width, Height, Depth, Levels, This, Usage, Format, Pool, parent, parent_ops);
915 if (FAILED(hr))
917 WARN("Failed to initialize volumetexture, returning %#x\n", hr);
918 HeapFree(GetProcessHeap(), 0, object);
919 *ppVolumeTexture = NULL;
920 return hr;
923 TRACE("(%p) : Created volume texture %p.\n", This, object);
924 *ppVolumeTexture = (IWineD3DVolumeTexture *)object;
926 return WINED3D_OK;
929 static HRESULT WINAPI IWineD3DDeviceImpl_CreateVolume(IWineD3DDevice *iface, UINT Width, UINT Height,
930 UINT Depth, DWORD Usage, WINED3DFORMAT Format, WINED3DPOOL Pool, IWineD3DVolume **ppVolume,
931 IUnknown *parent, const struct wined3d_parent_ops *parent_ops)
933 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
934 IWineD3DVolumeImpl *object;
935 HRESULT hr;
937 TRACE("(%p) : W(%d) H(%d) D(%d), Usage(%d), Fmt(%u,%s), Pool(%s)\n", This, Width, Height,
938 Depth, Usage, Format, debug_d3dformat(Format), debug_d3dpool(Pool));
940 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
941 if (!object)
943 ERR("Out of memory\n");
944 *ppVolume = NULL;
945 return WINED3DERR_OUTOFVIDEOMEMORY;
948 hr = volume_init(object, This, Width, Height, Depth, Usage, Format, Pool, parent, parent_ops);
949 if (FAILED(hr))
951 WARN("Failed to initialize volume, returning %#x.\n", hr);
952 HeapFree(GetProcessHeap(), 0, object);
953 return hr;
956 TRACE("(%p) : Created volume %p.\n", This, object);
957 *ppVolume = (IWineD3DVolume *)object;
959 return WINED3D_OK;
962 static HRESULT WINAPI IWineD3DDeviceImpl_CreateCubeTexture(IWineD3DDevice *iface, UINT EdgeLength, UINT Levels,
963 DWORD Usage, WINED3DFORMAT Format, WINED3DPOOL Pool, IWineD3DCubeTexture **ppCubeTexture,
964 IUnknown *parent, const struct wined3d_parent_ops *parent_ops)
966 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
967 IWineD3DCubeTextureImpl *object; /** NOTE: impl ref allowed since this is a create function **/
968 HRESULT hr;
970 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
971 if (!object)
973 ERR("Out of memory\n");
974 *ppCubeTexture = NULL;
975 return WINED3DERR_OUTOFVIDEOMEMORY;
978 hr = cubetexture_init(object, EdgeLength, Levels, This, Usage, Format, Pool, parent, parent_ops);
979 if (FAILED(hr))
981 WARN("Failed to initialize cubetexture, returning %#x\n", hr);
982 HeapFree(GetProcessHeap(), 0, object);
983 *ppCubeTexture = NULL;
984 return hr;
987 TRACE("(%p) : Created Cube Texture %p\n", This, object);
988 *ppCubeTexture = (IWineD3DCubeTexture *)object;
990 return WINED3D_OK;
993 static HRESULT WINAPI IWineD3DDeviceImpl_CreateQuery(IWineD3DDevice *iface,
994 WINED3DQUERYTYPE type, IWineD3DQuery **query, IUnknown *parent)
996 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
997 IWineD3DQueryImpl *object;
998 HRESULT hr;
1000 TRACE("iface %p, type %#x, query %p, parent %p.\n", iface, type, query, parent);
1002 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1003 if (!object)
1005 ERR("Failed to allocate query memory.\n");
1006 return E_OUTOFMEMORY;
1009 hr = query_init(object, This, type, parent);
1010 if (FAILED(hr))
1012 WARN("Failed to initialize query, hr %#x.\n", hr);
1013 HeapFree(GetProcessHeap(), 0, object);
1014 return hr;
1017 TRACE("Created query %p.\n", object);
1018 *query = (IWineD3DQuery *)object;
1020 return WINED3D_OK;
1023 static HRESULT WINAPI IWineD3DDeviceImpl_CreateSwapChain(IWineD3DDevice *iface,
1024 WINED3DPRESENT_PARAMETERS *present_parameters, IWineD3DSwapChain **swapchain,
1025 IUnknown *parent, WINED3DSURFTYPE surface_type)
1027 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1028 IWineD3DSwapChainImpl *object;
1029 HRESULT hr;
1031 TRACE("iface %p, present_parameters %p, swapchain %p, parent %p, surface_type %#x.\n",
1032 iface, present_parameters, swapchain, parent, surface_type);
1034 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1035 if (!object)
1037 ERR("Failed to allocate swapchain memory.\n");
1038 return E_OUTOFMEMORY;
1041 hr = swapchain_init(object, surface_type, This, present_parameters, parent);
1042 if (FAILED(hr))
1044 WARN("Failed to initialize swapchain, hr %#x.\n", hr);
1045 HeapFree(GetProcessHeap(), 0, object);
1046 return hr;
1049 TRACE("Created swapchain %p.\n", object);
1050 *swapchain = (IWineD3DSwapChain *)object;
1052 return WINED3D_OK;
1055 /** NOTE: These are ahead of the other getters and setters to save using a forward declaration **/
1056 static UINT WINAPI IWineD3DDeviceImpl_GetNumberOfSwapChains(IWineD3DDevice *iface) {
1057 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1058 TRACE("(%p)\n", This);
1060 return This->NumberOfSwapChains;
1063 static HRESULT WINAPI IWineD3DDeviceImpl_GetSwapChain(IWineD3DDevice *iface, UINT iSwapChain, IWineD3DSwapChain **pSwapChain) {
1064 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1065 TRACE("(%p) : swapchain %d\n", This, iSwapChain);
1067 if(iSwapChain < This->NumberOfSwapChains) {
1068 *pSwapChain = This->swapchains[iSwapChain];
1069 IWineD3DSwapChain_AddRef(*pSwapChain);
1070 TRACE("(%p) returning %p\n", This, *pSwapChain);
1071 return WINED3D_OK;
1072 } else {
1073 TRACE("Swapchain out of range\n");
1074 *pSwapChain = NULL;
1075 return WINED3DERR_INVALIDCALL;
1079 static HRESULT WINAPI IWineD3DDeviceImpl_CreateVertexDeclaration(IWineD3DDevice *iface,
1080 IWineD3DVertexDeclaration **declaration, IUnknown *parent, const struct wined3d_parent_ops *parent_ops,
1081 const WINED3DVERTEXELEMENT *elements, UINT element_count)
1083 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1084 IWineD3DVertexDeclarationImpl *object = NULL;
1085 HRESULT hr;
1087 TRACE("iface %p, declaration %p, parent %p, elements %p, element_count %u.\n",
1088 iface, declaration, parent, elements, element_count);
1090 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1091 if(!object)
1093 ERR("Failed to allocate vertex declaration memory.\n");
1094 return E_OUTOFMEMORY;
1097 hr = vertexdeclaration_init(object, This, elements, element_count, parent, parent_ops);
1098 if (FAILED(hr))
1100 WARN("Failed to initialize vertex declaration, hr %#x.\n", hr);
1101 HeapFree(GetProcessHeap(), 0, object);
1102 return hr;
1105 TRACE("Created vertex declaration %p.\n", object);
1106 *declaration = (IWineD3DVertexDeclaration *)object;
1108 return WINED3D_OK;
1111 struct wined3d_fvf_convert_state
1113 const struct wined3d_gl_info *gl_info;
1114 WINED3DVERTEXELEMENT *elements;
1115 UINT offset;
1116 UINT idx;
1119 static void append_decl_element(struct wined3d_fvf_convert_state *state,
1120 WINED3DFORMAT format, WINED3DDECLUSAGE usage, UINT usage_idx)
1122 WINED3DVERTEXELEMENT *elements = state->elements;
1123 const struct wined3d_format_desc *format_desc;
1124 UINT offset = state->offset;
1125 UINT idx = state->idx;
1127 elements[idx].format = format;
1128 elements[idx].input_slot = 0;
1129 elements[idx].offset = offset;
1130 elements[idx].output_slot = 0;
1131 elements[idx].method = WINED3DDECLMETHOD_DEFAULT;
1132 elements[idx].usage = usage;
1133 elements[idx].usage_idx = usage_idx;
1135 format_desc = getFormatDescEntry(format, state->gl_info);
1136 state->offset += format_desc->component_count * format_desc->component_size;
1137 ++state->idx;
1140 static unsigned int ConvertFvfToDeclaration(IWineD3DDeviceImpl *This, /* For the GL info, which has the type table */
1141 DWORD fvf, WINED3DVERTEXELEMENT **ppVertexElements)
1143 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
1144 BOOL has_pos = (fvf & WINED3DFVF_POSITION_MASK) != 0;
1145 BOOL has_blend = (fvf & WINED3DFVF_XYZB5) > WINED3DFVF_XYZRHW;
1146 BOOL has_blend_idx = has_blend &&
1147 (((fvf & WINED3DFVF_XYZB5) == WINED3DFVF_XYZB5) ||
1148 (fvf & WINED3DFVF_LASTBETA_D3DCOLOR) ||
1149 (fvf & WINED3DFVF_LASTBETA_UBYTE4));
1150 BOOL has_normal = (fvf & WINED3DFVF_NORMAL) != 0;
1151 BOOL has_psize = (fvf & WINED3DFVF_PSIZE) != 0;
1152 BOOL has_diffuse = (fvf & WINED3DFVF_DIFFUSE) != 0;
1153 BOOL has_specular = (fvf & WINED3DFVF_SPECULAR) !=0;
1155 DWORD num_textures = (fvf & WINED3DFVF_TEXCOUNT_MASK) >> WINED3DFVF_TEXCOUNT_SHIFT;
1156 DWORD texcoords = (fvf & 0xFFFF0000) >> 16;
1157 struct wined3d_fvf_convert_state state;
1158 unsigned int size;
1159 unsigned int idx;
1160 DWORD num_blends = 1 + (((fvf & WINED3DFVF_XYZB5) - WINED3DFVF_XYZB1) >> 1);
1161 if (has_blend_idx) num_blends--;
1163 /* Compute declaration size */
1164 size = has_pos + (has_blend && num_blends > 0) + has_blend_idx + has_normal +
1165 has_psize + has_diffuse + has_specular + num_textures;
1167 state.gl_info = gl_info;
1168 state.elements = HeapAlloc(GetProcessHeap(), 0, size * sizeof(*state.elements));
1169 if (!state.elements) return ~0U;
1170 state.offset = 0;
1171 state.idx = 0;
1173 if (has_pos)
1175 if (!has_blend && (fvf & WINED3DFVF_XYZRHW))
1176 append_decl_element(&state, WINED3DFMT_R32G32B32A32_FLOAT, WINED3DDECLUSAGE_POSITIONT, 0);
1177 else if ((fvf & WINED3DFVF_XYZW) == WINED3DFVF_XYZW)
1178 append_decl_element(&state, WINED3DFMT_R32G32B32A32_FLOAT, WINED3DDECLUSAGE_POSITION, 0);
1179 else
1180 append_decl_element(&state, WINED3DFMT_R32G32B32_FLOAT, WINED3DDECLUSAGE_POSITION, 0);
1183 if (has_blend && (num_blends > 0))
1185 if ((fvf & WINED3DFVF_XYZB5) == WINED3DFVF_XYZB2 && (fvf & WINED3DFVF_LASTBETA_D3DCOLOR))
1186 append_decl_element(&state, WINED3DFMT_B8G8R8A8_UNORM, WINED3DDECLUSAGE_BLENDWEIGHT, 0);
1187 else
1189 switch (num_blends)
1191 case 1:
1192 append_decl_element(&state, WINED3DFMT_R32_FLOAT, WINED3DDECLUSAGE_BLENDWEIGHT, 0);
1193 break;
1194 case 2:
1195 append_decl_element(&state, WINED3DFMT_R32G32_FLOAT, WINED3DDECLUSAGE_BLENDWEIGHT, 0);
1196 break;
1197 case 3:
1198 append_decl_element(&state, WINED3DFMT_R32G32B32_FLOAT, WINED3DDECLUSAGE_BLENDWEIGHT, 0);
1199 break;
1200 case 4:
1201 append_decl_element(&state, WINED3DFMT_R32G32B32A32_FLOAT, WINED3DDECLUSAGE_BLENDWEIGHT, 0);
1202 break;
1203 default:
1204 ERR("Unexpected amount of blend values: %u\n", num_blends);
1209 if (has_blend_idx)
1211 if ((fvf & WINED3DFVF_LASTBETA_UBYTE4)
1212 || ((fvf & WINED3DFVF_XYZB5) == WINED3DFVF_XYZB2 && (fvf & WINED3DFVF_LASTBETA_D3DCOLOR)))
1213 append_decl_element(&state, WINED3DFMT_R8G8B8A8_UINT, WINED3DDECLUSAGE_BLENDINDICES, 0);
1214 else if (fvf & WINED3DFVF_LASTBETA_D3DCOLOR)
1215 append_decl_element(&state, WINED3DFMT_B8G8R8A8_UNORM, WINED3DDECLUSAGE_BLENDINDICES, 0);
1216 else
1217 append_decl_element(&state, WINED3DFMT_R32_FLOAT, WINED3DDECLUSAGE_BLENDINDICES, 0);
1220 if (has_normal) append_decl_element(&state, WINED3DFMT_R32G32B32_FLOAT, WINED3DDECLUSAGE_NORMAL, 0);
1221 if (has_psize) append_decl_element(&state, WINED3DFMT_R32_FLOAT, WINED3DDECLUSAGE_PSIZE, 0);
1222 if (has_diffuse) append_decl_element(&state, WINED3DFMT_B8G8R8A8_UNORM, WINED3DDECLUSAGE_COLOR, 0);
1223 if (has_specular) append_decl_element(&state, WINED3DFMT_B8G8R8A8_UNORM, WINED3DDECLUSAGE_COLOR, 1);
1225 for (idx = 0; idx < num_textures; ++idx)
1227 switch ((texcoords >> (idx * 2)) & 0x03)
1229 case WINED3DFVF_TEXTUREFORMAT1:
1230 append_decl_element(&state, WINED3DFMT_R32_FLOAT, WINED3DDECLUSAGE_TEXCOORD, idx);
1231 break;
1232 case WINED3DFVF_TEXTUREFORMAT2:
1233 append_decl_element(&state, WINED3DFMT_R32G32_FLOAT, WINED3DDECLUSAGE_TEXCOORD, idx);
1234 break;
1235 case WINED3DFVF_TEXTUREFORMAT3:
1236 append_decl_element(&state, WINED3DFMT_R32G32B32_FLOAT, WINED3DDECLUSAGE_TEXCOORD, idx);
1237 break;
1238 case WINED3DFVF_TEXTUREFORMAT4:
1239 append_decl_element(&state, WINED3DFMT_R32G32B32A32_FLOAT, WINED3DDECLUSAGE_TEXCOORD, idx);
1240 break;
1244 *ppVertexElements = state.elements;
1245 return size;
1248 static HRESULT WINAPI IWineD3DDeviceImpl_CreateVertexDeclarationFromFVF(IWineD3DDevice *iface,
1249 IWineD3DVertexDeclaration **declaration, IUnknown *parent,
1250 const struct wined3d_parent_ops *parent_ops, DWORD fvf)
1252 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
1253 WINED3DVERTEXELEMENT *elements;
1254 unsigned int size;
1255 DWORD hr;
1257 TRACE("iface %p, declaration %p, parent %p, fvf %#x.\n", iface, declaration, parent, fvf);
1259 size = ConvertFvfToDeclaration(This, fvf, &elements);
1260 if (size == ~0U) return E_OUTOFMEMORY;
1262 hr = IWineD3DDevice_CreateVertexDeclaration(iface, declaration, parent, parent_ops, elements, size);
1263 HeapFree(GetProcessHeap(), 0, elements);
1264 return hr;
1267 static HRESULT WINAPI IWineD3DDeviceImpl_CreateVertexShader(IWineD3DDevice *iface,
1268 const DWORD *pFunction, const struct wined3d_shader_signature *output_signature,
1269 IWineD3DVertexShader **ppVertexShader, IUnknown *parent,
1270 const struct wined3d_parent_ops *parent_ops)
1272 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1273 IWineD3DVertexShaderImpl *object;
1274 HRESULT hr;
1276 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1277 if (!object)
1279 ERR("Failed to allocate shader memory.\n");
1280 return E_OUTOFMEMORY;
1283 hr = vertexshader_init(object, This, pFunction, output_signature, parent, parent_ops);
1284 if (FAILED(hr))
1286 WARN("Failed to initialize vertex shader, hr %#x.\n", hr);
1287 HeapFree(GetProcessHeap(), 0, object);
1288 return hr;
1291 TRACE("Created vertex shader %p.\n", object);
1292 *ppVertexShader = (IWineD3DVertexShader *)object;
1294 return WINED3D_OK;
1297 static HRESULT WINAPI IWineD3DDeviceImpl_CreateGeometryShader(IWineD3DDevice *iface,
1298 const DWORD *byte_code, const struct wined3d_shader_signature *output_signature,
1299 IWineD3DGeometryShader **shader, IUnknown *parent,
1300 const struct wined3d_parent_ops *parent_ops)
1302 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1303 struct wined3d_geometryshader *object;
1304 HRESULT hr;
1306 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1307 if (!object)
1309 ERR("Failed to allocate shader memory.\n");
1310 return E_OUTOFMEMORY;
1313 hr = geometryshader_init(object, This, byte_code, output_signature, parent, parent_ops);
1314 if (FAILED(hr))
1316 WARN("Failed to initialize geometry shader, hr %#x.\n", hr);
1317 HeapFree(GetProcessHeap(), 0, object);
1318 return hr;
1321 TRACE("Created geometry shader %p.\n", object);
1322 *shader = (IWineD3DGeometryShader *)object;
1324 return WINED3D_OK;
1327 static HRESULT WINAPI IWineD3DDeviceImpl_CreatePixelShader(IWineD3DDevice *iface,
1328 const DWORD *pFunction, const struct wined3d_shader_signature *output_signature,
1329 IWineD3DPixelShader **ppPixelShader, IUnknown *parent,
1330 const struct wined3d_parent_ops *parent_ops)
1332 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1333 IWineD3DPixelShaderImpl *object;
1334 HRESULT hr;
1336 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1337 if (!object)
1339 ERR("Failed to allocate shader memory.\n");
1340 return E_OUTOFMEMORY;
1343 hr = pixelshader_init(object, This, pFunction, output_signature, parent, parent_ops);
1344 if (FAILED(hr))
1346 WARN("Failed to initialize pixel shader, hr %#x.\n", hr);
1347 HeapFree(GetProcessHeap(), 0, object);
1348 return hr;
1351 TRACE("Created pixel shader %p.\n", object);
1352 *ppPixelShader = (IWineD3DPixelShader *)object;
1354 return WINED3D_OK;
1357 static HRESULT WINAPI IWineD3DDeviceImpl_CreatePalette(IWineD3DDevice *iface, DWORD Flags,
1358 const PALETTEENTRY *PalEnt, IWineD3DPalette **Palette, IUnknown *Parent)
1360 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
1361 IWineD3DPaletteImpl *object;
1362 HRESULT hr;
1364 TRACE("iface %p, flags %#x, entries %p, palette %p, parent %p.\n",
1365 iface, Flags, PalEnt, Palette, Parent);
1367 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1368 if (!object)
1370 ERR("Failed to allocate palette memory.\n");
1371 return E_OUTOFMEMORY;
1374 hr = wined3d_palette_init(object, This, Flags, PalEnt, Parent);
1375 if (FAILED(hr))
1377 WARN("Failed to initialize palette, hr %#x.\n", hr);
1378 HeapFree(GetProcessHeap(), 0, object);
1379 return hr;
1382 TRACE("Created palette %p.\n", object);
1383 *Palette = (IWineD3DPalette *)object;
1385 return WINED3D_OK;
1388 static void IWineD3DDeviceImpl_LoadLogo(IWineD3DDeviceImpl *This, const char *filename) {
1389 HBITMAP hbm;
1390 BITMAP bm;
1391 HRESULT hr;
1392 HDC dcb = NULL, dcs = NULL;
1393 WINEDDCOLORKEY colorkey;
1395 hbm = LoadImageA(NULL, filename, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
1396 if(hbm)
1398 GetObjectA(hbm, sizeof(BITMAP), &bm);
1399 dcb = CreateCompatibleDC(NULL);
1400 if(!dcb) goto out;
1401 SelectObject(dcb, hbm);
1403 else
1405 /* Create a 32x32 white surface to indicate that wined3d is used, but the specified image
1406 * couldn't be loaded
1408 memset(&bm, 0, sizeof(bm));
1409 bm.bmWidth = 32;
1410 bm.bmHeight = 32;
1413 hr = IWineD3DDevice_CreateSurface((IWineD3DDevice *)This, bm.bmWidth, bm.bmHeight, WINED3DFMT_B5G6R5_UNORM, TRUE,
1414 FALSE, 0, &This->logo_surface, 0, WINED3DPOOL_DEFAULT, WINED3DMULTISAMPLE_NONE, 0, SURFACE_OPENGL,
1415 NULL, &wined3d_null_parent_ops);
1416 if(FAILED(hr)) {
1417 ERR("Wine logo requested, but failed to create surface\n");
1418 goto out;
1421 if(dcb) {
1422 hr = IWineD3DSurface_GetDC(This->logo_surface, &dcs);
1423 if(FAILED(hr)) goto out;
1424 BitBlt(dcs, 0, 0, bm.bmWidth, bm.bmHeight, dcb, 0, 0, SRCCOPY);
1425 IWineD3DSurface_ReleaseDC(This->logo_surface, dcs);
1427 colorkey.dwColorSpaceLowValue = 0;
1428 colorkey.dwColorSpaceHighValue = 0;
1429 IWineD3DSurface_SetColorKey(This->logo_surface, WINEDDCKEY_SRCBLT, &colorkey);
1430 } else {
1431 /* Fill the surface with a white color to show that wined3d is there */
1432 IWineD3DDevice_ColorFill((IWineD3DDevice *) This, This->logo_surface, NULL, 0xffffffff);
1435 out:
1436 if (dcb) DeleteDC(dcb);
1437 if (hbm) DeleteObject(hbm);
1440 /* Context activation is done by the caller. */
1441 static void create_dummy_textures(IWineD3DDeviceImpl *This)
1443 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
1444 unsigned int i;
1445 /* Under DirectX you can have texture stage operations even if no texture is
1446 bound, whereas opengl will only do texture operations when a valid texture is
1447 bound. We emulate this by creating dummy textures and binding them to each
1448 texture stage, but disable all stages by default. Hence if a stage is enabled
1449 then the default texture will kick in until replaced by a SetTexture call */
1450 ENTER_GL();
1452 if (gl_info->supported[APPLE_CLIENT_STORAGE])
1454 /* The dummy texture does not have client storage backing */
1455 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
1456 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
1459 for (i = 0; i < gl_info->limits.textures; ++i)
1461 GLubyte white = 255;
1463 /* Make appropriate texture active */
1464 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1465 checkGLcall("glActiveTextureARB");
1467 /* Generate an opengl texture name */
1468 glGenTextures(1, &This->dummyTextureName[i]);
1469 checkGLcall("glGenTextures");
1470 TRACE("Dummy Texture %d given name %d\n", i, This->dummyTextureName[i]);
1472 /* Generate a dummy 2d texture (not using 1d because they cause many
1473 * DRI drivers fall back to sw) */
1474 glBindTexture(GL_TEXTURE_2D, This->dummyTextureName[i]);
1475 checkGLcall("glBindTexture");
1477 glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, 1, 1, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, &white);
1478 checkGLcall("glTexImage2D");
1481 if (gl_info->supported[APPLE_CLIENT_STORAGE])
1483 /* Reenable because if supported it is enabled by default */
1484 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1485 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1488 LEAVE_GL();
1491 /* Context activation is done by the caller. */
1492 static void destroy_dummy_textures(IWineD3DDeviceImpl *device, const struct wined3d_gl_info *gl_info)
1494 ENTER_GL();
1495 glDeleteTextures(gl_info->limits.textures, device->dummyTextureName);
1496 checkGLcall("glDeleteTextures(gl_info->limits.textures, device->dummyTextureName)");
1497 LEAVE_GL();
1499 memset(device->dummyTextureName, 0, gl_info->limits.textures * sizeof(*device->dummyTextureName));
1502 static HRESULT WINAPI IWineD3DDeviceImpl_AcquireFocusWindow(IWineD3DDevice *iface, HWND window)
1504 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)iface;
1506 if (!wined3d_register_window(window, device))
1508 ERR("Failed to register window %p.\n", window);
1509 return E_FAIL;
1512 device->focus_window = window;
1513 SetForegroundWindow(window);
1515 return WINED3D_OK;
1518 static void WINAPI IWineD3DDeviceImpl_ReleaseFocusWindow(IWineD3DDevice *iface)
1520 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)iface;
1522 if (device->focus_window) wined3d_unregister_window(device->focus_window);
1523 device->focus_window = NULL;
1526 static HRESULT WINAPI IWineD3DDeviceImpl_Init3D(IWineD3DDevice *iface,
1527 WINED3DPRESENT_PARAMETERS *pPresentationParameters)
1529 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
1530 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
1531 IWineD3DSwapChainImpl *swapchain = NULL;
1532 struct wined3d_context *context;
1533 HRESULT hr;
1534 DWORD state;
1535 unsigned int i;
1537 TRACE("(%p)->(%p)\n", This, pPresentationParameters);
1539 if(This->d3d_initialized) return WINED3DERR_INVALIDCALL;
1540 if(!This->adapter->opengl) return WINED3DERR_INVALIDCALL;
1542 TRACE("(%p) : Creating stateblock\n", This);
1543 /* Creating the startup stateBlock - Note Special Case: 0 => Don't fill in yet! */
1544 hr = IWineD3DDevice_CreateStateBlock(iface,
1545 WINED3DSBT_INIT,
1546 (IWineD3DStateBlock **)&This->stateBlock,
1547 NULL);
1548 if (WINED3D_OK != hr) { /* Note: No parent needed for initial internal stateblock */
1549 WARN("Failed to create stateblock\n");
1550 goto err_out;
1552 TRACE("(%p) : Created stateblock (%p)\n", This, This->stateBlock);
1553 This->updateStateBlock = This->stateBlock;
1554 IWineD3DStateBlock_AddRef((IWineD3DStateBlock*)This->updateStateBlock);
1556 This->render_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1557 sizeof(IWineD3DSurface *) * gl_info->limits.buffers);
1558 This->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1559 sizeof(GLenum) * gl_info->limits.buffers);
1561 This->NumberOfPalettes = 1;
1562 This->palettes = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(PALETTEENTRY*));
1563 if(!This->palettes || !This->render_targets || !This->draw_buffers) {
1564 ERR("Out of memory!\n");
1565 hr = E_OUTOFMEMORY;
1566 goto err_out;
1568 This->palettes[0] = HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY) * 256);
1569 if(!This->palettes[0]) {
1570 ERR("Out of memory!\n");
1571 hr = E_OUTOFMEMORY;
1572 goto err_out;
1574 for (i = 0; i < 256; ++i) {
1575 This->palettes[0][i].peRed = 0xFF;
1576 This->palettes[0][i].peGreen = 0xFF;
1577 This->palettes[0][i].peBlue = 0xFF;
1578 This->palettes[0][i].peFlags = 0xFF;
1580 This->currentPalette = 0;
1582 /* Initialize the texture unit mapping to a 1:1 mapping */
1583 for (state = 0; state < MAX_COMBINED_SAMPLERS; ++state)
1585 if (state < gl_info->limits.fragment_samplers)
1587 This->texUnitMap[state] = state;
1588 This->rev_tex_unit_map[state] = state;
1589 } else {
1590 This->texUnitMap[state] = WINED3D_UNMAPPED_STAGE;
1591 This->rev_tex_unit_map[state] = WINED3D_UNMAPPED_STAGE;
1595 /* Setup the implicit swapchain. This also initializes a context. */
1596 TRACE("Creating implicit swapchain\n");
1597 hr = IWineD3DDeviceParent_CreateSwapChain(This->device_parent,
1598 pPresentationParameters, (IWineD3DSwapChain **)&swapchain);
1599 if (FAILED(hr))
1601 WARN("Failed to create implicit swapchain\n");
1602 goto err_out;
1605 This->NumberOfSwapChains = 1;
1606 This->swapchains = HeapAlloc(GetProcessHeap(), 0, This->NumberOfSwapChains * sizeof(IWineD3DSwapChain *));
1607 if(!This->swapchains) {
1608 ERR("Out of memory!\n");
1609 goto err_out;
1611 This->swapchains[0] = (IWineD3DSwapChain *) swapchain;
1613 if(swapchain->backBuffer && swapchain->backBuffer[0]) {
1614 TRACE("Setting rendertarget to %p\n", swapchain->backBuffer);
1615 This->render_targets[0] = swapchain->backBuffer[0];
1617 else {
1618 TRACE("Setting rendertarget to %p\n", swapchain->frontBuffer);
1619 This->render_targets[0] = swapchain->frontBuffer;
1621 IWineD3DSurface_AddRef(This->render_targets[0]);
1623 /* Depth Stencil support */
1624 This->stencilBufferTarget = This->auto_depth_stencil_buffer;
1625 if (NULL != This->stencilBufferTarget) {
1626 IWineD3DSurface_AddRef(This->stencilBufferTarget);
1629 hr = This->shader_backend->shader_alloc_private(iface);
1630 if(FAILED(hr)) {
1631 TRACE("Shader private data couldn't be allocated\n");
1632 goto err_out;
1634 hr = This->frag_pipe->alloc_private(iface);
1635 if(FAILED(hr)) {
1636 TRACE("Fragment pipeline private data couldn't be allocated\n");
1637 goto err_out;
1639 hr = This->blitter->alloc_private(iface);
1640 if(FAILED(hr)) {
1641 TRACE("Blitter private data couldn't be allocated\n");
1642 goto err_out;
1645 /* Set up some starting GL setup */
1647 /* Setup all the devices defaults */
1648 IWineD3DStateBlock_InitStartupStateBlock((IWineD3DStateBlock *)This->stateBlock);
1650 context = context_acquire(This, swapchain->frontBuffer, CTXUSAGE_RESOURCELOAD);
1652 create_dummy_textures(This);
1654 ENTER_GL();
1656 /* Initialize the current view state */
1657 This->view_ident = 1;
1658 This->contexts[0]->last_was_rhw = 0;
1659 glGetIntegerv(GL_MAX_LIGHTS, &This->maxConcurrentLights);
1660 checkGLcall("glGetIntegerv(GL_MAX_LIGHTS, &This->maxConcurrentLights)");
1662 switch(wined3d_settings.offscreen_rendering_mode) {
1663 case ORM_FBO:
1664 This->offscreenBuffer = GL_COLOR_ATTACHMENT0;
1665 break;
1667 case ORM_BACKBUFFER:
1669 if (context_get_current()->aux_buffers > 0)
1671 TRACE("Using auxilliary buffer for offscreen rendering\n");
1672 This->offscreenBuffer = GL_AUX0;
1673 } else {
1674 TRACE("Using back buffer for offscreen rendering\n");
1675 This->offscreenBuffer = GL_BACK;
1680 TRACE("(%p) All defaults now set up, leaving Init3D with %p\n", This, This);
1681 LEAVE_GL();
1683 context_release(context);
1685 /* Clear the screen */
1686 IWineD3DDevice_Clear((IWineD3DDevice *) This, 0, NULL,
1687 WINED3DCLEAR_TARGET | pPresentationParameters->EnableAutoDepthStencil ? WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL : 0,
1688 0x00, 1.0f, 0);
1690 This->d3d_initialized = TRUE;
1692 if(wined3d_settings.logo) {
1693 IWineD3DDeviceImpl_LoadLogo(This, wined3d_settings.logo);
1695 This->highest_dirty_ps_const = 0;
1696 This->highest_dirty_vs_const = 0;
1697 return WINED3D_OK;
1699 err_out:
1700 HeapFree(GetProcessHeap(), 0, This->render_targets);
1701 HeapFree(GetProcessHeap(), 0, This->draw_buffers);
1702 HeapFree(GetProcessHeap(), 0, This->swapchains);
1703 This->NumberOfSwapChains = 0;
1704 if(This->palettes) {
1705 HeapFree(GetProcessHeap(), 0, This->palettes[0]);
1706 HeapFree(GetProcessHeap(), 0, This->palettes);
1708 This->NumberOfPalettes = 0;
1709 if(swapchain) {
1710 IWineD3DSwapChain_Release( (IWineD3DSwapChain *) swapchain);
1712 if(This->stateBlock) {
1713 IWineD3DStateBlock_Release((IWineD3DStateBlock *) This->stateBlock);
1714 This->stateBlock = NULL;
1716 if (This->blit_priv) {
1717 This->blitter->free_private(iface);
1719 if (This->fragment_priv) {
1720 This->frag_pipe->free_private(iface);
1722 if (This->shader_priv) {
1723 This->shader_backend->shader_free_private(iface);
1725 return hr;
1728 static HRESULT WINAPI IWineD3DDeviceImpl_InitGDI(IWineD3DDevice *iface,
1729 WINED3DPRESENT_PARAMETERS *pPresentationParameters)
1731 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
1732 IWineD3DSwapChainImpl *swapchain = NULL;
1733 HRESULT hr;
1735 /* Setup the implicit swapchain */
1736 TRACE("Creating implicit swapchain\n");
1737 hr = IWineD3DDeviceParent_CreateSwapChain(This->device_parent,
1738 pPresentationParameters, (IWineD3DSwapChain **)&swapchain);
1739 if (FAILED(hr))
1741 WARN("Failed to create implicit swapchain\n");
1742 goto err_out;
1745 This->NumberOfSwapChains = 1;
1746 This->swapchains = HeapAlloc(GetProcessHeap(), 0, This->NumberOfSwapChains * sizeof(IWineD3DSwapChain *));
1747 if(!This->swapchains) {
1748 ERR("Out of memory!\n");
1749 goto err_out;
1751 This->swapchains[0] = (IWineD3DSwapChain *) swapchain;
1752 return WINED3D_OK;
1754 err_out:
1755 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
1756 return hr;
1759 static HRESULT WINAPI device_unload_resource(IWineD3DResource *resource, void *ctx)
1761 IWineD3DResource_UnLoad(resource);
1762 IWineD3DResource_Release(resource);
1763 return WINED3D_OK;
1766 static HRESULT WINAPI IWineD3DDeviceImpl_Uninit3D(IWineD3DDevice *iface,
1767 D3DCB_DESTROYSWAPCHAINFN D3DCB_DestroySwapChain)
1769 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
1770 const struct wined3d_gl_info *gl_info;
1771 struct wined3d_context *context;
1772 int sampler;
1773 UINT i;
1774 TRACE("(%p)\n", This);
1776 if(!This->d3d_initialized) return WINED3DERR_INVALIDCALL;
1778 /* I don't think that the interface guarantees that the device is destroyed from the same thread
1779 * it was created. Thus make sure a context is active for the glDelete* calls
1781 context = context_acquire(This, NULL, CTXUSAGE_RESOURCELOAD);
1782 gl_info = context->gl_info;
1784 if(This->logo_surface) IWineD3DSurface_Release(This->logo_surface);
1786 /* Unload resources */
1787 IWineD3DDevice_EnumResources(iface, device_unload_resource, NULL);
1789 TRACE("Deleting high order patches\n");
1790 for(i = 0; i < PATCHMAP_SIZE; i++) {
1791 struct list *e1, *e2;
1792 struct WineD3DRectPatch *patch;
1793 LIST_FOR_EACH_SAFE(e1, e2, &This->patches[i]) {
1794 patch = LIST_ENTRY(e1, struct WineD3DRectPatch, entry);
1795 IWineD3DDevice_DeletePatch(iface, patch->Handle);
1799 /* Delete the mouse cursor texture */
1800 if(This->cursorTexture) {
1801 ENTER_GL();
1802 glDeleteTextures(1, &This->cursorTexture);
1803 LEAVE_GL();
1804 This->cursorTexture = 0;
1807 for (sampler = 0; sampler < MAX_FRAGMENT_SAMPLERS; ++sampler) {
1808 IWineD3DDevice_SetTexture(iface, sampler, NULL);
1810 for (sampler = 0; sampler < MAX_VERTEX_SAMPLERS; ++sampler) {
1811 IWineD3DDevice_SetTexture(iface, WINED3DVERTEXTEXTURESAMPLER0 + sampler, NULL);
1814 /* Destroy the depth blt resources, they will be invalid after the reset. Also free shader
1815 * private data, it might contain opengl pointers
1817 if(This->depth_blt_texture) {
1818 ENTER_GL();
1819 glDeleteTextures(1, &This->depth_blt_texture);
1820 LEAVE_GL();
1821 This->depth_blt_texture = 0;
1823 if (This->depth_blt_rb) {
1824 ENTER_GL();
1825 gl_info->fbo_ops.glDeleteRenderbuffers(1, &This->depth_blt_rb);
1826 LEAVE_GL();
1827 This->depth_blt_rb = 0;
1828 This->depth_blt_rb_w = 0;
1829 This->depth_blt_rb_h = 0;
1832 /* Release the update stateblock */
1833 if(IWineD3DStateBlock_Release((IWineD3DStateBlock *)This->updateStateBlock) > 0){
1834 if(This->updateStateBlock != This->stateBlock)
1835 FIXME("(%p) Something's still holding the Update stateblock\n",This);
1837 This->updateStateBlock = NULL;
1839 { /* because were not doing proper internal refcounts releasing the primary state block
1840 causes recursion with the extra checks in ResourceReleased, to avoid this we have
1841 to set this->stateBlock = NULL; first */
1842 IWineD3DStateBlock *stateBlock = (IWineD3DStateBlock *)This->stateBlock;
1843 This->stateBlock = NULL;
1845 /* Release the stateblock */
1846 if(IWineD3DStateBlock_Release(stateBlock) > 0){
1847 FIXME("(%p) Something's still holding the Update stateblock\n",This);
1851 /* Destroy the shader backend. Note that this has to happen after all shaders are destroyed. */
1852 This->blitter->free_private(iface);
1853 This->frag_pipe->free_private(iface);
1854 This->shader_backend->shader_free_private(iface);
1856 /* Release the buffers (with sanity checks)*/
1857 TRACE("Releasing the depth stencil buffer at %p\n", This->stencilBufferTarget);
1858 if(This->stencilBufferTarget != NULL && (IWineD3DSurface_Release(This->stencilBufferTarget) >0)){
1859 if(This->auto_depth_stencil_buffer != This->stencilBufferTarget)
1860 FIXME("(%p) Something's still holding the stencilBufferTarget\n",This);
1862 This->stencilBufferTarget = NULL;
1864 TRACE("Releasing the render target at %p\n", This->render_targets[0]);
1865 if(IWineD3DSurface_Release(This->render_targets[0]) >0){
1866 /* This check is a bit silly, it should be in swapchain_release FIXME("(%p) Something's still holding the renderTarget\n",This); */
1868 TRACE("Setting rendertarget to NULL\n");
1869 This->render_targets[0] = NULL;
1871 if (This->auto_depth_stencil_buffer) {
1872 if (IWineD3DSurface_Release(This->auto_depth_stencil_buffer) > 0)
1874 FIXME("(%p) Something's still holding the auto depth stencil buffer\n", This);
1876 This->auto_depth_stencil_buffer = NULL;
1879 context_release(context);
1881 for(i=0; i < This->NumberOfSwapChains; i++) {
1882 TRACE("Releasing the implicit swapchain %d\n", i);
1883 if (D3DCB_DestroySwapChain(This->swapchains[i]) > 0) {
1884 FIXME("(%p) Something's still holding the implicit swapchain\n", This);
1888 HeapFree(GetProcessHeap(), 0, This->swapchains);
1889 This->swapchains = NULL;
1890 This->NumberOfSwapChains = 0;
1892 for (i = 0; i < This->NumberOfPalettes; i++) HeapFree(GetProcessHeap(), 0, This->palettes[i]);
1893 HeapFree(GetProcessHeap(), 0, This->palettes);
1894 This->palettes = NULL;
1895 This->NumberOfPalettes = 0;
1897 HeapFree(GetProcessHeap(), 0, This->render_targets);
1898 HeapFree(GetProcessHeap(), 0, This->draw_buffers);
1899 This->render_targets = NULL;
1900 This->draw_buffers = NULL;
1902 This->d3d_initialized = FALSE;
1904 return WINED3D_OK;
1907 static HRESULT WINAPI IWineD3DDeviceImpl_UninitGDI(IWineD3DDevice *iface, D3DCB_DESTROYSWAPCHAINFN D3DCB_DestroySwapChain) {
1908 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
1909 unsigned int i;
1911 for(i=0; i < This->NumberOfSwapChains; i++) {
1912 TRACE("Releasing the implicit swapchain %d\n", i);
1913 if (D3DCB_DestroySwapChain(This->swapchains[i]) > 0) {
1914 FIXME("(%p) Something's still holding the implicit swapchain\n", This);
1918 HeapFree(GetProcessHeap(), 0, This->swapchains);
1919 This->swapchains = NULL;
1920 This->NumberOfSwapChains = 0;
1921 return WINED3D_OK;
1924 /* Enables thread safety in the wined3d device and its resources. Called by DirectDraw
1925 * from SetCooperativeLevel if DDSCL_MULTITHREADED is specified, and by d3d8/9 from
1926 * CreateDevice if D3DCREATE_MULTITHREADED is passed.
1928 * There is no way to deactivate thread safety once it is enabled.
1930 static void WINAPI IWineD3DDeviceImpl_SetMultithreaded(IWineD3DDevice *iface) {
1931 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
1933 /*For now just store the flag(needed in case of ddraw) */
1934 This->createParms.BehaviorFlags |= WINED3DCREATE_MULTITHREADED;
1937 static HRESULT WINAPI IWineD3DDeviceImpl_SetDisplayMode(IWineD3DDevice *iface, UINT iSwapChain,
1938 const WINED3DDISPLAYMODE* pMode) {
1939 DEVMODEW devmode;
1940 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1941 const struct wined3d_format_desc *format_desc = getFormatDescEntry(pMode->Format, &This->adapter->gl_info);
1942 LONG ret;
1943 RECT clip_rc;
1945 TRACE("(%p)->(%d,%p) Mode=%dx%dx@%d, %s\n", This, iSwapChain, pMode, pMode->Width, pMode->Height, pMode->RefreshRate, debug_d3dformat(pMode->Format));
1947 /* Resize the screen even without a window:
1948 * The app could have unset it with SetCooperativeLevel, but not called
1949 * RestoreDisplayMode first. Then the release will call RestoreDisplayMode,
1950 * but we don't have any hwnd
1953 memset(&devmode, 0, sizeof(devmode));
1954 devmode.dmSize = sizeof(devmode);
1955 devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1956 devmode.dmBitsPerPel = format_desc->byte_count * 8;
1957 devmode.dmPelsWidth = pMode->Width;
1958 devmode.dmPelsHeight = pMode->Height;
1960 devmode.dmDisplayFrequency = pMode->RefreshRate;
1961 if (pMode->RefreshRate != 0) {
1962 devmode.dmFields |= DM_DISPLAYFREQUENCY;
1965 /* Only change the mode if necessary */
1966 if( (This->ddraw_width == pMode->Width) &&
1967 (This->ddraw_height == pMode->Height) &&
1968 (This->ddraw_format == pMode->Format) &&
1969 (pMode->RefreshRate == 0) ) {
1970 return WINED3D_OK;
1973 ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL);
1974 if (ret != DISP_CHANGE_SUCCESSFUL) {
1975 if(devmode.dmDisplayFrequency != 0) {
1976 WARN("ChangeDisplaySettingsExW failed, trying without the refresh rate\n");
1977 devmode.dmFields &= ~DM_DISPLAYFREQUENCY;
1978 devmode.dmDisplayFrequency = 0;
1979 ret = ChangeDisplaySettingsExW(NULL, &devmode, NULL, CDS_FULLSCREEN, NULL) != DISP_CHANGE_SUCCESSFUL;
1981 if(ret != DISP_CHANGE_SUCCESSFUL) {
1982 return WINED3DERR_NOTAVAILABLE;
1986 /* Store the new values */
1987 This->ddraw_width = pMode->Width;
1988 This->ddraw_height = pMode->Height;
1989 This->ddraw_format = pMode->Format;
1991 /* And finally clip mouse to our screen */
1992 SetRect(&clip_rc, 0, 0, pMode->Width, pMode->Height);
1993 ClipCursor(&clip_rc);
1995 return WINED3D_OK;
1998 static HRESULT WINAPI IWineD3DDeviceImpl_GetDirect3D(IWineD3DDevice *iface, IWineD3D **ppD3D) {
1999 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2000 *ppD3D = This->wined3d;
2001 TRACE("Returning %p.\n", *ppD3D);
2002 IWineD3D_AddRef(*ppD3D);
2003 return WINED3D_OK;
2006 static UINT WINAPI IWineD3DDeviceImpl_GetAvailableTextureMem(IWineD3DDevice *iface) {
2007 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2009 TRACE("(%p) : simulating %dMB, returning %dMB left\n", This,
2010 (This->adapter->TextureRam/(1024*1024)),
2011 ((This->adapter->TextureRam - This->adapter->UsedTextureRam) / (1024*1024)));
2012 /* return simulated texture memory left */
2013 return (This->adapter->TextureRam - This->adapter->UsedTextureRam);
2016 /*****
2017 * Get / Set Stream Source
2018 *****/
2019 static HRESULT WINAPI IWineD3DDeviceImpl_SetStreamSource(IWineD3DDevice *iface, UINT StreamNumber,
2020 IWineD3DBuffer *pStreamData, UINT OffsetInBytes, UINT Stride)
2022 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2023 IWineD3DBuffer *oldSrc;
2025 if (StreamNumber >= MAX_STREAMS) {
2026 WARN("Stream out of range %d\n", StreamNumber);
2027 return WINED3DERR_INVALIDCALL;
2028 } else if(OffsetInBytes & 0x3) {
2029 WARN("OffsetInBytes is not 4 byte aligned: %d\n", OffsetInBytes);
2030 return WINED3DERR_INVALIDCALL;
2033 oldSrc = This->updateStateBlock->streamSource[StreamNumber];
2034 TRACE("(%p) : StreamNo: %u, OldStream (%p), NewStream (%p), OffsetInBytes %u, NewStride %u\n", This, StreamNumber, oldSrc, pStreamData, OffsetInBytes, Stride);
2036 This->updateStateBlock->changed.streamSource |= 1 << StreamNumber;
2038 if(oldSrc == pStreamData &&
2039 This->updateStateBlock->streamStride[StreamNumber] == Stride &&
2040 This->updateStateBlock->streamOffset[StreamNumber] == OffsetInBytes) {
2041 TRACE("Application is setting the old values over, nothing to do\n");
2042 return WINED3D_OK;
2045 This->updateStateBlock->streamSource[StreamNumber] = pStreamData;
2046 if (pStreamData) {
2047 This->updateStateBlock->streamStride[StreamNumber] = Stride;
2048 This->updateStateBlock->streamOffset[StreamNumber] = OffsetInBytes;
2051 /* Handle recording of state blocks */
2052 if (This->isRecordingState) {
2053 TRACE("Recording... not performing anything\n");
2054 if (pStreamData) IWineD3DBuffer_AddRef(pStreamData);
2055 if (oldSrc) IWineD3DBuffer_Release(oldSrc);
2056 return WINED3D_OK;
2059 if (pStreamData != NULL) {
2060 InterlockedIncrement(&((struct wined3d_buffer *)pStreamData)->bind_count);
2061 IWineD3DBuffer_AddRef(pStreamData);
2063 if (oldSrc != NULL) {
2064 InterlockedDecrement(&((struct wined3d_buffer *)oldSrc)->bind_count);
2065 IWineD3DBuffer_Release(oldSrc);
2068 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_STREAMSRC);
2070 return WINED3D_OK;
2073 static HRESULT WINAPI IWineD3DDeviceImpl_GetStreamSource(IWineD3DDevice *iface,
2074 UINT StreamNumber, IWineD3DBuffer **pStream, UINT *pOffset, UINT *pStride)
2076 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2078 TRACE("(%p) : StreamNo: %u, Stream (%p), Offset %u, Stride %u\n", This, StreamNumber,
2079 This->stateBlock->streamSource[StreamNumber],
2080 This->stateBlock->streamOffset[StreamNumber],
2081 This->stateBlock->streamStride[StreamNumber]);
2083 if (StreamNumber >= MAX_STREAMS) {
2084 WARN("Stream out of range %d\n", StreamNumber);
2085 return WINED3DERR_INVALIDCALL;
2087 *pStream = This->stateBlock->streamSource[StreamNumber];
2088 *pStride = This->stateBlock->streamStride[StreamNumber];
2089 if (pOffset) {
2090 *pOffset = This->stateBlock->streamOffset[StreamNumber];
2093 if (*pStream != NULL) {
2094 IWineD3DBuffer_AddRef(*pStream); /* We have created a new reference to the VB */
2096 return WINED3D_OK;
2099 static HRESULT WINAPI IWineD3DDeviceImpl_SetStreamSourceFreq(IWineD3DDevice *iface, UINT StreamNumber, UINT Divider) {
2100 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2101 UINT oldFlags = This->updateStateBlock->streamFlags[StreamNumber];
2102 UINT oldFreq = This->updateStateBlock->streamFreq[StreamNumber];
2104 /* Verify input at least in d3d9 this is invalid*/
2105 if( (Divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && (Divider & WINED3DSTREAMSOURCE_INDEXEDDATA)){
2106 WARN("INSTANCEDATA and INDEXEDDATA were set, returning D3DERR_INVALIDCALL\n");
2107 return WINED3DERR_INVALIDCALL;
2109 if( (Divider & WINED3DSTREAMSOURCE_INSTANCEDATA) && StreamNumber == 0 ){
2110 WARN("INSTANCEDATA used on stream 0, returning D3DERR_INVALIDCALL\n");
2111 return WINED3DERR_INVALIDCALL;
2113 if( Divider == 0 ){
2114 WARN("Divider is 0, returning D3DERR_INVALIDCALL\n");
2115 return WINED3DERR_INVALIDCALL;
2118 TRACE("(%p) StreamNumber(%d), Divider(%d)\n", This, StreamNumber, Divider);
2119 This->updateStateBlock->streamFlags[StreamNumber] = Divider & (WINED3DSTREAMSOURCE_INSTANCEDATA | WINED3DSTREAMSOURCE_INDEXEDDATA );
2121 This->updateStateBlock->changed.streamFreq |= 1 << StreamNumber;
2122 This->updateStateBlock->streamFreq[StreamNumber] = Divider & 0x7FFFFF;
2124 if(This->updateStateBlock->streamFreq[StreamNumber] != oldFreq ||
2125 This->updateStateBlock->streamFlags[StreamNumber] != oldFlags) {
2126 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_STREAMSRC);
2129 return WINED3D_OK;
2132 static HRESULT WINAPI IWineD3DDeviceImpl_GetStreamSourceFreq(IWineD3DDevice *iface, UINT StreamNumber, UINT* Divider) {
2133 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2135 TRACE("(%p) StreamNumber(%d), Divider(%p)\n", This, StreamNumber, Divider);
2136 *Divider = This->updateStateBlock->streamFreq[StreamNumber] | This->updateStateBlock->streamFlags[StreamNumber];
2138 TRACE("(%p) : returning %d\n", This, *Divider);
2140 return WINED3D_OK;
2143 /*****
2144 * Get / Set & Multiply Transform
2145 *****/
2146 static HRESULT WINAPI IWineD3DDeviceImpl_SetTransform(IWineD3DDevice *iface, WINED3DTRANSFORMSTATETYPE d3dts, CONST WINED3DMATRIX* lpmatrix) {
2147 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2149 /* Most of this routine, comments included copied from ddraw tree initially: */
2150 TRACE("(%p) : Transform State=%s\n", This, debug_d3dtstype(d3dts));
2152 /* Handle recording of state blocks */
2153 if (This->isRecordingState) {
2154 TRACE("Recording... not performing anything\n");
2155 This->updateStateBlock->changed.transform[d3dts >> 5] |= 1 << (d3dts & 0x1f);
2156 This->updateStateBlock->transforms[d3dts] = *lpmatrix;
2157 return WINED3D_OK;
2161 * If the new matrix is the same as the current one,
2162 * we cut off any further processing. this seems to be a reasonable
2163 * optimization because as was noticed, some apps (warcraft3 for example)
2164 * tend towards setting the same matrix repeatedly for some reason.
2166 * From here on we assume that the new matrix is different, wherever it matters.
2168 if (!memcmp(&This->stateBlock->transforms[d3dts].u.m[0][0], lpmatrix, sizeof(WINED3DMATRIX))) {
2169 TRACE("The app is setting the same matrix over again\n");
2170 return WINED3D_OK;
2171 } else {
2172 conv_mat(lpmatrix, &This->stateBlock->transforms[d3dts].u.m[0][0]);
2176 ScreenCoord = ProjectionMat * ViewMat * WorldMat * ObjectCoord
2177 where ViewMat = Camera space, WorldMat = world space.
2179 In OpenGL, camera and world space is combined into GL_MODELVIEW
2180 matrix. The Projection matrix stay projection matrix.
2183 /* Capture the times we can just ignore the change for now */
2184 if (d3dts == WINED3DTS_VIEW) { /* handle the VIEW matrix */
2185 This->view_ident = !memcmp(lpmatrix, identity, 16 * sizeof(float));
2186 /* Handled by the state manager */
2189 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_TRANSFORM(d3dts));
2190 return WINED3D_OK;
2193 static HRESULT WINAPI IWineD3DDeviceImpl_GetTransform(IWineD3DDevice *iface, WINED3DTRANSFORMSTATETYPE State, WINED3DMATRIX* pMatrix) {
2194 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2195 TRACE("(%p) : for Transform State %s\n", This, debug_d3dtstype(State));
2196 *pMatrix = This->stateBlock->transforms[State];
2197 return WINED3D_OK;
2200 static HRESULT WINAPI IWineD3DDeviceImpl_MultiplyTransform(IWineD3DDevice *iface, WINED3DTRANSFORMSTATETYPE State, CONST WINED3DMATRIX* pMatrix) {
2201 const WINED3DMATRIX *mat = NULL;
2202 WINED3DMATRIX temp;
2204 /* Note: Using 'updateStateBlock' rather than 'stateblock' in the code
2205 * below means it will be recorded in a state block change, but it
2206 * works regardless where it is recorded.
2207 * If this is found to be wrong, change to StateBlock.
2209 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2210 TRACE("(%p) : For state %s\n", This, debug_d3dtstype(State));
2212 if (State <= HIGHEST_TRANSFORMSTATE)
2214 mat = &This->updateStateBlock->transforms[State];
2215 } else {
2216 FIXME("Unhandled transform state!!\n");
2219 multiply_matrix(&temp, mat, pMatrix);
2221 /* Apply change via set transform - will reapply to eg. lights this way */
2222 return IWineD3DDeviceImpl_SetTransform(iface, State, &temp);
2225 /*****
2226 * Get / Set Light
2227 *****/
2228 /* Note lights are real special cases. Although the device caps state only eg. 8 are supported,
2229 you can reference any indexes you want as long as that number max are enabled at any
2230 one point in time! Therefore since the indexes can be anything, we need a hashmap of them.
2231 However, this causes stateblock problems. When capturing the state block, I duplicate the hashmap,
2232 but when recording, just build a chain pretty much of commands to be replayed. */
2234 static HRESULT WINAPI IWineD3DDeviceImpl_SetLight(IWineD3DDevice *iface, DWORD Index, CONST WINED3DLIGHT* pLight) {
2235 float rho;
2236 struct wined3d_light_info *object = NULL;
2237 UINT Hi = LIGHTMAP_HASHFUNC(Index);
2238 struct list *e;
2240 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2241 TRACE("(%p) : Idx(%d), pLight(%p). Hash index is %d\n", This, Index, pLight, Hi);
2243 /* Check the parameter range. Need for speed most wanted sets junk lights which confuse
2244 * the gl driver.
2246 if(!pLight) {
2247 WARN("Light pointer = NULL, returning WINED3DERR_INVALIDCALL\n");
2248 return WINED3DERR_INVALIDCALL;
2251 switch(pLight->Type) {
2252 case WINED3DLIGHT_POINT:
2253 case WINED3DLIGHT_SPOT:
2254 case WINED3DLIGHT_PARALLELPOINT:
2255 case WINED3DLIGHT_GLSPOT:
2256 /* Incorrect attenuation values can cause the gl driver to crash. Happens with Need for speed
2257 * most wanted
2259 if (pLight->Attenuation0 < 0.0f || pLight->Attenuation1 < 0.0f || pLight->Attenuation2 < 0.0f)
2261 WARN("Attenuation is negative, returning WINED3DERR_INVALIDCALL\n");
2262 return WINED3DERR_INVALIDCALL;
2264 break;
2266 case WINED3DLIGHT_DIRECTIONAL:
2267 /* Ignores attenuation */
2268 break;
2270 default:
2271 WARN("Light type out of range, returning WINED3DERR_INVALIDCALL\n");
2272 return WINED3DERR_INVALIDCALL;
2275 LIST_FOR_EACH(e, &This->updateStateBlock->lightMap[Hi])
2277 object = LIST_ENTRY(e, struct wined3d_light_info, entry);
2278 if(object->OriginalIndex == Index) break;
2279 object = NULL;
2282 if(!object) {
2283 TRACE("Adding new light\n");
2284 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
2285 if(!object) {
2286 ERR("Out of memory error when allocating a light\n");
2287 return E_OUTOFMEMORY;
2289 list_add_head(&This->updateStateBlock->lightMap[Hi], &object->entry);
2290 object->glIndex = -1;
2291 object->OriginalIndex = Index;
2294 /* Initialize the object */
2295 TRACE("Light %d setting to type %d, Diffuse(%f,%f,%f,%f), Specular(%f,%f,%f,%f), Ambient(%f,%f,%f,%f)\n", Index, pLight->Type,
2296 pLight->Diffuse.r, pLight->Diffuse.g, pLight->Diffuse.b, pLight->Diffuse.a,
2297 pLight->Specular.r, pLight->Specular.g, pLight->Specular.b, pLight->Specular.a,
2298 pLight->Ambient.r, pLight->Ambient.g, pLight->Ambient.b, pLight->Ambient.a);
2299 TRACE("... Pos(%f,%f,%f), Dirn(%f,%f,%f)\n", pLight->Position.x, pLight->Position.y, pLight->Position.z,
2300 pLight->Direction.x, pLight->Direction.y, pLight->Direction.z);
2301 TRACE("... Range(%f), Falloff(%f), Theta(%f), Phi(%f)\n", pLight->Range, pLight->Falloff, pLight->Theta, pLight->Phi);
2303 /* Save away the information */
2304 object->OriginalParms = *pLight;
2306 switch (pLight->Type) {
2307 case WINED3DLIGHT_POINT:
2308 /* Position */
2309 object->lightPosn[0] = pLight->Position.x;
2310 object->lightPosn[1] = pLight->Position.y;
2311 object->lightPosn[2] = pLight->Position.z;
2312 object->lightPosn[3] = 1.0f;
2313 object->cutoff = 180.0f;
2314 /* FIXME: Range */
2315 break;
2317 case WINED3DLIGHT_DIRECTIONAL:
2318 /* Direction */
2319 object->lightPosn[0] = -pLight->Direction.x;
2320 object->lightPosn[1] = -pLight->Direction.y;
2321 object->lightPosn[2] = -pLight->Direction.z;
2322 object->lightPosn[3] = 0.0f;
2323 object->exponent = 0.0f;
2324 object->cutoff = 180.0f;
2325 break;
2327 case WINED3DLIGHT_SPOT:
2328 /* Position */
2329 object->lightPosn[0] = pLight->Position.x;
2330 object->lightPosn[1] = pLight->Position.y;
2331 object->lightPosn[2] = pLight->Position.z;
2332 object->lightPosn[3] = 1.0f;
2334 /* Direction */
2335 object->lightDirn[0] = pLight->Direction.x;
2336 object->lightDirn[1] = pLight->Direction.y;
2337 object->lightDirn[2] = pLight->Direction.z;
2338 object->lightDirn[3] = 1.0f;
2341 * opengl-ish and d3d-ish spot lights use too different models for the
2342 * light "intensity" as a function of the angle towards the main light direction,
2343 * so we only can approximate very roughly.
2344 * however spot lights are rather rarely used in games (if ever used at all).
2345 * furthermore if still used, probably nobody pays attention to such details.
2347 if (pLight->Falloff == 0) {
2348 /* Falloff = 0 is easy, because d3d's and opengl's spot light equations have the
2349 * falloff resp. exponent parameter as an exponent, so the spot light lighting
2350 * will always be 1.0 for both of them, and we don't have to care for the
2351 * rest of the rather complex calculation
2353 object->exponent = 0.0f;
2354 } else {
2355 rho = pLight->Theta + (pLight->Phi - pLight->Theta)/(2*pLight->Falloff);
2356 if (rho < 0.0001f) rho = 0.0001f;
2357 object->exponent = -0.3f/logf(cosf(rho/2));
2359 if (object->exponent > 128.0f)
2361 object->exponent = 128.0f;
2363 object->cutoff = pLight->Phi*90/M_PI;
2365 /* FIXME: Range */
2366 break;
2368 default:
2369 FIXME("Unrecognized light type %d\n", pLight->Type);
2372 /* Update the live definitions if the light is currently assigned a glIndex */
2373 if (object->glIndex != -1 && !This->isRecordingState) {
2374 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(object->glIndex));
2376 return WINED3D_OK;
2379 static HRESULT WINAPI IWineD3DDeviceImpl_GetLight(IWineD3DDevice *iface, DWORD Index, WINED3DLIGHT *pLight)
2381 struct wined3d_light_info *lightInfo = NULL;
2382 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2383 DWORD Hi = LIGHTMAP_HASHFUNC(Index);
2384 struct list *e;
2385 TRACE("(%p) : Idx(%d), pLight(%p)\n", This, Index, pLight);
2387 LIST_FOR_EACH(e, &This->stateBlock->lightMap[Hi])
2389 lightInfo = LIST_ENTRY(e, struct wined3d_light_info, entry);
2390 if(lightInfo->OriginalIndex == Index) break;
2391 lightInfo = NULL;
2394 if (lightInfo == NULL) {
2395 TRACE("Light information requested but light not defined\n");
2396 return WINED3DERR_INVALIDCALL;
2399 *pLight = lightInfo->OriginalParms;
2400 return WINED3D_OK;
2403 /*****
2404 * Get / Set Light Enable
2405 * (Note for consistency, renamed d3dx function by adding the 'set' prefix)
2406 *****/
2407 static HRESULT WINAPI IWineD3DDeviceImpl_SetLightEnable(IWineD3DDevice *iface, DWORD Index, BOOL Enable)
2409 struct wined3d_light_info *lightInfo = NULL;
2410 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2411 UINT Hi = LIGHTMAP_HASHFUNC(Index);
2412 struct list *e;
2413 TRACE("(%p) : Idx(%d), enable? %d\n", This, Index, Enable);
2415 LIST_FOR_EACH(e, &This->updateStateBlock->lightMap[Hi])
2417 lightInfo = LIST_ENTRY(e, struct wined3d_light_info, entry);
2418 if(lightInfo->OriginalIndex == Index) break;
2419 lightInfo = NULL;
2421 TRACE("Found light: %p\n", lightInfo);
2423 /* Special case - enabling an undefined light creates one with a strict set of parms! */
2424 if (lightInfo == NULL) {
2426 TRACE("Light enabled requested but light not defined, so defining one!\n");
2427 IWineD3DDeviceImpl_SetLight(iface, Index, &WINED3D_default_light);
2429 /* Search for it again! Should be fairly quick as near head of list */
2430 LIST_FOR_EACH(e, &This->updateStateBlock->lightMap[Hi])
2432 lightInfo = LIST_ENTRY(e, struct wined3d_light_info, entry);
2433 if(lightInfo->OriginalIndex == Index) break;
2434 lightInfo = NULL;
2436 if (lightInfo == NULL) {
2437 FIXME("Adding default lights has failed dismally\n");
2438 return WINED3DERR_INVALIDCALL;
2442 if(!Enable) {
2443 if(lightInfo->glIndex != -1) {
2444 if(!This->isRecordingState) {
2445 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(lightInfo->glIndex));
2448 This->updateStateBlock->activeLights[lightInfo->glIndex] = NULL;
2449 lightInfo->glIndex = -1;
2450 } else {
2451 TRACE("Light already disabled, nothing to do\n");
2453 lightInfo->enabled = FALSE;
2454 } else {
2455 lightInfo->enabled = TRUE;
2456 if (lightInfo->glIndex != -1) {
2457 /* nop */
2458 TRACE("Nothing to do as light was enabled\n");
2459 } else {
2460 int i;
2461 /* Find a free gl light */
2462 for(i = 0; i < This->maxConcurrentLights; i++) {
2463 if(This->updateStateBlock->activeLights[i] == NULL) {
2464 This->updateStateBlock->activeLights[i] = lightInfo;
2465 lightInfo->glIndex = i;
2466 break;
2469 if(lightInfo->glIndex == -1) {
2470 /* Our tests show that Windows returns D3D_OK in this situation, even with
2471 * D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE devices. This
2472 * is consistent among ddraw, d3d8 and d3d9. GetLightEnable returns TRUE
2473 * as well for those lights.
2475 * TODO: Test how this affects rendering
2477 WARN("Too many concurrently active lights\n");
2478 return WINED3D_OK;
2481 /* i == lightInfo->glIndex */
2482 if(!This->isRecordingState) {
2483 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_ACTIVELIGHT(i));
2488 return WINED3D_OK;
2491 static HRESULT WINAPI IWineD3DDeviceImpl_GetLightEnable(IWineD3DDevice *iface, DWORD Index,BOOL* pEnable)
2493 struct wined3d_light_info *lightInfo = NULL;
2494 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2495 struct list *e;
2496 UINT Hi = LIGHTMAP_HASHFUNC(Index);
2497 TRACE("(%p) : for idx(%d)\n", This, Index);
2499 LIST_FOR_EACH(e, &This->stateBlock->lightMap[Hi])
2501 lightInfo = LIST_ENTRY(e, struct wined3d_light_info, entry);
2502 if(lightInfo->OriginalIndex == Index) break;
2503 lightInfo = NULL;
2506 if (lightInfo == NULL) {
2507 TRACE("Light enabled state requested but light not defined\n");
2508 return WINED3DERR_INVALIDCALL;
2510 /* true is 128 according to SetLightEnable */
2511 *pEnable = lightInfo->enabled ? 128 : 0;
2512 return WINED3D_OK;
2515 /*****
2516 * Get / Set Clip Planes
2517 *****/
2518 static HRESULT WINAPI IWineD3DDeviceImpl_SetClipPlane(IWineD3DDevice *iface, DWORD Index, CONST float *pPlane) {
2519 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2520 TRACE("(%p) : for idx %d, %p\n", This, Index, pPlane);
2522 /* Validate Index */
2523 if (Index >= This->adapter->gl_info.limits.clipplanes)
2525 TRACE("Application has requested clipplane this device doesn't support\n");
2526 return WINED3DERR_INVALIDCALL;
2529 This->updateStateBlock->changed.clipplane |= 1 << Index;
2531 if(This->updateStateBlock->clipplane[Index][0] == pPlane[0] &&
2532 This->updateStateBlock->clipplane[Index][1] == pPlane[1] &&
2533 This->updateStateBlock->clipplane[Index][2] == pPlane[2] &&
2534 This->updateStateBlock->clipplane[Index][3] == pPlane[3]) {
2535 TRACE("Application is setting old values over, nothing to do\n");
2536 return WINED3D_OK;
2539 This->updateStateBlock->clipplane[Index][0] = pPlane[0];
2540 This->updateStateBlock->clipplane[Index][1] = pPlane[1];
2541 This->updateStateBlock->clipplane[Index][2] = pPlane[2];
2542 This->updateStateBlock->clipplane[Index][3] = pPlane[3];
2544 /* Handle recording of state blocks */
2545 if (This->isRecordingState) {
2546 TRACE("Recording... not performing anything\n");
2547 return WINED3D_OK;
2550 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_CLIPPLANE(Index));
2552 return WINED3D_OK;
2555 static HRESULT WINAPI IWineD3DDeviceImpl_GetClipPlane(IWineD3DDevice *iface, DWORD Index, float *pPlane) {
2556 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2557 TRACE("(%p) : for idx %d\n", This, Index);
2559 /* Validate Index */
2560 if (Index >= This->adapter->gl_info.limits.clipplanes)
2562 TRACE("Application has requested clipplane this device doesn't support\n");
2563 return WINED3DERR_INVALIDCALL;
2566 pPlane[0] = This->stateBlock->clipplane[Index][0];
2567 pPlane[1] = This->stateBlock->clipplane[Index][1];
2568 pPlane[2] = This->stateBlock->clipplane[Index][2];
2569 pPlane[3] = This->stateBlock->clipplane[Index][3];
2570 return WINED3D_OK;
2573 /*****
2574 * Get / Set Clip Plane Status
2575 * WARNING: This code relies on the fact that D3DCLIPSTATUS8 == D3DCLIPSTATUS9
2576 *****/
2577 static HRESULT WINAPI IWineD3DDeviceImpl_SetClipStatus(IWineD3DDevice *iface, CONST WINED3DCLIPSTATUS* pClipStatus) {
2578 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2579 FIXME("(%p) : stub\n", This);
2580 if (NULL == pClipStatus) {
2581 return WINED3DERR_INVALIDCALL;
2583 This->updateStateBlock->clip_status.ClipUnion = pClipStatus->ClipUnion;
2584 This->updateStateBlock->clip_status.ClipIntersection = pClipStatus->ClipIntersection;
2585 return WINED3D_OK;
2588 static HRESULT WINAPI IWineD3DDeviceImpl_GetClipStatus(IWineD3DDevice *iface, WINED3DCLIPSTATUS* pClipStatus) {
2589 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2590 FIXME("(%p) : stub\n", This);
2591 if (NULL == pClipStatus) {
2592 return WINED3DERR_INVALIDCALL;
2594 pClipStatus->ClipUnion = This->updateStateBlock->clip_status.ClipUnion;
2595 pClipStatus->ClipIntersection = This->updateStateBlock->clip_status.ClipIntersection;
2596 return WINED3D_OK;
2599 /*****
2600 * Get / Set Material
2601 *****/
2602 static HRESULT WINAPI IWineD3DDeviceImpl_SetMaterial(IWineD3DDevice *iface, CONST WINED3DMATERIAL* pMaterial) {
2603 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2605 This->updateStateBlock->changed.material = TRUE;
2606 This->updateStateBlock->material = *pMaterial;
2608 /* Handle recording of state blocks */
2609 if (This->isRecordingState) {
2610 TRACE("Recording... not performing anything\n");
2611 return WINED3D_OK;
2614 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_MATERIAL);
2615 return WINED3D_OK;
2618 static HRESULT WINAPI IWineD3DDeviceImpl_GetMaterial(IWineD3DDevice *iface, WINED3DMATERIAL* pMaterial) {
2619 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2620 *pMaterial = This->updateStateBlock->material;
2621 TRACE("(%p) : Diffuse (%f,%f,%f,%f)\n", This, pMaterial->Diffuse.r, pMaterial->Diffuse.g,
2622 pMaterial->Diffuse.b, pMaterial->Diffuse.a);
2623 TRACE("(%p) : Ambient (%f,%f,%f,%f)\n", This, pMaterial->Ambient.r, pMaterial->Ambient.g,
2624 pMaterial->Ambient.b, pMaterial->Ambient.a);
2625 TRACE("(%p) : Specular (%f,%f,%f,%f)\n", This, pMaterial->Specular.r, pMaterial->Specular.g,
2626 pMaterial->Specular.b, pMaterial->Specular.a);
2627 TRACE("(%p) : Emissive (%f,%f,%f,%f)\n", This, pMaterial->Emissive.r, pMaterial->Emissive.g,
2628 pMaterial->Emissive.b, pMaterial->Emissive.a);
2629 TRACE("(%p) : Power (%f)\n", This, pMaterial->Power);
2631 return WINED3D_OK;
2634 /*****
2635 * Get / Set Indices
2636 *****/
2637 static HRESULT WINAPI IWineD3DDeviceImpl_SetIndexBuffer(IWineD3DDevice *iface,
2638 IWineD3DBuffer *pIndexData, WINED3DFORMAT fmt)
2640 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2641 IWineD3DBuffer *oldIdxs;
2643 TRACE("(%p) : Setting to %p\n", This, pIndexData);
2644 oldIdxs = This->updateStateBlock->pIndexData;
2646 This->updateStateBlock->changed.indices = TRUE;
2647 This->updateStateBlock->pIndexData = pIndexData;
2648 This->updateStateBlock->IndexFmt = fmt;
2650 /* Handle recording of state blocks */
2651 if (This->isRecordingState) {
2652 TRACE("Recording... not performing anything\n");
2653 if(pIndexData) IWineD3DBuffer_AddRef(pIndexData);
2654 if(oldIdxs) IWineD3DBuffer_Release(oldIdxs);
2655 return WINED3D_OK;
2658 if(oldIdxs != pIndexData) {
2659 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_INDEXBUFFER);
2660 if(pIndexData) {
2661 InterlockedIncrement(&((struct wined3d_buffer *)pIndexData)->bind_count);
2662 IWineD3DBuffer_AddRef(pIndexData);
2664 if(oldIdxs) {
2665 InterlockedDecrement(&((struct wined3d_buffer *)oldIdxs)->bind_count);
2666 IWineD3DBuffer_Release(oldIdxs);
2670 return WINED3D_OK;
2673 static HRESULT WINAPI IWineD3DDeviceImpl_GetIndexBuffer(IWineD3DDevice *iface, IWineD3DBuffer **ppIndexData)
2675 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2677 *ppIndexData = This->stateBlock->pIndexData;
2679 /* up ref count on ppindexdata */
2680 if (*ppIndexData) {
2681 IWineD3DBuffer_AddRef(*ppIndexData);
2682 TRACE("(%p) index data set to %p\n", This, ppIndexData);
2683 }else{
2684 TRACE("(%p) No index data set\n", This);
2686 TRACE("Returning %p\n", *ppIndexData);
2688 return WINED3D_OK;
2691 /* Method to offer d3d9 a simple way to set the base vertex index without messing with the index buffer */
2692 static HRESULT WINAPI IWineD3DDeviceImpl_SetBaseVertexIndex(IWineD3DDevice *iface, INT BaseIndex) {
2693 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2694 TRACE("(%p)->(%d)\n", This, BaseIndex);
2696 if(This->updateStateBlock->baseVertexIndex == BaseIndex) {
2697 TRACE("Application is setting the old value over, nothing to do\n");
2698 return WINED3D_OK;
2701 This->updateStateBlock->baseVertexIndex = BaseIndex;
2703 if (This->isRecordingState) {
2704 TRACE("Recording... not performing anything\n");
2705 return WINED3D_OK;
2707 /* The base vertex index affects the stream sources */
2708 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_STREAMSRC);
2709 return WINED3D_OK;
2712 static HRESULT WINAPI IWineD3DDeviceImpl_GetBaseVertexIndex(IWineD3DDevice *iface, INT* base_index) {
2713 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2714 TRACE("(%p) : base_index %p\n", This, base_index);
2716 *base_index = This->stateBlock->baseVertexIndex;
2718 TRACE("Returning %u\n", *base_index);
2720 return WINED3D_OK;
2723 /*****
2724 * Get / Set Viewports
2725 *****/
2726 static HRESULT WINAPI IWineD3DDeviceImpl_SetViewport(IWineD3DDevice *iface, CONST WINED3DVIEWPORT* pViewport) {
2727 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2729 TRACE("(%p)\n", This);
2730 This->updateStateBlock->changed.viewport = TRUE;
2731 This->updateStateBlock->viewport = *pViewport;
2733 /* Handle recording of state blocks */
2734 if (This->isRecordingState) {
2735 TRACE("Recording... not performing anything\n");
2736 return WINED3D_OK;
2739 TRACE("(%p) : x=%d, y=%d, wid=%d, hei=%d, minz=%f, maxz=%f\n", This,
2740 pViewport->X, pViewport->Y, pViewport->Width, pViewport->Height, pViewport->MinZ, pViewport->MaxZ);
2742 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_VIEWPORT);
2743 return WINED3D_OK;
2747 static HRESULT WINAPI IWineD3DDeviceImpl_GetViewport(IWineD3DDevice *iface, WINED3DVIEWPORT* pViewport) {
2748 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2749 TRACE("(%p)\n", This);
2750 *pViewport = This->stateBlock->viewport;
2751 return WINED3D_OK;
2754 /*****
2755 * Get / Set Render States
2756 * TODO: Verify against dx9 definitions
2757 *****/
2758 static HRESULT WINAPI IWineD3DDeviceImpl_SetRenderState(IWineD3DDevice *iface, WINED3DRENDERSTATETYPE State, DWORD Value) {
2760 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2761 DWORD oldValue = This->stateBlock->renderState[State];
2763 TRACE("(%p)->state = %s(%d), value = %d\n", This, debug_d3drenderstate(State), State, Value);
2765 This->updateStateBlock->changed.renderState[State >> 5] |= 1 << (State & 0x1f);
2766 This->updateStateBlock->renderState[State] = Value;
2768 /* Handle recording of state blocks */
2769 if (This->isRecordingState) {
2770 TRACE("Recording... not performing anything\n");
2771 return WINED3D_OK;
2774 /* Compared here and not before the assignment to allow proper stateblock recording */
2775 if(Value == oldValue) {
2776 TRACE("Application is setting the old value over, nothing to do\n");
2777 } else {
2778 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(State));
2781 return WINED3D_OK;
2784 static HRESULT WINAPI IWineD3DDeviceImpl_GetRenderState(IWineD3DDevice *iface, WINED3DRENDERSTATETYPE State, DWORD *pValue) {
2785 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2786 TRACE("(%p) for State %d = %d\n", This, State, This->stateBlock->renderState[State]);
2787 *pValue = This->stateBlock->renderState[State];
2788 return WINED3D_OK;
2791 /*****
2792 * Get / Set Sampler States
2793 * TODO: Verify against dx9 definitions
2794 *****/
2796 static HRESULT WINAPI IWineD3DDeviceImpl_SetSamplerState(IWineD3DDevice *iface, DWORD Sampler, WINED3DSAMPLERSTATETYPE Type, DWORD Value) {
2797 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2798 DWORD oldValue;
2800 TRACE("(%p) : Sampler %#x, Type %s (%#x), Value %#x\n",
2801 This, Sampler, debug_d3dsamplerstate(Type), Type, Value);
2803 if (Sampler >= WINED3DVERTEXTEXTURESAMPLER0 && Sampler <= WINED3DVERTEXTEXTURESAMPLER3) {
2804 Sampler -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2807 if (Sampler >= sizeof(This->stateBlock->samplerState)/sizeof(This->stateBlock->samplerState[0])) {
2808 ERR("Current Sampler overflows sampleState0 array (sampler %d)\n", Sampler);
2809 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2812 * SetSampler is designed to allow for more than the standard up to 8 textures
2813 * and Geforce has stopped supporting more than 6 standard textures in openGL.
2814 * So I have to use ARB for Gforce. (maybe if the sampler > 4 then use ARB?)
2816 * http://developer.nvidia.com/object/General_FAQ.html#t6
2818 * There are two new settings for GForce
2819 * the sampler one:
2820 * GL_MAX_TEXTURE_IMAGE_UNITS_ARB
2821 * and the texture one:
2822 * GL_MAX_TEXTURE_COORDS_ARB.
2823 * Ok GForce say it's ok to use glTexParameter/glGetTexParameter(...).
2824 ******************/
2826 oldValue = This->stateBlock->samplerState[Sampler][Type];
2827 This->updateStateBlock->samplerState[Sampler][Type] = Value;
2828 This->updateStateBlock->changed.samplerState[Sampler] |= 1 << Type;
2830 /* Handle recording of state blocks */
2831 if (This->isRecordingState) {
2832 TRACE("Recording... not performing anything\n");
2833 return WINED3D_OK;
2836 if(oldValue == Value) {
2837 TRACE("Application is setting the old value over, nothing to do\n");
2838 return WINED3D_OK;
2841 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(Sampler));
2843 return WINED3D_OK;
2846 static HRESULT WINAPI IWineD3DDeviceImpl_GetSamplerState(IWineD3DDevice *iface, DWORD Sampler, WINED3DSAMPLERSTATETYPE Type, DWORD* Value) {
2847 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2849 TRACE("(%p) : Sampler %#x, Type %s (%#x)\n",
2850 This, Sampler, debug_d3dsamplerstate(Type), Type);
2852 if (Sampler >= WINED3DVERTEXTEXTURESAMPLER0 && Sampler <= WINED3DVERTEXTEXTURESAMPLER3) {
2853 Sampler -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
2856 if (Sampler >= sizeof(This->stateBlock->samplerState)/sizeof(This->stateBlock->samplerState[0])) {
2857 ERR("Current Sampler overflows sampleState0 array (sampler %d)\n", Sampler);
2858 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
2860 *Value = This->stateBlock->samplerState[Sampler][Type];
2861 TRACE("(%p) : Returning %#x\n", This, *Value);
2863 return WINED3D_OK;
2866 static HRESULT WINAPI IWineD3DDeviceImpl_SetScissorRect(IWineD3DDevice *iface, CONST RECT* pRect) {
2867 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2869 This->updateStateBlock->changed.scissorRect = TRUE;
2870 if(EqualRect(&This->updateStateBlock->scissorRect, pRect)) {
2871 TRACE("App is setting the old scissor rectangle over, nothing to do\n");
2872 return WINED3D_OK;
2874 CopyRect(&This->updateStateBlock->scissorRect, pRect);
2876 if(This->isRecordingState) {
2877 TRACE("Recording... not performing anything\n");
2878 return WINED3D_OK;
2881 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SCISSORRECT);
2883 return WINED3D_OK;
2886 static HRESULT WINAPI IWineD3DDeviceImpl_GetScissorRect(IWineD3DDevice *iface, RECT* pRect) {
2887 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2889 *pRect = This->updateStateBlock->scissorRect;
2890 TRACE("(%p)Returning a Scissor Rect of %d:%d-%d:%d\n", This, pRect->left, pRect->top, pRect->right, pRect->bottom);
2891 return WINED3D_OK;
2894 static HRESULT WINAPI IWineD3DDeviceImpl_SetVertexDeclaration(IWineD3DDevice* iface, IWineD3DVertexDeclaration* pDecl) {
2895 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
2896 IWineD3DVertexDeclaration *oldDecl = This->updateStateBlock->vertexDecl;
2898 TRACE("(%p) : pDecl=%p\n", This, pDecl);
2900 if (pDecl) IWineD3DVertexDeclaration_AddRef(pDecl);
2901 if (oldDecl) IWineD3DVertexDeclaration_Release(oldDecl);
2903 This->updateStateBlock->vertexDecl = pDecl;
2904 This->updateStateBlock->changed.vertexDecl = TRUE;
2906 if (This->isRecordingState) {
2907 TRACE("Recording... not performing anything\n");
2908 return WINED3D_OK;
2909 } else if(pDecl == oldDecl) {
2910 /* Checked after the assignment to allow proper stateblock recording */
2911 TRACE("Application is setting the old declaration over, nothing to do\n");
2912 return WINED3D_OK;
2915 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_VDECL);
2916 return WINED3D_OK;
2919 static HRESULT WINAPI IWineD3DDeviceImpl_GetVertexDeclaration(IWineD3DDevice* iface, IWineD3DVertexDeclaration** ppDecl) {
2920 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2922 TRACE("(%p) : ppDecl=%p\n", This, ppDecl);
2924 *ppDecl = This->stateBlock->vertexDecl;
2925 if (NULL != *ppDecl) IWineD3DVertexDeclaration_AddRef(*ppDecl);
2926 return WINED3D_OK;
2929 static HRESULT WINAPI IWineD3DDeviceImpl_SetVertexShader(IWineD3DDevice *iface, IWineD3DVertexShader* pShader) {
2930 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2931 IWineD3DVertexShader* oldShader = This->updateStateBlock->vertexShader;
2933 This->updateStateBlock->vertexShader = pShader;
2934 This->updateStateBlock->changed.vertexShader = TRUE;
2936 if (This->isRecordingState) {
2937 if(pShader) IWineD3DVertexShader_AddRef(pShader);
2938 if(oldShader) IWineD3DVertexShader_Release(oldShader);
2939 TRACE("Recording... not performing anything\n");
2940 return WINED3D_OK;
2941 } else if(oldShader == pShader) {
2942 /* Checked here to allow proper stateblock recording */
2943 TRACE("App is setting the old shader over, nothing to do\n");
2944 return WINED3D_OK;
2947 TRACE("(%p) : setting pShader(%p)\n", This, pShader);
2948 if(pShader) IWineD3DVertexShader_AddRef(pShader);
2949 if(oldShader) IWineD3DVertexShader_Release(oldShader);
2951 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_VSHADER);
2953 return WINED3D_OK;
2956 static HRESULT WINAPI IWineD3DDeviceImpl_GetVertexShader(IWineD3DDevice *iface, IWineD3DVertexShader** ppShader) {
2957 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2959 if (NULL == ppShader) {
2960 return WINED3DERR_INVALIDCALL;
2962 *ppShader = This->stateBlock->vertexShader;
2963 if( NULL != *ppShader)
2964 IWineD3DVertexShader_AddRef(*ppShader);
2966 TRACE("(%p) : returning %p\n", This, *ppShader);
2967 return WINED3D_OK;
2970 static HRESULT WINAPI IWineD3DDeviceImpl_SetVertexShaderConstantB(
2971 IWineD3DDevice *iface,
2972 UINT start,
2973 CONST BOOL *srcData,
2974 UINT count) {
2976 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2977 unsigned int i, cnt = min(count, MAX_CONST_B - start);
2979 TRACE("(iface %p, srcData %p, start %d, count %d)\n",
2980 iface, srcData, start, count);
2982 if (!srcData || start >= MAX_CONST_B) return WINED3DERR_INVALIDCALL;
2984 memcpy(&This->updateStateBlock->vertexShaderConstantB[start], srcData, cnt * sizeof(BOOL));
2985 for (i = 0; i < cnt; i++)
2986 TRACE("Set BOOL constant %u to %s\n", start + i, srcData[i]? "true":"false");
2988 for (i = start; i < cnt + start; ++i) {
2989 This->updateStateBlock->changed.vertexShaderConstantsB |= (1 << i);
2992 if (!This->isRecordingState) IWineD3DDeviceImpl_MarkStateDirty(This, STATE_VERTEXSHADERCONSTANT);
2994 return WINED3D_OK;
2997 static HRESULT WINAPI IWineD3DDeviceImpl_GetVertexShaderConstantB(
2998 IWineD3DDevice *iface,
2999 UINT start,
3000 BOOL *dstData,
3001 UINT count) {
3003 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3004 int cnt = min(count, MAX_CONST_B - start);
3006 TRACE("(iface %p, dstData %p, start %d, count %d)\n",
3007 iface, dstData, start, count);
3009 if (dstData == NULL || cnt < 0)
3010 return WINED3DERR_INVALIDCALL;
3012 memcpy(dstData, &This->stateBlock->vertexShaderConstantB[start], cnt * sizeof(BOOL));
3013 return WINED3D_OK;
3016 static HRESULT WINAPI IWineD3DDeviceImpl_SetVertexShaderConstantI(
3017 IWineD3DDevice *iface,
3018 UINT start,
3019 CONST int *srcData,
3020 UINT count) {
3022 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3023 unsigned int i, cnt = min(count, MAX_CONST_I - start);
3025 TRACE("(iface %p, srcData %p, start %d, count %d)\n",
3026 iface, srcData, start, count);
3028 if (!srcData || start >= MAX_CONST_I) return WINED3DERR_INVALIDCALL;
3030 memcpy(&This->updateStateBlock->vertexShaderConstantI[start * 4], srcData, cnt * sizeof(int) * 4);
3031 for (i = 0; i < cnt; i++)
3032 TRACE("Set INT constant %u to { %d, %d, %d, %d }\n", start + i,
3033 srcData[i*4], srcData[i*4+1], srcData[i*4+2], srcData[i*4+3]);
3035 for (i = start; i < cnt + start; ++i) {
3036 This->updateStateBlock->changed.vertexShaderConstantsI |= (1 << i);
3039 if (!This->isRecordingState) IWineD3DDeviceImpl_MarkStateDirty(This, STATE_VERTEXSHADERCONSTANT);
3041 return WINED3D_OK;
3044 static HRESULT WINAPI IWineD3DDeviceImpl_GetVertexShaderConstantI(
3045 IWineD3DDevice *iface,
3046 UINT start,
3047 int *dstData,
3048 UINT count) {
3050 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3051 int cnt = min(count, MAX_CONST_I - start);
3053 TRACE("(iface %p, dstData %p, start %d, count %d)\n",
3054 iface, dstData, start, count);
3056 if (dstData == NULL || ((signed int) MAX_CONST_I - (signed int) start) <= 0)
3057 return WINED3DERR_INVALIDCALL;
3059 memcpy(dstData, &This->stateBlock->vertexShaderConstantI[start * 4], cnt * sizeof(int) * 4);
3060 return WINED3D_OK;
3063 static HRESULT WINAPI IWineD3DDeviceImpl_SetVertexShaderConstantF(
3064 IWineD3DDevice *iface,
3065 UINT start,
3066 CONST float *srcData,
3067 UINT count) {
3069 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3070 UINT i;
3072 TRACE("(iface %p, srcData %p, start %d, count %d)\n",
3073 iface, srcData, start, count);
3075 /* Specifically test start > limit to catch MAX_UINT overflows when adding start + count */
3076 if (srcData == NULL || start + count > This->d3d_vshader_constantF || start > This->d3d_vshader_constantF)
3077 return WINED3DERR_INVALIDCALL;
3079 memcpy(&This->updateStateBlock->vertexShaderConstantF[start * 4], srcData, count * sizeof(float) * 4);
3080 if(TRACE_ON(d3d)) {
3081 for (i = 0; i < count; i++)
3082 TRACE("Set FLOAT constant %u to { %f, %f, %f, %f }\n", start + i,
3083 srcData[i*4], srcData[i*4+1], srcData[i*4+2], srcData[i*4+3]);
3086 if (!This->isRecordingState)
3088 This->shader_backend->shader_update_float_vertex_constants(iface, start, count);
3089 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_VERTEXSHADERCONSTANT);
3092 memset(This->updateStateBlock->changed.vertexShaderConstantsF + start, 1,
3093 sizeof(*This->updateStateBlock->changed.vertexShaderConstantsF) * count);
3095 return WINED3D_OK;
3098 static HRESULT WINAPI IWineD3DDeviceImpl_GetVertexShaderConstantF(
3099 IWineD3DDevice *iface,
3100 UINT start,
3101 float *dstData,
3102 UINT count) {
3104 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3105 int cnt = min(count, This->d3d_vshader_constantF - start);
3107 TRACE("(iface %p, dstData %p, start %d, count %d)\n",
3108 iface, dstData, start, count);
3110 if (dstData == NULL || cnt < 0)
3111 return WINED3DERR_INVALIDCALL;
3113 memcpy(dstData, &This->stateBlock->vertexShaderConstantF[start * 4], cnt * sizeof(float) * 4);
3114 return WINED3D_OK;
3117 static inline void markTextureStagesDirty(IWineD3DDeviceImpl *This, DWORD stage) {
3118 DWORD i;
3119 for(i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
3121 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_TEXTURESTAGE(stage, i));
3125 static void device_map_stage(IWineD3DDeviceImpl *This, DWORD stage, DWORD unit)
3127 DWORD i = This->rev_tex_unit_map[unit];
3128 DWORD j = This->texUnitMap[stage];
3130 This->texUnitMap[stage] = unit;
3131 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
3133 This->texUnitMap[i] = WINED3D_UNMAPPED_STAGE;
3136 This->rev_tex_unit_map[unit] = stage;
3137 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
3139 This->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
3143 static void device_update_fixed_function_usage_map(IWineD3DDeviceImpl *This) {
3144 int i;
3146 This->fixed_function_usage_map = 0;
3147 for (i = 0; i < MAX_TEXTURES; ++i) {
3148 WINED3DTEXTUREOP color_op = This->stateBlock->textureState[i][WINED3DTSS_COLOROP];
3149 WINED3DTEXTUREOP alpha_op = This->stateBlock->textureState[i][WINED3DTSS_ALPHAOP];
3150 DWORD color_arg1 = This->stateBlock->textureState[i][WINED3DTSS_COLORARG1] & WINED3DTA_SELECTMASK;
3151 DWORD color_arg2 = This->stateBlock->textureState[i][WINED3DTSS_COLORARG2] & WINED3DTA_SELECTMASK;
3152 DWORD color_arg3 = This->stateBlock->textureState[i][WINED3DTSS_COLORARG0] & WINED3DTA_SELECTMASK;
3153 DWORD alpha_arg1 = This->stateBlock->textureState[i][WINED3DTSS_ALPHAARG1] & WINED3DTA_SELECTMASK;
3154 DWORD alpha_arg2 = This->stateBlock->textureState[i][WINED3DTSS_ALPHAARG2] & WINED3DTA_SELECTMASK;
3155 DWORD alpha_arg3 = This->stateBlock->textureState[i][WINED3DTSS_ALPHAARG0] & WINED3DTA_SELECTMASK;
3157 if (color_op == WINED3DTOP_DISABLE) {
3158 /* Not used, and disable higher stages */
3159 break;
3162 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3DTOP_SELECTARG2)
3163 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3DTOP_SELECTARG1)
3164 || ((color_arg3 == WINED3DTA_TEXTURE) && (color_op == WINED3DTOP_MULTIPLYADD || color_op == WINED3DTOP_LERP))
3165 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3DTOP_SELECTARG2)
3166 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3DTOP_SELECTARG1)
3167 || ((alpha_arg3 == WINED3DTA_TEXTURE) && (alpha_op == WINED3DTOP_MULTIPLYADD || alpha_op == WINED3DTOP_LERP))) {
3168 This->fixed_function_usage_map |= (1 << i);
3171 if ((color_op == WINED3DTOP_BUMPENVMAP || color_op == WINED3DTOP_BUMPENVMAPLUMINANCE) && i < MAX_TEXTURES - 1) {
3172 This->fixed_function_usage_map |= (1 << (i + 1));
3177 static void device_map_fixed_function_samplers(IWineD3DDeviceImpl *This, const struct wined3d_gl_info *gl_info)
3179 unsigned int i, tex;
3180 WORD ffu_map;
3182 device_update_fixed_function_usage_map(This);
3183 ffu_map = This->fixed_function_usage_map;
3185 if (This->max_ffp_textures == gl_info->limits.texture_stages
3186 || This->stateBlock->lowest_disabled_stage <= This->max_ffp_textures)
3188 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3190 if (!(ffu_map & 1)) continue;
3192 if (This->texUnitMap[i] != i) {
3193 device_map_stage(This, i, i);
3194 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(i));
3195 markTextureStagesDirty(This, i);
3198 return;
3201 /* Now work out the mapping */
3202 tex = 0;
3203 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3205 if (!(ffu_map & 1)) continue;
3207 if (This->texUnitMap[i] != tex) {
3208 device_map_stage(This, i, tex);
3209 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(i));
3210 markTextureStagesDirty(This, i);
3213 ++tex;
3217 static void device_map_psamplers(IWineD3DDeviceImpl *This, const struct wined3d_gl_info *gl_info)
3219 const WINED3DSAMPLER_TEXTURE_TYPE *sampler_type =
3220 ((IWineD3DPixelShaderImpl *)This->stateBlock->pixelShader)->baseShader.reg_maps.sampler_type;
3221 unsigned int i;
3223 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
3224 if (sampler_type[i] && This->texUnitMap[i] != i)
3226 device_map_stage(This, i, i);
3227 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(i));
3228 if (i < gl_info->limits.texture_stages)
3230 markTextureStagesDirty(This, i);
3236 static BOOL device_unit_free_for_vs(IWineD3DDeviceImpl *This, const DWORD *pshader_sampler_tokens,
3237 const DWORD *vshader_sampler_tokens, DWORD unit)
3239 DWORD current_mapping = This->rev_tex_unit_map[unit];
3241 /* Not currently used */
3242 if (current_mapping == WINED3D_UNMAPPED_STAGE) return TRUE;
3244 if (current_mapping < MAX_FRAGMENT_SAMPLERS) {
3245 /* Used by a fragment sampler */
3247 if (!pshader_sampler_tokens) {
3248 /* No pixel shader, check fixed function */
3249 return current_mapping >= MAX_TEXTURES || !(This->fixed_function_usage_map & (1 << current_mapping));
3252 /* Pixel shader, check the shader's sampler map */
3253 return !pshader_sampler_tokens[current_mapping];
3256 /* Used by a vertex sampler */
3257 return !vshader_sampler_tokens[current_mapping - MAX_FRAGMENT_SAMPLERS];
3260 static void device_map_vsamplers(IWineD3DDeviceImpl *This, BOOL ps, const struct wined3d_gl_info *gl_info)
3262 const WINED3DSAMPLER_TEXTURE_TYPE *vshader_sampler_type =
3263 ((IWineD3DVertexShaderImpl *)This->stateBlock->vertexShader)->baseShader.reg_maps.sampler_type;
3264 const WINED3DSAMPLER_TEXTURE_TYPE *pshader_sampler_type = NULL;
3265 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
3266 int i;
3268 if (ps) {
3269 IWineD3DPixelShaderImpl *pshader = (IWineD3DPixelShaderImpl *)This->stateBlock->pixelShader;
3271 /* Note that we only care if a sampler is sampled or not, not the sampler's specific type.
3272 * Otherwise we'd need to call shader_update_samplers() here for 1.x pixelshaders. */
3273 pshader_sampler_type = pshader->baseShader.reg_maps.sampler_type;
3276 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
3277 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
3278 if (vshader_sampler_type[i])
3280 if (This->texUnitMap[vsampler_idx] != WINED3D_UNMAPPED_STAGE)
3282 /* Already mapped somewhere */
3283 continue;
3286 while (start >= 0) {
3287 if (device_unit_free_for_vs(This, pshader_sampler_type, vshader_sampler_type, start))
3289 device_map_stage(This, vsampler_idx, start);
3290 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(vsampler_idx));
3292 --start;
3293 break;
3296 --start;
3302 void IWineD3DDeviceImpl_FindTexUnitMap(IWineD3DDeviceImpl *This)
3304 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
3305 BOOL vs = use_vs(This->stateBlock);
3306 BOOL ps = use_ps(This->stateBlock);
3308 * Rules are:
3309 * -> Pixel shaders need a 1:1 map. In theory the shader input could be mapped too, but
3310 * that would be really messy and require shader recompilation
3311 * -> When the mapping of a stage is changed, sampler and ALL texture stage states have
3312 * to be reset. Because of that try to work with a 1:1 mapping as much as possible
3314 if (ps) device_map_psamplers(This, gl_info);
3315 else device_map_fixed_function_samplers(This, gl_info);
3317 if (vs) device_map_vsamplers(This, ps, gl_info);
3320 static HRESULT WINAPI IWineD3DDeviceImpl_SetPixelShader(IWineD3DDevice *iface, IWineD3DPixelShader *pShader) {
3321 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3322 IWineD3DPixelShader *oldShader = This->updateStateBlock->pixelShader;
3323 This->updateStateBlock->pixelShader = pShader;
3324 This->updateStateBlock->changed.pixelShader = TRUE;
3326 /* Handle recording of state blocks */
3327 if (This->isRecordingState) {
3328 TRACE("Recording... not performing anything\n");
3331 if (This->isRecordingState) {
3332 TRACE("Recording... not performing anything\n");
3333 if(pShader) IWineD3DPixelShader_AddRef(pShader);
3334 if(oldShader) IWineD3DPixelShader_Release(oldShader);
3335 return WINED3D_OK;
3338 if(pShader == oldShader) {
3339 TRACE("App is setting the old pixel shader over, nothing to do\n");
3340 return WINED3D_OK;
3343 if(pShader) IWineD3DPixelShader_AddRef(pShader);
3344 if(oldShader) IWineD3DPixelShader_Release(oldShader);
3346 TRACE("(%p) : setting pShader(%p)\n", This, pShader);
3347 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_PIXELSHADER);
3349 return WINED3D_OK;
3352 static HRESULT WINAPI IWineD3DDeviceImpl_GetPixelShader(IWineD3DDevice *iface, IWineD3DPixelShader **ppShader) {
3353 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3355 if (NULL == ppShader) {
3356 WARN("(%p) : PShader is NULL, returning INVALIDCALL\n", This);
3357 return WINED3DERR_INVALIDCALL;
3360 *ppShader = This->stateBlock->pixelShader;
3361 if (NULL != *ppShader) {
3362 IWineD3DPixelShader_AddRef(*ppShader);
3364 TRACE("(%p) : returning %p\n", This, *ppShader);
3365 return WINED3D_OK;
3368 static HRESULT WINAPI IWineD3DDeviceImpl_SetPixelShaderConstantB(
3369 IWineD3DDevice *iface,
3370 UINT start,
3371 CONST BOOL *srcData,
3372 UINT count) {
3374 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3375 unsigned int i, cnt = min(count, MAX_CONST_B - start);
3377 TRACE("(iface %p, srcData %p, start %u, count %u)\n",
3378 iface, srcData, start, count);
3380 if (!srcData || start >= MAX_CONST_B) return WINED3DERR_INVALIDCALL;
3382 memcpy(&This->updateStateBlock->pixelShaderConstantB[start], srcData, cnt * sizeof(BOOL));
3383 for (i = 0; i < cnt; i++)
3384 TRACE("Set BOOL constant %u to %s\n", start + i, srcData[i]? "true":"false");
3386 for (i = start; i < cnt + start; ++i) {
3387 This->updateStateBlock->changed.pixelShaderConstantsB |= (1 << i);
3390 if (!This->isRecordingState) IWineD3DDeviceImpl_MarkStateDirty(This, STATE_PIXELSHADERCONSTANT);
3392 return WINED3D_OK;
3395 static HRESULT WINAPI IWineD3DDeviceImpl_GetPixelShaderConstantB(
3396 IWineD3DDevice *iface,
3397 UINT start,
3398 BOOL *dstData,
3399 UINT count) {
3401 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3402 int cnt = min(count, MAX_CONST_B - start);
3404 TRACE("(iface %p, dstData %p, start %d, count %d)\n",
3405 iface, dstData, start, count);
3407 if (dstData == NULL || cnt < 0)
3408 return WINED3DERR_INVALIDCALL;
3410 memcpy(dstData, &This->stateBlock->pixelShaderConstantB[start], cnt * sizeof(BOOL));
3411 return WINED3D_OK;
3414 static HRESULT WINAPI IWineD3DDeviceImpl_SetPixelShaderConstantI(
3415 IWineD3DDevice *iface,
3416 UINT start,
3417 CONST int *srcData,
3418 UINT count) {
3420 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3421 unsigned int i, cnt = min(count, MAX_CONST_I - start);
3423 TRACE("(iface %p, srcData %p, start %u, count %u)\n",
3424 iface, srcData, start, count);
3426 if (!srcData || start >= MAX_CONST_I) return WINED3DERR_INVALIDCALL;
3428 memcpy(&This->updateStateBlock->pixelShaderConstantI[start * 4], srcData, cnt * sizeof(int) * 4);
3429 for (i = 0; i < cnt; i++)
3430 TRACE("Set INT constant %u to { %d, %d, %d, %d }\n", start + i,
3431 srcData[i*4], srcData[i*4+1], srcData[i*4+2], srcData[i*4+3]);
3433 for (i = start; i < cnt + start; ++i) {
3434 This->updateStateBlock->changed.pixelShaderConstantsI |= (1 << i);
3437 if (!This->isRecordingState) IWineD3DDeviceImpl_MarkStateDirty(This, STATE_PIXELSHADERCONSTANT);
3439 return WINED3D_OK;
3442 static HRESULT WINAPI IWineD3DDeviceImpl_GetPixelShaderConstantI(
3443 IWineD3DDevice *iface,
3444 UINT start,
3445 int *dstData,
3446 UINT count) {
3448 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3449 int cnt = min(count, MAX_CONST_I - start);
3451 TRACE("(iface %p, dstData %p, start %d, count %d)\n",
3452 iface, dstData, start, count);
3454 if (dstData == NULL || cnt < 0)
3455 return WINED3DERR_INVALIDCALL;
3457 memcpy(dstData, &This->stateBlock->pixelShaderConstantI[start * 4], cnt * sizeof(int) * 4);
3458 return WINED3D_OK;
3461 static HRESULT WINAPI IWineD3DDeviceImpl_SetPixelShaderConstantF(
3462 IWineD3DDevice *iface,
3463 UINT start,
3464 CONST float *srcData,
3465 UINT count) {
3467 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3468 UINT i;
3470 TRACE("(iface %p, srcData %p, start %d, count %d)\n",
3471 iface, srcData, start, count);
3473 /* Specifically test start > limit to catch MAX_UINT overflows when adding start + count */
3474 if (srcData == NULL || start + count > This->d3d_pshader_constantF || start > This->d3d_pshader_constantF)
3475 return WINED3DERR_INVALIDCALL;
3477 memcpy(&This->updateStateBlock->pixelShaderConstantF[start * 4], srcData, count * sizeof(float) * 4);
3478 if(TRACE_ON(d3d)) {
3479 for (i = 0; i < count; i++)
3480 TRACE("Set FLOAT constant %u to { %f, %f, %f, %f }\n", start + i,
3481 srcData[i*4], srcData[i*4+1], srcData[i*4+2], srcData[i*4+3]);
3484 if (!This->isRecordingState)
3486 This->shader_backend->shader_update_float_pixel_constants(iface, start, count);
3487 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_PIXELSHADERCONSTANT);
3490 memset(This->updateStateBlock->changed.pixelShaderConstantsF + start, 1,
3491 sizeof(*This->updateStateBlock->changed.pixelShaderConstantsF) * count);
3493 return WINED3D_OK;
3496 static HRESULT WINAPI IWineD3DDeviceImpl_GetPixelShaderConstantF(
3497 IWineD3DDevice *iface,
3498 UINT start,
3499 float *dstData,
3500 UINT count) {
3502 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3503 int cnt = min(count, This->d3d_pshader_constantF - start);
3505 TRACE("(iface %p, dstData %p, start %d, count %d)\n",
3506 iface, dstData, start, count);
3508 if (dstData == NULL || cnt < 0)
3509 return WINED3DERR_INVALIDCALL;
3511 memcpy(dstData, &This->stateBlock->pixelShaderConstantF[start * 4], cnt * sizeof(float) * 4);
3512 return WINED3D_OK;
3515 /* Context activation is done by the caller. */
3516 #define copy_and_next(dest, src, size) memcpy(dest, src, size); dest += (size)
3517 static HRESULT process_vertices_strided(IWineD3DDeviceImpl *This, DWORD dwDestIndex, DWORD dwCount,
3518 const struct wined3d_stream_info *stream_info, struct wined3d_buffer *dest, DWORD dwFlags,
3519 DWORD DestFVF)
3521 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
3522 char *dest_ptr, *dest_conv = NULL, *dest_conv_addr = NULL;
3523 unsigned int i;
3524 WINED3DVIEWPORT vp;
3525 WINED3DMATRIX mat, proj_mat, view_mat, world_mat;
3526 BOOL doClip;
3527 DWORD numTextures;
3529 if (stream_info->use_map & (1 << WINED3D_FFP_NORMAL))
3531 WARN(" lighting state not saved yet... Some strange stuff may happen !\n");
3534 if (!(stream_info->use_map & (1 << WINED3D_FFP_POSITION)))
3536 ERR("Source has no position mask\n");
3537 return WINED3DERR_INVALIDCALL;
3540 /* We might access VBOs from this code, so hold the lock */
3541 ENTER_GL();
3543 if (dest->resource.allocatedMemory == NULL) {
3544 buffer_get_sysmem(dest);
3547 /* Get a pointer into the destination vbo(create one if none exists) and
3548 * write correct opengl data into it. It's cheap and allows us to run drawStridedFast
3550 if (!dest->buffer_object && gl_info->supported[ARB_VERTEX_BUFFER_OBJECT])
3552 dest->flags |= WINED3D_BUFFER_CREATEBO;
3553 IWineD3DBuffer_PreLoad((IWineD3DBuffer *)dest);
3556 if (dest->buffer_object)
3558 unsigned char extrabytes = 0;
3559 /* If the destination vertex buffer has D3DFVF_XYZ position(non-rhw), native d3d writes RHW position, where the RHW
3560 * gets written into the 4 bytes after the Z position. In the case of a dest buffer that only has D3DFVF_XYZ data,
3561 * this may write 4 extra bytes beyond the area that should be written
3563 if(DestFVF == WINED3DFVF_XYZ) extrabytes = 4;
3564 dest_conv_addr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCount * get_flexible_vertex_size(DestFVF) + extrabytes);
3565 if(!dest_conv_addr) {
3566 ERR("Out of memory\n");
3567 /* Continue without storing converted vertices */
3569 dest_conv = dest_conv_addr;
3572 /* Should I clip?
3573 * a) WINED3DRS_CLIPPING is enabled
3574 * b) WINED3DVOP_CLIP is passed
3576 if(This->stateBlock->renderState[WINED3DRS_CLIPPING]) {
3577 static BOOL warned = FALSE;
3579 * The clipping code is not quite correct. Some things need
3580 * to be checked against IDirect3DDevice3 (!), d3d8 and d3d9,
3581 * so disable clipping for now.
3582 * (The graphics in Half-Life are broken, and my processvertices
3583 * test crashes with IDirect3DDevice3)
3584 doClip = TRUE;
3586 doClip = FALSE;
3587 if(!warned) {
3588 warned = TRUE;
3589 FIXME("Clipping is broken and disabled for now\n");
3591 } else doClip = FALSE;
3592 dest_ptr = ((char *) buffer_get_sysmem(dest)) + dwDestIndex * get_flexible_vertex_size(DestFVF);
3594 IWineD3DDevice_GetTransform( (IWineD3DDevice *) This,
3595 WINED3DTS_VIEW,
3596 &view_mat);
3597 IWineD3DDevice_GetTransform( (IWineD3DDevice *) This,
3598 WINED3DTS_PROJECTION,
3599 &proj_mat);
3600 IWineD3DDevice_GetTransform( (IWineD3DDevice *) This,
3601 WINED3DTS_WORLDMATRIX(0),
3602 &world_mat);
3604 TRACE("View mat:\n");
3605 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);
3606 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);
3607 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);
3608 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);
3610 TRACE("Proj mat:\n");
3611 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);
3612 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);
3613 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);
3614 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);
3616 TRACE("World mat:\n");
3617 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);
3618 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);
3619 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);
3620 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);
3622 /* Get the viewport */
3623 IWineD3DDevice_GetViewport( (IWineD3DDevice *) This, &vp);
3624 TRACE("Viewport: X=%d, Y=%d, Width=%d, Height=%d, MinZ=%f, MaxZ=%f\n",
3625 vp.X, vp.Y, vp.Width, vp.Height, vp.MinZ, vp.MaxZ);
3627 multiply_matrix(&mat,&view_mat,&world_mat);
3628 multiply_matrix(&mat,&proj_mat,&mat);
3630 numTextures = (DestFVF & WINED3DFVF_TEXCOUNT_MASK) >> WINED3DFVF_TEXCOUNT_SHIFT;
3632 for (i = 0; i < dwCount; i+= 1) {
3633 unsigned int tex_index;
3635 if ( ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZ ) ||
3636 ((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW ) ) {
3637 /* The position first */
3638 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_POSITION];
3639 const float *p = (const float *)(element->data + i * element->stride);
3640 float x, y, z, rhw;
3641 TRACE("In: ( %06.2f %06.2f %06.2f )\n", p[0], p[1], p[2]);
3643 /* Multiplication with world, view and projection matrix */
3644 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);
3645 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);
3646 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);
3647 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);
3649 TRACE("x=%f y=%f z=%f rhw=%f\n", x, y, z, rhw);
3651 /* WARNING: The following things are taken from d3d7 and were not yet checked
3652 * against d3d8 or d3d9!
3655 /* Clipping conditions: From msdn
3657 * A vertex is clipped if it does not match the following requirements
3658 * -rhw < x <= rhw
3659 * -rhw < y <= rhw
3660 * 0 < z <= rhw
3661 * 0 < rhw ( Not in d3d7, but tested in d3d7)
3663 * If clipping is on is determined by the D3DVOP_CLIP flag in D3D7, and
3664 * by the D3DRS_CLIPPING in D3D9(according to the msdn, not checked)
3668 if( !doClip ||
3669 ( (-rhw -eps < x) && (-rhw -eps < y) && ( -eps < z) &&
3670 (x <= rhw + eps) && (y <= rhw + eps ) && (z <= rhw + eps) &&
3671 ( rhw > eps ) ) ) {
3673 /* "Normal" viewport transformation (not clipped)
3674 * 1) The values are divided by rhw
3675 * 2) The y axis is negative, so multiply it with -1
3676 * 3) Screen coordinates go from -(Width/2) to +(Width/2) and
3677 * -(Height/2) to +(Height/2). The z range is MinZ to MaxZ
3678 * 4) Multiply x with Width/2 and add Width/2
3679 * 5) The same for the height
3680 * 6) Add the viewpoint X and Y to the 2D coordinates and
3681 * The minimum Z value to z
3682 * 7) rhw = 1 / rhw Reciprocal of Homogeneous W....
3684 * Well, basically it's simply a linear transformation into viewport
3685 * coordinates
3688 x /= rhw;
3689 y /= rhw;
3690 z /= rhw;
3692 y *= -1;
3694 x *= vp.Width / 2;
3695 y *= vp.Height / 2;
3696 z *= vp.MaxZ - vp.MinZ;
3698 x += vp.Width / 2 + vp.X;
3699 y += vp.Height / 2 + vp.Y;
3700 z += vp.MinZ;
3702 rhw = 1 / rhw;
3703 } else {
3704 /* That vertex got clipped
3705 * Contrary to OpenGL it is not dropped completely, it just
3706 * undergoes a different calculation.
3708 TRACE("Vertex got clipped\n");
3709 x += rhw;
3710 y += rhw;
3712 x /= 2;
3713 y /= 2;
3715 /* Msdn mentions that Direct3D9 keeps a list of clipped vertices
3716 * outside of the main vertex buffer memory. That needs some more
3717 * investigation...
3721 TRACE("Writing (%f %f %f) %f\n", x, y, z, rhw);
3724 ( (float *) dest_ptr)[0] = x;
3725 ( (float *) dest_ptr)[1] = y;
3726 ( (float *) dest_ptr)[2] = z;
3727 ( (float *) dest_ptr)[3] = rhw; /* SIC, see ddraw test! */
3729 dest_ptr += 3 * sizeof(float);
3731 if((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW) {
3732 dest_ptr += sizeof(float);
3735 if(dest_conv) {
3736 float w = 1 / rhw;
3737 ( (float *) dest_conv)[0] = x * w;
3738 ( (float *) dest_conv)[1] = y * w;
3739 ( (float *) dest_conv)[2] = z * w;
3740 ( (float *) dest_conv)[3] = w;
3742 dest_conv += 3 * sizeof(float);
3744 if((DestFVF & WINED3DFVF_POSITION_MASK) == WINED3DFVF_XYZRHW) {
3745 dest_conv += sizeof(float);
3749 if (DestFVF & WINED3DFVF_PSIZE) {
3750 dest_ptr += sizeof(DWORD);
3751 if(dest_conv) dest_conv += sizeof(DWORD);
3753 if (DestFVF & WINED3DFVF_NORMAL) {
3754 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_NORMAL];
3755 const float *normal = (const float *)(element->data + i * element->stride);
3756 /* AFAIK this should go into the lighting information */
3757 FIXME("Didn't expect the destination to have a normal\n");
3758 copy_and_next(dest_ptr, normal, 3 * sizeof(float));
3759 if(dest_conv) {
3760 copy_and_next(dest_conv, normal, 3 * sizeof(float));
3764 if (DestFVF & WINED3DFVF_DIFFUSE) {
3765 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_DIFFUSE];
3766 const DWORD *color_d = (const DWORD *)(element->data + i * element->stride);
3767 if (!(stream_info->use_map & (1 << WINED3D_FFP_DIFFUSE)))
3769 static BOOL warned = FALSE;
3771 if(!warned) {
3772 ERR("No diffuse color in source, but destination has one\n");
3773 warned = TRUE;
3776 *( (DWORD *) dest_ptr) = 0xffffffff;
3777 dest_ptr += sizeof(DWORD);
3779 if(dest_conv) {
3780 *( (DWORD *) dest_conv) = 0xffffffff;
3781 dest_conv += sizeof(DWORD);
3784 else {
3785 copy_and_next(dest_ptr, color_d, sizeof(DWORD));
3786 if(dest_conv) {
3787 *( (DWORD *) dest_conv) = (*color_d & 0xff00ff00) ; /* Alpha + green */
3788 *( (DWORD *) dest_conv) |= (*color_d & 0x00ff0000) >> 16; /* Red */
3789 *( (DWORD *) dest_conv) |= (*color_d & 0xff0000ff) << 16; /* Blue */
3790 dest_conv += sizeof(DWORD);
3795 if (DestFVF & WINED3DFVF_SPECULAR)
3797 /* What's the color value in the feedback buffer? */
3798 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_SPECULAR];
3799 const DWORD *color_s = (const DWORD *)(element->data + i * element->stride);
3800 if (!(stream_info->use_map & (1 << WINED3D_FFP_SPECULAR)))
3802 static BOOL warned = FALSE;
3804 if(!warned) {
3805 ERR("No specular color in source, but destination has one\n");
3806 warned = TRUE;
3809 *( (DWORD *) dest_ptr) = 0xFF000000;
3810 dest_ptr += sizeof(DWORD);
3812 if(dest_conv) {
3813 *( (DWORD *) dest_conv) = 0xFF000000;
3814 dest_conv += sizeof(DWORD);
3817 else {
3818 copy_and_next(dest_ptr, color_s, sizeof(DWORD));
3819 if(dest_conv) {
3820 *( (DWORD *) dest_conv) = (*color_s & 0xff00ff00) ; /* Alpha + green */
3821 *( (DWORD *) dest_conv) |= (*color_s & 0x00ff0000) >> 16; /* Red */
3822 *( (DWORD *) dest_conv) |= (*color_s & 0xff0000ff) << 16; /* Blue */
3823 dest_conv += sizeof(DWORD);
3828 for (tex_index = 0; tex_index < numTextures; tex_index++) {
3829 const struct wined3d_stream_info_element *element = &stream_info->elements[WINED3D_FFP_TEXCOORD0 + tex_index];
3830 const float *tex_coord = (const float *)(element->data + i * element->stride);
3831 if (!(stream_info->use_map & (1 << (WINED3D_FFP_TEXCOORD0 + tex_index))))
3833 ERR("No source texture, but destination requests one\n");
3834 dest_ptr+=GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float);
3835 if(dest_conv) dest_conv += GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float);
3837 else {
3838 copy_and_next(dest_ptr, tex_coord, GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float));
3839 if(dest_conv) {
3840 copy_and_next(dest_conv, tex_coord, GET_TEXCOORD_SIZE_FROM_FVF(DestFVF, tex_index) * sizeof(float));
3846 if(dest_conv) {
3847 GL_EXTCALL(glBindBufferARB(GL_ARRAY_BUFFER_ARB, dest->buffer_object));
3848 checkGLcall("glBindBufferARB(GL_ARRAY_BUFFER_ARB)");
3849 GL_EXTCALL(glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, dwDestIndex * get_flexible_vertex_size(DestFVF),
3850 dwCount * get_flexible_vertex_size(DestFVF),
3851 dest_conv_addr));
3852 checkGLcall("glBufferSubDataARB(GL_ARRAY_BUFFER_ARB)");
3853 HeapFree(GetProcessHeap(), 0, dest_conv_addr);
3856 LEAVE_GL();
3858 return WINED3D_OK;
3860 #undef copy_and_next
3862 static HRESULT WINAPI IWineD3DDeviceImpl_ProcessVertices(IWineD3DDevice *iface, UINT SrcStartIndex, UINT DestIndex,
3863 UINT VertexCount, IWineD3DBuffer *pDestBuffer, IWineD3DVertexDeclaration *pVertexDecl, DWORD Flags,
3864 DWORD DestFVF)
3866 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3867 struct wined3d_stream_info stream_info;
3868 struct wined3d_context *context;
3869 BOOL vbo = FALSE, streamWasUP = This->stateBlock->streamIsUP;
3870 HRESULT hr;
3872 TRACE("(%p)->(%d,%d,%d,%p,%p,%d\n", This, SrcStartIndex, DestIndex, VertexCount, pDestBuffer, pVertexDecl, Flags);
3874 if(pVertexDecl) {
3875 ERR("Output vertex declaration not implemented yet\n");
3878 /* Need any context to write to the vbo. */
3879 context = context_acquire(This, NULL, CTXUSAGE_RESOURCELOAD);
3881 /* ProcessVertices reads from vertex buffers, which have to be assigned. DrawPrimitive and DrawPrimitiveUP
3882 * control the streamIsUP flag, thus restore it afterwards.
3884 This->stateBlock->streamIsUP = FALSE;
3885 device_stream_info_from_declaration(This, FALSE, &stream_info, &vbo);
3886 This->stateBlock->streamIsUP = streamWasUP;
3888 if(vbo || SrcStartIndex) {
3889 unsigned int i;
3890 /* ProcessVertices can't convert FROM a vbo, and vertex buffers used to source into ProcessVertices are
3891 * unlikely to ever be used for drawing. Release vbos in those buffers and fix up the stream_info structure
3893 * Also get the start index in, but only loop over all elements if there's something to add at all.
3895 for (i = 0; i < (sizeof(stream_info.elements) / sizeof(*stream_info.elements)); ++i)
3897 struct wined3d_stream_info_element *e;
3899 if (!(stream_info.use_map & (1 << i))) continue;
3901 e = &stream_info.elements[i];
3902 if (e->buffer_object)
3904 struct wined3d_buffer *vb = (struct wined3d_buffer *)This->stateBlock->streamSource[e->stream_idx];
3905 e->buffer_object = 0;
3906 e->data = (BYTE *)((unsigned long)e->data + (unsigned long)buffer_get_sysmem(vb));
3907 ENTER_GL();
3908 GL_EXTCALL(glDeleteBuffersARB(1, &vb->buffer_object));
3909 vb->buffer_object = 0;
3910 LEAVE_GL();
3912 if (e->data) e->data += e->stride * SrcStartIndex;
3916 hr = process_vertices_strided(This, DestIndex, VertexCount, &stream_info,
3917 (struct wined3d_buffer *)pDestBuffer, Flags, DestFVF);
3919 context_release(context);
3921 return hr;
3924 /*****
3925 * Get / Set Texture Stage States
3926 * TODO: Verify against dx9 definitions
3927 *****/
3928 static HRESULT WINAPI IWineD3DDeviceImpl_SetTextureStageState(IWineD3DDevice *iface, DWORD Stage, WINED3DTEXTURESTAGESTATETYPE Type, DWORD Value) {
3929 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3930 DWORD oldValue = This->updateStateBlock->textureState[Stage][Type];
3931 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
3933 TRACE("(%p) : Stage=%d, Type=%s(%d), Value=%d\n", This, Stage, debug_d3dtexturestate(Type), Type, Value);
3935 if (Stage >= gl_info->limits.texture_stages)
3937 WARN("Attempting to set stage %u which is higher than the max stage %u, ignoring.\n",
3938 Stage, gl_info->limits.texture_stages - 1);
3939 return WINED3D_OK;
3942 This->updateStateBlock->changed.textureState[Stage] |= 1 << Type;
3943 This->updateStateBlock->textureState[Stage][Type] = Value;
3945 if (This->isRecordingState) {
3946 TRACE("Recording... not performing anything\n");
3947 return WINED3D_OK;
3950 /* Checked after the assignments to allow proper stateblock recording */
3951 if(oldValue == Value) {
3952 TRACE("App is setting the old value over, nothing to do\n");
3953 return WINED3D_OK;
3956 if(Stage > This->stateBlock->lowest_disabled_stage &&
3957 This->StateTable[STATE_TEXTURESTAGE(0, Type)].representative == STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP)) {
3958 /* Colorop change above lowest disabled stage? That won't change anything in the gl setup
3959 * Changes in other states are important on disabled stages too
3961 return WINED3D_OK;
3964 if(Type == WINED3DTSS_COLOROP) {
3965 unsigned int i;
3967 if(Value == WINED3DTOP_DISABLE && oldValue != WINED3DTOP_DISABLE) {
3968 /* Previously enabled stage disabled now. Make sure to dirtify all enabled stages above Stage,
3969 * they have to be disabled
3971 * The current stage is dirtified below.
3973 for(i = Stage + 1; i < This->stateBlock->lowest_disabled_stage; i++) {
3974 TRACE("Additionally dirtifying stage %u\n", i);
3975 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP));
3977 This->stateBlock->lowest_disabled_stage = Stage;
3978 TRACE("New lowest disabled: %u\n", Stage);
3979 } else if(Value != WINED3DTOP_DISABLE && oldValue == WINED3DTOP_DISABLE) {
3980 /* Previously disabled stage enabled. Stages above it may need enabling
3981 * stage must be lowest_disabled_stage here, if it's bigger success is returned above,
3982 * and stages below the lowest disabled stage can't be enabled(because they are enabled already).
3984 * Again stage Stage doesn't need to be dirtified here, it is handled below.
3987 for (i = Stage + 1; i < This->adapter->gl_info.limits.texture_stages; ++i)
3989 if(This->updateStateBlock->textureState[i][WINED3DTSS_COLOROP] == WINED3DTOP_DISABLE) {
3990 break;
3992 TRACE("Additionally dirtifying stage %u due to enable\n", i);
3993 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP));
3995 This->stateBlock->lowest_disabled_stage = i;
3996 TRACE("New lowest disabled: %u\n", i);
4000 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_TEXTURESTAGE(Stage, Type));
4002 return WINED3D_OK;
4005 static HRESULT WINAPI IWineD3DDeviceImpl_GetTextureStageState(IWineD3DDevice *iface, DWORD Stage, WINED3DTEXTURESTAGESTATETYPE Type, DWORD* pValue) {
4006 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4007 TRACE("(%p) : requesting Stage %d, Type %d getting %d\n", This, Stage, Type, This->updateStateBlock->textureState[Stage][Type]);
4008 *pValue = This->updateStateBlock->textureState[Stage][Type];
4009 return WINED3D_OK;
4012 /*****
4013 * Get / Set Texture
4014 *****/
4015 static HRESULT WINAPI IWineD3DDeviceImpl_SetTexture(IWineD3DDevice *iface,
4016 DWORD stage, IWineD3DBaseTexture *texture)
4018 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4019 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4020 IWineD3DBaseTexture *prev;
4022 TRACE("iface %p, stage %u, texture %p.\n", iface, stage, texture);
4024 if (stage >= WINED3DVERTEXTEXTURESAMPLER0 && stage <= WINED3DVERTEXTEXTURESAMPLER3)
4025 stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
4027 /* Windows accepts overflowing this array... we do not. */
4028 if (stage >= sizeof(This->stateBlock->textures) / sizeof(*This->stateBlock->textures))
4030 WARN("Ignoring invalid stage %u.\n", stage);
4031 return WINED3D_OK;
4034 /* SetTexture isn't allowed on textures in WINED3DPOOL_SCRATCH */
4035 if (texture && ((IWineD3DTextureImpl *)texture)->resource.pool == WINED3DPOOL_SCRATCH)
4037 WARN("Rejecting attempt to set scratch texture.\n");
4038 return WINED3DERR_INVALIDCALL;
4041 This->updateStateBlock->changed.textures |= 1 << stage;
4043 prev = This->updateStateBlock->textures[stage];
4044 TRACE("Previous texture %p.\n", prev);
4046 if (texture == prev)
4048 TRACE("App is setting the same texture again, nothing to do.\n");
4049 return WINED3D_OK;
4052 TRACE("Setting new texture to %p.\n", texture);
4053 This->updateStateBlock->textures[stage] = texture;
4055 if (This->isRecordingState)
4057 TRACE("Recording... not performing anything\n");
4059 if (texture) IWineD3DBaseTexture_AddRef(texture);
4060 if (prev) IWineD3DBaseTexture_Release(prev);
4062 return WINED3D_OK;
4065 if (texture)
4067 IWineD3DBaseTextureImpl *t = (IWineD3DBaseTextureImpl *)texture;
4068 LONG bind_count = InterlockedIncrement(&t->baseTexture.bindCount);
4069 UINT dimensions = IWineD3DBaseTexture_GetTextureDimensions(texture);
4071 IWineD3DBaseTexture_AddRef(texture);
4073 if (!prev || dimensions != IWineD3DBaseTexture_GetTextureDimensions(prev))
4075 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_PIXELSHADER);
4078 if (!prev && stage < gl_info->limits.texture_stages)
4080 /* The source arguments for color and alpha ops have different
4081 * meanings when a NULL texture is bound, so the COLOROP and
4082 * ALPHAOP have to be dirtified. */
4083 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_TEXTURESTAGE(stage, WINED3DTSS_COLOROP));
4084 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_TEXTURESTAGE(stage, WINED3DTSS_ALPHAOP));
4087 if (bind_count == 1) t->baseTexture.sampler = stage;
4090 if (prev)
4092 IWineD3DBaseTextureImpl *t = (IWineD3DBaseTextureImpl *)prev;
4093 LONG bind_count = InterlockedDecrement(&t->baseTexture.bindCount);
4095 IWineD3DBaseTexture_Release(prev);
4097 if (!texture && stage < gl_info->limits.texture_stages)
4099 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_TEXTURESTAGE(stage, WINED3DTSS_COLOROP));
4100 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_TEXTURESTAGE(stage, WINED3DTSS_ALPHAOP));
4103 if (bind_count && t->baseTexture.sampler == stage)
4105 unsigned int i;
4107 /* Search for other stages the texture is bound to. Shouldn't
4108 * happen if applications bind textures to a single stage only. */
4109 TRACE("Searching for other stages the texture is bound to.\n");
4110 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
4112 if (This->updateStateBlock->textures[i] == prev)
4114 TRACE("Texture is also bound to stage %u.\n", i);
4115 t->baseTexture.sampler = i;
4116 break;
4122 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(stage));
4124 return WINED3D_OK;
4127 static HRESULT WINAPI IWineD3DDeviceImpl_GetTexture(IWineD3DDevice *iface, DWORD Stage, IWineD3DBaseTexture** ppTexture) {
4128 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4130 TRACE("(%p) : Stage %#x, ppTexture %p\n", This, Stage, ppTexture);
4132 if (Stage >= WINED3DVERTEXTEXTURESAMPLER0 && Stage <= WINED3DVERTEXTEXTURESAMPLER3) {
4133 Stage -= (WINED3DVERTEXTEXTURESAMPLER0 - MAX_FRAGMENT_SAMPLERS);
4136 if (Stage >= sizeof(This->stateBlock->textures)/sizeof(This->stateBlock->textures[0])) {
4137 ERR("Current stage overflows textures array (stage %d)\n", Stage);
4138 return WINED3D_OK; /* Windows accepts overflowing this array ... we do not. */
4141 *ppTexture=This->stateBlock->textures[Stage];
4142 if (*ppTexture)
4143 IWineD3DBaseTexture_AddRef(*ppTexture);
4145 TRACE("(%p) : Returning %p\n", This, *ppTexture);
4147 return WINED3D_OK;
4150 /*****
4151 * Get Back Buffer
4152 *****/
4153 static HRESULT WINAPI IWineD3DDeviceImpl_GetBackBuffer(IWineD3DDevice *iface, UINT swapchain_idx,
4154 UINT backbuffer_idx, WINED3DBACKBUFFER_TYPE backbuffer_type, IWineD3DSurface **backbuffer)
4156 IWineD3DSwapChain *swapchain;
4157 HRESULT hr;
4159 TRACE("iface %p, swapchain_idx %u, backbuffer_idx %u, backbuffer_type %#x, backbuffer %p.\n",
4160 iface, swapchain_idx, backbuffer_idx, backbuffer_type, backbuffer);
4162 hr = IWineD3DDeviceImpl_GetSwapChain(iface, swapchain_idx, &swapchain);
4163 if (FAILED(hr))
4165 WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
4166 return hr;
4169 hr = IWineD3DSwapChain_GetBackBuffer(swapchain, backbuffer_idx, backbuffer_type, backbuffer);
4170 IWineD3DSwapChain_Release(swapchain);
4171 if (FAILED(hr))
4173 WARN("Failed to get backbuffer %u, hr %#x.\n", backbuffer_idx, hr);
4174 return hr;
4177 return WINED3D_OK;
4180 static HRESULT WINAPI IWineD3DDeviceImpl_GetDeviceCaps(IWineD3DDevice *iface, WINED3DCAPS* pCaps) {
4181 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4182 WARN("(%p) : stub, calling idirect3d for now\n", This);
4183 return IWineD3D_GetDeviceCaps(This->wined3d, This->adapter->ordinal, This->devType, pCaps);
4186 static HRESULT WINAPI IWineD3DDeviceImpl_GetDisplayMode(IWineD3DDevice *iface, UINT iSwapChain, WINED3DDISPLAYMODE* pMode) {
4187 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4188 IWineD3DSwapChain *swapChain;
4189 HRESULT hr;
4191 if(iSwapChain > 0) {
4192 hr = IWineD3DDeviceImpl_GetSwapChain(iface, iSwapChain, &swapChain);
4193 if (hr == WINED3D_OK) {
4194 hr = IWineD3DSwapChain_GetDisplayMode(swapChain, pMode);
4195 IWineD3DSwapChain_Release(swapChain);
4196 } else {
4197 FIXME("(%p) Error getting display mode\n", This);
4199 } else {
4200 /* Don't read the real display mode,
4201 but return the stored mode instead. X11 can't change the color
4202 depth, and some apps are pretty angry if they SetDisplayMode from
4203 24 to 16 bpp and find out that GetDisplayMode still returns 24 bpp
4205 Also don't relay to the swapchain because with ddraw it's possible
4206 that there isn't a swapchain at all */
4207 pMode->Width = This->ddraw_width;
4208 pMode->Height = This->ddraw_height;
4209 pMode->Format = This->ddraw_format;
4210 pMode->RefreshRate = 0;
4211 hr = WINED3D_OK;
4214 return hr;
4217 /*****
4218 * Stateblock related functions
4219 *****/
4221 static HRESULT WINAPI IWineD3DDeviceImpl_BeginStateBlock(IWineD3DDevice *iface) {
4222 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4223 IWineD3DStateBlock *stateblock;
4224 HRESULT hr;
4226 TRACE("(%p)\n", This);
4228 if (This->isRecordingState) return WINED3DERR_INVALIDCALL;
4230 hr = IWineD3DDeviceImpl_CreateStateBlock(iface, WINED3DSBT_RECORDED, &stateblock, NULL);
4231 if (FAILED(hr)) return hr;
4233 IWineD3DStateBlock_Release((IWineD3DStateBlock*)This->updateStateBlock);
4234 This->updateStateBlock = (IWineD3DStateBlockImpl *)stateblock;
4235 This->isRecordingState = TRUE;
4237 TRACE("(%p) recording stateblock %p\n", This, stateblock);
4239 return WINED3D_OK;
4242 static HRESULT WINAPI IWineD3DDeviceImpl_EndStateBlock(IWineD3DDevice *iface, IWineD3DStateBlock** ppStateBlock) {
4243 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4244 IWineD3DStateBlockImpl *object = This->updateStateBlock;
4246 if (!This->isRecordingState) {
4247 WARN("(%p) not recording! returning error\n", This);
4248 *ppStateBlock = NULL;
4249 return WINED3DERR_INVALIDCALL;
4252 stateblock_init_contained_states(object);
4254 *ppStateBlock = (IWineD3DStateBlock*) object;
4255 This->isRecordingState = FALSE;
4256 This->updateStateBlock = This->stateBlock;
4257 IWineD3DStateBlock_AddRef((IWineD3DStateBlock*)This->updateStateBlock);
4258 /* IWineD3DStateBlock_AddRef(*ppStateBlock); don't need to do this, since we should really just release UpdateStateBlock first */
4259 TRACE("(%p) returning token (ptr to stateblock) of %p\n", This, *ppStateBlock);
4260 return WINED3D_OK;
4263 /*****
4264 * Scene related functions
4265 *****/
4266 static HRESULT WINAPI IWineD3DDeviceImpl_BeginScene(IWineD3DDevice *iface) {
4267 /* At the moment we have no need for any functionality at the beginning
4268 of a scene */
4269 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4270 TRACE("(%p)\n", This);
4272 if(This->inScene) {
4273 TRACE("Already in Scene, returning WINED3DERR_INVALIDCALL\n");
4274 return WINED3DERR_INVALIDCALL;
4276 This->inScene = TRUE;
4277 return WINED3D_OK;
4280 static HRESULT WINAPI IWineD3DDeviceImpl_EndScene(IWineD3DDevice *iface)
4282 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4283 struct wined3d_context *context;
4285 TRACE("(%p)\n", This);
4287 if(!This->inScene) {
4288 TRACE("Not in scene, returning WINED3DERR_INVALIDCALL\n");
4289 return WINED3DERR_INVALIDCALL;
4292 context = context_acquire(This, NULL, CTXUSAGE_RESOURCELOAD);
4293 /* We only have to do this if we need to read the, swapbuffers performs a flush for us */
4294 wglFlush();
4295 /* No checkGLcall here to avoid locking the lock just for checking a call that hardly ever
4296 * fails. */
4297 context_release(context);
4299 This->inScene = FALSE;
4300 return WINED3D_OK;
4303 static HRESULT WINAPI IWineD3DDeviceImpl_Present(IWineD3DDevice *iface,
4304 const RECT *pSourceRect, const RECT *pDestRect,
4305 HWND hDestWindowOverride, const RGNDATA *pDirtyRegion)
4307 IWineD3DSwapChain *swapChain = NULL;
4308 int i;
4309 int swapchains = IWineD3DDeviceImpl_GetNumberOfSwapChains(iface);
4311 TRACE("iface %p.\n", iface);
4313 for(i = 0 ; i < swapchains ; i ++) {
4315 IWineD3DDeviceImpl_GetSwapChain(iface, i, &swapChain);
4316 TRACE("presentinng chain %d, %p\n", i, swapChain);
4317 IWineD3DSwapChain_Present(swapChain, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, 0);
4318 IWineD3DSwapChain_Release(swapChain);
4321 return WINED3D_OK;
4324 static BOOL is_full_clear(IWineD3DSurfaceImpl *target, const WINED3DVIEWPORT *viewport,
4325 const RECT *scissor_rect, const WINED3DRECT *clear_rect)
4327 /* partial viewport*/
4328 if (viewport->X != 0 || viewport->Y != 0
4329 || viewport->Width < target->currentDesc.Width
4330 || viewport->Height < target->currentDesc.Height)
4331 return FALSE;
4333 /* partial scissor rect */
4334 if (scissor_rect && (scissor_rect->left > 0 || scissor_rect->top > 0
4335 || scissor_rect->right < target->currentDesc.Width
4336 || scissor_rect->bottom < target->currentDesc.Height))
4337 return FALSE;
4339 /* partial clear rect */
4340 if (clear_rect && (clear_rect->x1 > 0 || clear_rect->y1 > 0
4341 || clear_rect->x2 < target->currentDesc.Width
4342 || clear_rect->y2 < target->currentDesc.Height))
4343 return FALSE;
4345 return TRUE;
4348 /* Not called from the VTable (internal subroutine) */
4349 HRESULT IWineD3DDeviceImpl_ClearSurface(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, DWORD Count,
4350 const WINED3DRECT *pRects, DWORD Flags, WINED3DCOLOR Color, float Z, DWORD Stencil)
4352 IWineD3DStateBlockImpl *stateblock = This->stateBlock;
4353 const RECT *scissor_rect = stateblock->renderState[WINED3DRS_SCISSORTESTENABLE] ? &stateblock->scissorRect : NULL;
4354 const WINED3DRECT *clear_rect = (Count > 0 && pRects) ? pRects : NULL;
4355 const WINED3DVIEWPORT *vp = &stateblock->viewport;
4356 GLbitfield glMask = 0;
4357 unsigned int i;
4358 WINED3DRECT curRect;
4359 RECT vp_rect;
4360 UINT drawable_width, drawable_height;
4361 IWineD3DSurfaceImpl *depth_stencil = (IWineD3DSurfaceImpl *) This->stencilBufferTarget;
4362 struct wined3d_context *context;
4364 /* When we're clearing parts of the drawable, make sure that the target surface is well up to date in the
4365 * drawable. After the clear we'll mark the drawable up to date, so we have to make sure that this is true
4366 * for the cleared parts, and the untouched parts.
4368 * If we're clearing the whole target there is no need to copy it into the drawable, it will be overwritten
4369 * anyway. If we're not clearing the color buffer we don't have to copy either since we're not going to set
4370 * the drawable up to date. We have to check all settings that limit the clear area though. Do not bother
4371 * checking all this if the dest surface is in the drawable anyway.
4373 if (Flags & WINED3DCLEAR_TARGET && !(target->Flags & SFLAG_INDRAWABLE))
4375 if (!is_full_clear(target, vp, scissor_rect, clear_rect))
4376 IWineD3DSurface_LoadLocation((IWineD3DSurface *)target, SFLAG_INDRAWABLE, NULL);
4379 context = context_acquire(This, (IWineD3DSurface *)target, CTXUSAGE_CLEAR);
4380 if (!context->valid)
4382 context_release(context);
4383 WARN("Invalid context, skipping clear.\n");
4384 return WINED3D_OK;
4387 target->get_drawable_size(context, &drawable_width, &drawable_height);
4389 ENTER_GL();
4391 /* Only set the values up once, as they are not changing */
4392 if (Flags & WINED3DCLEAR_STENCIL)
4394 if (context->gl_info->supported[EXT_STENCIL_TWO_SIDE])
4396 glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
4397 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_TWOSIDEDSTENCILMODE));
4399 glStencilMask(~0U);
4400 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_STENCILWRITEMASK));
4401 glClearStencil(Stencil);
4402 checkGLcall("glClearStencil");
4403 glMask = glMask | GL_STENCIL_BUFFER_BIT;
4406 if (Flags & WINED3DCLEAR_ZBUFFER)
4408 DWORD location = context->render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
4409 if (!(depth_stencil->Flags & location) && !is_full_clear(depth_stencil, vp, scissor_rect, clear_rect))
4410 surface_load_ds_location(This->stencilBufferTarget, context, location);
4412 glDepthMask(GL_TRUE);
4413 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_ZWRITEENABLE));
4414 glClearDepth(Z);
4415 checkGLcall("glClearDepth");
4416 glMask = glMask | GL_DEPTH_BUFFER_BIT;
4419 if (Flags & WINED3DCLEAR_TARGET)
4421 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
4422 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORWRITEENABLE));
4423 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1));
4424 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2));
4425 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3));
4426 glClearColor(D3DCOLOR_R(Color), D3DCOLOR_G(Color), D3DCOLOR_B(Color), D3DCOLOR_A(Color));
4427 checkGLcall("glClearColor");
4428 glMask = glMask | GL_COLOR_BUFFER_BIT;
4431 vp_rect.left = vp->X;
4432 vp_rect.top = vp->Y;
4433 vp_rect.right = vp->X + vp->Width;
4434 vp_rect.bottom = vp->Y + vp->Height;
4435 if (!(Count > 0 && pRects)) {
4436 if(This->stateBlock->renderState[WINED3DRS_SCISSORTESTENABLE]) {
4437 IntersectRect(&vp_rect, &vp_rect, &This->stateBlock->scissorRect);
4439 if (context->render_offscreen)
4441 glScissor(vp_rect.left, vp_rect.top,
4442 vp_rect.right - vp_rect.left, vp_rect.bottom - vp_rect.top);
4443 } else {
4444 glScissor(vp_rect.left, drawable_height - vp_rect.bottom,
4445 vp_rect.right - vp_rect.left, vp_rect.bottom - vp_rect.top);
4447 checkGLcall("glScissor");
4448 glClear(glMask);
4449 checkGLcall("glClear");
4450 } else {
4451 /* Now process each rect in turn */
4452 for (i = 0; i < Count; i++) {
4453 /* Note gl uses lower left, width/height */
4454 IntersectRect((RECT *)&curRect, &vp_rect, (const RECT *)&pRects[i]);
4455 if(This->stateBlock->renderState[WINED3DRS_SCISSORTESTENABLE]) {
4456 IntersectRect((RECT *) &curRect, (RECT *) &curRect, &This->stateBlock->scissorRect);
4458 TRACE("(%p) Rect=(%d,%d)->(%d,%d) glRect=(%d,%d), len=%d, hei=%d\n", This,
4459 pRects[i].x1, pRects[i].y1, pRects[i].x2, pRects[i].y2,
4460 curRect.x1, (target->currentDesc.Height - curRect.y2),
4461 curRect.x2 - curRect.x1, curRect.y2 - curRect.y1);
4463 /* Tests show that rectangles where x1 > x2 or y1 > y2 are ignored silently.
4464 * The rectangle is not cleared, no error is returned, but further rectanlges are
4465 * still cleared if they are valid
4467 if(curRect.x1 > curRect.x2 || curRect.y1 > curRect.y2) {
4468 TRACE("Rectangle with negative dimensions, ignoring\n");
4469 continue;
4472 if (context->render_offscreen)
4474 glScissor(curRect.x1, curRect.y1,
4475 curRect.x2 - curRect.x1, curRect.y2 - curRect.y1);
4476 } else {
4477 glScissor(curRect.x1, drawable_height - curRect.y2,
4478 curRect.x2 - curRect.x1, curRect.y2 - curRect.y1);
4480 checkGLcall("glScissor");
4482 glClear(glMask);
4483 checkGLcall("glClear");
4487 if (Flags & WINED3DCLEAR_TARGET)
4489 IWineD3DSurface_ModifyLocation((IWineD3DSurface *)target, SFLAG_INDRAWABLE, TRUE);
4491 if (Flags & WINED3DCLEAR_ZBUFFER) {
4492 /* Note that WINED3DCLEAR_ZBUFFER implies a depth stencil exists on the device */
4493 DWORD location = context->render_offscreen ? SFLAG_DS_OFFSCREEN : SFLAG_DS_ONSCREEN;
4494 surface_modify_ds_location(This->stencilBufferTarget, location);
4497 LEAVE_GL();
4499 if (wined3d_settings.strict_draw_ordering || ((target->Flags & SFLAG_SWAPCHAIN)
4500 && ((IWineD3DSwapChainImpl *)target->container)->frontBuffer == (IWineD3DSurface *)target))
4501 wglFlush(); /* Flush to ensure ordering across contexts. */
4503 context_release(context);
4505 return WINED3D_OK;
4508 static HRESULT WINAPI IWineD3DDeviceImpl_Clear(IWineD3DDevice *iface, DWORD Count, CONST WINED3DRECT* pRects,
4509 DWORD Flags, WINED3DCOLOR Color, float Z, DWORD Stencil) {
4510 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4511 IWineD3DSurfaceImpl *target = (IWineD3DSurfaceImpl *)This->render_targets[0];
4513 TRACE("(%p) Count (%d), pRects (%p), Flags (%x), Color (0x%08x), Z (%f), Stencil (%d)\n", This,
4514 Count, pRects, Flags, Color, Z, Stencil);
4516 if(Flags & (WINED3DCLEAR_ZBUFFER | WINED3DCLEAR_STENCIL) && This->stencilBufferTarget == NULL) {
4517 WARN("Clearing depth and/or stencil without a depth stencil buffer attached, returning WINED3DERR_INVALIDCALL\n");
4518 /* TODO: What about depth stencil buffers without stencil bits? */
4519 return WINED3DERR_INVALIDCALL;
4522 return IWineD3DDeviceImpl_ClearSurface(This, target, Count, pRects, Flags, Color, Z, Stencil);
4525 /*****
4526 * Drawing functions
4527 *****/
4529 static void WINAPI IWineD3DDeviceImpl_SetPrimitiveType(IWineD3DDevice *iface,
4530 WINED3DPRIMITIVETYPE primitive_type)
4532 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4534 TRACE("iface %p, primitive_type %s\n", iface, debug_d3dprimitivetype(primitive_type));
4536 This->updateStateBlock->changed.primitive_type = TRUE;
4537 This->updateStateBlock->gl_primitive_type = gl_primitive_type_from_d3d(primitive_type);
4540 static void WINAPI IWineD3DDeviceImpl_GetPrimitiveType(IWineD3DDevice *iface,
4541 WINED3DPRIMITIVETYPE *primitive_type)
4543 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4545 TRACE("iface %p, primitive_type %p\n", iface, primitive_type);
4547 *primitive_type = d3d_primitive_type_from_gl(This->stateBlock->gl_primitive_type);
4549 TRACE("Returning %s\n", debug_d3dprimitivetype(*primitive_type));
4552 static HRESULT WINAPI IWineD3DDeviceImpl_DrawPrimitive(IWineD3DDevice *iface, UINT StartVertex, UINT vertex_count)
4554 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4556 TRACE("(%p) : start %u, count %u\n", This, StartVertex, vertex_count);
4558 if(!This->stateBlock->vertexDecl) {
4559 WARN("(%p) : Called without a valid vertex declaration set\n", This);
4560 return WINED3DERR_INVALIDCALL;
4563 /* The index buffer is not needed here, but restore it, otherwise it is hell to keep track of */
4564 if(This->stateBlock->streamIsUP) {
4565 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_INDEXBUFFER);
4566 This->stateBlock->streamIsUP = FALSE;
4569 if(This->stateBlock->loadBaseVertexIndex != 0) {
4570 This->stateBlock->loadBaseVertexIndex = 0;
4571 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_STREAMSRC);
4573 /* Account for the loading offset due to index buffers. Instead of reloading all sources correct it with the startvertex parameter */
4574 drawPrimitive(iface, vertex_count, StartVertex /* start_idx */, 0 /* indxSize */, NULL /* indxData */);
4575 return WINED3D_OK;
4578 static HRESULT WINAPI IWineD3DDeviceImpl_DrawIndexedPrimitive(IWineD3DDevice *iface, UINT startIndex, UINT index_count)
4580 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4581 UINT idxStride = 2;
4582 IWineD3DBuffer *pIB;
4583 GLuint vbo;
4585 pIB = This->stateBlock->pIndexData;
4586 if (!pIB) {
4587 /* D3D9 returns D3DERR_INVALIDCALL when DrawIndexedPrimitive is called
4588 * without an index buffer set. (The first time at least...)
4589 * D3D8 simply dies, but I doubt it can do much harm to return
4590 * D3DERR_INVALIDCALL there as well. */
4591 WARN("(%p) : Called without a valid index buffer set, returning WINED3DERR_INVALIDCALL\n", This);
4592 return WINED3DERR_INVALIDCALL;
4595 if(!This->stateBlock->vertexDecl) {
4596 WARN("(%p) : Called without a valid vertex declaration set\n", This);
4597 return WINED3DERR_INVALIDCALL;
4600 if(This->stateBlock->streamIsUP) {
4601 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_INDEXBUFFER);
4602 This->stateBlock->streamIsUP = FALSE;
4604 vbo = ((struct wined3d_buffer *) pIB)->buffer_object;
4606 TRACE("(%p) : startIndex %u, index count %u.\n", This, startIndex, index_count);
4608 if (This->stateBlock->IndexFmt == WINED3DFMT_R16_UINT) {
4609 idxStride = 2;
4610 } else {
4611 idxStride = 4;
4614 if(This->stateBlock->loadBaseVertexIndex != This->stateBlock->baseVertexIndex) {
4615 This->stateBlock->loadBaseVertexIndex = This->stateBlock->baseVertexIndex;
4616 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_STREAMSRC);
4619 drawPrimitive(iface, index_count, startIndex, idxStride,
4620 vbo ? NULL : ((struct wined3d_buffer *)pIB)->resource.allocatedMemory);
4622 return WINED3D_OK;
4625 static HRESULT WINAPI IWineD3DDeviceImpl_DrawPrimitiveUP(IWineD3DDevice *iface, UINT vertex_count,
4626 const void *pVertexStreamZeroData, UINT VertexStreamZeroStride)
4628 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4629 IWineD3DBuffer *vb;
4631 TRACE("(%p) : vertex count %u, pVtxData %p, stride %u\n",
4632 This, vertex_count, pVertexStreamZeroData, VertexStreamZeroStride);
4634 if(!This->stateBlock->vertexDecl) {
4635 WARN("(%p) : Called without a valid vertex declaration set\n", This);
4636 return WINED3DERR_INVALIDCALL;
4639 /* Note in the following, it's not this type, but that's the purpose of streamIsUP */
4640 vb = This->stateBlock->streamSource[0];
4641 This->stateBlock->streamSource[0] = (IWineD3DBuffer *)pVertexStreamZeroData;
4642 if (vb) IWineD3DBuffer_Release(vb);
4643 This->stateBlock->streamOffset[0] = 0;
4644 This->stateBlock->streamStride[0] = VertexStreamZeroStride;
4645 This->stateBlock->streamIsUP = TRUE;
4646 This->stateBlock->loadBaseVertexIndex = 0;
4648 /* TODO: Only mark dirty if drawing from a different UP address */
4649 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_STREAMSRC);
4651 drawPrimitive(iface, vertex_count, 0 /* start_idx */, 0 /* indxSize*/, NULL /* indxData */);
4653 /* MSDN specifies stream zero settings must be set to NULL */
4654 This->stateBlock->streamStride[0] = 0;
4655 This->stateBlock->streamSource[0] = NULL;
4657 /* stream zero settings set to null at end, as per the msdn. No need to mark dirty here, the app has to set
4658 * the new stream sources or use UP drawing again
4660 return WINED3D_OK;
4663 static HRESULT WINAPI IWineD3DDeviceImpl_DrawIndexedPrimitiveUP(IWineD3DDevice *iface,
4664 UINT index_count, const void *pIndexData, WINED3DFORMAT IndexDataFormat,
4665 const void *pVertexStreamZeroData, UINT VertexStreamZeroStride)
4667 int idxStride;
4668 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4669 IWineD3DBuffer *vb;
4670 IWineD3DBuffer *ib;
4672 TRACE("(%p) : index count %u, pidxdata %p, IdxFmt %u, pVtxdata %p, stride=%u.\n",
4673 This, index_count, pIndexData, IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride);
4675 if(!This->stateBlock->vertexDecl) {
4676 WARN("(%p) : Called without a valid vertex declaration set\n", This);
4677 return WINED3DERR_INVALIDCALL;
4680 if (IndexDataFormat == WINED3DFMT_R16_UINT) {
4681 idxStride = 2;
4682 } else {
4683 idxStride = 4;
4686 /* Note in the following, it's not this type, but that's the purpose of streamIsUP */
4687 vb = This->stateBlock->streamSource[0];
4688 This->stateBlock->streamSource[0] = (IWineD3DBuffer *)pVertexStreamZeroData;
4689 if (vb) IWineD3DBuffer_Release(vb);
4690 This->stateBlock->streamIsUP = TRUE;
4691 This->stateBlock->streamOffset[0] = 0;
4692 This->stateBlock->streamStride[0] = VertexStreamZeroStride;
4694 /* Set to 0 as per msdn. Do it now due to the stream source loading during drawPrimitive */
4695 This->stateBlock->baseVertexIndex = 0;
4696 This->stateBlock->loadBaseVertexIndex = 0;
4697 /* Mark the state dirty until we have nicer tracking of the stream source pointers */
4698 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_VDECL);
4699 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_INDEXBUFFER);
4701 drawPrimitive(iface, index_count, 0 /* start_idx */, idxStride, pIndexData);
4703 /* MSDN specifies stream zero settings and index buffer must be set to NULL */
4704 This->stateBlock->streamSource[0] = NULL;
4705 This->stateBlock->streamStride[0] = 0;
4706 ib = This->stateBlock->pIndexData;
4707 if(ib) {
4708 IWineD3DBuffer_Release(ib);
4709 This->stateBlock->pIndexData = NULL;
4711 /* No need to mark the stream source state dirty here. Either the app calls UP drawing again, or it has to call
4712 * SetStreamSource to specify a vertex buffer
4715 return WINED3D_OK;
4718 static HRESULT WINAPI IWineD3DDeviceImpl_DrawPrimitiveStrided(IWineD3DDevice *iface,
4719 UINT vertex_count, const WineDirect3DVertexStridedData *DrawPrimStrideData)
4721 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
4723 /* Mark the state dirty until we have nicer tracking
4724 * its fine to change baseVertexIndex because that call is only called by ddraw which does not need
4725 * that value.
4727 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_VDECL);
4728 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_INDEXBUFFER);
4729 This->stateBlock->baseVertexIndex = 0;
4730 This->up_strided = DrawPrimStrideData;
4731 drawPrimitive(iface, vertex_count, 0, 0, NULL);
4732 This->up_strided = NULL;
4733 return WINED3D_OK;
4736 static HRESULT WINAPI IWineD3DDeviceImpl_DrawIndexedPrimitiveStrided(IWineD3DDevice *iface,
4737 UINT vertex_count, const WineDirect3DVertexStridedData *DrawPrimStrideData,
4738 UINT NumVertices, const void *pIndexData, WINED3DFORMAT IndexDataFormat)
4740 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
4741 DWORD idxSize = (IndexDataFormat == WINED3DFMT_R32_UINT ? 4 : 2);
4743 /* Mark the state dirty until we have nicer tracking
4744 * its fine to change baseVertexIndex because that call is only called by ddraw which does not need
4745 * that value.
4747 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_VDECL);
4748 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_INDEXBUFFER);
4749 This->stateBlock->streamIsUP = TRUE;
4750 This->stateBlock->baseVertexIndex = 0;
4751 This->up_strided = DrawPrimStrideData;
4752 drawPrimitive(iface, vertex_count, 0 /* start_idx */, idxSize, pIndexData);
4753 This->up_strided = NULL;
4754 return WINED3D_OK;
4757 /* This is a helper function for UpdateTexture, there is no UpdateVolume method in D3D. */
4758 static HRESULT IWineD3DDeviceImpl_UpdateVolume(IWineD3DDevice *iface,
4759 IWineD3DVolume *pSourceVolume, IWineD3DVolume *pDestinationVolume)
4761 WINED3DLOCKED_BOX src;
4762 WINED3DLOCKED_BOX dst;
4763 HRESULT hr;
4765 TRACE("iface %p, src_volume %p, dst_volume %p.\n",
4766 iface, pSourceVolume, pDestinationVolume);
4768 /* TODO: Implement direct loading into the gl volume instead of using memcpy and
4769 * dirtification to improve loading performance.
4771 hr = IWineD3DVolume_LockBox(pSourceVolume, &src, NULL, WINED3DLOCK_READONLY);
4772 if(FAILED(hr)) return hr;
4773 hr = IWineD3DVolume_LockBox(pDestinationVolume, &dst, NULL, WINED3DLOCK_DISCARD);
4774 if(FAILED(hr)) {
4775 IWineD3DVolume_UnlockBox(pSourceVolume);
4776 return hr;
4779 memcpy(dst.pBits, src.pBits, ((IWineD3DVolumeImpl *) pDestinationVolume)->resource.size);
4781 hr = IWineD3DVolume_UnlockBox(pDestinationVolume);
4782 if(FAILED(hr)) {
4783 IWineD3DVolume_UnlockBox(pSourceVolume);
4784 } else {
4785 hr = IWineD3DVolume_UnlockBox(pSourceVolume);
4787 return hr;
4790 static HRESULT WINAPI IWineD3DDeviceImpl_UpdateTexture(IWineD3DDevice *iface,
4791 IWineD3DBaseTexture *src_texture, IWineD3DBaseTexture *dst_texture)
4793 unsigned int level_count, i;
4794 WINED3DRESOURCETYPE type;
4795 HRESULT hr;
4797 TRACE("iface %p, src_texture %p, dst_texture %p.\n", iface, src_texture, dst_texture);
4799 /* Verify that the source and destination textures are non-NULL. */
4800 if (!src_texture || !dst_texture)
4802 WARN("Source and destination textures must be non-NULL, returning WINED3DERR_INVALIDCALL.\n");
4803 return WINED3DERR_INVALIDCALL;
4806 if (src_texture == dst_texture)
4808 WARN("Source and destination are the same object, returning WINED3DERR_INVALIDCALL.\n");
4809 return WINED3DERR_INVALIDCALL;
4812 /* Verify that the source and destination textures are the same type. */
4813 type = IWineD3DBaseTexture_GetType(src_texture);
4814 if (IWineD3DBaseTexture_GetType(dst_texture) != type)
4816 WARN("Source and destination have different types, returning WINED3DERR_INVALIDCALL.\n");
4817 return WINED3DERR_INVALIDCALL;
4820 /* Check that both textures have the identical numbers of levels. */
4821 level_count = IWineD3DBaseTexture_GetLevelCount(src_texture);
4822 if (IWineD3DBaseTexture_GetLevelCount(dst_texture) != level_count)
4824 WARN("Source and destination have different level counts, returning WINED3DERR_INVALIDCALL.\n");
4825 return WINED3DERR_INVALIDCALL;
4828 /* Make sure that the destination texture is loaded. */
4829 ((IWineD3DBaseTextureImpl *)dst_texture)->baseTexture.internal_preload(dst_texture, SRGB_RGB);
4831 /* Update every surface level of the texture. */
4832 switch (type)
4834 case WINED3DRTYPE_TEXTURE:
4836 IWineD3DSurface *src_surface;
4837 IWineD3DSurface *dst_surface;
4839 for (i = 0; i < level_count; ++i)
4841 IWineD3DTexture_GetSurfaceLevel((IWineD3DTexture *)src_texture, i, &src_surface);
4842 IWineD3DTexture_GetSurfaceLevel((IWineD3DTexture *)dst_texture, i, &dst_surface);
4843 hr = IWineD3DDevice_UpdateSurface(iface, src_surface, NULL, dst_surface, NULL);
4844 IWineD3DSurface_Release(dst_surface);
4845 IWineD3DSurface_Release(src_surface);
4846 if (FAILED(hr))
4848 WARN("IWineD3DDevice_UpdateSurface failed, hr %#x.\n", hr);
4849 return hr;
4852 break;
4855 case WINED3DRTYPE_CUBETEXTURE:
4857 IWineD3DSurface *src_surface;
4858 IWineD3DSurface *dst_surface;
4859 WINED3DCUBEMAP_FACES face;
4861 for (i = 0; i < level_count; ++i)
4863 /* Update each cube face. */
4864 for (face = WINED3DCUBEMAP_FACE_POSITIVE_X; face <= WINED3DCUBEMAP_FACE_NEGATIVE_Z; ++face)
4866 hr = IWineD3DCubeTexture_GetCubeMapSurface((IWineD3DCubeTexture *)src_texture,
4867 face, i, &src_surface);
4868 if (FAILED(hr)) ERR("Failed to get src cube surface face %u, level %u, hr %#x.\n", face, i, hr);
4869 hr = IWineD3DCubeTexture_GetCubeMapSurface((IWineD3DCubeTexture *)dst_texture,
4870 face, i, &dst_surface);
4871 if (FAILED(hr)) ERR("Failed to get dst cube surface face %u, level %u, hr %#x.\n", face, i, hr);
4872 hr = IWineD3DDevice_UpdateSurface(iface, src_surface, NULL, dst_surface, NULL);
4873 IWineD3DSurface_Release(dst_surface);
4874 IWineD3DSurface_Release(src_surface);
4875 if (FAILED(hr))
4877 WARN("IWineD3DDevice_UpdateSurface failed, hr %#x.\n", hr);
4878 return hr;
4882 break;
4885 case WINED3DRTYPE_VOLUMETEXTURE:
4887 IWineD3DVolume *src_volume;
4888 IWineD3DVolume *dst_volume;
4890 for (i = 0; i < level_count; ++i)
4892 IWineD3DVolumeTexture_GetVolumeLevel((IWineD3DVolumeTexture *)src_texture, i, &src_volume);
4893 IWineD3DVolumeTexture_GetVolumeLevel((IWineD3DVolumeTexture *)dst_texture, i, &dst_volume);
4894 hr = IWineD3DDeviceImpl_UpdateVolume(iface, src_volume, dst_volume);
4895 IWineD3DVolume_Release(dst_volume);
4896 IWineD3DVolume_Release(src_volume);
4897 if (FAILED(hr))
4899 WARN("IWineD3DDeviceImpl_UpdateVolume failed, hr %#x.\n", hr);
4900 return hr;
4903 break;
4906 default:
4907 FIXME("Unsupported texture type %#x.\n", type);
4908 return WINED3DERR_INVALIDCALL;
4911 return WINED3D_OK;
4914 static HRESULT WINAPI IWineD3DDeviceImpl_GetFrontBufferData(IWineD3DDevice *iface,UINT iSwapChain, IWineD3DSurface *pDestSurface) {
4915 IWineD3DSwapChain *swapChain;
4916 HRESULT hr;
4917 hr = IWineD3DDeviceImpl_GetSwapChain(iface, iSwapChain, &swapChain);
4918 if(hr == WINED3D_OK) {
4919 hr = IWineD3DSwapChain_GetFrontBufferData(swapChain, pDestSurface);
4920 IWineD3DSwapChain_Release(swapChain);
4922 return hr;
4925 static HRESULT WINAPI IWineD3DDeviceImpl_ValidateDevice(IWineD3DDevice *iface, DWORD* pNumPasses) {
4926 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4927 IWineD3DBaseTextureImpl *texture;
4928 DWORD i;
4930 TRACE("(%p) : %p\n", This, pNumPasses);
4932 for(i = 0; i < MAX_COMBINED_SAMPLERS; i++) {
4933 if(This->stateBlock->samplerState[i][WINED3DSAMP_MINFILTER] == WINED3DTEXF_NONE) {
4934 WARN("Sampler state %u has minfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4935 return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4937 if(This->stateBlock->samplerState[i][WINED3DSAMP_MAGFILTER] == WINED3DTEXF_NONE) {
4938 WARN("Sampler state %u has magfilter D3DTEXF_NONE, returning D3DERR_UNSUPPORTEDTEXTUREFILTER\n", i);
4939 return WINED3DERR_UNSUPPORTEDTEXTUREFILTER;
4942 texture = (IWineD3DBaseTextureImpl *) This->stateBlock->textures[i];
4943 if (!texture || texture->resource.format_desc->Flags & WINED3DFMT_FLAG_FILTERING) continue;
4945 if(This->stateBlock->samplerState[i][WINED3DSAMP_MAGFILTER] != WINED3DTEXF_POINT) {
4946 WARN("Non-filterable texture and mag filter enabled on samper %u, returning E_FAIL\n", i);
4947 return E_FAIL;
4949 if(This->stateBlock->samplerState[i][WINED3DSAMP_MINFILTER] != WINED3DTEXF_POINT) {
4950 WARN("Non-filterable texture and min filter enabled on samper %u, returning E_FAIL\n", i);
4951 return E_FAIL;
4953 if(This->stateBlock->samplerState[i][WINED3DSAMP_MIPFILTER] != WINED3DTEXF_NONE &&
4954 This->stateBlock->samplerState[i][WINED3DSAMP_MIPFILTER] != WINED3DTEXF_POINT /* sic! */) {
4955 WARN("Non-filterable texture and mip filter enabled on samper %u, returning E_FAIL\n", i);
4956 return E_FAIL;
4960 /* return a sensible default */
4961 *pNumPasses = 1;
4963 TRACE("returning D3D_OK\n");
4964 return WINED3D_OK;
4967 static void dirtify_p8_texture_samplers(IWineD3DDeviceImpl *device)
4969 int i;
4971 for (i = 0; i < MAX_COMBINED_SAMPLERS; ++i)
4973 IWineD3DBaseTextureImpl *texture = (IWineD3DBaseTextureImpl*)device->stateBlock->textures[i];
4974 if (texture && (texture->resource.format_desc->format == WINED3DFMT_P8_UINT
4975 || texture->resource.format_desc->format == WINED3DFMT_P8_UINT_A8_UNORM))
4977 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_SAMPLER(i));
4982 static HRESULT WINAPI IWineD3DDeviceImpl_SetPaletteEntries(IWineD3DDevice *iface, UINT PaletteNumber, CONST PALETTEENTRY* pEntries) {
4983 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4984 int j;
4985 UINT NewSize;
4986 PALETTEENTRY **palettes;
4988 TRACE("(%p) : PaletteNumber %u\n", This, PaletteNumber);
4990 if (PaletteNumber >= MAX_PALETTES) {
4991 ERR("(%p) : (%u) Out of range 0-%u, returning Invalid Call\n", This, PaletteNumber, MAX_PALETTES);
4992 return WINED3DERR_INVALIDCALL;
4995 if (PaletteNumber >= This->NumberOfPalettes) {
4996 NewSize = This->NumberOfPalettes;
4997 do {
4998 NewSize *= 2;
4999 } while(PaletteNumber >= NewSize);
5000 palettes = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, This->palettes, sizeof(PALETTEENTRY*) * NewSize);
5001 if (!palettes) {
5002 ERR("Out of memory!\n");
5003 return E_OUTOFMEMORY;
5005 This->palettes = palettes;
5006 This->NumberOfPalettes = NewSize;
5009 if (!This->palettes[PaletteNumber]) {
5010 This->palettes[PaletteNumber] = HeapAlloc(GetProcessHeap(), 0, sizeof(PALETTEENTRY) * 256);
5011 if (!This->palettes[PaletteNumber]) {
5012 ERR("Out of memory!\n");
5013 return E_OUTOFMEMORY;
5017 for (j = 0; j < 256; ++j) {
5018 This->palettes[PaletteNumber][j].peRed = pEntries[j].peRed;
5019 This->palettes[PaletteNumber][j].peGreen = pEntries[j].peGreen;
5020 This->palettes[PaletteNumber][j].peBlue = pEntries[j].peBlue;
5021 This->palettes[PaletteNumber][j].peFlags = pEntries[j].peFlags;
5023 if (PaletteNumber == This->currentPalette) dirtify_p8_texture_samplers(This);
5024 TRACE("(%p) : returning\n", This);
5025 return WINED3D_OK;
5028 static HRESULT WINAPI IWineD3DDeviceImpl_GetPaletteEntries(IWineD3DDevice *iface, UINT PaletteNumber, PALETTEENTRY* pEntries) {
5029 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5030 int j;
5031 TRACE("(%p) : PaletteNumber %u\n", This, PaletteNumber);
5032 if (PaletteNumber >= This->NumberOfPalettes || !This->palettes[PaletteNumber]) {
5033 /* What happens in such situation isn't documented; Native seems to silently abort
5034 on such conditions. Return Invalid Call. */
5035 ERR("(%p) : (%u) Nonexistent palette. NumberOfPalettes %u\n", This, PaletteNumber, This->NumberOfPalettes);
5036 return WINED3DERR_INVALIDCALL;
5038 for (j = 0; j < 256; ++j) {
5039 pEntries[j].peRed = This->palettes[PaletteNumber][j].peRed;
5040 pEntries[j].peGreen = This->palettes[PaletteNumber][j].peGreen;
5041 pEntries[j].peBlue = This->palettes[PaletteNumber][j].peBlue;
5042 pEntries[j].peFlags = This->palettes[PaletteNumber][j].peFlags;
5044 TRACE("(%p) : returning\n", This);
5045 return WINED3D_OK;
5048 static HRESULT WINAPI IWineD3DDeviceImpl_SetCurrentTexturePalette(IWineD3DDevice *iface, UINT PaletteNumber) {
5049 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5050 TRACE("(%p) : PaletteNumber %u\n", This, PaletteNumber);
5051 /* Native appears to silently abort on attempt to make an uninitialized palette current and render.
5052 (tested with reference rasterizer). Return Invalid Call. */
5053 if (PaletteNumber >= This->NumberOfPalettes || !This->palettes[PaletteNumber]) {
5054 ERR("(%p) : (%u) Nonexistent palette. NumberOfPalettes %u\n", This, PaletteNumber, This->NumberOfPalettes);
5055 return WINED3DERR_INVALIDCALL;
5057 /*TODO: stateblocks */
5058 if (This->currentPalette != PaletteNumber) {
5059 This->currentPalette = PaletteNumber;
5060 dirtify_p8_texture_samplers(This);
5062 TRACE("(%p) : returning\n", This);
5063 return WINED3D_OK;
5066 static HRESULT WINAPI IWineD3DDeviceImpl_GetCurrentTexturePalette(IWineD3DDevice *iface, UINT* PaletteNumber) {
5067 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5068 if (PaletteNumber == NULL) {
5069 WARN("(%p) : returning Invalid Call\n", This);
5070 return WINED3DERR_INVALIDCALL;
5072 /*TODO: stateblocks */
5073 *PaletteNumber = This->currentPalette;
5074 TRACE("(%p) : returning %u\n", This, *PaletteNumber);
5075 return WINED3D_OK;
5078 static HRESULT WINAPI IWineD3DDeviceImpl_SetSoftwareVertexProcessing(IWineD3DDevice *iface, BOOL bSoftware) {
5079 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5080 static BOOL warned;
5081 if (!warned)
5083 FIXME("(%p) : stub\n", This);
5084 warned = TRUE;
5087 This->softwareVertexProcessing = bSoftware;
5088 return WINED3D_OK;
5092 static BOOL WINAPI IWineD3DDeviceImpl_GetSoftwareVertexProcessing(IWineD3DDevice *iface) {
5093 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5094 static BOOL warned;
5095 if (!warned)
5097 FIXME("(%p) : stub\n", This);
5098 warned = TRUE;
5100 return This->softwareVertexProcessing;
5103 static HRESULT WINAPI IWineD3DDeviceImpl_GetRasterStatus(IWineD3DDevice *iface,
5104 UINT swapchain_idx, WINED3DRASTER_STATUS *raster_status)
5106 IWineD3DSwapChain *swapchain;
5107 HRESULT hr;
5109 TRACE("iface %p, swapchain_idx %u, raster_status %p.\n",
5110 iface, swapchain_idx, raster_status);
5112 hr = IWineD3DDeviceImpl_GetSwapChain(iface, swapchain_idx, &swapchain);
5113 if (FAILED(hr))
5115 WARN("Failed to get swapchain %u, hr %#x.\n", swapchain_idx, hr);
5116 return hr;
5119 hr = IWineD3DSwapChain_GetRasterStatus(swapchain, raster_status);
5120 IWineD3DSwapChain_Release(swapchain);
5121 if (FAILED(hr))
5123 WARN("Failed to get raster status, hr %#x.\n", hr);
5124 return hr;
5127 return WINED3D_OK;
5130 static HRESULT WINAPI IWineD3DDeviceImpl_SetNPatchMode(IWineD3DDevice *iface, float nSegments)
5132 static BOOL warned;
5133 if(nSegments != 0.0f) {
5134 if (!warned)
5136 FIXME("iface %p, nSegments %.8e stub!\n", iface, nSegments);
5137 warned = TRUE;
5140 return WINED3D_OK;
5143 static float WINAPI IWineD3DDeviceImpl_GetNPatchMode(IWineD3DDevice *iface)
5145 static BOOL warned;
5146 if (!warned)
5148 FIXME("iface %p stub!\n", iface);
5149 warned = TRUE;
5151 return 0.0f;
5154 static HRESULT WINAPI IWineD3DDeviceImpl_UpdateSurface(IWineD3DDevice *iface,
5155 IWineD3DSurface *src_surface, const RECT *src_rect,
5156 IWineD3DSurface *dst_surface, const POINT *dst_point)
5158 IWineD3DSurfaceImpl *src_impl = (IWineD3DSurfaceImpl *)src_surface;
5159 IWineD3DSurfaceImpl *dst_impl = (IWineD3DSurfaceImpl *)dst_surface;
5160 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5161 const struct wined3d_format_desc *src_format;
5162 const struct wined3d_format_desc *dst_format;
5163 struct wined3d_context *context;
5164 const unsigned char *data;
5165 UINT update_w, update_h;
5166 CONVERT_TYPES convert;
5167 UINT src_w, src_h;
5168 UINT dst_x, dst_y;
5169 DWORD sampler;
5170 struct wined3d_format_desc dummy_desc;
5172 TRACE("iface %p, src_surface %p, src_rect %s, dst_surface %p, dst_point %s",
5173 iface, src_surface, wine_dbgstr_rect(src_rect),
5174 dst_surface, wine_dbgstr_point(dst_point));
5176 if (src_impl->resource.pool != WINED3DPOOL_SYSTEMMEM || dst_impl->resource.pool != WINED3DPOOL_DEFAULT)
5178 WARN("source %p must be SYSTEMMEM and dest %p must be DEFAULT, returning WINED3DERR_INVALIDCALL\n",
5179 src_surface, dst_surface);
5180 return WINED3DERR_INVALIDCALL;
5183 src_format = src_impl->resource.format_desc;
5184 dst_format = dst_impl->resource.format_desc;
5186 if (src_format->format != dst_format->format)
5188 WARN("Source and destination surfaces should have the same format.\n");
5189 return WINED3DERR_INVALIDCALL;
5192 dst_x = dst_point ? dst_point->x : 0;
5193 dst_y = dst_point ? dst_point->y : 0;
5195 /* This call loads the OpenGL surface directly, instead of copying the
5196 * surface to the destination's sysmem copy. If surface conversion is
5197 * needed, use BltFast instead to copy in sysmem and use regular surface
5198 * loading. */
5199 d3dfmt_get_conv(dst_impl, FALSE, TRUE, &dummy_desc, &convert);
5200 if (convert != NO_CONVERSION)
5201 return IWineD3DSurface_BltFast(dst_surface, dst_x, dst_y, src_surface, src_rect, 0);
5203 context = context_acquire(This, NULL, CTXUSAGE_RESOURCELOAD);
5205 ENTER_GL();
5206 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
5207 checkGLcall("glActiveTextureARB");
5208 LEAVE_GL();
5210 /* Make sure the surface is loaded and up to date */
5211 surface_internal_preload(dst_surface, SRGB_RGB);
5212 IWineD3DSurface_BindTexture(dst_surface, FALSE);
5214 src_w = src_impl->currentDesc.Width;
5215 src_h = src_impl->currentDesc.Height;
5216 update_w = src_rect ? src_rect->right - src_rect->left : src_w;
5217 update_h = src_rect ? src_rect->bottom - src_rect->top : src_h;
5219 data = IWineD3DSurface_GetData(src_surface);
5220 if (!data) ERR("Source surface has no allocated memory, but should be a sysmem surface.\n");
5222 ENTER_GL();
5224 if (dst_format->Flags & WINED3DFMT_FLAG_COMPRESSED)
5226 UINT row_length = (update_w / src_format->block_width) * src_format->block_byte_count;
5227 UINT row_count = update_h / src_format->block_height;
5228 UINT src_pitch = IWineD3DSurface_GetPitch(src_surface);
5230 if (src_rect)
5232 data += (src_rect->top / src_format->block_height) * src_pitch;
5233 data += (src_rect->left / src_format->block_width) * src_format->block_byte_count;
5236 TRACE("glCompressedTexSubImage2DARB, target %#x, level %d, x %d, y %d, w %d, h %d, "
5237 "format %#x, image_size %#x, data %p.\n", dst_impl->texture_target, dst_impl->texture_level,
5238 dst_x, dst_y, update_w, update_h, dst_format->glFormat, row_count * row_length, data);
5240 if (row_length == src_pitch)
5242 GL_EXTCALL(glCompressedTexSubImage2DARB(dst_impl->texture_target, dst_impl->texture_level,
5243 dst_x, dst_y, update_w, update_h, dst_format->glInternal, row_count * row_length, data));
5245 else
5247 UINT row, y;
5249 /* glCompressedTexSubImage2DARB() ignores pixel store state, so we
5250 * can't use the unpack row length like below. */
5251 for (row = 0, y = dst_y; row < row_count; ++row)
5253 GL_EXTCALL(glCompressedTexSubImage2DARB(dst_impl->texture_target, dst_impl->texture_level,
5254 dst_x, y, update_w, src_format->block_height, dst_format->glInternal, row_length, data));
5255 y += src_format->block_height;
5256 data += src_pitch;
5259 checkGLcall("glCompressedTexSubImage2DARB");
5261 else
5263 if (src_rect)
5265 data += src_rect->top * src_w * src_format->byte_count;
5266 data += src_rect->left * src_format->byte_count;
5269 TRACE("glTexSubImage2D, target %#x, level %d, x %d, y %d, w %d, h %d, format %#x, type %#x, data %p.\n",
5270 dst_impl->texture_target, dst_impl->texture_level, dst_x, dst_y,
5271 update_w, update_h, dst_format->glFormat, dst_format->glType, data);
5273 glPixelStorei(GL_UNPACK_ROW_LENGTH, src_w);
5274 glTexSubImage2D(dst_impl->texture_target, dst_impl->texture_level, dst_x, dst_y,
5275 update_w, update_h, dst_format->glFormat, dst_format->glType, data);
5276 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
5277 checkGLcall("glTexSubImage2D");
5280 LEAVE_GL();
5281 context_release(context);
5283 IWineD3DSurface_ModifyLocation(dst_surface, SFLAG_INTEXTURE, TRUE);
5284 sampler = This->rev_tex_unit_map[0];
5285 if (sampler != WINED3D_UNMAPPED_STAGE)
5287 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(sampler));
5290 return WINED3D_OK;
5293 static HRESULT WINAPI IWineD3DDeviceImpl_DrawRectPatch(IWineD3DDevice *iface, UINT Handle, CONST float* pNumSegs, CONST WINED3DRECTPATCH_INFO* pRectPatchInfo) {
5294 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5295 struct WineD3DRectPatch *patch;
5296 GLenum old_primitive_type;
5297 unsigned int i;
5298 struct list *e;
5299 BOOL found;
5300 TRACE("(%p) Handle(%d) noSegs(%p) rectpatch(%p)\n", This, Handle, pNumSegs, pRectPatchInfo);
5302 if(!(Handle || pRectPatchInfo)) {
5303 /* TODO: Write a test for the return value, thus the FIXME */
5304 FIXME("Both Handle and pRectPatchInfo are NULL\n");
5305 return WINED3DERR_INVALIDCALL;
5308 if(Handle) {
5309 i = PATCHMAP_HASHFUNC(Handle);
5310 found = FALSE;
5311 LIST_FOR_EACH(e, &This->patches[i]) {
5312 patch = LIST_ENTRY(e, struct WineD3DRectPatch, entry);
5313 if(patch->Handle == Handle) {
5314 found = TRUE;
5315 break;
5319 if(!found) {
5320 TRACE("Patch does not exist. Creating a new one\n");
5321 patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
5322 patch->Handle = Handle;
5323 list_add_head(&This->patches[i], &patch->entry);
5324 } else {
5325 TRACE("Found existing patch %p\n", patch);
5327 } else {
5328 /* Since opengl does not load tesselated vertex attributes into numbered vertex
5329 * attributes we have to tesselate, read back, and draw. This needs a patch
5330 * management structure instance. Create one.
5332 * A possible improvement is to check if a vertex shader is used, and if not directly
5333 * draw the patch.
5335 FIXME("Drawing an uncached patch. This is slow\n");
5336 patch = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*patch));
5339 if(pNumSegs[0] != patch->numSegs[0] || pNumSegs[1] != patch->numSegs[1] ||
5340 pNumSegs[2] != patch->numSegs[2] || pNumSegs[3] != patch->numSegs[3] ||
5341 (pRectPatchInfo && memcmp(pRectPatchInfo, &patch->RectPatchInfo, sizeof(*pRectPatchInfo)) != 0) ) {
5342 HRESULT hr;
5343 TRACE("Tesselation density or patch info changed, retesselating\n");
5345 if(pRectPatchInfo) {
5346 patch->RectPatchInfo = *pRectPatchInfo;
5348 patch->numSegs[0] = pNumSegs[0];
5349 patch->numSegs[1] = pNumSegs[1];
5350 patch->numSegs[2] = pNumSegs[2];
5351 patch->numSegs[3] = pNumSegs[3];
5353 hr = tesselate_rectpatch(This, patch);
5354 if(FAILED(hr)) {
5355 WARN("Patch tesselation failed\n");
5357 /* Do not release the handle to store the params of the patch */
5358 if(!Handle) {
5359 HeapFree(GetProcessHeap(), 0, patch);
5361 return hr;
5365 This->currentPatch = patch;
5366 old_primitive_type = This->stateBlock->gl_primitive_type;
5367 This->stateBlock->gl_primitive_type = GL_TRIANGLES;
5368 IWineD3DDevice_DrawPrimitiveStrided(iface, patch->numSegs[0] * patch->numSegs[1] * 2 * 3, &patch->strided);
5369 This->stateBlock->gl_primitive_type = old_primitive_type;
5370 This->currentPatch = NULL;
5372 /* Destroy uncached patches */
5373 if(!Handle) {
5374 HeapFree(GetProcessHeap(), 0, patch->mem);
5375 HeapFree(GetProcessHeap(), 0, patch);
5377 return WINED3D_OK;
5380 static HRESULT WINAPI IWineD3DDeviceImpl_DrawTriPatch(IWineD3DDevice *iface,
5381 UINT handle, const float *segment_count, const WINED3DTRIPATCH_INFO *patch_info)
5383 FIXME("iface %p, handle %#x, segment_count %p, patch_info %p stub!\n",
5384 iface, handle, segment_count, patch_info);
5386 return WINED3D_OK;
5389 static HRESULT WINAPI IWineD3DDeviceImpl_DeletePatch(IWineD3DDevice *iface, UINT Handle) {
5390 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5391 int i;
5392 struct WineD3DRectPatch *patch;
5393 struct list *e;
5394 TRACE("(%p) Handle(%d)\n", This, Handle);
5396 i = PATCHMAP_HASHFUNC(Handle);
5397 LIST_FOR_EACH(e, &This->patches[i]) {
5398 patch = LIST_ENTRY(e, struct WineD3DRectPatch, entry);
5399 if(patch->Handle == Handle) {
5400 TRACE("Deleting patch %p\n", patch);
5401 list_remove(&patch->entry);
5402 HeapFree(GetProcessHeap(), 0, patch->mem);
5403 HeapFree(GetProcessHeap(), 0, patch);
5404 return WINED3D_OK;
5408 /* TODO: Write a test for the return value */
5409 FIXME("Attempt to destroy nonexistent patch\n");
5410 return WINED3DERR_INVALIDCALL;
5413 static void color_fill_fbo(IWineD3DDevice *iface, IWineD3DSurface *surface,
5414 const WINED3DRECT *rect, const float color[4])
5416 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
5417 struct wined3d_context *context;
5419 if (rect) IWineD3DSurface_LoadLocation(surface, SFLAG_INDRAWABLE, NULL);
5420 IWineD3DSurface_ModifyLocation(surface, SFLAG_INDRAWABLE, TRUE);
5422 if (!surface_is_offscreen(surface))
5424 TRACE("Surface %p is onscreen\n", surface);
5426 context = context_acquire(This, surface, CTXUSAGE_RESOURCELOAD);
5427 ENTER_GL();
5428 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
5429 context_set_draw_buffer(context, surface_get_gl_buffer(surface));
5431 else
5433 TRACE("Surface %p is offscreen\n", surface);
5435 context = context_acquire(This, NULL, CTXUSAGE_RESOURCELOAD);
5436 ENTER_GL();
5437 context_bind_fbo(context, GL_FRAMEBUFFER, &context->dst_fbo);
5438 context_attach_surface_fbo(context, GL_FRAMEBUFFER, 0, surface);
5439 context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER, NULL, FALSE);
5442 if (rect) {
5443 glEnable(GL_SCISSOR_TEST);
5444 if(surface_is_offscreen(surface)) {
5445 glScissor(rect->x1, rect->y1, rect->x2 - rect->x1, rect->y2 - rect->y1);
5446 } else {
5447 glScissor(rect->x1, ((IWineD3DSurfaceImpl *)surface)->currentDesc.Height - rect->y2,
5448 rect->x2 - rect->x1, rect->y2 - rect->y1);
5450 checkGLcall("glScissor");
5451 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SCISSORRECT);
5452 } else {
5453 glDisable(GL_SCISSOR_TEST);
5455 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
5457 glDisable(GL_BLEND);
5458 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE));
5460 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
5461 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORWRITEENABLE));
5462 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1));
5463 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2));
5464 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3));
5466 glClearColor(color[0], color[1], color[2], color[3]);
5467 glClear(GL_COLOR_BUFFER_BIT);
5468 checkGLcall("glClear");
5470 LEAVE_GL();
5472 if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
5474 context_release(context);
5477 static HRESULT WINAPI IWineD3DDeviceImpl_ColorFill(IWineD3DDevice *iface,
5478 IWineD3DSurface *pSurface, const WINED3DRECT *pRect, WINED3DCOLOR color)
5480 IWineD3DSurfaceImpl *surface = (IWineD3DSurfaceImpl *) pSurface;
5481 WINEDDBLTFX BltFx;
5483 TRACE("iface %p, surface %p, rect %p, color 0x%08x.\n", iface, pSurface, pRect, color);
5485 if (surface->resource.pool != WINED3DPOOL_DEFAULT && surface->resource.pool != WINED3DPOOL_SYSTEMMEM) {
5486 FIXME("call to colorfill with non WINED3DPOOL_DEFAULT or WINED3DPOOL_SYSTEMMEM surface\n");
5487 return WINED3DERR_INVALIDCALL;
5490 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
5491 const float c[4] = {D3DCOLOR_R(color), D3DCOLOR_G(color), D3DCOLOR_B(color), D3DCOLOR_A(color)};
5492 color_fill_fbo(iface, pSurface, pRect, c);
5493 return WINED3D_OK;
5494 } else {
5495 /* Just forward this to the DirectDraw blitting engine */
5496 memset(&BltFx, 0, sizeof(BltFx));
5497 BltFx.dwSize = sizeof(BltFx);
5498 BltFx.u5.dwFillColor = color_convert_argb_to_fmt(color, surface->resource.format_desc->format);
5499 return IWineD3DSurface_Blt(pSurface, (const RECT *)pRect, NULL, NULL,
5500 WINEDDBLT_COLORFILL, &BltFx, WINED3DTEXF_POINT);
5504 static void WINAPI IWineD3DDeviceImpl_ClearRendertargetView(IWineD3DDevice *iface,
5505 IWineD3DRendertargetView *rendertarget_view, const float color[4])
5507 IWineD3DResource *resource;
5508 IWineD3DSurface *surface;
5509 HRESULT hr;
5511 hr = IWineD3DRendertargetView_GetResource(rendertarget_view, &resource);
5512 if (FAILED(hr))
5514 ERR("Failed to get resource, hr %#x\n", hr);
5515 return;
5518 if (IWineD3DResource_GetType(resource) != WINED3DRTYPE_SURFACE)
5520 FIXME("Only supported on surface resources\n");
5521 IWineD3DResource_Release(resource);
5522 return;
5525 surface = (IWineD3DSurface *)resource;
5527 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
5529 color_fill_fbo(iface, surface, NULL, color);
5531 else
5533 WINEDDBLTFX BltFx;
5534 WINED3DCOLOR c;
5536 WARN("Converting to WINED3DCOLOR, this might give incorrect results\n");
5538 c = ((DWORD)(color[2] * 255.0f));
5539 c |= ((DWORD)(color[1] * 255.0f)) << 8;
5540 c |= ((DWORD)(color[0] * 255.0f)) << 16;
5541 c |= ((DWORD)(color[3] * 255.0f)) << 24;
5543 /* Just forward this to the DirectDraw blitting engine */
5544 memset(&BltFx, 0, sizeof(BltFx));
5545 BltFx.dwSize = sizeof(BltFx);
5546 BltFx.u5.dwFillColor = color_convert_argb_to_fmt(c, ((IWineD3DSurfaceImpl *)surface)->resource.format_desc->format);
5547 hr = IWineD3DSurface_Blt(surface, NULL, NULL, NULL, WINEDDBLT_COLORFILL, &BltFx, WINED3DTEXF_POINT);
5548 if (FAILED(hr))
5550 ERR("Blt failed, hr %#x\n", hr);
5554 IWineD3DResource_Release(resource);
5557 /* rendertarget and depth stencil functions */
5558 static HRESULT WINAPI IWineD3DDeviceImpl_GetRenderTarget(IWineD3DDevice* iface,DWORD RenderTargetIndex, IWineD3DSurface **ppRenderTarget) {
5559 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5561 if (RenderTargetIndex >= This->adapter->gl_info.limits.buffers)
5563 ERR("(%p) : Only %d render targets are supported.\n",
5564 This, This->adapter->gl_info.limits.buffers);
5565 return WINED3DERR_INVALIDCALL;
5568 *ppRenderTarget = This->render_targets[RenderTargetIndex];
5569 TRACE("(%p) : RenderTarget %d Index returning %p\n", This, RenderTargetIndex, *ppRenderTarget);
5570 /* Note inc ref on returned surface */
5571 if(*ppRenderTarget != NULL)
5572 IWineD3DSurface_AddRef(*ppRenderTarget);
5573 return WINED3D_OK;
5576 static HRESULT WINAPI IWineD3DDeviceImpl_SetFrontBackBuffers(IWineD3DDevice *iface,
5577 IWineD3DSurface *front, IWineD3DSurface *back)
5579 IWineD3DSurfaceImpl *front_impl = (IWineD3DSurfaceImpl *)front;
5580 IWineD3DSurfaceImpl *back_impl = (IWineD3DSurfaceImpl *)back;
5581 IWineD3DSwapChainImpl *swapchain;
5582 HRESULT hr;
5584 TRACE("iface %p, front %p, back %p.\n", iface, front, back);
5586 if (FAILED(hr = IWineD3DDevice_GetSwapChain(iface, 0, (IWineD3DSwapChain **)&swapchain)))
5588 ERR("Failed to get the swapchain, hr %#x.\n", hr);
5589 return hr;
5592 if (front_impl && !(front_impl->resource.usage & WINED3DUSAGE_RENDERTARGET))
5594 ERR("Trying to set a front buffer which doesn't have WINED3DUSAGE_RENDERTARGET usage.\n");
5595 IWineD3DSwapChain_Release((IWineD3DSwapChain *)swapchain);
5596 return WINED3DERR_INVALIDCALL;
5599 if (back_impl)
5601 if (!(back_impl->resource.usage & WINED3DUSAGE_RENDERTARGET))
5603 ERR("Trying to set a back buffer which doesn't have WINED3DUSAGE_RENDERTARGET usage.\n");
5604 IWineD3DSwapChain_Release((IWineD3DSwapChain *)swapchain);
5605 return WINED3DERR_INVALIDCALL;
5608 if (!swapchain->backBuffer)
5610 swapchain->backBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*swapchain->backBuffer));
5611 if (!swapchain->backBuffer)
5613 ERR("Failed to allocate back buffer array memory.\n");
5614 IWineD3DSwapChain_Release((IWineD3DSwapChain *)swapchain);
5615 return E_OUTOFMEMORY;
5620 if (swapchain->frontBuffer != front)
5622 TRACE("Changing the front buffer from %p to %p.\n", swapchain->frontBuffer, front);
5624 if (swapchain->frontBuffer)
5626 IWineD3DSurface_SetContainer(swapchain->frontBuffer, NULL);
5627 ((IWineD3DSurfaceImpl *)swapchain->frontBuffer)->Flags &= ~SFLAG_SWAPCHAIN;
5629 swapchain->frontBuffer = front;
5631 if (front)
5633 IWineD3DSurface_SetContainer(front, (IWineD3DBase *)swapchain);
5634 front_impl->Flags |= SFLAG_SWAPCHAIN;
5638 if (swapchain->backBuffer[0] != back)
5640 TRACE("Changing the back buffer from %p to %p.\n", swapchain->backBuffer[0], back);
5642 if (swapchain->backBuffer[0])
5644 IWineD3DSurface_SetContainer(swapchain->backBuffer[0], NULL);
5645 ((IWineD3DSurfaceImpl *)swapchain->backBuffer[0])->Flags &= ~SFLAG_SWAPCHAIN;
5647 swapchain->backBuffer[0] = back;
5649 if (back)
5651 swapchain->presentParms.BackBufferWidth = back_impl->currentDesc.Width;
5652 swapchain->presentParms.BackBufferHeight = back_impl->currentDesc.Height;
5653 swapchain->presentParms.BackBufferFormat = back_impl->resource.format_desc->format;
5654 swapchain->presentParms.BackBufferCount = 1;
5656 IWineD3DSurface_SetContainer(back, (IWineD3DBase *)swapchain);
5657 back_impl->Flags |= SFLAG_SWAPCHAIN;
5659 else
5661 swapchain->presentParms.BackBufferCount = 0;
5662 HeapFree(GetProcessHeap(), 0, swapchain->backBuffer);
5663 swapchain->backBuffer = NULL;
5667 IWineD3DSwapChain_Release((IWineD3DSwapChain *)swapchain);
5668 return WINED3D_OK;
5671 static HRESULT WINAPI IWineD3DDeviceImpl_GetDepthStencilSurface(IWineD3DDevice* iface, IWineD3DSurface **ppZStencilSurface) {
5672 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5673 *ppZStencilSurface = This->stencilBufferTarget;
5674 TRACE("(%p) : zStencilSurface returning %p\n", This, *ppZStencilSurface);
5676 if(*ppZStencilSurface != NULL) {
5677 /* Note inc ref on returned surface */
5678 IWineD3DSurface_AddRef(*ppZStencilSurface);
5679 return WINED3D_OK;
5680 } else {
5681 return WINED3DERR_NOTFOUND;
5685 void stretch_rect_fbo(IWineD3DDevice *iface, IWineD3DSurface *src_surface, const RECT *src_rect_in,
5686 IWineD3DSurface *dst_surface, const RECT *dst_rect_in, const WINED3DTEXTUREFILTERTYPE filter)
5688 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5689 GLbitfield mask = GL_COLOR_BUFFER_BIT; /* TODO: Support blitting depth/stencil surfaces */
5690 const struct wined3d_gl_info *gl_info;
5691 struct wined3d_context *context;
5692 GLenum gl_filter;
5693 POINT offset = {0, 0};
5694 RECT src_rect, dst_rect;
5696 TRACE("(%p) : src_surface %p, src_rect_in %p, dst_surface %p, dst_rect_in %p, filter %s (0x%08x)\n",
5697 This, src_surface, src_rect_in, dst_surface, dst_rect_in, debug_d3dtexturefiltertype(filter), filter);
5698 TRACE("src_rect_in %s\n", wine_dbgstr_rect(src_rect_in));
5699 TRACE("dst_rect_in %s\n", wine_dbgstr_rect(dst_rect_in));
5701 src_rect = *src_rect_in;
5702 dst_rect = *dst_rect_in;
5704 switch (filter) {
5705 case WINED3DTEXF_LINEAR:
5706 gl_filter = GL_LINEAR;
5707 break;
5709 default:
5710 FIXME("Unsupported filter mode %s (0x%08x)\n", debug_d3dtexturefiltertype(filter), filter);
5711 case WINED3DTEXF_NONE:
5712 case WINED3DTEXF_POINT:
5713 gl_filter = GL_NEAREST;
5714 break;
5717 /* Make sure the drawables are up-to-date. Note that loading the
5718 * destination surface isn't strictly required if we overwrite the
5719 * entire surface. */
5720 IWineD3DSurface_LoadLocation(src_surface, SFLAG_INDRAWABLE, NULL);
5721 IWineD3DSurface_LoadLocation(dst_surface, SFLAG_INDRAWABLE, NULL);
5723 if (!surface_is_offscreen(src_surface)) context = context_acquire(This, src_surface, CTXUSAGE_RESOURCELOAD);
5724 else if (!surface_is_offscreen(dst_surface)) context = context_acquire(This, dst_surface, CTXUSAGE_RESOURCELOAD);
5725 else context = context_acquire(This, NULL, CTXUSAGE_RESOURCELOAD);
5727 if (!context->valid)
5729 context_release(context);
5730 WARN("Invalid context, skipping blit.\n");
5731 return;
5734 gl_info = context->gl_info;
5736 if (!surface_is_offscreen(src_surface))
5738 GLenum buffer = surface_get_gl_buffer(src_surface);
5740 TRACE("Source surface %p is onscreen\n", src_surface);
5742 if(buffer == GL_FRONT) {
5743 RECT windowsize;
5744 UINT h;
5745 ClientToScreen(context->win_handle, &offset);
5746 GetClientRect(context->win_handle, &windowsize);
5747 h = windowsize.bottom - windowsize.top;
5748 src_rect.left -= offset.x; src_rect.right -=offset.x;
5749 src_rect.top = offset.y + h - src_rect.top;
5750 src_rect.bottom = offset.y + h - src_rect.bottom;
5751 } else {
5752 src_rect.top = ((IWineD3DSurfaceImpl *)src_surface)->currentDesc.Height - src_rect.top;
5753 src_rect.bottom = ((IWineD3DSurfaceImpl *)src_surface)->currentDesc.Height - src_rect.bottom;
5756 ENTER_GL();
5757 context_bind_fbo(context, GL_READ_FRAMEBUFFER, NULL);
5758 glReadBuffer(buffer);
5759 checkGLcall("glReadBuffer()");
5760 } else {
5761 TRACE("Source surface %p is offscreen\n", src_surface);
5762 ENTER_GL();
5763 context_bind_fbo(context, GL_READ_FRAMEBUFFER, &context->src_fbo);
5764 context_attach_surface_fbo(context, GL_READ_FRAMEBUFFER, 0, src_surface);
5765 glReadBuffer(GL_COLOR_ATTACHMENT0);
5766 checkGLcall("glReadBuffer()");
5767 context_attach_depth_stencil_fbo(context, GL_READ_FRAMEBUFFER, NULL, FALSE);
5769 LEAVE_GL();
5771 /* Attach dst surface to dst fbo */
5772 if (!surface_is_offscreen(dst_surface))
5774 GLenum buffer = surface_get_gl_buffer(dst_surface);
5776 TRACE("Destination surface %p is onscreen\n", dst_surface);
5778 if(buffer == GL_FRONT) {
5779 RECT windowsize;
5780 UINT h;
5781 ClientToScreen(context->win_handle, &offset);
5782 GetClientRect(context->win_handle, &windowsize);
5783 h = windowsize.bottom - windowsize.top;
5784 dst_rect.left -= offset.x; dst_rect.right -=offset.x;
5785 dst_rect.top = offset.y + h - dst_rect.top;
5786 dst_rect.bottom = offset.y + h - dst_rect.bottom;
5787 } else {
5788 /* Screen coords = window coords, surface height = window height */
5789 dst_rect.top = ((IWineD3DSurfaceImpl *)dst_surface)->currentDesc.Height - dst_rect.top;
5790 dst_rect.bottom = ((IWineD3DSurfaceImpl *)dst_surface)->currentDesc.Height - dst_rect.bottom;
5793 ENTER_GL();
5794 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, NULL);
5795 context_set_draw_buffer(context, buffer);
5797 else
5799 TRACE("Destination surface %p is offscreen\n", dst_surface);
5801 ENTER_GL();
5802 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, &context->dst_fbo);
5803 context_attach_surface_fbo(context, GL_DRAW_FRAMEBUFFER, 0, dst_surface);
5804 context_set_draw_buffer(context, GL_COLOR_ATTACHMENT0);
5805 context_attach_depth_stencil_fbo(context, GL_DRAW_FRAMEBUFFER, NULL, FALSE);
5807 glDisable(GL_SCISSOR_TEST);
5808 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
5810 gl_info->fbo_ops.glBlitFramebuffer(src_rect.left, src_rect.top, src_rect.right, src_rect.bottom,
5811 dst_rect.left, dst_rect.top, dst_rect.right, dst_rect.bottom, mask, gl_filter);
5812 checkGLcall("glBlitFramebuffer()");
5814 LEAVE_GL();
5816 if (wined3d_settings.strict_draw_ordering) wglFlush(); /* Flush to ensure ordering across contexts. */
5818 context_release(context);
5820 IWineD3DSurface_ModifyLocation(dst_surface, SFLAG_INDRAWABLE, TRUE);
5823 static HRESULT WINAPI IWineD3DDeviceImpl_SetRenderTarget(IWineD3DDevice *iface, DWORD RenderTargetIndex, IWineD3DSurface *pRenderTarget,
5824 BOOL set_viewport) {
5825 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5827 TRACE("(%p) : Setting rendertarget %d to %p\n", This, RenderTargetIndex, pRenderTarget);
5829 if (RenderTargetIndex >= This->adapter->gl_info.limits.buffers)
5831 WARN("(%p) : Unsupported target %u set, returning WINED3DERR_INVALIDCALL(only %u supported)\n",
5832 This, RenderTargetIndex, This->adapter->gl_info.limits.buffers);
5833 return WINED3DERR_INVALIDCALL;
5836 /* MSDN says that null disables the render target
5837 but a device must always be associated with a render target
5838 nope MSDN says that we return invalid call to a null rendertarget with an index of 0
5840 if (RenderTargetIndex == 0 && pRenderTarget == NULL) {
5841 FIXME("Trying to set render target 0 to NULL\n");
5842 return WINED3DERR_INVALIDCALL;
5844 if (pRenderTarget && !(((IWineD3DSurfaceImpl *)pRenderTarget)->resource.usage & WINED3DUSAGE_RENDERTARGET)) {
5845 FIXME("(%p)Trying to set the render target to a surface(%p) that wasn't created with a usage of WINED3DUSAGE_RENDERTARGET\n",This ,pRenderTarget);
5846 return WINED3DERR_INVALIDCALL;
5849 /* If we are trying to set what we already have, don't bother */
5850 if (pRenderTarget == This->render_targets[RenderTargetIndex]) {
5851 TRACE("Trying to do a NOP SetRenderTarget operation\n");
5852 return WINED3D_OK;
5854 if(pRenderTarget) IWineD3DSurface_AddRef(pRenderTarget);
5855 if(This->render_targets[RenderTargetIndex]) IWineD3DSurface_Release(This->render_targets[RenderTargetIndex]);
5856 This->render_targets[RenderTargetIndex] = pRenderTarget;
5858 /* Render target 0 is special */
5859 if(RenderTargetIndex == 0 && set_viewport) {
5860 /* Finally, reset the viewport and scissor rect as the MSDN states.
5861 * Tests show that stateblock recording is ignored, the change goes
5862 * directly into the primary stateblock.
5864 This->stateBlock->viewport.Height = ((IWineD3DSurfaceImpl *)This->render_targets[0])->currentDesc.Height;
5865 This->stateBlock->viewport.Width = ((IWineD3DSurfaceImpl *)This->render_targets[0])->currentDesc.Width;
5866 This->stateBlock->viewport.X = 0;
5867 This->stateBlock->viewport.Y = 0;
5868 This->stateBlock->viewport.MaxZ = 1.0f;
5869 This->stateBlock->viewport.MinZ = 0.0f;
5870 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_VIEWPORT);
5872 This->stateBlock->scissorRect.top = 0;
5873 This->stateBlock->scissorRect.left = 0;
5874 This->stateBlock->scissorRect.right = This->stateBlock->viewport.Width;
5875 This->stateBlock->scissorRect.bottom = This->stateBlock->viewport.Height;
5876 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SCISSORRECT);
5878 return WINED3D_OK;
5881 static HRESULT WINAPI IWineD3DDeviceImpl_SetDepthStencilSurface(IWineD3DDevice *iface, IWineD3DSurface *pNewZStencil) {
5882 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5883 HRESULT hr = WINED3D_OK;
5884 IWineD3DSurface *tmp;
5886 TRACE("(%p) Swapping z-buffer. Old = %p, new = %p\n",This, This->stencilBufferTarget, pNewZStencil);
5888 if (pNewZStencil == This->stencilBufferTarget) {
5889 TRACE("Trying to do a NOP SetRenderTarget operation\n");
5890 } else {
5891 /** OpenGL doesn't support 'sharing' of the stencilBuffer so we may incur an extra memory overhead
5892 * depending on the renter target implementation being used.
5893 * A shared context implementation will share all buffers between all rendertargets (including swapchains),
5894 * implementations that use separate pbuffers for different swapchains or rendertargets will have to duplicate the
5895 * stencil buffer and incur an extra memory overhead
5896 ******************************************************/
5898 if (This->stencilBufferTarget) {
5899 if (((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms.Flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
5900 || ((IWineD3DSurfaceImpl *)This->stencilBufferTarget)->Flags & SFLAG_DISCARD) {
5901 surface_modify_ds_location(This->stencilBufferTarget, SFLAG_DS_DISCARDED);
5902 } else {
5903 struct wined3d_context *context = context_acquire(This, This->render_targets[0], CTXUSAGE_RESOURCELOAD);
5904 surface_load_ds_location(This->stencilBufferTarget, context, SFLAG_DS_OFFSCREEN);
5905 surface_modify_ds_location(This->stencilBufferTarget, SFLAG_DS_OFFSCREEN);
5906 context_release(context);
5910 tmp = This->stencilBufferTarget;
5911 This->stencilBufferTarget = pNewZStencil;
5912 /* should we be calling the parent or the wined3d surface? */
5913 if (NULL != This->stencilBufferTarget) IWineD3DSurface_AddRef(This->stencilBufferTarget);
5914 if (NULL != tmp) IWineD3DSurface_Release(tmp);
5915 hr = WINED3D_OK;
5917 if((!tmp && pNewZStencil) || (!pNewZStencil && tmp)) {
5918 /* Swapping NULL / non NULL depth stencil affects the depth and tests */
5919 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_ZENABLE));
5920 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_STENCILENABLE));
5921 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_RENDER(WINED3DRS_STENCILWRITEMASK));
5925 return hr;
5928 static HRESULT WINAPI IWineD3DDeviceImpl_SetCursorProperties(IWineD3DDevice* iface, UINT XHotSpot,
5929 UINT YHotSpot, IWineD3DSurface *pCursorBitmap) {
5930 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
5931 /* TODO: the use of Impl is deprecated. */
5932 IWineD3DSurfaceImpl * pSur = (IWineD3DSurfaceImpl *) pCursorBitmap;
5933 WINED3DLOCKED_RECT lockedRect;
5935 TRACE("(%p) : Spot Pos(%u,%u)\n", This, XHotSpot, YHotSpot);
5937 /* some basic validation checks */
5938 if(This->cursorTexture) {
5939 struct wined3d_context *context = context_acquire(This, NULL, CTXUSAGE_RESOURCELOAD);
5940 ENTER_GL();
5941 glDeleteTextures(1, &This->cursorTexture);
5942 LEAVE_GL();
5943 context_release(context);
5944 This->cursorTexture = 0;
5947 if ( (pSur->currentDesc.Width == 32) && (pSur->currentDesc.Height == 32) )
5948 This->haveHardwareCursor = TRUE;
5949 else
5950 This->haveHardwareCursor = FALSE;
5952 if(pCursorBitmap) {
5953 WINED3DLOCKED_RECT rect;
5955 /* MSDN: Cursor must be A8R8G8B8 */
5956 if (pSur->resource.format_desc->format != WINED3DFMT_B8G8R8A8_UNORM)
5958 ERR("(%p) : surface(%p) has an invalid format\n", This, pCursorBitmap);
5959 return WINED3DERR_INVALIDCALL;
5962 /* MSDN: Cursor must be smaller than the display mode */
5963 if(pSur->currentDesc.Width > This->ddraw_width ||
5964 pSur->currentDesc.Height > This->ddraw_height) {
5965 ERR("(%p) : Surface(%p) is %dx%d pixels, but screen res is %dx%d\n", This, pSur, pSur->currentDesc.Width, pSur->currentDesc.Height, This->ddraw_width, This->ddraw_height);
5966 return WINED3DERR_INVALIDCALL;
5969 if (!This->haveHardwareCursor) {
5970 /* TODO: MSDN: Cursor sizes must be a power of 2 */
5972 /* Do not store the surface's pointer because the application may
5973 * release it after setting the cursor image. Windows doesn't
5974 * addref the set surface, so we can't do this either without
5975 * creating circular refcount dependencies. Copy out the gl texture
5976 * instead.
5978 This->cursorWidth = pSur->currentDesc.Width;
5979 This->cursorHeight = pSur->currentDesc.Height;
5980 if (SUCCEEDED(IWineD3DSurface_LockRect(pCursorBitmap, &rect, NULL, WINED3DLOCK_READONLY)))
5982 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
5983 const struct wined3d_format_desc *format_desc = getFormatDescEntry(WINED3DFMT_B8G8R8A8_UNORM, gl_info);
5984 struct wined3d_context *context;
5985 char *mem, *bits = rect.pBits;
5986 GLint intfmt = format_desc->glInternal;
5987 GLint format = format_desc->glFormat;
5988 GLint type = format_desc->glType;
5989 INT height = This->cursorHeight;
5990 INT width = This->cursorWidth;
5991 INT bpp = format_desc->byte_count;
5992 DWORD sampler;
5993 INT i;
5995 /* Reformat the texture memory (pitch and width can be
5996 * different) */
5997 mem = HeapAlloc(GetProcessHeap(), 0, width * height * bpp);
5998 for(i = 0; i < height; i++)
5999 memcpy(&mem[width * bpp * i], &bits[rect.Pitch * i], width * bpp);
6000 IWineD3DSurface_UnlockRect(pCursorBitmap);
6002 context = context_acquire(This, NULL, CTXUSAGE_RESOURCELOAD);
6004 ENTER_GL();
6006 if (gl_info->supported[APPLE_CLIENT_STORAGE])
6008 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
6009 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE)");
6012 /* Make sure that a proper texture unit is selected */
6013 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
6014 checkGLcall("glActiveTextureARB");
6015 sampler = This->rev_tex_unit_map[0];
6016 if (sampler != WINED3D_UNMAPPED_STAGE)
6018 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(sampler));
6020 /* Create a new cursor texture */
6021 glGenTextures(1, &This->cursorTexture);
6022 checkGLcall("glGenTextures");
6023 glBindTexture(GL_TEXTURE_2D, This->cursorTexture);
6024 checkGLcall("glBindTexture");
6025 /* Copy the bitmap memory into the cursor texture */
6026 glTexImage2D(GL_TEXTURE_2D, 0, intfmt, width, height, 0, format, type, mem);
6027 HeapFree(GetProcessHeap(), 0, mem);
6028 checkGLcall("glTexImage2D");
6030 if (gl_info->supported[APPLE_CLIENT_STORAGE])
6032 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
6033 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
6036 LEAVE_GL();
6038 context_release(context);
6040 else
6042 FIXME("A cursor texture was not returned.\n");
6043 This->cursorTexture = 0;
6046 else
6048 /* Draw a hardware cursor */
6049 ICONINFO cursorInfo;
6050 HCURSOR cursor;
6051 /* Create and clear maskBits because it is not needed for
6052 * 32-bit cursors. 32x32 bits split into 32-bit chunks == 32
6053 * chunks. */
6054 DWORD *maskBits = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6055 (pSur->currentDesc.Width * pSur->currentDesc.Height / 8));
6056 IWineD3DSurface_LockRect(pCursorBitmap, &lockedRect, NULL,
6057 WINED3DLOCK_NO_DIRTY_UPDATE |
6058 WINED3DLOCK_READONLY
6060 TRACE("width: %i height: %i\n", pSur->currentDesc.Width,
6061 pSur->currentDesc.Height);
6063 cursorInfo.fIcon = FALSE;
6064 cursorInfo.xHotspot = XHotSpot;
6065 cursorInfo.yHotspot = YHotSpot;
6066 cursorInfo.hbmMask = CreateBitmap(pSur->currentDesc.Width, pSur->currentDesc.Height,
6067 1, 1, maskBits);
6068 cursorInfo.hbmColor = CreateBitmap(pSur->currentDesc.Width, pSur->currentDesc.Height,
6069 1, 32, lockedRect.pBits);
6070 IWineD3DSurface_UnlockRect(pCursorBitmap);
6071 /* Create our cursor and clean up. */
6072 cursor = CreateIconIndirect(&cursorInfo);
6073 SetCursor(cursor);
6074 if (cursorInfo.hbmMask) DeleteObject(cursorInfo.hbmMask);
6075 if (cursorInfo.hbmColor) DeleteObject(cursorInfo.hbmColor);
6076 if (This->hardwareCursor) DestroyCursor(This->hardwareCursor);
6077 This->hardwareCursor = cursor;
6078 HeapFree(GetProcessHeap(), 0, maskBits);
6082 This->xHotSpot = XHotSpot;
6083 This->yHotSpot = YHotSpot;
6084 return WINED3D_OK;
6087 static void WINAPI IWineD3DDeviceImpl_SetCursorPosition(IWineD3DDevice* iface, int XScreenSpace, int YScreenSpace, DWORD Flags) {
6088 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
6089 TRACE("(%p) : SetPos to (%u,%u)\n", This, XScreenSpace, YScreenSpace);
6091 This->xScreenSpace = XScreenSpace;
6092 This->yScreenSpace = YScreenSpace;
6094 return;
6098 static BOOL WINAPI IWineD3DDeviceImpl_ShowCursor(IWineD3DDevice* iface, BOOL bShow) {
6099 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
6100 BOOL oldVisible = This->bCursorVisible;
6101 POINT pt;
6103 TRACE("(%p) : visible(%d)\n", This, bShow);
6106 * When ShowCursor is first called it should make the cursor appear at the OS's last
6107 * known cursor position. Because of this, some applications just repetitively call
6108 * ShowCursor in order to update the cursor's position. This behavior is undocumented.
6110 GetCursorPos(&pt);
6111 This->xScreenSpace = pt.x;
6112 This->yScreenSpace = pt.y;
6114 if (This->haveHardwareCursor) {
6115 This->bCursorVisible = bShow;
6116 if (bShow)
6117 SetCursor(This->hardwareCursor);
6118 else
6119 SetCursor(NULL);
6121 else
6123 if (This->cursorTexture)
6124 This->bCursorVisible = bShow;
6127 return oldVisible;
6130 static HRESULT WINAPI evict_managed_resource(IWineD3DResource *resource, void *data) {
6131 TRACE("checking resource %p for eviction\n", resource);
6132 if(((IWineD3DResourceImpl *) resource)->resource.pool == WINED3DPOOL_MANAGED) {
6133 TRACE("Evicting %p\n", resource);
6134 IWineD3DResource_UnLoad(resource);
6136 IWineD3DResource_Release(resource);
6137 return S_OK;
6140 static HRESULT WINAPI IWineD3DDeviceImpl_EvictManagedResources(IWineD3DDevice *iface)
6142 TRACE("iface %p.\n", iface);
6144 IWineD3DDevice_EnumResources(iface, evict_managed_resource, NULL);
6145 return WINED3D_OK;
6148 static HRESULT updateSurfaceDesc(IWineD3DSurfaceImpl *surface, const WINED3DPRESENT_PARAMETERS* pPresentationParameters)
6150 IWineD3DDeviceImpl *device = surface->resource.device;
6151 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
6153 /* Reallocate proper memory for the front and back buffer and adjust their sizes */
6154 if(surface->Flags & SFLAG_DIBSECTION) {
6155 /* Release the DC */
6156 SelectObject(surface->hDC, surface->dib.holdbitmap);
6157 DeleteDC(surface->hDC);
6158 /* Release the DIB section */
6159 DeleteObject(surface->dib.DIBsection);
6160 surface->dib.bitmap_data = NULL;
6161 surface->resource.allocatedMemory = NULL;
6162 surface->Flags &= ~SFLAG_DIBSECTION;
6164 surface->currentDesc.Width = pPresentationParameters->BackBufferWidth;
6165 surface->currentDesc.Height = pPresentationParameters->BackBufferHeight;
6166 if (gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] || gl_info->supported[ARB_TEXTURE_RECTANGLE]
6167 || gl_info->supported[WINE_NORMALIZED_TEXRECT])
6169 surface->pow2Width = pPresentationParameters->BackBufferWidth;
6170 surface->pow2Height = pPresentationParameters->BackBufferHeight;
6171 } else {
6172 surface->pow2Width = surface->pow2Height = 1;
6173 while (surface->pow2Width < pPresentationParameters->BackBufferWidth) surface->pow2Width <<= 1;
6174 while (surface->pow2Height < pPresentationParameters->BackBufferHeight) surface->pow2Height <<= 1;
6176 surface->glRect.left = 0;
6177 surface->glRect.top = 0;
6178 surface->glRect.right = surface->pow2Width;
6179 surface->glRect.bottom = surface->pow2Height;
6181 if (surface->texture_name)
6183 struct wined3d_context *context = context_acquire(device, NULL, CTXUSAGE_RESOURCELOAD);
6184 ENTER_GL();
6185 glDeleteTextures(1, &surface->texture_name);
6186 LEAVE_GL();
6187 context_release(context);
6188 surface->texture_name = 0;
6189 surface->Flags &= ~SFLAG_CLIENT;
6191 if(surface->pow2Width != pPresentationParameters->BackBufferWidth ||
6192 surface->pow2Height != pPresentationParameters->BackBufferHeight) {
6193 surface->Flags |= SFLAG_NONPOW2;
6194 } else {
6195 surface->Flags &= ~SFLAG_NONPOW2;
6197 HeapFree(GetProcessHeap(), 0, surface->resource.heapMemory);
6198 surface->resource.allocatedMemory = NULL;
6199 surface->resource.heapMemory = NULL;
6200 surface->resource.size = IWineD3DSurface_GetPitch((IWineD3DSurface *) surface) * surface->pow2Width;
6202 /* Put all surfaces into sysmem - the drawable might disappear if the backbuffer was rendered
6203 * to a FBO */
6204 if(!surface_init_sysmem((IWineD3DSurface *) surface))
6206 return E_OUTOFMEMORY;
6208 return WINED3D_OK;
6211 static HRESULT WINAPI reset_unload_resources(IWineD3DResource *resource, void *data) {
6212 TRACE("Unloading resource %p\n", resource);
6213 IWineD3DResource_UnLoad(resource);
6214 IWineD3DResource_Release(resource);
6215 return S_OK;
6218 static BOOL is_display_mode_supported(IWineD3DDeviceImpl *This, const WINED3DPRESENT_PARAMETERS *pp)
6220 UINT i, count;
6221 WINED3DDISPLAYMODE m;
6222 HRESULT hr;
6224 /* All Windowed modes are supported, as is leaving the current mode */
6225 if(pp->Windowed) return TRUE;
6226 if(!pp->BackBufferWidth) return TRUE;
6227 if(!pp->BackBufferHeight) return TRUE;
6229 count = IWineD3D_GetAdapterModeCount(This->wined3d, This->adapter->ordinal, WINED3DFMT_UNKNOWN);
6230 for(i = 0; i < count; i++) {
6231 memset(&m, 0, sizeof(m));
6232 hr = IWineD3D_EnumAdapterModes(This->wined3d, This->adapter->ordinal, WINED3DFMT_UNKNOWN, i, &m);
6233 if(FAILED(hr)) {
6234 ERR("EnumAdapterModes failed\n");
6236 if(m.Width == pp->BackBufferWidth && m.Height == pp->BackBufferHeight) {
6237 /* Mode found, it is supported */
6238 return TRUE;
6241 /* Mode not found -> not supported */
6242 return FALSE;
6245 static void delete_opengl_contexts(IWineD3DDevice *iface, IWineD3DSwapChainImpl *swapchain)
6247 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
6248 const struct wined3d_gl_info *gl_info;
6249 struct wined3d_context *context;
6250 IWineD3DBaseShaderImpl *shader;
6252 context = context_acquire(This, NULL, CTXUSAGE_RESOURCELOAD);
6253 gl_info = context->gl_info;
6255 IWineD3DDevice_EnumResources(iface, reset_unload_resources, NULL);
6256 LIST_FOR_EACH_ENTRY(shader, &This->shaders, IWineD3DBaseShaderImpl, baseShader.shader_list_entry) {
6257 This->shader_backend->shader_destroy((IWineD3DBaseShader *) shader);
6260 ENTER_GL();
6261 if(This->depth_blt_texture) {
6262 glDeleteTextures(1, &This->depth_blt_texture);
6263 This->depth_blt_texture = 0;
6265 if (This->depth_blt_rb) {
6266 gl_info->fbo_ops.glDeleteRenderbuffers(1, &This->depth_blt_rb);
6267 This->depth_blt_rb = 0;
6268 This->depth_blt_rb_w = 0;
6269 This->depth_blt_rb_h = 0;
6271 LEAVE_GL();
6273 This->blitter->free_private(iface);
6274 This->frag_pipe->free_private(iface);
6275 This->shader_backend->shader_free_private(iface);
6276 destroy_dummy_textures(This, gl_info);
6278 context_release(context);
6280 while (This->numContexts)
6282 context_destroy(This, This->contexts[0]);
6284 HeapFree(GetProcessHeap(), 0, swapchain->context);
6285 swapchain->context = NULL;
6286 swapchain->num_contexts = 0;
6289 static HRESULT create_primary_opengl_context(IWineD3DDevice *iface, IWineD3DSwapChainImpl *swapchain)
6291 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
6292 struct wined3d_context *context;
6293 HRESULT hr;
6294 IWineD3DSurfaceImpl *target;
6296 /* Recreate the primary swapchain's context */
6297 swapchain->context = HeapAlloc(GetProcessHeap(), 0, sizeof(*swapchain->context));
6298 if (!swapchain->context)
6300 ERR("Failed to allocate memory for swapchain context array.\n");
6301 return E_OUTOFMEMORY;
6304 target = (IWineD3DSurfaceImpl *)(swapchain->backBuffer ? swapchain->backBuffer[0] : swapchain->frontBuffer);
6305 if (!(context = context_create(swapchain, target, swapchain->ds_format)))
6307 WARN("Failed to create context.\n");
6308 HeapFree(GetProcessHeap(), 0, swapchain->context);
6309 return E_FAIL;
6312 swapchain->context[0] = context;
6313 swapchain->num_contexts = 1;
6314 create_dummy_textures(This);
6315 context_release(context);
6317 hr = This->shader_backend->shader_alloc_private(iface);
6318 if (FAILED(hr))
6320 ERR("Failed to allocate shader private data, hr %#x.\n", hr);
6321 goto err;
6324 hr = This->frag_pipe->alloc_private(iface);
6325 if (FAILED(hr))
6327 ERR("Failed to allocate fragment pipe private data, hr %#x.\n", hr);
6328 This->shader_backend->shader_free_private(iface);
6329 goto err;
6332 hr = This->blitter->alloc_private(iface);
6333 if (FAILED(hr))
6335 ERR("Failed to allocate blitter private data, hr %#x.\n", hr);
6336 This->frag_pipe->free_private(iface);
6337 This->shader_backend->shader_free_private(iface);
6338 goto err;
6341 return WINED3D_OK;
6343 err:
6344 context_acquire(This, NULL, CTXUSAGE_RESOURCELOAD);
6345 destroy_dummy_textures(This, context->gl_info);
6346 context_release(context);
6347 context_destroy(This, context);
6348 HeapFree(GetProcessHeap(), 0, swapchain->context);
6349 swapchain->num_contexts = 0;
6350 return hr;
6353 static HRESULT WINAPI IWineD3DDeviceImpl_Reset(IWineD3DDevice* iface, WINED3DPRESENT_PARAMETERS* pPresentationParameters) {
6354 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
6355 IWineD3DSwapChainImpl *swapchain;
6356 HRESULT hr;
6357 BOOL DisplayModeChanged = FALSE;
6358 WINED3DDISPLAYMODE mode;
6359 TRACE("(%p)\n", This);
6361 hr = IWineD3DDevice_GetSwapChain(iface, 0, (IWineD3DSwapChain **) &swapchain);
6362 if(FAILED(hr)) {
6363 ERR("Failed to get the first implicit swapchain\n");
6364 return hr;
6367 if(!is_display_mode_supported(This, pPresentationParameters)) {
6368 WARN("Rejecting Reset() call because the requested display mode is not supported\n");
6369 WARN("Requested mode: %d, %d\n", pPresentationParameters->BackBufferWidth,
6370 pPresentationParameters->BackBufferHeight);
6371 IWineD3DSwapChain_Release((IWineD3DSwapChain *)swapchain);
6372 return WINED3DERR_INVALIDCALL;
6375 /* Is it necessary to recreate the gl context? Actually every setting can be changed
6376 * on an existing gl context, so there's no real need for recreation.
6378 * TODO: Figure out how Reset influences resources in D3DPOOL_DEFAULT, D3DPOOL_SYSTEMMEMORY and D3DPOOL_MANAGED
6380 * TODO: Figure out what happens to explicit swapchains, or if we have more than one implicit swapchain
6382 TRACE("New params:\n");
6383 TRACE("BackBufferWidth = %d\n", pPresentationParameters->BackBufferWidth);
6384 TRACE("BackBufferHeight = %d\n", pPresentationParameters->BackBufferHeight);
6385 TRACE("BackBufferFormat = %s\n", debug_d3dformat(pPresentationParameters->BackBufferFormat));
6386 TRACE("BackBufferCount = %d\n", pPresentationParameters->BackBufferCount);
6387 TRACE("MultiSampleType = %d\n", pPresentationParameters->MultiSampleType);
6388 TRACE("MultiSampleQuality = %d\n", pPresentationParameters->MultiSampleQuality);
6389 TRACE("SwapEffect = %d\n", pPresentationParameters->SwapEffect);
6390 TRACE("hDeviceWindow = %p\n", pPresentationParameters->hDeviceWindow);
6391 TRACE("Windowed = %s\n", pPresentationParameters->Windowed ? "true" : "false");
6392 TRACE("EnableAutoDepthStencil = %s\n", pPresentationParameters->EnableAutoDepthStencil ? "true" : "false");
6393 TRACE("Flags = %08x\n", pPresentationParameters->Flags);
6394 TRACE("FullScreen_RefreshRateInHz = %d\n", pPresentationParameters->FullScreen_RefreshRateInHz);
6395 TRACE("PresentationInterval = %d\n", pPresentationParameters->PresentationInterval);
6397 /* No special treatment of these parameters. Just store them */
6398 swapchain->presentParms.SwapEffect = pPresentationParameters->SwapEffect;
6399 swapchain->presentParms.Flags = pPresentationParameters->Flags;
6400 swapchain->presentParms.PresentationInterval = pPresentationParameters->PresentationInterval;
6401 swapchain->presentParms.FullScreen_RefreshRateInHz = pPresentationParameters->FullScreen_RefreshRateInHz;
6403 /* What to do about these? */
6404 if(pPresentationParameters->BackBufferCount != 0 &&
6405 pPresentationParameters->BackBufferCount != swapchain->presentParms.BackBufferCount) {
6406 ERR("Cannot change the back buffer count yet\n");
6408 if(pPresentationParameters->BackBufferFormat != WINED3DFMT_UNKNOWN &&
6409 pPresentationParameters->BackBufferFormat != swapchain->presentParms.BackBufferFormat) {
6410 ERR("Cannot change the back buffer format yet\n");
6412 if(pPresentationParameters->hDeviceWindow != NULL &&
6413 pPresentationParameters->hDeviceWindow != swapchain->presentParms.hDeviceWindow) {
6414 ERR("Cannot change the device window yet\n");
6416 if (pPresentationParameters->EnableAutoDepthStencil && !This->auto_depth_stencil_buffer) {
6417 HRESULT hrc;
6419 TRACE("Creating the depth stencil buffer\n");
6421 hrc = IWineD3DDeviceParent_CreateDepthStencilSurface(This->device_parent,
6422 This->parent,
6423 pPresentationParameters->BackBufferWidth,
6424 pPresentationParameters->BackBufferHeight,
6425 pPresentationParameters->AutoDepthStencilFormat,
6426 pPresentationParameters->MultiSampleType,
6427 pPresentationParameters->MultiSampleQuality,
6428 FALSE,
6429 &This->auto_depth_stencil_buffer);
6431 if (FAILED(hrc)) {
6432 ERR("Failed to create the depth stencil buffer\n");
6433 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
6434 return WINED3DERR_INVALIDCALL;
6438 /* Reset the depth stencil */
6439 if (pPresentationParameters->EnableAutoDepthStencil)
6440 IWineD3DDevice_SetDepthStencilSurface(iface, This->auto_depth_stencil_buffer);
6441 else
6442 IWineD3DDevice_SetDepthStencilSurface(iface, NULL);
6444 TRACE("Resetting stateblock\n");
6445 IWineD3DStateBlock_Release((IWineD3DStateBlock *)This->updateStateBlock);
6446 IWineD3DStateBlock_Release((IWineD3DStateBlock *)This->stateBlock);
6448 delete_opengl_contexts(iface, swapchain);
6450 if(pPresentationParameters->Windowed) {
6451 mode.Width = swapchain->orig_width;
6452 mode.Height = swapchain->orig_height;
6453 mode.RefreshRate = 0;
6454 mode.Format = swapchain->presentParms.BackBufferFormat;
6455 } else {
6456 mode.Width = pPresentationParameters->BackBufferWidth;
6457 mode.Height = pPresentationParameters->BackBufferHeight;
6458 mode.RefreshRate = pPresentationParameters->FullScreen_RefreshRateInHz;
6459 mode.Format = swapchain->presentParms.BackBufferFormat;
6462 /* Should Width == 800 && Height == 0 set 800x600? */
6463 if(pPresentationParameters->BackBufferWidth != 0 && pPresentationParameters->BackBufferHeight != 0 &&
6464 (pPresentationParameters->BackBufferWidth != swapchain->presentParms.BackBufferWidth ||
6465 pPresentationParameters->BackBufferHeight != swapchain->presentParms.BackBufferHeight))
6467 UINT i;
6469 if(!pPresentationParameters->Windowed) {
6470 DisplayModeChanged = TRUE;
6472 swapchain->presentParms.BackBufferWidth = pPresentationParameters->BackBufferWidth;
6473 swapchain->presentParms.BackBufferHeight = pPresentationParameters->BackBufferHeight;
6475 hr = updateSurfaceDesc((IWineD3DSurfaceImpl *)swapchain->frontBuffer, pPresentationParameters);
6476 if(FAILED(hr))
6478 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
6479 return hr;
6482 for(i = 0; i < swapchain->presentParms.BackBufferCount; i++) {
6483 hr = updateSurfaceDesc((IWineD3DSurfaceImpl *)swapchain->backBuffer[i], pPresentationParameters);
6484 if(FAILED(hr))
6486 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
6487 return hr;
6490 if(This->auto_depth_stencil_buffer) {
6491 hr = updateSurfaceDesc((IWineD3DSurfaceImpl *)This->auto_depth_stencil_buffer, pPresentationParameters);
6492 if(FAILED(hr))
6494 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
6495 return hr;
6500 if (!pPresentationParameters->Windowed != !swapchain->presentParms.Windowed
6501 || DisplayModeChanged)
6503 IWineD3DDevice_SetDisplayMode(iface, 0, &mode);
6505 if (!pPresentationParameters->Windowed)
6507 if(swapchain->presentParms.Windowed) {
6508 /* switch from windowed to fs */
6509 swapchain_setup_fullscreen_window(swapchain, pPresentationParameters->BackBufferWidth,
6510 pPresentationParameters->BackBufferHeight);
6511 } else {
6512 /* Fullscreen -> fullscreen mode change */
6513 MoveWindow(swapchain->device_window, 0, 0,
6514 pPresentationParameters->BackBufferWidth, pPresentationParameters->BackBufferHeight,
6515 TRUE);
6518 else if (!swapchain->presentParms.Windowed)
6520 /* Fullscreen -> windowed switch */
6521 swapchain_restore_fullscreen_window(swapchain);
6523 swapchain->presentParms.Windowed = pPresentationParameters->Windowed;
6524 } else if(!pPresentationParameters->Windowed) {
6525 DWORD style = This->style, exStyle = This->exStyle;
6526 /* If we're in fullscreen, and the mode wasn't changed, we have to get the window back into
6527 * the right position. Some applications(Battlefield 2, Guild Wars) move it and then call
6528 * Reset to clear up their mess. Guild Wars also loses the device during that.
6530 This->style = 0;
6531 This->exStyle = 0;
6532 swapchain_setup_fullscreen_window(swapchain, pPresentationParameters->BackBufferWidth,
6533 pPresentationParameters->BackBufferHeight);
6534 This->style = style;
6535 This->exStyle = exStyle;
6538 /* Note: No parent needed for initial internal stateblock */
6539 hr = IWineD3DDevice_CreateStateBlock(iface, WINED3DSBT_INIT, (IWineD3DStateBlock **)&This->stateBlock, NULL);
6540 if (FAILED(hr)) ERR("Resetting the stateblock failed with error 0x%08x\n", hr);
6541 else TRACE("Created stateblock %p\n", This->stateBlock);
6542 This->updateStateBlock = This->stateBlock;
6543 IWineD3DStateBlock_AddRef((IWineD3DStateBlock *)This->updateStateBlock);
6545 hr = IWineD3DStateBlock_InitStartupStateBlock((IWineD3DStateBlock *) This->stateBlock);
6546 if(FAILED(hr)) {
6547 ERR("Resetting the stateblock failed with error 0x%08x\n", hr);
6550 if(wined3d_settings.offscreen_rendering_mode == ORM_FBO)
6552 RECT client_rect;
6553 GetClientRect(swapchain->win_handle, &client_rect);
6555 if(!swapchain->presentParms.BackBufferCount)
6557 TRACE("Single buffered rendering\n");
6558 swapchain->render_to_fbo = FALSE;
6560 else if(swapchain->presentParms.BackBufferWidth != client_rect.right ||
6561 swapchain->presentParms.BackBufferHeight != client_rect.bottom )
6563 TRACE("Rendering to FBO. Backbuffer %ux%u, window %ux%u\n",
6564 swapchain->presentParms.BackBufferWidth,
6565 swapchain->presentParms.BackBufferHeight,
6566 client_rect.right, client_rect.bottom);
6567 swapchain->render_to_fbo = TRUE;
6569 else
6571 TRACE("Rendering directly to GL_BACK\n");
6572 swapchain->render_to_fbo = FALSE;
6576 hr = create_primary_opengl_context(iface, swapchain);
6577 IWineD3DSwapChain_Release((IWineD3DSwapChain *) swapchain);
6579 /* All done. There is no need to reload resources or shaders, this will happen automatically on the
6580 * first use
6582 return hr;
6585 static HRESULT WINAPI IWineD3DDeviceImpl_SetDialogBoxMode(IWineD3DDevice *iface, BOOL enable_dialogs)
6587 TRACE("iface %p, enable_dialogs %#x.\n", iface, enable_dialogs);
6589 if (!enable_dialogs) FIXME("Dialogs cannot be disabled yet.\n");
6591 return WINED3D_OK;
6595 static HRESULT WINAPI IWineD3DDeviceImpl_GetCreationParameters(IWineD3DDevice *iface, WINED3DDEVICE_CREATION_PARAMETERS *pParameters) {
6596 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
6597 TRACE("(%p) : pParameters %p\n", This, pParameters);
6599 *pParameters = This->createParms;
6600 return WINED3D_OK;
6603 static void WINAPI IWineD3DDeviceImpl_SetGammaRamp(IWineD3DDevice * iface, UINT iSwapChain, DWORD Flags, CONST WINED3DGAMMARAMP* pRamp) {
6604 IWineD3DSwapChain *swapchain;
6606 TRACE("Relaying to swapchain\n");
6608 if (IWineD3DDeviceImpl_GetSwapChain(iface, iSwapChain, &swapchain) == WINED3D_OK) {
6609 IWineD3DSwapChain_SetGammaRamp(swapchain, Flags, pRamp);
6610 IWineD3DSwapChain_Release(swapchain);
6614 static void WINAPI IWineD3DDeviceImpl_GetGammaRamp(IWineD3DDevice *iface, UINT iSwapChain, WINED3DGAMMARAMP* pRamp) {
6615 IWineD3DSwapChain *swapchain;
6617 TRACE("Relaying to swapchain\n");
6619 if (IWineD3DDeviceImpl_GetSwapChain(iface, iSwapChain, &swapchain) == WINED3D_OK) {
6620 IWineD3DSwapChain_GetGammaRamp(swapchain, pRamp);
6621 IWineD3DSwapChain_Release(swapchain);
6626 /** ********************************************************
6627 * Notification functions
6628 ** ********************************************************/
6629 /** This function must be called in the release of a resource when ref == 0,
6630 * the contents of resource must still be correct,
6631 * any handles to other resource held by the caller must be closed
6632 * (e.g. a texture should release all held surfaces because telling the device that it's been released.)
6633 *****************************************************/
6634 void device_resource_add(IWineD3DDeviceImpl *This, IWineD3DResource *resource)
6636 TRACE("(%p) : Adding resource %p\n", This, resource);
6638 list_add_head(&This->resources, &((IWineD3DResourceImpl *) resource)->resource.resource_list_entry);
6641 static void device_resource_remove(IWineD3DDeviceImpl *This, IWineD3DResource *resource)
6643 TRACE("(%p) : Removing resource %p\n", This, resource);
6645 list_remove(&((IWineD3DResourceImpl *) resource)->resource.resource_list_entry);
6648 void device_resource_released(IWineD3DDeviceImpl *This, IWineD3DResource *resource)
6650 WINED3DRESOURCETYPE type = IWineD3DResource_GetType(resource);
6651 int counter;
6653 TRACE("(%p) : resource %p\n", This, resource);
6655 context_resource_released((IWineD3DDevice *)This, resource, type);
6657 switch (type) {
6658 /* TODO: check front and back buffers, rendertargets etc.. possibly swapchains? */
6659 case WINED3DRTYPE_SURFACE: {
6660 unsigned int i;
6662 if (This->d3d_initialized)
6664 for (i = 0; i < This->adapter->gl_info.limits.buffers; ++i)
6666 if (This->render_targets[i] == (IWineD3DSurface *)resource) {
6667 This->render_targets[i] = NULL;
6670 if (This->stencilBufferTarget == (IWineD3DSurface *)resource) {
6671 This->stencilBufferTarget = NULL;
6675 break;
6677 case WINED3DRTYPE_TEXTURE:
6678 case WINED3DRTYPE_CUBETEXTURE:
6679 case WINED3DRTYPE_VOLUMETEXTURE:
6680 for (counter = 0; counter < MAX_COMBINED_SAMPLERS; counter++) {
6681 if (This->stateBlock != NULL && This->stateBlock->textures[counter] == (IWineD3DBaseTexture *)resource) {
6682 WARN("Texture being released is still by a stateblock, Stage = %u Texture = %p\n", counter, resource);
6683 This->stateBlock->textures[counter] = NULL;
6685 if (This->updateStateBlock != This->stateBlock ){
6686 if (This->updateStateBlock->textures[counter] == (IWineD3DBaseTexture *)resource) {
6687 WARN("Texture being released is still by a stateblock, Stage = %u Texture = %p\n", counter, resource);
6688 This->updateStateBlock->textures[counter] = NULL;
6692 break;
6693 case WINED3DRTYPE_VOLUME:
6694 /* TODO: nothing really? */
6695 break;
6696 case WINED3DRTYPE_BUFFER:
6698 int streamNumber;
6699 TRACE("Cleaning up stream pointers\n");
6701 for(streamNumber = 0; streamNumber < MAX_STREAMS; streamNumber ++){
6702 /* FINDOUT: should a warn be generated if were recording and updateStateBlock->streamSource is lost?
6703 FINDOUT: should changes.streamSource[StreamNumber] be set ?
6705 if (This->updateStateBlock != NULL ) { /* ==NULL when device is being destroyed */
6706 if ((IWineD3DResource *)This->updateStateBlock->streamSource[streamNumber] == resource) {
6707 FIXME("Vertex buffer released while bound to a state block, stream %d\n", streamNumber);
6708 This->updateStateBlock->streamSource[streamNumber] = 0;
6709 /* Set changed flag? */
6712 if (This->stateBlock != NULL ) { /* only happens if there is an error in the application, or on reset/release (because we don't manage internal tracking properly) */
6713 if ((IWineD3DResource *)This->stateBlock->streamSource[streamNumber] == resource) {
6714 TRACE("Vertex buffer released while bound to a state block, stream %d\n", streamNumber);
6715 This->stateBlock->streamSource[streamNumber] = 0;
6720 if (This->updateStateBlock != NULL ) { /* ==NULL when device is being destroyed */
6721 if (This->updateStateBlock->pIndexData == (IWineD3DBuffer *)resource) {
6722 This->updateStateBlock->pIndexData = NULL;
6725 if (This->stateBlock != NULL ) { /* ==NULL when device is being destroyed */
6726 if (This->stateBlock->pIndexData == (IWineD3DBuffer *)resource) {
6727 This->stateBlock->pIndexData = NULL;
6731 break;
6733 default:
6734 FIXME("(%p) unknown resource type %p %u\n", This, resource, IWineD3DResource_GetType(resource));
6735 break;
6739 /* Remove the resource from the resourceStore */
6740 device_resource_remove(This, resource);
6742 TRACE("Resource released\n");
6746 static HRESULT WINAPI IWineD3DDeviceImpl_EnumResources(IWineD3DDevice *iface, D3DCB_ENUMRESOURCES pCallback, void *pData) {
6747 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
6748 IWineD3DResourceImpl *resource, *cursor;
6749 HRESULT ret;
6750 TRACE("(%p)->(%p,%p)\n", This, pCallback, pData);
6752 LIST_FOR_EACH_ENTRY_SAFE(resource, cursor, &This->resources, IWineD3DResourceImpl, resource.resource_list_entry) {
6753 TRACE("enumerating resource %p\n", resource);
6754 IWineD3DResource_AddRef((IWineD3DResource *) resource);
6755 ret = pCallback((IWineD3DResource *) resource, pData);
6756 if(ret == S_FALSE) {
6757 TRACE("Canceling enumeration\n");
6758 break;
6761 return WINED3D_OK;
6764 static HRESULT WINAPI IWineD3DDeviceImpl_GetSurfaceFromDC(IWineD3DDevice *iface, HDC dc, IWineD3DSurface **surface)
6766 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
6767 IWineD3DResourceImpl *resource;
6769 LIST_FOR_EACH_ENTRY(resource, &This->resources, IWineD3DResourceImpl, resource.resource_list_entry)
6771 WINED3DRESOURCETYPE type = IWineD3DResource_GetType((IWineD3DResource *)resource);
6772 if (type == WINED3DRTYPE_SURFACE)
6774 if (((IWineD3DSurfaceImpl *)resource)->hDC == dc)
6776 TRACE("Found surface %p for dc %p.\n", resource, dc);
6777 *surface = (IWineD3DSurface *)resource;
6778 return WINED3D_OK;
6783 return WINED3DERR_INVALIDCALL;
6786 /**********************************************************
6787 * IWineD3DDevice VTbl follows
6788 **********************************************************/
6790 static const IWineD3DDeviceVtbl IWineD3DDevice_Vtbl =
6792 /*** IUnknown methods ***/
6793 IWineD3DDeviceImpl_QueryInterface,
6794 IWineD3DDeviceImpl_AddRef,
6795 IWineD3DDeviceImpl_Release,
6796 /*** IWineD3DDevice methods ***/
6797 IWineD3DDeviceImpl_GetParent,
6798 /*** Creation methods**/
6799 IWineD3DDeviceImpl_CreateBuffer,
6800 IWineD3DDeviceImpl_CreateVertexBuffer,
6801 IWineD3DDeviceImpl_CreateIndexBuffer,
6802 IWineD3DDeviceImpl_CreateStateBlock,
6803 IWineD3DDeviceImpl_CreateSurface,
6804 IWineD3DDeviceImpl_CreateRendertargetView,
6805 IWineD3DDeviceImpl_CreateTexture,
6806 IWineD3DDeviceImpl_CreateVolumeTexture,
6807 IWineD3DDeviceImpl_CreateVolume,
6808 IWineD3DDeviceImpl_CreateCubeTexture,
6809 IWineD3DDeviceImpl_CreateQuery,
6810 IWineD3DDeviceImpl_CreateSwapChain,
6811 IWineD3DDeviceImpl_CreateVertexDeclaration,
6812 IWineD3DDeviceImpl_CreateVertexDeclarationFromFVF,
6813 IWineD3DDeviceImpl_CreateVertexShader,
6814 IWineD3DDeviceImpl_CreateGeometryShader,
6815 IWineD3DDeviceImpl_CreatePixelShader,
6816 IWineD3DDeviceImpl_CreatePalette,
6817 /*** Odd functions **/
6818 IWineD3DDeviceImpl_Init3D,
6819 IWineD3DDeviceImpl_InitGDI,
6820 IWineD3DDeviceImpl_Uninit3D,
6821 IWineD3DDeviceImpl_UninitGDI,
6822 IWineD3DDeviceImpl_SetMultithreaded,
6823 IWineD3DDeviceImpl_EvictManagedResources,
6824 IWineD3DDeviceImpl_GetAvailableTextureMem,
6825 IWineD3DDeviceImpl_GetBackBuffer,
6826 IWineD3DDeviceImpl_GetCreationParameters,
6827 IWineD3DDeviceImpl_GetDeviceCaps,
6828 IWineD3DDeviceImpl_GetDirect3D,
6829 IWineD3DDeviceImpl_GetDisplayMode,
6830 IWineD3DDeviceImpl_SetDisplayMode,
6831 IWineD3DDeviceImpl_GetNumberOfSwapChains,
6832 IWineD3DDeviceImpl_GetRasterStatus,
6833 IWineD3DDeviceImpl_GetSwapChain,
6834 IWineD3DDeviceImpl_Reset,
6835 IWineD3DDeviceImpl_SetDialogBoxMode,
6836 IWineD3DDeviceImpl_SetCursorProperties,
6837 IWineD3DDeviceImpl_SetCursorPosition,
6838 IWineD3DDeviceImpl_ShowCursor,
6839 /*** Getters and setters **/
6840 IWineD3DDeviceImpl_SetClipPlane,
6841 IWineD3DDeviceImpl_GetClipPlane,
6842 IWineD3DDeviceImpl_SetClipStatus,
6843 IWineD3DDeviceImpl_GetClipStatus,
6844 IWineD3DDeviceImpl_SetCurrentTexturePalette,
6845 IWineD3DDeviceImpl_GetCurrentTexturePalette,
6846 IWineD3DDeviceImpl_SetDepthStencilSurface,
6847 IWineD3DDeviceImpl_GetDepthStencilSurface,
6848 IWineD3DDeviceImpl_SetGammaRamp,
6849 IWineD3DDeviceImpl_GetGammaRamp,
6850 IWineD3DDeviceImpl_SetIndexBuffer,
6851 IWineD3DDeviceImpl_GetIndexBuffer,
6852 IWineD3DDeviceImpl_SetBaseVertexIndex,
6853 IWineD3DDeviceImpl_GetBaseVertexIndex,
6854 IWineD3DDeviceImpl_SetLight,
6855 IWineD3DDeviceImpl_GetLight,
6856 IWineD3DDeviceImpl_SetLightEnable,
6857 IWineD3DDeviceImpl_GetLightEnable,
6858 IWineD3DDeviceImpl_SetMaterial,
6859 IWineD3DDeviceImpl_GetMaterial,
6860 IWineD3DDeviceImpl_SetNPatchMode,
6861 IWineD3DDeviceImpl_GetNPatchMode,
6862 IWineD3DDeviceImpl_SetPaletteEntries,
6863 IWineD3DDeviceImpl_GetPaletteEntries,
6864 IWineD3DDeviceImpl_SetPixelShader,
6865 IWineD3DDeviceImpl_GetPixelShader,
6866 IWineD3DDeviceImpl_SetPixelShaderConstantB,
6867 IWineD3DDeviceImpl_GetPixelShaderConstantB,
6868 IWineD3DDeviceImpl_SetPixelShaderConstantI,
6869 IWineD3DDeviceImpl_GetPixelShaderConstantI,
6870 IWineD3DDeviceImpl_SetPixelShaderConstantF,
6871 IWineD3DDeviceImpl_GetPixelShaderConstantF,
6872 IWineD3DDeviceImpl_SetRenderState,
6873 IWineD3DDeviceImpl_GetRenderState,
6874 IWineD3DDeviceImpl_SetRenderTarget,
6875 IWineD3DDeviceImpl_GetRenderTarget,
6876 IWineD3DDeviceImpl_SetFrontBackBuffers,
6877 IWineD3DDeviceImpl_SetSamplerState,
6878 IWineD3DDeviceImpl_GetSamplerState,
6879 IWineD3DDeviceImpl_SetScissorRect,
6880 IWineD3DDeviceImpl_GetScissorRect,
6881 IWineD3DDeviceImpl_SetSoftwareVertexProcessing,
6882 IWineD3DDeviceImpl_GetSoftwareVertexProcessing,
6883 IWineD3DDeviceImpl_SetStreamSource,
6884 IWineD3DDeviceImpl_GetStreamSource,
6885 IWineD3DDeviceImpl_SetStreamSourceFreq,
6886 IWineD3DDeviceImpl_GetStreamSourceFreq,
6887 IWineD3DDeviceImpl_SetTexture,
6888 IWineD3DDeviceImpl_GetTexture,
6889 IWineD3DDeviceImpl_SetTextureStageState,
6890 IWineD3DDeviceImpl_GetTextureStageState,
6891 IWineD3DDeviceImpl_SetTransform,
6892 IWineD3DDeviceImpl_GetTransform,
6893 IWineD3DDeviceImpl_SetVertexDeclaration,
6894 IWineD3DDeviceImpl_GetVertexDeclaration,
6895 IWineD3DDeviceImpl_SetVertexShader,
6896 IWineD3DDeviceImpl_GetVertexShader,
6897 IWineD3DDeviceImpl_SetVertexShaderConstantB,
6898 IWineD3DDeviceImpl_GetVertexShaderConstantB,
6899 IWineD3DDeviceImpl_SetVertexShaderConstantI,
6900 IWineD3DDeviceImpl_GetVertexShaderConstantI,
6901 IWineD3DDeviceImpl_SetVertexShaderConstantF,
6902 IWineD3DDeviceImpl_GetVertexShaderConstantF,
6903 IWineD3DDeviceImpl_SetViewport,
6904 IWineD3DDeviceImpl_GetViewport,
6905 IWineD3DDeviceImpl_MultiplyTransform,
6906 IWineD3DDeviceImpl_ValidateDevice,
6907 IWineD3DDeviceImpl_ProcessVertices,
6908 /*** State block ***/
6909 IWineD3DDeviceImpl_BeginStateBlock,
6910 IWineD3DDeviceImpl_EndStateBlock,
6911 /*** Scene management ***/
6912 IWineD3DDeviceImpl_BeginScene,
6913 IWineD3DDeviceImpl_EndScene,
6914 IWineD3DDeviceImpl_Present,
6915 IWineD3DDeviceImpl_Clear,
6916 IWineD3DDeviceImpl_ClearRendertargetView,
6917 /*** Drawing ***/
6918 IWineD3DDeviceImpl_SetPrimitiveType,
6919 IWineD3DDeviceImpl_GetPrimitiveType,
6920 IWineD3DDeviceImpl_DrawPrimitive,
6921 IWineD3DDeviceImpl_DrawIndexedPrimitive,
6922 IWineD3DDeviceImpl_DrawPrimitiveUP,
6923 IWineD3DDeviceImpl_DrawIndexedPrimitiveUP,
6924 IWineD3DDeviceImpl_DrawPrimitiveStrided,
6925 IWineD3DDeviceImpl_DrawIndexedPrimitiveStrided,
6926 IWineD3DDeviceImpl_DrawRectPatch,
6927 IWineD3DDeviceImpl_DrawTriPatch,
6928 IWineD3DDeviceImpl_DeletePatch,
6929 IWineD3DDeviceImpl_ColorFill,
6930 IWineD3DDeviceImpl_UpdateTexture,
6931 IWineD3DDeviceImpl_UpdateSurface,
6932 IWineD3DDeviceImpl_GetFrontBufferData,
6933 /*** object tracking ***/
6934 IWineD3DDeviceImpl_EnumResources,
6935 IWineD3DDeviceImpl_GetSurfaceFromDC,
6936 IWineD3DDeviceImpl_AcquireFocusWindow,
6937 IWineD3DDeviceImpl_ReleaseFocusWindow,
6940 HRESULT device_init(IWineD3DDeviceImpl *device, IWineD3DImpl *wined3d,
6941 UINT adapter_idx, WINED3DDEVTYPE device_type, HWND focus_window, DWORD flags,
6942 IUnknown *parent, IWineD3DDeviceParent *device_parent)
6944 struct wined3d_adapter *adapter = &wined3d->adapters[adapter_idx];
6945 const struct fragment_pipeline *fragment_pipeline;
6946 struct shader_caps shader_caps;
6947 struct fragment_caps ffp_caps;
6948 WINED3DDISPLAYMODE mode;
6949 unsigned int i;
6950 HRESULT hr;
6952 device->lpVtbl = &IWineD3DDevice_Vtbl;
6953 device->ref = 1;
6954 device->wined3d = (IWineD3D *)wined3d;
6955 IWineD3D_AddRef(device->wined3d);
6956 device->adapter = wined3d->adapter_count ? adapter : NULL;
6957 device->parent = parent;
6958 device->device_parent = device_parent;
6959 list_init(&device->resources);
6960 list_init(&device->shaders);
6962 device->surface_alignment = wined3d->dxVersion == 7 ? DDRAW_PITCH_ALIGNMENT : D3D8_PITCH_ALIGNMENT;
6963 device->posFixup[0] = 1.0f; /* This is needed to get the x coord unmodified through a MAD. */
6965 /* Get the initial screen setup for ddraw. */
6966 hr = IWineD3D_GetAdapterDisplayMode((IWineD3D *)wined3d, adapter_idx, &mode);
6967 if (FAILED(hr))
6969 ERR("Failed to get the adapter's display mode, hr %#x.\n", hr);
6970 IWineD3D_Release(device->wined3d);
6971 return hr;
6973 device->ddraw_width = mode.Width;
6974 device->ddraw_height = mode.Height;
6975 device->ddraw_format = mode.Format;
6977 /* Save the creation parameters. */
6978 device->createParms.AdapterOrdinal = adapter_idx;
6979 device->createParms.DeviceType = device_type;
6980 device->createParms.hFocusWindow = focus_window;
6981 device->createParms.BehaviorFlags = flags;
6983 device->devType = device_type;
6984 for (i = 0; i < PATCHMAP_SIZE; ++i) list_init(&device->patches[i]);
6986 select_shader_mode(&adapter->gl_info, &device->ps_selected_mode, &device->vs_selected_mode);
6987 device->shader_backend = adapter->shader_backend;
6989 memset(&shader_caps, 0, sizeof(shader_caps));
6990 device->shader_backend->shader_get_caps(&adapter->gl_info, &shader_caps);
6991 device->d3d_vshader_constantF = shader_caps.MaxVertexShaderConst;
6992 device->d3d_pshader_constantF = shader_caps.MaxPixelShaderConst;
6993 device->vs_clipping = shader_caps.VSClipping;
6995 memset(&ffp_caps, 0, sizeof(ffp_caps));
6996 fragment_pipeline = adapter->fragment_pipe;
6997 device->frag_pipe = fragment_pipeline;
6998 fragment_pipeline->get_caps(&adapter->gl_info, &ffp_caps);
6999 device->max_ffp_textures = ffp_caps.MaxSimultaneousTextures;
7001 hr = compile_state_table(device->StateTable, device->multistate_funcs, &adapter->gl_info,
7002 ffp_vertexstate_template, fragment_pipeline, misc_state_template);
7003 if (FAILED(hr))
7005 ERR("Failed to compile state table, hr %#x.\n", hr);
7006 IWineD3D_Release(device->wined3d);
7007 return hr;
7010 device->blitter = adapter->blitter;
7012 return WINED3D_OK;
7016 void IWineD3DDeviceImpl_MarkStateDirty(IWineD3DDeviceImpl *This, DWORD state) {
7017 DWORD rep = This->StateTable[state].representative;
7018 struct wined3d_context *context;
7019 DWORD idx;
7020 BYTE shift;
7021 UINT i;
7023 for(i = 0; i < This->numContexts; i++) {
7024 context = This->contexts[i];
7025 if(isStateDirty(context, rep)) continue;
7027 context->dirtyArray[context->numDirtyEntries++] = rep;
7028 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
7029 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
7030 context->isStateDirty[idx] |= (1 << shift);
7034 void get_drawable_size_fbo(struct wined3d_context *context, UINT *width, UINT *height)
7036 IWineD3DSurfaceImpl *surface = (IWineD3DSurfaceImpl *)context->current_rt;
7037 /* The drawable size of a fbo target is the opengl texture size, which is the power of two size. */
7038 *width = surface->pow2Width;
7039 *height = surface->pow2Height;
7042 void get_drawable_size_backbuffer(struct wined3d_context *context, UINT *width, UINT *height)
7044 IWineD3DSwapChainImpl *swapchain = context->swapchain;
7045 /* The drawable size of a backbuffer / aux buffer offscreen target is the size of the
7046 * current context's drawable, which is the size of the back buffer of the swapchain
7047 * the active context belongs to. */
7048 *width = swapchain->presentParms.BackBufferWidth;
7049 *height = swapchain->presentParms.BackBufferHeight;
7052 LRESULT device_process_message(IWineD3DDeviceImpl *device, HWND window,
7053 UINT message, WPARAM wparam, LPARAM lparam, WNDPROC proc)
7055 if (device->filter_messages)
7057 TRACE("Filtering message: window %p, message %#x, wparam %#lx, lparam %#lx.\n",
7058 window, message, wparam, lparam);
7059 return DefWindowProcW(window, message, wparam, lparam);
7062 if (message == WM_DESTROY)
7064 TRACE("unregister window %p.\n", window);
7065 wined3d_unregister_window(window);
7067 if (device->focus_window == window) device->focus_window = NULL;
7068 else ERR("Window %p is not the focus window for device %p.\n", window, device);
7071 return CallWindowProcW(proc, window, message, wparam, lparam);