wined3d: Handle stream output buffer bind flag.
[wine.git] / dlls / wined3d / buffer.c
blob3c6bc61aa95ca7b70e117e74852fb9bf3bbc0833
1 /*
2 * Copyright 2002-2005 Jason Edmeades
3 * Copyright 2002-2005 Raphael Junqueira
4 * Copyright 2004 Christian Costa
5 * Copyright 2005 Oliver Stieber
6 * Copyright 2007-2011, 2013-2014 Stefan Dösinger for CodeWeavers
7 * Copyright 2009-2010 Henri Verbeet for CodeWeavers
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 #include "config.h"
26 #include "wine/port.h"
28 #include "wined3d_private.h"
30 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
32 #define WINED3D_BUFFER_HASDESC 0x01 /* A vertex description has been found. */
33 #define WINED3D_BUFFER_USE_BO 0x02 /* Use a buffer object for this buffer. */
34 #define WINED3D_BUFFER_PIN_SYSMEM 0x04 /* Keep a system memory copy for this buffer. */
35 #define WINED3D_BUFFER_DISCARD 0x08 /* A DISCARD lock has occurred since the last preload. */
36 #define WINED3D_BUFFER_APPLESYNC 0x10 /* Using sync as in GL_APPLE_flush_buffer_range. */
38 #define VB_MAXDECLCHANGES 100 /* After that number of decl changes we stop converting */
39 #define VB_RESETDECLCHANGE 1000 /* Reset the decl changecount after that number of draws */
40 #define VB_MAXFULLCONVERSIONS 5 /* Number of full conversions before we stop converting */
41 #define VB_RESETFULLCONVS 20 /* Reset full conversion counts after that number of draws */
43 static void wined3d_buffer_evict_sysmem(struct wined3d_buffer *buffer)
45 if (buffer->flags & WINED3D_BUFFER_PIN_SYSMEM)
47 TRACE("Not evicting system memory for buffer %p.\n", buffer);
48 return;
51 TRACE("Evicting system memory for buffer %p.\n", buffer);
52 wined3d_buffer_invalidate_location(buffer, WINED3D_LOCATION_SYSMEM);
53 wined3d_resource_free_sysmem(&buffer->resource);
56 static void buffer_invalidate_bo_range(struct wined3d_buffer *buffer, unsigned int offset, unsigned int size)
58 if (!offset && (!size || size == buffer->resource.size))
59 goto invalidate_all;
61 if (offset > buffer->resource.size || size > buffer->resource.size - offset)
63 WARN("Invalid range specified, invalidating entire buffer.\n");
64 goto invalidate_all;
67 if (!wined3d_array_reserve((void **)&buffer->maps, &buffer->maps_size,
68 buffer->modified_areas + 1, sizeof(*buffer->maps)))
70 ERR("Failed to allocate maps array, invalidating entire buffer.\n");
71 goto invalidate_all;
74 buffer->maps[buffer->modified_areas].offset = offset;
75 buffer->maps[buffer->modified_areas].size = size;
76 ++buffer->modified_areas;
77 return;
79 invalidate_all:
80 buffer->modified_areas = 1;
81 buffer->maps[0].offset = 0;
82 buffer->maps[0].size = buffer->resource.size;
85 static inline void buffer_clear_dirty_areas(struct wined3d_buffer *This)
87 This->modified_areas = 0;
90 static BOOL buffer_is_dirty(const struct wined3d_buffer *buffer)
92 return !!buffer->modified_areas;
95 static BOOL buffer_is_fully_dirty(const struct wined3d_buffer *buffer)
97 return buffer->modified_areas == 1
98 && !buffer->maps->offset && buffer->maps->size == buffer->resource.size;
101 static void wined3d_buffer_validate_location(struct wined3d_buffer *buffer, DWORD location)
103 TRACE("buffer %p, location %s.\n", buffer, wined3d_debug_location(location));
105 if (location & WINED3D_LOCATION_BUFFER)
106 buffer_clear_dirty_areas(buffer);
108 buffer->locations |= location;
110 TRACE("New locations flags are %s.\n", wined3d_debug_location(buffer->locations));
113 static void wined3d_buffer_invalidate_range(struct wined3d_buffer *buffer, DWORD location,
114 unsigned int offset, unsigned int size)
116 TRACE("buffer %p, location %s, offset %u, size %u.\n",
117 buffer, wined3d_debug_location(location), offset, size);
119 if (location & WINED3D_LOCATION_BUFFER)
120 buffer_invalidate_bo_range(buffer, offset, size);
122 buffer->locations &= ~location;
124 TRACE("New locations flags are %s.\n", wined3d_debug_location(buffer->locations));
126 if (!buffer->locations)
127 ERR("Buffer %p does not have any up to date location.\n", buffer);
130 void wined3d_buffer_invalidate_location(struct wined3d_buffer *buffer, DWORD location)
132 wined3d_buffer_invalidate_range(buffer, location, 0, 0);
135 /* Context activation is done by the caller. */
136 static void buffer_bind(struct wined3d_buffer *buffer, struct wined3d_context *context)
138 const struct wined3d_gl_info *gl_info = context->gl_info;
140 if (buffer->buffer_type_hint == GL_ELEMENT_ARRAY_BUFFER)
141 context_invalidate_state(context, STATE_INDEXBUFFER);
143 GL_EXTCALL(glBindBuffer(buffer->buffer_type_hint, buffer->buffer_object));
146 /* Context activation is done by the caller. */
147 static void buffer_destroy_buffer_object(struct wined3d_buffer *buffer, const struct wined3d_context *context)
149 const struct wined3d_gl_info *gl_info = context->gl_info;
150 struct wined3d_resource *resource = &buffer->resource;
152 if (!buffer->buffer_object)
153 return;
155 GL_EXTCALL(glDeleteBuffers(1, &buffer->buffer_object));
156 checkGLcall("glDeleteBuffers");
157 buffer->buffer_object = 0;
159 /* The stream source state handler might have read the memory of the
160 * vertex buffer already and got the memory in the vbo which is not
161 * valid any longer. Dirtify the stream source to force a reload. This
162 * happens only once per changed vertexbuffer and should occur rather
163 * rarely. */
164 if (resource->bind_count)
166 if (buffer->bind_flags & WINED3D_BIND_VERTEX_BUFFER)
167 device_invalidate_state(resource->device, STATE_STREAMSRC);
168 if (buffer->bind_flags & WINED3D_BIND_INDEX_BUFFER)
169 device_invalidate_state(resource->device, STATE_INDEXBUFFER);
170 if (buffer->bind_flags & WINED3D_BIND_CONSTANT_BUFFER)
172 device_invalidate_state(resource->device, STATE_CONSTANT_BUFFER(WINED3D_SHADER_TYPE_VERTEX));
173 device_invalidate_state(resource->device, STATE_CONSTANT_BUFFER(WINED3D_SHADER_TYPE_HULL));
174 device_invalidate_state(resource->device, STATE_CONSTANT_BUFFER(WINED3D_SHADER_TYPE_DOMAIN));
175 device_invalidate_state(resource->device, STATE_CONSTANT_BUFFER(WINED3D_SHADER_TYPE_GEOMETRY));
176 device_invalidate_state(resource->device, STATE_CONSTANT_BUFFER(WINED3D_SHADER_TYPE_PIXEL));
177 device_invalidate_state(resource->device, STATE_CONSTANT_BUFFER(WINED3D_SHADER_TYPE_COMPUTE));
181 if (buffer->query)
183 wined3d_event_query_destroy(buffer->query);
184 buffer->query = NULL;
186 buffer->flags &= ~WINED3D_BUFFER_APPLESYNC;
189 /* Context activation is done by the caller. */
190 static BOOL buffer_create_buffer_object(struct wined3d_buffer *buffer, struct wined3d_context *context)
192 const struct wined3d_gl_info *gl_info = context->gl_info;
193 GLenum gl_usage = GL_STATIC_DRAW;
194 GLenum error;
196 TRACE("Creating an OpenGL buffer object for wined3d_buffer %p with usage %s.\n",
197 buffer, debug_d3dusage(buffer->resource.usage));
199 /* Make sure that the gl error is cleared. Do not use checkGLcall
200 * here because checkGLcall just prints a fixme and continues. However,
201 * if an error during VBO creation occurs we can fall back to non-VBO operation
202 * with full functionality(but performance loss).
204 while (gl_info->gl_ops.gl.p_glGetError() != GL_NO_ERROR);
206 /* Basically the FVF parameter passed to CreateVertexBuffer is no good.
207 * The vertex declaration from the device determines how the data in the
208 * buffer is interpreted. This means that on each draw call the buffer has
209 * to be verified to check if the rhw and color values are in the correct
210 * format. */
212 GL_EXTCALL(glGenBuffers(1, &buffer->buffer_object));
213 error = gl_info->gl_ops.gl.p_glGetError();
214 if (!buffer->buffer_object || error != GL_NO_ERROR)
216 ERR("Failed to create a BO with error %s (%#x).\n", debug_glerror(error), error);
217 goto fail;
220 buffer_bind(buffer, context);
221 error = gl_info->gl_ops.gl.p_glGetError();
222 if (error != GL_NO_ERROR)
224 ERR("Failed to bind the BO with error %s (%#x).\n", debug_glerror(error), error);
225 goto fail;
228 if (buffer->resource.usage & WINED3DUSAGE_DYNAMIC)
230 TRACE("Buffer has WINED3DUSAGE_DYNAMIC set.\n");
231 gl_usage = GL_STREAM_DRAW_ARB;
233 if (gl_info->supported[APPLE_FLUSH_BUFFER_RANGE])
235 GL_EXTCALL(glBufferParameteriAPPLE(buffer->buffer_type_hint, GL_BUFFER_FLUSHING_UNMAP_APPLE, GL_FALSE));
236 GL_EXTCALL(glBufferParameteriAPPLE(buffer->buffer_type_hint, GL_BUFFER_SERIALIZED_MODIFY_APPLE, GL_FALSE));
237 checkGLcall("glBufferParameteriAPPLE");
238 buffer->flags |= WINED3D_BUFFER_APPLESYNC;
240 /* No setup is needed here for GL_ARB_map_buffer_range. */
243 GL_EXTCALL(glBufferData(buffer->buffer_type_hint, buffer->resource.size, NULL, gl_usage));
244 error = gl_info->gl_ops.gl.p_glGetError();
245 if (error != GL_NO_ERROR)
247 ERR("glBufferData failed with error %s (%#x).\n", debug_glerror(error), error);
248 goto fail;
251 buffer->buffer_object_usage = gl_usage;
252 buffer_invalidate_bo_range(buffer, 0, 0);
254 return TRUE;
256 fail:
257 /* Clean up all BO init, but continue because we can work without a BO :-) */
258 ERR("Failed to create a buffer object. Continuing, but performance issues may occur.\n");
259 buffer->flags &= ~WINED3D_BUFFER_USE_BO;
260 buffer_destroy_buffer_object(buffer, context);
261 buffer_clear_dirty_areas(buffer);
262 return FALSE;
265 static BOOL buffer_process_converted_attribute(struct wined3d_buffer *buffer,
266 const enum wined3d_buffer_conversion_type conversion_type,
267 const struct wined3d_stream_info_element *attrib, DWORD *stride_this_run)
269 const struct wined3d_format *format = attrib->format;
270 BOOL ret = FALSE;
271 unsigned int i;
272 DWORD_PTR data;
274 /* Check for some valid situations which cause us pain. One is if the buffer is used for
275 * constant attributes(stride = 0), the other one is if the buffer is used on two streams
276 * with different strides. In the 2nd case we might have to drop conversion entirely,
277 * it is possible that the same bytes are once read as FLOAT2 and once as UBYTE4N.
279 if (!attrib->stride)
281 FIXME("%s used with stride 0, let's hope we get the vertex stride from somewhere else.\n",
282 debug_d3dformat(format->id));
284 else if (attrib->stride != *stride_this_run && *stride_this_run)
286 FIXME("Got two concurrent strides, %d and %d.\n", attrib->stride, *stride_this_run);
288 else
290 *stride_this_run = attrib->stride;
291 if (buffer->stride != *stride_this_run)
293 /* We rely that this happens only on the first converted attribute that is found,
294 * if at all. See above check
296 TRACE("Reconverting because converted attributes occur, and the stride changed.\n");
297 buffer->stride = *stride_this_run;
298 HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY, buffer->conversion_map);
299 buffer->conversion_map = wined3d_calloc(buffer->stride, sizeof(*buffer->conversion_map));
300 ret = TRUE;
304 data = ((DWORD_PTR)attrib->data.addr) % buffer->stride;
305 for (i = 0; i < format->attribute_size; ++i)
307 DWORD_PTR idx = (data + i) % buffer->stride;
308 if (buffer->conversion_map[idx] != conversion_type)
310 TRACE("Byte %lu in vertex changed:\n", idx);
311 TRACE(" It was type %#x, is %#x now.\n", buffer->conversion_map[idx], conversion_type);
312 ret = TRUE;
313 buffer->conversion_map[idx] = conversion_type;
317 return ret;
320 #define WINED3D_BUFFER_FIXUP_D3DCOLOR 0x01
321 #define WINED3D_BUFFER_FIXUP_XYZRHW 0x02
323 static BOOL buffer_check_attribute(struct wined3d_buffer *This, const struct wined3d_stream_info *si,
324 const struct wined3d_state *state, UINT attrib_idx, DWORD fixup_flags, DWORD *stride_this_run)
326 const struct wined3d_stream_info_element *attrib = &si->elements[attrib_idx];
327 enum wined3d_format_id format;
328 BOOL ret = FALSE;
330 /* Ignore attributes that do not have our vbo. After that check we can be sure that the attribute is
331 * there, on nonexistent attribs the vbo is 0.
333 if (!(si->use_map & (1u << attrib_idx))
334 || state->streams[attrib->stream_idx].buffer != This)
335 return FALSE;
337 format = attrib->format->id;
338 /* Look for newly appeared conversion */
339 if (fixup_flags & WINED3D_BUFFER_FIXUP_D3DCOLOR && format == WINED3DFMT_B8G8R8A8_UNORM)
341 ret = buffer_process_converted_attribute(This, CONV_D3DCOLOR, attrib, stride_this_run);
343 else if (fixup_flags & WINED3D_BUFFER_FIXUP_XYZRHW && si->position_transformed)
345 if (format != WINED3DFMT_R32G32B32A32_FLOAT)
347 FIXME("Unexpected format %s for transformed position.\n", debug_d3dformat(format));
348 return FALSE;
351 ret = buffer_process_converted_attribute(This, CONV_POSITIONT, attrib, stride_this_run);
353 else if (This->conversion_map)
355 ret = buffer_process_converted_attribute(This, CONV_NONE, attrib, stride_this_run);
358 return ret;
361 static BOOL buffer_find_decl(struct wined3d_buffer *This, const struct wined3d_stream_info *si,
362 const struct wined3d_state *state, DWORD fixup_flags)
364 UINT stride_this_run = 0;
365 BOOL ret = FALSE;
367 /* In d3d7 the vertex buffer declaration NEVER changes because it is stored in the d3d7 vertex buffer.
368 * Once we have our declaration there is no need to look it up again. Index buffers also never need
369 * conversion, so once the (empty) conversion structure is created don't bother checking again
371 if (This->flags & WINED3D_BUFFER_HASDESC)
373 if(This->resource.usage & WINED3DUSAGE_STATICDECL) return FALSE;
376 if (!fixup_flags)
378 TRACE("No fixup required.\n");
379 if(This->conversion_map)
381 HeapFree(GetProcessHeap(), 0, This->conversion_map);
382 This->conversion_map = NULL;
383 This->stride = 0;
384 return TRUE;
387 return FALSE;
390 TRACE("Finding vertex buffer conversion information\n");
391 /* Certain declaration types need some fixups before we can pass them to
392 * opengl. This means D3DCOLOR attributes with fixed function vertex
393 * processing, FLOAT4 POSITIONT with fixed function, and FLOAT16 if
394 * GL_ARB_half_float_vertex is not supported.
396 * Note for d3d8 and d3d9:
397 * The vertex buffer FVF doesn't help with finding them, we have to use
398 * the decoded vertex declaration and pick the things that concern the
399 * current buffer. A problem with this is that this can change between
400 * draws, so we have to validate the information and reprocess the buffer
401 * if it changes, and avoid false positives for performance reasons.
402 * WineD3D doesn't even know the vertex buffer any more, it is managed
403 * by the client libraries and passed to SetStreamSource and ProcessVertices
404 * as needed.
406 * We have to distinguish between vertex shaders and fixed function to
407 * pick the way we access the strided vertex information.
409 * This code sets up a per-byte array with the size of the detected
410 * stride of the arrays in the buffer. For each byte we have a field
411 * that marks the conversion needed on this byte. For example, the
412 * following declaration with fixed function vertex processing:
414 * POSITIONT, FLOAT4
415 * NORMAL, FLOAT3
416 * DIFFUSE, FLOAT16_4
417 * SPECULAR, D3DCOLOR
419 * Will result in
420 * { POSITIONT }{ NORMAL }{ DIFFUSE }{SPECULAR }
421 * [P][P][P][P][P][P][P][P][P][P][P][P][P][P][P][P][0][0][0][0][0][0][0][0][0][0][0][0][F][F][F][F][F][F][F][F][C][C][C][C]
423 * Where in this example map P means 4 component position conversion, 0
424 * means no conversion, F means FLOAT16_2 conversion and C means D3DCOLOR
425 * conversion (red / blue swizzle).
427 * If we're doing conversion and the stride changes we have to reconvert
428 * the whole buffer. Note that we do not mind if the semantic changes,
429 * we only care for the conversion type. So if the NORMAL is replaced
430 * with a TEXCOORD, nothing has to be done, or if the DIFFUSE is replaced
431 * with a D3DCOLOR BLENDWEIGHT we can happily dismiss the change. Some
432 * conversion types depend on the semantic as well, for example a FLOAT4
433 * texcoord needs no conversion while a FLOAT4 positiont needs one
436 ret = buffer_check_attribute(This, si, state, WINED3D_FFP_POSITION,
437 fixup_flags, &stride_this_run) || ret;
438 fixup_flags &= ~WINED3D_BUFFER_FIXUP_XYZRHW;
440 ret = buffer_check_attribute(This, si, state, WINED3D_FFP_BLENDWEIGHT,
441 fixup_flags, &stride_this_run) || ret;
442 ret = buffer_check_attribute(This, si, state, WINED3D_FFP_BLENDINDICES,
443 fixup_flags, &stride_this_run) || ret;
444 ret = buffer_check_attribute(This, si, state, WINED3D_FFP_NORMAL,
445 fixup_flags, &stride_this_run) || ret;
446 ret = buffer_check_attribute(This, si, state, WINED3D_FFP_DIFFUSE,
447 fixup_flags, &stride_this_run) || ret;
448 ret = buffer_check_attribute(This, si, state, WINED3D_FFP_SPECULAR,
449 fixup_flags, &stride_this_run) || ret;
450 ret = buffer_check_attribute(This, si, state, WINED3D_FFP_TEXCOORD0,
451 fixup_flags, &stride_this_run) || ret;
452 ret = buffer_check_attribute(This, si, state, WINED3D_FFP_TEXCOORD1,
453 fixup_flags, &stride_this_run) || ret;
454 ret = buffer_check_attribute(This, si, state, WINED3D_FFP_TEXCOORD2,
455 fixup_flags, &stride_this_run) || ret;
456 ret = buffer_check_attribute(This, si, state, WINED3D_FFP_TEXCOORD3,
457 fixup_flags, &stride_this_run) || ret;
458 ret = buffer_check_attribute(This, si, state, WINED3D_FFP_TEXCOORD4,
459 fixup_flags, &stride_this_run) || ret;
460 ret = buffer_check_attribute(This, si, state, WINED3D_FFP_TEXCOORD5,
461 fixup_flags, &stride_this_run) || ret;
462 ret = buffer_check_attribute(This, si, state, WINED3D_FFP_TEXCOORD6,
463 fixup_flags, &stride_this_run) || ret;
464 ret = buffer_check_attribute(This, si, state, WINED3D_FFP_TEXCOORD7,
465 fixup_flags, &stride_this_run) || ret;
467 if (!stride_this_run && This->conversion_map)
469 /* Sanity test */
470 if (!ret) ERR("no converted attributes found, old conversion map exists, and no declaration change?\n");
471 HeapFree(GetProcessHeap(), 0, This->conversion_map);
472 This->conversion_map = NULL;
473 This->stride = 0;
476 if (ret) TRACE("Conversion information changed\n");
478 return ret;
481 static inline unsigned int fixup_d3dcolor(DWORD *dst_color)
483 DWORD src_color = *dst_color;
485 /* Color conversion like in draw_primitive_immediate_mode(). Watch out for
486 * endianness. If we want this to work on big-endian machines as well we
487 * have to consider more things.
489 * 0xff000000: Alpha mask
490 * 0x00ff0000: Blue mask
491 * 0x0000ff00: Green mask
492 * 0x000000ff: Red mask
494 *dst_color = 0;
495 *dst_color |= (src_color & 0xff00ff00u); /* Alpha Green */
496 *dst_color |= (src_color & 0x00ff0000u) >> 16; /* Red */
497 *dst_color |= (src_color & 0x000000ffu) << 16; /* Blue */
499 return sizeof(*dst_color);
502 static inline unsigned int fixup_transformed_pos(struct wined3d_vec4 *p)
504 /* rhw conversion like in position_float4(). */
505 if (p->w != 1.0f && p->w != 0.0f)
507 float w = 1.0f / p->w;
508 p->x *= w;
509 p->y *= w;
510 p->z *= w;
511 p->w = w;
514 return sizeof(*p);
517 ULONG CDECL wined3d_buffer_incref(struct wined3d_buffer *buffer)
519 ULONG refcount = InterlockedIncrement(&buffer->resource.ref);
521 TRACE("%p increasing refcount to %u.\n", buffer, refcount);
523 return refcount;
526 /* Context activation is done by the caller. */
527 static void wined3d_buffer_upload_ranges(struct wined3d_buffer *buffer, struct wined3d_context *context,
528 const void *data, unsigned int data_offset, unsigned int range_count, const struct wined3d_map_range *ranges)
530 const struct wined3d_gl_info *gl_info = context->gl_info;
531 const struct wined3d_map_range *range;
533 buffer_bind(buffer, context);
535 while (range_count--)
537 range = &ranges[range_count];
538 GL_EXTCALL(glBufferSubData(buffer->buffer_type_hint,
539 range->offset, range->size, (BYTE *)data + range->offset - data_offset));
541 checkGLcall("glBufferSubData");
544 static void buffer_conversion_upload(struct wined3d_buffer *buffer, struct wined3d_context *context)
546 unsigned int i, j, range_idx, start, end, vertex_count;
547 BYTE *data;
549 if (!wined3d_buffer_load_location(buffer, context, WINED3D_LOCATION_SYSMEM))
551 ERR("Failed to load system memory.\n");
552 return;
554 buffer->flags |= WINED3D_BUFFER_PIN_SYSMEM;
556 /* Now for each vertex in the buffer that needs conversion. */
557 vertex_count = buffer->resource.size / buffer->stride;
559 if (!(data = HeapAlloc(GetProcessHeap(), 0, buffer->resource.size)))
561 ERR("Out of memory.\n");
562 return;
565 for (range_idx = 0; range_idx < buffer->modified_areas; ++range_idx)
567 start = buffer->maps[range_idx].offset;
568 end = start + buffer->maps[range_idx].size;
570 memcpy(data + start, (BYTE *)buffer->resource.heap_memory + start, end - start);
571 for (i = start / buffer->stride; i < min((end / buffer->stride) + 1, vertex_count); ++i)
573 for (j = 0; j < buffer->stride;)
575 switch (buffer->conversion_map[j])
577 case CONV_NONE:
578 /* Done already */
579 j += sizeof(DWORD);
580 break;
581 case CONV_D3DCOLOR:
582 j += fixup_d3dcolor((DWORD *) (data + i * buffer->stride + j));
583 break;
584 case CONV_POSITIONT:
585 j += fixup_transformed_pos((struct wined3d_vec4 *) (data + i * buffer->stride + j));
586 break;
587 default:
588 FIXME("Unimplemented conversion %d in shifted conversion.\n", buffer->conversion_map[j]);
589 ++j;
595 wined3d_buffer_upload_ranges(buffer, context, data, 0, buffer->modified_areas, buffer->maps);
597 HeapFree(GetProcessHeap(), 0, data);
600 static BOOL wined3d_buffer_prepare_location(struct wined3d_buffer *buffer,
601 struct wined3d_context *context, DWORD location)
603 switch (location)
605 case WINED3D_LOCATION_SYSMEM:
606 if (buffer->resource.heap_memory)
607 return TRUE;
609 if (!wined3d_resource_allocate_sysmem(&buffer->resource))
611 ERR("Failed to allocate system memory.\n");
612 return FALSE;
614 return TRUE;
616 case WINED3D_LOCATION_BUFFER:
617 if (buffer->buffer_object)
618 return TRUE;
620 if (!(buffer->flags & WINED3D_BUFFER_USE_BO))
622 WARN("Trying to create BO for buffer %p with no WINED3D_BUFFER_USE_BO.\n", buffer);
623 return FALSE;
625 return buffer_create_buffer_object(buffer, context);
627 default:
628 ERR("Invalid location %s.\n", wined3d_debug_location(location));
629 return FALSE;
633 BOOL wined3d_buffer_load_location(struct wined3d_buffer *buffer,
634 struct wined3d_context *context, DWORD location)
636 const struct wined3d_gl_info *gl_info = context->gl_info;
638 TRACE("buffer %p, context %p, location %s.\n",
639 buffer, context, wined3d_debug_location(location));
641 if (buffer->locations & location)
643 TRACE("Location (%#x) is already up to date.\n", location);
644 return TRUE;
647 if (!buffer->locations)
649 ERR("Buffer %p does not have any up to date location.\n", buffer);
650 wined3d_buffer_validate_location(buffer, WINED3D_LOCATION_DISCARDED);
651 return wined3d_buffer_load_location(buffer, context, location);
654 TRACE("Current buffer location %s.\n", wined3d_debug_location(buffer->locations));
656 if (!wined3d_buffer_prepare_location(buffer, context, location))
657 return FALSE;
659 if (buffer->locations & WINED3D_LOCATION_DISCARDED)
661 TRACE("Buffer previously discarded, nothing to do.\n");
662 wined3d_buffer_validate_location(buffer, location);
663 wined3d_buffer_invalidate_location(buffer, WINED3D_LOCATION_DISCARDED);
664 return TRUE;
667 switch (location)
669 case WINED3D_LOCATION_SYSMEM:
670 buffer_bind(buffer, context);
671 GL_EXTCALL(glGetBufferSubData(buffer->buffer_type_hint, 0, buffer->resource.size,
672 buffer->resource.heap_memory));
673 checkGLcall("buffer download");
674 break;
676 case WINED3D_LOCATION_BUFFER:
677 if (!buffer->conversion_map)
678 wined3d_buffer_upload_ranges(buffer, context, buffer->resource.heap_memory,
679 0, buffer->modified_areas, buffer->maps);
680 else
681 buffer_conversion_upload(buffer, context);
682 break;
684 default:
685 ERR("Invalid location %s.\n", wined3d_debug_location(location));
686 return FALSE;
689 wined3d_buffer_validate_location(buffer, location);
690 if (buffer->resource.heap_memory && location == WINED3D_LOCATION_BUFFER
691 && !(buffer->resource.usage & WINED3DUSAGE_DYNAMIC))
692 wined3d_buffer_evict_sysmem(buffer);
694 return TRUE;
697 /* Context activation is done by the caller. */
698 BYTE *wined3d_buffer_load_sysmem(struct wined3d_buffer *buffer, struct wined3d_context *context)
700 if (wined3d_buffer_load_location(buffer, context, WINED3D_LOCATION_SYSMEM))
701 buffer->flags |= WINED3D_BUFFER_PIN_SYSMEM;
702 return buffer->resource.heap_memory;
705 DWORD wined3d_buffer_get_memory(struct wined3d_buffer *buffer,
706 struct wined3d_bo_address *data, DWORD locations)
708 TRACE("buffer %p, data %p, locations %s.\n",
709 buffer, data, wined3d_debug_location(locations));
711 if (locations & WINED3D_LOCATION_BUFFER)
713 data->buffer_object = buffer->buffer_object;
714 data->addr = NULL;
715 return WINED3D_LOCATION_BUFFER;
717 if (locations & WINED3D_LOCATION_SYSMEM)
719 data->buffer_object = 0;
720 data->addr = buffer->resource.heap_memory;
721 return WINED3D_LOCATION_SYSMEM;
724 ERR("Unexpected locations %s.\n", wined3d_debug_location(locations));
725 data->buffer_object = 0;
726 data->addr = NULL;
727 return 0;
730 static void buffer_unload(struct wined3d_resource *resource)
732 struct wined3d_buffer *buffer = buffer_from_resource(resource);
734 TRACE("buffer %p.\n", buffer);
736 if (buffer->buffer_object)
738 struct wined3d_context *context;
740 context = context_acquire(resource->device, NULL, 0);
742 wined3d_buffer_load_location(buffer, context, WINED3D_LOCATION_SYSMEM);
743 wined3d_buffer_invalidate_location(buffer, WINED3D_LOCATION_BUFFER);
744 buffer_destroy_buffer_object(buffer, context);
745 buffer_clear_dirty_areas(buffer);
747 context_release(context);
749 HeapFree(GetProcessHeap(), 0, buffer->conversion_map);
750 buffer->conversion_map = NULL;
751 buffer->stride = 0;
752 buffer->conversion_stride = 0;
753 buffer->flags &= ~WINED3D_BUFFER_HASDESC;
756 resource_unload(resource);
759 static void wined3d_buffer_drop_bo(struct wined3d_buffer *buffer)
761 buffer->flags &= ~WINED3D_BUFFER_USE_BO;
762 buffer_unload(&buffer->resource);
765 static void wined3d_buffer_destroy_object(void *object)
767 struct wined3d_buffer *buffer = object;
768 struct wined3d_context *context;
770 if (buffer->buffer_object)
772 context = context_acquire(buffer->resource.device, NULL, 0);
773 buffer_destroy_buffer_object(buffer, context);
774 context_release(context);
776 HeapFree(GetProcessHeap(), 0, buffer->conversion_map);
779 HeapFree(GetProcessHeap(), 0, buffer->maps);
780 HeapFree(GetProcessHeap(), 0, buffer);
783 ULONG CDECL wined3d_buffer_decref(struct wined3d_buffer *buffer)
785 ULONG refcount = InterlockedDecrement(&buffer->resource.ref);
787 TRACE("%p decreasing refcount to %u.\n", buffer, refcount);
789 if (!refcount)
791 buffer->resource.parent_ops->wined3d_object_destroyed(buffer->resource.parent);
792 resource_cleanup(&buffer->resource);
793 wined3d_cs_destroy_object(buffer->resource.device->cs, wined3d_buffer_destroy_object, buffer);
796 return refcount;
799 void * CDECL wined3d_buffer_get_parent(const struct wined3d_buffer *buffer)
801 TRACE("buffer %p.\n", buffer);
803 return buffer->resource.parent;
806 /* The caller provides a context and binds the buffer */
807 static void buffer_sync_apple(struct wined3d_buffer *This, DWORD flags, const struct wined3d_gl_info *gl_info)
809 enum wined3d_event_query_result ret;
811 /* No fencing needs to be done if the app promises not to overwrite
812 * existing data. */
813 if (flags & WINED3D_MAP_NOOVERWRITE)
814 return;
816 if (flags & WINED3D_MAP_DISCARD)
818 GL_EXTCALL(glBufferData(This->buffer_type_hint, This->resource.size, NULL, This->buffer_object_usage));
819 checkGLcall("glBufferData");
820 return;
823 if(!This->query)
825 TRACE("Creating event query for buffer %p\n", This);
827 if (!wined3d_event_query_supported(gl_info))
829 FIXME("Event queries not supported, dropping async buffer locks.\n");
830 goto drop_query;
833 This->query = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*This->query));
834 if (!This->query)
836 ERR("Failed to allocate event query memory, dropping async buffer locks.\n");
837 goto drop_query;
840 /* Since we don't know about old draws a glFinish is needed once */
841 gl_info->gl_ops.gl.p_glFinish();
842 return;
844 TRACE("Synchronizing buffer %p\n", This);
845 ret = wined3d_event_query_finish(This->query, This->resource.device);
846 switch(ret)
848 case WINED3D_EVENT_QUERY_NOT_STARTED:
849 case WINED3D_EVENT_QUERY_OK:
850 /* All done */
851 return;
853 case WINED3D_EVENT_QUERY_WRONG_THREAD:
854 WARN("Cannot synchronize buffer lock due to a thread conflict\n");
855 goto drop_query;
857 default:
858 ERR("wined3d_event_query_finish returned %u, dropping async buffer locks\n", ret);
859 goto drop_query;
862 drop_query:
863 if(This->query)
865 wined3d_event_query_destroy(This->query);
866 This->query = NULL;
869 gl_info->gl_ops.gl.p_glFinish();
870 GL_EXTCALL(glBufferParameteriAPPLE(This->buffer_type_hint, GL_BUFFER_SERIALIZED_MODIFY_APPLE, GL_TRUE));
871 checkGLcall("glBufferParameteriAPPLE(This->buffer_type_hint, GL_BUFFER_SERIALIZED_MODIFY_APPLE, GL_TRUE)");
872 This->flags &= ~WINED3D_BUFFER_APPLESYNC;
875 static void buffer_mark_used(struct wined3d_buffer *buffer)
877 buffer->flags &= ~WINED3D_BUFFER_DISCARD;
880 /* Context activation is done by the caller. */
881 void wined3d_buffer_load(struct wined3d_buffer *buffer, struct wined3d_context *context,
882 const struct wined3d_state *state)
884 const struct wined3d_gl_info *gl_info = context->gl_info;
885 BOOL decl_changed = FALSE;
887 TRACE("buffer %p.\n", buffer);
889 if (buffer->resource.map_count)
891 WARN("Buffer is mapped, skipping preload.\n");
892 return;
895 buffer_mark_used(buffer);
897 /* TODO: Make converting independent from VBOs */
898 if (!(buffer->flags & WINED3D_BUFFER_USE_BO))
900 /* Not doing any conversion */
901 return;
904 if (!wined3d_buffer_prepare_location(buffer, context, WINED3D_LOCATION_BUFFER))
906 ERR("Failed to prepare buffer location.\n");
907 return;
910 /* Reading the declaration makes only sense if we have valid state information
911 * (i.e., if this function is called during draws). */
912 if (state)
914 DWORD fixup_flags = 0;
916 if (!use_vs(state))
918 if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA] && !context->d3d_info->ffp_generic_attributes)
919 fixup_flags |= WINED3D_BUFFER_FIXUP_D3DCOLOR;
920 if (!context->d3d_info->xyzrhw)
921 fixup_flags |= WINED3D_BUFFER_FIXUP_XYZRHW;
924 decl_changed = buffer_find_decl(buffer, &context->stream_info, state, fixup_flags);
925 buffer->flags |= WINED3D_BUFFER_HASDESC;
928 if (!decl_changed && !(buffer->flags & WINED3D_BUFFER_HASDESC && buffer_is_dirty(buffer)))
930 ++buffer->draw_count;
931 if (buffer->draw_count > VB_RESETDECLCHANGE)
932 buffer->decl_change_count = 0;
933 if (buffer->draw_count > VB_RESETFULLCONVS)
934 buffer->full_conversion_count = 0;
935 return;
938 /* If applications change the declaration over and over, reconverting all the time is a huge
939 * performance hit. So count the declaration changes and release the VBO if there are too many
940 * of them (and thus stop converting)
942 if (decl_changed)
944 ++buffer->decl_change_count;
945 buffer->draw_count = 0;
947 if (buffer->decl_change_count > VB_MAXDECLCHANGES
948 || (buffer->conversion_map && (buffer->resource.usage & WINED3DUSAGE_DYNAMIC)))
950 FIXME("Too many declaration changes or converting dynamic buffer, stopping converting.\n");
951 wined3d_buffer_drop_bo(buffer);
952 return;
955 /* The declaration changed, reload the whole buffer. */
956 WARN("Reloading buffer because of a vertex declaration change.\n");
957 buffer_invalidate_bo_range(buffer, 0, 0);
959 else
961 /* However, it is perfectly fine to change the declaration every now and then. We don't want a game that
962 * changes it every minute drop the VBO after VB_MAX_DECL_CHANGES minutes. So count draws without
963 * decl changes and reset the decl change count after a specific number of them
965 if (buffer->conversion_map && buffer_is_fully_dirty(buffer))
967 ++buffer->full_conversion_count;
968 if (buffer->full_conversion_count > VB_MAXFULLCONVERSIONS)
970 FIXME("Too many full buffer conversions, stopping converting.\n");
971 wined3d_buffer_drop_bo(buffer);
972 return;
975 else
977 ++buffer->draw_count;
978 if (buffer->draw_count > VB_RESETDECLCHANGE)
979 buffer->decl_change_count = 0;
980 if (buffer->draw_count > VB_RESETFULLCONVS)
981 buffer->full_conversion_count = 0;
985 if (!wined3d_buffer_load_location(buffer, context, WINED3D_LOCATION_BUFFER))
986 ERR("Failed to load buffer location.\n");
989 struct wined3d_resource * CDECL wined3d_buffer_get_resource(struct wined3d_buffer *buffer)
991 TRACE("buffer %p.\n", buffer);
993 return &buffer->resource;
996 static HRESULT wined3d_buffer_map(struct wined3d_buffer *buffer, UINT offset, UINT size, BYTE **data, DWORD flags)
998 struct wined3d_device *device = buffer->resource.device;
999 struct wined3d_context *context;
1000 LONG count;
1001 BYTE *base;
1003 TRACE("buffer %p, offset %u, size %u, data %p, flags %#x.\n", buffer, offset, size, data, flags);
1005 /* Filter redundant WINED3D_MAP_DISCARD maps. The 3DMark2001 multitexture
1006 * fill rate test seems to depend on this. When we map a buffer with
1007 * GL_MAP_INVALIDATE_BUFFER_BIT, the driver is free to discard the
1008 * previous contents of the buffer. The r600g driver only does this when
1009 * the buffer is currently in use, while the proprietary NVIDIA driver
1010 * appears to do this unconditionally. */
1011 if (buffer->flags & WINED3D_BUFFER_DISCARD)
1012 flags &= ~WINED3D_MAP_DISCARD;
1013 count = ++buffer->resource.map_count;
1015 if (buffer->buffer_object)
1017 unsigned int dirty_offset = offset, dirty_size = size;
1019 /* DISCARD invalidates the entire buffer, regardless of the specified
1020 * offset and size. Some applications also depend on the entire buffer
1021 * being uploaded in that case. Two such applications are Port Royale
1022 * and Darkstar One. */
1023 if (flags & WINED3D_MAP_DISCARD)
1025 dirty_offset = 0;
1026 dirty_size = 0;
1029 if (!(flags & (WINED3D_MAP_NOOVERWRITE | WINED3D_MAP_DISCARD | WINED3D_MAP_READONLY))
1030 || ((flags & WINED3D_MAP_READONLY) && (buffer->locations & WINED3D_LOCATION_SYSMEM))
1031 || buffer->flags & WINED3D_BUFFER_PIN_SYSMEM)
1033 if (!(buffer->locations & WINED3D_LOCATION_SYSMEM))
1035 context = context_acquire(device, NULL, 0);
1036 wined3d_buffer_load_location(buffer, context, WINED3D_LOCATION_SYSMEM);
1037 context_release(context);
1040 if (!(flags & WINED3D_MAP_READONLY))
1041 wined3d_buffer_invalidate_range(buffer, WINED3D_LOCATION_BUFFER, dirty_offset, dirty_size);
1043 else
1045 const struct wined3d_gl_info *gl_info;
1047 context = context_acquire(device, NULL, 0);
1048 gl_info = context->gl_info;
1050 if (flags & WINED3D_MAP_DISCARD)
1051 wined3d_buffer_validate_location(buffer, WINED3D_LOCATION_BUFFER);
1052 else
1053 wined3d_buffer_load_location(buffer, context, WINED3D_LOCATION_BUFFER);
1055 if (!(flags & WINED3D_MAP_READONLY))
1056 buffer_invalidate_bo_range(buffer, dirty_offset, dirty_size);
1058 if ((flags & WINED3D_MAP_DISCARD) && buffer->resource.heap_memory)
1059 wined3d_buffer_evict_sysmem(buffer);
1061 if (count == 1)
1063 buffer_bind(buffer, context);
1065 if (gl_info->supported[ARB_MAP_BUFFER_RANGE])
1067 GLbitfield mapflags = wined3d_resource_gl_map_flags(flags);
1068 buffer->map_ptr = GL_EXTCALL(glMapBufferRange(buffer->buffer_type_hint,
1069 0, buffer->resource.size, mapflags));
1070 checkGLcall("glMapBufferRange");
1072 else
1074 if (buffer->flags & WINED3D_BUFFER_APPLESYNC)
1075 buffer_sync_apple(buffer, flags, gl_info);
1076 buffer->map_ptr = GL_EXTCALL(glMapBuffer(buffer->buffer_type_hint,
1077 GL_READ_WRITE));
1078 checkGLcall("glMapBuffer");
1081 if (((DWORD_PTR)buffer->map_ptr) & (RESOURCE_ALIGNMENT - 1))
1083 WARN("Pointer %p is not %u byte aligned.\n", buffer->map_ptr, RESOURCE_ALIGNMENT);
1085 GL_EXTCALL(glUnmapBuffer(buffer->buffer_type_hint));
1086 checkGLcall("glUnmapBuffer");
1087 buffer->map_ptr = NULL;
1089 if (buffer->resource.usage & WINED3DUSAGE_DYNAMIC)
1091 /* The extra copy is more expensive than not using VBOs at
1092 * all on the Nvidia Linux driver, which is the only driver
1093 * that returns unaligned pointers.
1095 TRACE("Dynamic buffer, dropping VBO.\n");
1096 wined3d_buffer_drop_bo(buffer);
1098 else
1100 TRACE("Falling back to doublebuffered operation.\n");
1101 wined3d_buffer_load_location(buffer, context, WINED3D_LOCATION_SYSMEM);
1102 buffer->flags |= WINED3D_BUFFER_PIN_SYSMEM;
1104 TRACE("New pointer is %p.\n", buffer->resource.heap_memory);
1108 context_release(context);
1111 if (flags & WINED3D_MAP_DISCARD)
1112 buffer->flags |= WINED3D_BUFFER_DISCARD;
1115 base = buffer->map_ptr ? buffer->map_ptr : buffer->resource.heap_memory;
1116 *data = base + offset;
1118 TRACE("Returning memory at %p (base %p, offset %u).\n", *data, base, offset);
1119 /* TODO: check Flags compatibility with buffer->currentDesc.Usage (see MSDN) */
1121 return WINED3D_OK;
1124 static void wined3d_buffer_unmap(struct wined3d_buffer *buffer)
1126 ULONG i;
1128 TRACE("buffer %p.\n", buffer);
1130 /* In the case that the number of Unmap calls > the
1131 * number of Map calls, d3d returns always D3D_OK.
1132 * This is also needed to prevent Map from returning garbage on
1133 * the next call (this will happen if the lock_count is < 0). */
1134 if (!buffer->resource.map_count)
1136 WARN("Unmap called without a previous map call.\n");
1137 return;
1140 if (--buffer->resource.map_count)
1142 /* Delay loading the buffer until everything is unlocked */
1143 TRACE("Ignoring unmap.\n");
1144 return;
1147 if (buffer->map_ptr)
1149 struct wined3d_device *device = buffer->resource.device;
1150 const struct wined3d_gl_info *gl_info;
1151 struct wined3d_context *context;
1153 context = context_acquire(device, NULL, 0);
1154 gl_info = context->gl_info;
1156 buffer_bind(buffer, context);
1158 if (gl_info->supported[ARB_MAP_BUFFER_RANGE])
1160 for (i = 0; i < buffer->modified_areas; ++i)
1162 GL_EXTCALL(glFlushMappedBufferRange(buffer->buffer_type_hint,
1163 buffer->maps[i].offset, buffer->maps[i].size));
1164 checkGLcall("glFlushMappedBufferRange");
1167 else if (buffer->flags & WINED3D_BUFFER_APPLESYNC)
1169 for (i = 0; i < buffer->modified_areas; ++i)
1171 GL_EXTCALL(glFlushMappedBufferRangeAPPLE(buffer->buffer_type_hint,
1172 buffer->maps[i].offset, buffer->maps[i].size));
1173 checkGLcall("glFlushMappedBufferRangeAPPLE");
1177 GL_EXTCALL(glUnmapBuffer(buffer->buffer_type_hint));
1178 if (wined3d_settings.strict_draw_ordering)
1179 gl_info->gl_ops.gl.p_glFlush(); /* Flush to ensure ordering across contexts. */
1180 context_release(context);
1182 buffer_clear_dirty_areas(buffer);
1183 buffer->map_ptr = NULL;
1187 HRESULT wined3d_buffer_copy(struct wined3d_buffer *dst_buffer, unsigned int dst_offset,
1188 struct wined3d_buffer *src_buffer, unsigned int src_offset, unsigned int size)
1190 const struct wined3d_gl_info *gl_info;
1191 struct wined3d_bo_address dst, src;
1192 struct wined3d_context *context;
1193 struct wined3d_device *device;
1194 BYTE *dst_ptr, *src_ptr;
1195 DWORD dst_location;
1196 HRESULT hr;
1198 buffer_mark_used(dst_buffer);
1199 buffer_mark_used(src_buffer);
1201 device = dst_buffer->resource.device;
1203 context = context_acquire(device, NULL, 0);
1204 gl_info = context->gl_info;
1206 dst_location = wined3d_buffer_get_memory(dst_buffer, &dst, dst_buffer->locations);
1207 wined3d_buffer_get_memory(src_buffer, &src, src_buffer->locations);
1209 if (dst.buffer_object && src.buffer_object)
1211 if (gl_info->supported[ARB_COPY_BUFFER])
1213 GL_EXTCALL(glBindBuffer(GL_COPY_READ_BUFFER, src.buffer_object));
1214 GL_EXTCALL(glBindBuffer(GL_COPY_WRITE_BUFFER, dst.buffer_object));
1215 GL_EXTCALL(glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER,
1216 src_offset, dst_offset, size));
1217 checkGLcall("direct buffer copy");
1219 else
1221 if (FAILED(hr = wined3d_buffer_map(dst_buffer, dst_offset, size, &dst_ptr, 0)))
1223 WARN("Failed to map dst_buffer, hr %#x.\n", hr);
1224 context_release(context);
1225 return WINED3DERR_INVALIDCALL;
1227 if (FAILED(hr = wined3d_buffer_map(src_buffer, src_offset, size, &src_ptr, WINED3D_MAP_READONLY)))
1229 WARN("Failed to map src_buffer, hr %#x.\n", hr);
1230 wined3d_buffer_unmap(dst_buffer);
1231 context_release(context);
1232 return WINED3DERR_INVALIDCALL;
1235 memcpy(dst_ptr, src_ptr, size);
1237 wined3d_buffer_unmap(src_buffer);
1238 wined3d_buffer_unmap(dst_buffer);
1241 else if (!dst.buffer_object && src.buffer_object)
1243 buffer_bind(src_buffer, context);
1244 GL_EXTCALL(glGetBufferSubData(src_buffer->buffer_type_hint, src_offset, size, dst.addr + dst_offset));
1245 checkGLcall("buffer download");
1247 else if (dst.buffer_object && !src.buffer_object)
1249 buffer_bind(dst_buffer, context);
1250 GL_EXTCALL(glBufferSubData(dst_buffer->buffer_type_hint, dst_offset, size, src.addr + src_offset));
1251 checkGLcall("buffer upload");
1253 else
1255 memcpy(dst.addr + dst_offset, src.addr + src_offset, size);
1258 wined3d_buffer_invalidate_range(dst_buffer, ~dst_location, dst_offset, size);
1260 context_release(context);
1261 return WINED3D_OK;
1264 void wined3d_buffer_upload_data(struct wined3d_buffer *buffer, struct wined3d_context *context,
1265 const struct wined3d_box *box, const void *data)
1267 struct wined3d_map_range range;
1269 if (box)
1271 range.offset = box->left;
1272 range.size = box->right - box->left;
1274 else
1276 range.offset = 0;
1277 range.size = buffer->resource.size;
1280 wined3d_buffer_upload_ranges(buffer, context, data, range.offset, 1, &range);
1283 static ULONG buffer_resource_incref(struct wined3d_resource *resource)
1285 return wined3d_buffer_incref(buffer_from_resource(resource));
1288 static ULONG buffer_resource_decref(struct wined3d_resource *resource)
1290 return wined3d_buffer_decref(buffer_from_resource(resource));
1293 static void buffer_resource_preload(struct wined3d_resource *resource)
1295 struct wined3d_context *context;
1297 context = context_acquire(resource->device, NULL, 0);
1298 wined3d_buffer_load(buffer_from_resource(resource), context, NULL);
1299 context_release(context);
1302 static HRESULT buffer_resource_sub_resource_map(struct wined3d_resource *resource, unsigned int sub_resource_idx,
1303 struct wined3d_map_desc *map_desc, const struct wined3d_box *box, DWORD flags)
1305 struct wined3d_buffer *buffer = buffer_from_resource(resource);
1306 UINT offset, size;
1308 if (sub_resource_idx)
1310 WARN("Invalid sub_resource_idx %u.\n", sub_resource_idx);
1311 return E_INVALIDARG;
1314 if (box)
1316 offset = box->left;
1317 size = box->right - box->left;
1319 else
1321 offset = size = 0;
1324 map_desc->row_pitch = map_desc->slice_pitch = buffer->desc.byte_width;
1325 return wined3d_buffer_map(buffer, offset, size, (BYTE **)&map_desc->data, flags);
1328 static HRESULT buffer_resource_sub_resource_unmap(struct wined3d_resource *resource, unsigned int sub_resource_idx)
1330 if (sub_resource_idx)
1332 WARN("Invalid sub_resource_idx %u.\n", sub_resource_idx);
1333 return E_INVALIDARG;
1336 wined3d_buffer_unmap(buffer_from_resource(resource));
1337 return WINED3D_OK;
1340 static const struct wined3d_resource_ops buffer_resource_ops =
1342 buffer_resource_incref,
1343 buffer_resource_decref,
1344 buffer_resource_preload,
1345 buffer_unload,
1346 buffer_resource_sub_resource_map,
1347 buffer_resource_sub_resource_unmap,
1350 static GLenum buffer_type_hint_from_bind_flags(const struct wined3d_gl_info *gl_info,
1351 unsigned int bind_flags)
1353 if (bind_flags == WINED3D_BIND_INDEX_BUFFER)
1354 return GL_ELEMENT_ARRAY_BUFFER;
1356 if (bind_flags & (WINED3D_BIND_SHADER_RESOURCE | WINED3D_BIND_UNORDERED_ACCESS)
1357 && gl_info->supported[ARB_TEXTURE_BUFFER_OBJECT])
1358 return GL_TEXTURE_BUFFER;
1360 if (bind_flags & WINED3D_BIND_CONSTANT_BUFFER)
1361 return GL_UNIFORM_BUFFER;
1363 if (bind_flags & WINED3D_BIND_STREAM_OUTPUT)
1364 return GL_TRANSFORM_FEEDBACK_BUFFER;
1366 if (bind_flags & ~(WINED3D_BIND_VERTEX_BUFFER | WINED3D_BIND_INDEX_BUFFER))
1367 FIXME("Unhandled bind flags %#x.\n", bind_flags);
1369 return GL_ARRAY_BUFFER;
1372 static HRESULT buffer_init(struct wined3d_buffer *buffer, struct wined3d_device *device,
1373 UINT size, DWORD usage, enum wined3d_format_id format_id, enum wined3d_pool pool, unsigned int bind_flags,
1374 const struct wined3d_sub_resource_data *data, void *parent, const struct wined3d_parent_ops *parent_ops)
1376 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1377 const struct wined3d_format *format = wined3d_get_format(gl_info, format_id, usage);
1378 BOOL dynamic_buffer_ok;
1379 HRESULT hr;
1381 if (!size)
1383 WARN("Size 0 requested, returning WINED3DERR_INVALIDCALL.\n");
1384 return WINED3DERR_INVALIDCALL;
1387 if (data && !data->data)
1389 WARN("Invalid sub-resource data specified.\n");
1390 return E_INVALIDARG;
1393 hr = resource_init(&buffer->resource, device, WINED3D_RTYPE_BUFFER, format,
1394 WINED3D_MULTISAMPLE_NONE, 0, usage, pool, size, 1, 1, size, parent, parent_ops, &buffer_resource_ops);
1395 if (FAILED(hr))
1397 WARN("Failed to initialize resource, hr %#x.\n", hr);
1398 return hr;
1400 buffer->buffer_type_hint = buffer_type_hint_from_bind_flags(gl_info, bind_flags);
1401 buffer->bind_flags = bind_flags;
1402 buffer->locations = WINED3D_LOCATION_SYSMEM;
1404 TRACE("buffer %p, size %#x, usage %#x, format %s, memory @ %p.\n",
1405 buffer, buffer->resource.size, buffer->resource.usage,
1406 debug_d3dformat(buffer->resource.format->id), buffer->resource.heap_memory);
1408 if (device->create_parms.flags & WINED3DCREATE_SOFTWARE_VERTEXPROCESSING || pool == WINED3D_POOL_MANAGED)
1410 /* SWvp and managed buffers always return the same pointer in buffer
1411 * maps and retain data in DISCARD maps. Keep a system memory copy of
1412 * the buffer to provide the same behavior to the application. */
1413 TRACE("Using doublebuffer mode.\n");
1414 buffer->flags |= WINED3D_BUFFER_PIN_SYSMEM;
1417 /* Observations show that draw_primitive_immediate_mode() is faster on
1418 * dynamic vertex buffers than converting + draw_primitive_arrays().
1419 * (Half-Life 2 and others.) */
1420 dynamic_buffer_ok = gl_info->supported[APPLE_FLUSH_BUFFER_RANGE] || gl_info->supported[ARB_MAP_BUFFER_RANGE];
1422 if (!gl_info->supported[ARB_VERTEX_BUFFER_OBJECT])
1424 TRACE("Not creating a BO because GL_ARB_vertex_buffer is not supported.\n");
1426 else if (buffer->resource.pool == WINED3D_POOL_SYSTEM_MEM)
1428 TRACE("Not creating a BO because the buffer is in system memory.\n");
1430 else if (!dynamic_buffer_ok && (buffer->resource.usage & WINED3DUSAGE_DYNAMIC))
1432 TRACE("Not creating a BO because the buffer has dynamic usage and no GL support.\n");
1434 else
1436 buffer->flags |= WINED3D_BUFFER_USE_BO;
1439 if (!(buffer->maps = HeapAlloc(GetProcessHeap(), 0, sizeof(*buffer->maps))))
1441 ERR("Out of memory.\n");
1442 buffer_unload(&buffer->resource);
1443 resource_cleanup(&buffer->resource);
1444 wined3d_resource_wait_idle(&buffer->resource);
1445 return E_OUTOFMEMORY;
1447 buffer->maps_size = 1;
1449 if (data)
1450 wined3d_device_update_sub_resource(device, &buffer->resource,
1451 0, NULL, data->data, data->row_pitch, data->slice_pitch);
1453 return WINED3D_OK;
1456 HRESULT CDECL wined3d_buffer_create(struct wined3d_device *device, const struct wined3d_buffer_desc *desc,
1457 const struct wined3d_sub_resource_data *data, void *parent, const struct wined3d_parent_ops *parent_ops,
1458 struct wined3d_buffer **buffer)
1460 struct wined3d_buffer *object;
1461 HRESULT hr;
1463 TRACE("device %p, desc %p, data %p, parent %p, parent_ops %p, buffer %p.\n",
1464 device, desc, data, parent, parent_ops, buffer);
1466 if (!(object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object))))
1467 return E_OUTOFMEMORY;
1469 FIXME("Ignoring access flags (pool).\n");
1471 if (FAILED(hr = buffer_init(object, device, desc->byte_width, desc->usage, WINED3DFMT_UNKNOWN,
1472 WINED3D_POOL_MANAGED, desc->bind_flags, data, parent, parent_ops)))
1474 WARN("Failed to initialize buffer, hr %#x.\n", hr);
1475 HeapFree(GetProcessHeap(), 0, object);
1476 return hr;
1478 object->desc = *desc;
1480 TRACE("Created buffer %p.\n", object);
1482 *buffer = object;
1484 return WINED3D_OK;
1487 HRESULT CDECL wined3d_buffer_create_vb(struct wined3d_device *device, UINT size, DWORD usage, enum wined3d_pool pool,
1488 void *parent, const struct wined3d_parent_ops *parent_ops, struct wined3d_buffer **buffer)
1490 struct wined3d_buffer *object;
1491 HRESULT hr;
1493 TRACE("device %p, size %u, usage %#x, pool %#x, parent %p, parent_ops %p, buffer %p.\n",
1494 device, size, usage, pool, parent, parent_ops, buffer);
1496 if (pool == WINED3D_POOL_SCRATCH)
1498 /* The d3d9 tests shows that this is not allowed. It doesn't make much
1499 * sense anyway, SCRATCH buffers wouldn't be usable anywhere. */
1500 WARN("Vertex buffer in WINED3D_POOL_SCRATCH requested, returning WINED3DERR_INVALIDCALL.\n");
1501 *buffer = NULL;
1502 return WINED3DERR_INVALIDCALL;
1505 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1506 if (!object)
1508 *buffer = NULL;
1509 return WINED3DERR_OUTOFVIDEOMEMORY;
1512 hr = buffer_init(object, device, size, usage, WINED3DFMT_UNKNOWN,
1513 pool, WINED3D_BIND_VERTEX_BUFFER, NULL, parent, parent_ops);
1514 if (FAILED(hr))
1516 WARN("Failed to initialize buffer, hr %#x.\n", hr);
1517 HeapFree(GetProcessHeap(), 0, object);
1518 return hr;
1521 TRACE("Created buffer %p.\n", object);
1522 *buffer = object;
1524 return WINED3D_OK;
1527 HRESULT CDECL wined3d_buffer_create_ib(struct wined3d_device *device, UINT size, DWORD usage, enum wined3d_pool pool,
1528 void *parent, const struct wined3d_parent_ops *parent_ops, struct wined3d_buffer **buffer)
1530 struct wined3d_buffer *object;
1531 HRESULT hr;
1533 TRACE("device %p, size %u, usage %#x, pool %#x, parent %p, parent_ops %p, buffer %p.\n",
1534 device, size, usage, pool, parent, parent_ops, buffer);
1536 object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1537 if (!object)
1539 *buffer = NULL;
1540 return WINED3DERR_OUTOFVIDEOMEMORY;
1543 hr = buffer_init(object, device, size, usage | WINED3DUSAGE_STATICDECL,
1544 WINED3DFMT_UNKNOWN, pool, WINED3D_BIND_INDEX_BUFFER, NULL,
1545 parent, parent_ops);
1546 if (FAILED(hr))
1548 WARN("Failed to initialize buffer, hr %#x\n", hr);
1549 HeapFree(GetProcessHeap(), 0, object);
1550 return hr;
1553 TRACE("Created buffer %p.\n", object);
1554 *buffer = object;
1556 return WINED3D_OK;