简体   繁体   English

纹理中的OpenGL片段着色器

[英]OpenGL fragment shader in a texture

I have a simple RGBA texture that I will project on a rectangle/quad in OpenGL. 我有一个简单的RGBA纹理,将在OpenGL中投影在一个矩形/四边形上。

However, I want to do some operations in the rgb pixels of that texture, eg, I want the displayed color to be some function of the RGB pixels of the original image. 但是,我想在该纹理的rgb像素中执行一些操作,例如,我希望显示的颜色是原始图像的RGB像素的某个函数。

My questions are: can I apply a fragment shader to a 2D texture? 我的问题是:我可以将片段着色器应用于2D纹理吗? And if I can, How do I access the rgb value of the original texture image? 如果可以,如何访问原始纹理图像的rgb值?

Any help would be appreciated. 任何帮助,将不胜感激。

You can certainly do this. 您当然可以做到。 Render the quad as usual and send the texture to the fragment shader as a sampler2D uniform. 照常渲染四边形,然后将纹理作为sampler2D制服发送到片段着色器。

Inside the fragment shader, you can then make calls to either texture or texelFetch . 在片段着色器内部,然后可以调用texturetexelFetch texture samples your texture, and texelFetch looks up an RGB texel from the texture without performing interpolation, etc. texture对您的texture采样,并且texelFetch从纹理中查找RGB texel,而无需执行插值等操作。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM