Search code examples
javaopengllwjgl

Modifying pixel RGBA values of texture using glTexSubImage2D does not update the texture


I have a OpenGL Texture, and I would like to change RGBA values of pixels in the Texture on the run. I want to do the modification on the CPU side. I would like to create a function to change a pixel in a texture in selected coordinates to a selected RGBA value.

I have tried the following:

glTexSubImage2D(GL_TEXTURE_2D,0,x,y,1,1,GL_RGBA,GL_UNSIGNED_BYTE,data);

where x and y are the coordinates of the modified pixel and data is an int array of red, green, blue and alpha. I however am not sure, if I have used the correct parameters, because the texture is not changing when i use this. I want to create a function, that changes a pixels color in a texture in specified coordinates to a specified color using glTexSubImage2D.


Solution

  • You have to create a Direct buffer, to commit the data by glTexSubImage2D

    I recommend to create a ByteBuffer, somehow like this:

    ByteBuffer buffer = ByteBuffer.allocateDirect(data.length);
    buffer.put(data);
    buffer.flip();
    glTexSubImage2D(GL_TEXTURE_2D,0,x,y,1,1,GL_RGBA,GL_UNSIGNED_BYTE,buffer);
    

    If data already is a direct buffer, but it is a IntBuffer, then the 8th parameter of glTexSubImage2D, which specifies the data type of a single color channel, has to be GL_UNSIGNED_INT or GL_INT:

    glTexSubImage2D(GL_TEXTURE_2D,0,x,y,1,1,GL_RGBA,GL_UNSIGNED_INT,data);