BuffersGL 3.0

glMapBufferRange

Maps part of a buffer, with flags that say exactly what may happen to its old contents.

Signature

void *glMapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access);

How it works

Like glMapBuffer, but for a byte range, and with access bits instead of a single enum. The extra bits let you promise things the driver cannot know: that the old data in the range can be thrown away, or that you will not touch memory the GPU is still reading.

It is the building block of every efficient streaming scheme; the Buffer Streaming & Sync chapter shows how to combine it with fences.

Parameters

targetGLenum

Slot whose bound buffer is mapped.

offsetGLintptr

First byte of the range.

lengthGLsizeiptr

Number of bytes to map.

accessGLbitfield

Bitwise OR of access flags.

Common values

GL_MAP_WRITE_BIT / GL_MAP_READ_BIT
What you will do through the pointer (at least one is required).
GL_MAP_INVALIDATE_RANGE_BIT
The old contents of the range may be discarded.
GL_MAP_INVALIDATE_BUFFER_BIT
The old contents of the whole buffer may be discarded.
GL_MAP_UNSYNCHRONIZED_BIT
Do not wait for the GPU — you guarantee it is not using this range.
GL_MAP_FLUSH_EXPLICIT_BIT
You will report the written sub-ranges yourself with glFlushMappedBufferRange.

Return value

A pointer to the start of the range, or NULL on failure.

Tips & pitfalls

  • The invalidate bits cannot be combined with GL_MAP_READ_BIT.

Errors

When the call is invalid it does nothing and sets an error, which glGetError returns:

GL_INVALID_VALUE
offset or length is negative, or the range goes past the end of the buffer.
GL_INVALID_OPERATION
The buffer is already mapped, neither read nor write was requested, or the flags contradict each other.

Example

example.cpp
1glBindBuffer(GL_ARRAY_BUFFER, vbo);
2void* p = glMapBufferRange(GL_ARRAY_BUFFER, 0, bytes,
3                           GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);
4std::memcpy(p, vertices.data(), bytes);
5glUnmapBuffer(GL_ARRAY_BUFFER);
Official Khronos documentation