manatttta
manatttta

Reputation: 3124

OpenGL fragment shader in a texture

I have a simple RGBA texture that I will project on a rectangle/quad in OpenGL.

However, I want to do some operations in the rgb pixels of that texture, e.g., I want the displayed color to be some function of the RGB pixels of the original image.

My questions are: can I apply a fragment shader to a 2D texture? And if I can, How do I access the rgb value of the original texture image?

Any help would be appreciated.

Upvotes: 0

Views: 1081

Answers (1)

Open Kastle
Open Kastle

Reputation: 427

You can certainly do this. Render the quad as usual and send the texture to the fragment shader as a sampler2D uniform.

Inside the fragment shader, you can then make calls to either texture or texelFetch. texture samples your texture, and texelFetch looks up an RGB texel from the texture without performing interpolation, etc.

Here is an example of what your fragment shader might look like:

Fragment shader

#version 330 core

uniform vec2 resolution;
uniform sampler2D myTexture;

out vec3 color;

void main()
{
    vec2 pos = gl_FragCoord.xy / resolution.xy;
    pos.y = resolution.y - pos.y;

    color = texture(myTexture, pos).xyz;
}

And then on the application side:

Initialization

glGenTextures(1, &m_textureID);
glBindTexture(GL_TEXTURE_2D, m_textureID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, m_imageWidth, m_imageHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, pImage);

m_textureUniformID = glGetUniformLocation(m_programID, "myTexture");

Render loop

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_textureID);
glUniform1i(m_textureUniformID, 0);

Upvotes: 1

Related Questions