TexturesGL 1.1

glTexSubImage2D

Overwrites a rectangle of an existing texture's pixels, without reallocating it.

Part of the family glTexSubImage*

Signature

void glTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
                     GLsizei width, GLsizei height,
                     GLenum format, GLenum type, const void *pixels);

How it works

glTexImage2D allocates storage (and can fill it); glTexSubImage2D only writes into storage that already exists. Use it to update textures that change: a video frame, a font atlas growing glyph by glyph, a paint canvas. It is also the way to fill textures made with glTexStorage2D, whose storage cannot be reallocated.

The texture bound to target on the active unit is the one written.

Parameters

targetGLenum

GL_TEXTURE_2D, or a cubemap face (GL_TEXTURE_CUBE_MAP_POSITIVE_X + i).

levelGLint

Mip level to write.

xoffset, yoffsetGLint

Bottom-left corner of the region inside the texture.

width, heightGLsizei

Size of the region; it must fit inside the level.

formatGLenum

Channels of your data: GL_RGBA, GL_RGB, GL_RED…

typeGLenum

Type of each channel: GL_UNSIGNED_BYTE, GL_FLOAT…

pixelsconst void *

Source data (or an offset into a bound GL_PIXEL_UNPACK_BUFFER).

Tips & pitfalls

  • After changing level 0, regenerate the mipmaps (glGenerateMipmap) or the far-away look keeps the old image.

  • With a texture ID in hand, the DSA form glTextureSubImage2D avoids the bind.

Errors

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

GL_INVALID_VALUE
The region goes outside the texture level.
GL_INVALID_OPERATION
The level has no storage yet, or format/type do not suit its internal format.

Example

example.cpp
1glBindTexture(GL_TEXTURE_2D, videoTex);
2glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, frameW, frameH, GL_RGBA, GL_UNSIGNED_BYTE, frame);
Official Khronos documentation