GLSL:gl_FragCoord问题 [英] GLSL: gl_FragCoord issues
问题描述
我正在针对OpenGL ES 2.0使用GLSL进行实验.我有一个四边形和正在渲染的纹理.我可以这样成功完成:
I am experimenting with GLSL for OpenGL ES 2.0. I have a quad and a texture I am rendering. I can successfully do it this way:
//VERTEX SHADER
attribute highp vec4 vertex;
attribute mediump vec2 coord0;
uniform mediump mat4 worldViewProjection;
varying mediump vec2 tc0;
void main()
{
// Transforming The Vertex
gl_Position = worldViewProjection * vertex;
// Passing The Texture Coordinate Of Texture Unit 0 To The Fragment Shader
tc0 = vec2(coord0);
}
//FRAGMENT SHADER
varying mediump vec2 tc0;
uniform sampler2D my_color_texture;
void main()
{
gl_FragColor = texture2D(my_color_texture, tc0);
}
到目前为止,一切都很好.但是,我想做一些基于像素的过滤,例如中位数.因此,我想使用像素坐标而不是规范化的(tc0
),然后将结果转换回规范化的坐标.因此,我想使用gl_FragCoord
而不是uv属性(tc0
).但是我不知道如何返回归一化的坐标,因为我不知道gl_FragCoords的范围.知道我怎么能得到吗?我已经做到了这一点,使用固定值进行规范化",尽管它不能完美工作,因为它会导致拉伸和平铺(但至少会显示出一些东西):
So far so good. However, I'd like to do some pixel-based filtering, e.g. Median. So, I'd like to work in pixel coordinates rather than in normalized (tc0
) and then convert the result back to normalized coords. Therefore, I'd like to use gl_FragCoord
instead of a uv attribute (tc0
). But I don't know how to go back to normalized coords because I don't know the range of gl_FragCoords. Any idea how I could get it? I have got that far, using a fixed value for 'normalization', though it's not working perfectly as it is causing stretching and tiling (but at least is showing something):
//FRAGMENT SHADER
varying mediump vec2 tc0;
uniform sampler2D my_color_texture;
void main()
{
gl_FragColor = texture2D(my_color_texture, vec2(gl_FragCoord) / vec2(256, 256));
}
因此,一个简单的问题是,应该使用什么代替vec2(256, 256)
,以便获得与使用uv坐标相同的结果.
So, the simple question is, what should I use in the place of vec2(256, 256)
so that I could get the same result as if I were using the uv coords.
谢谢!
推荐答案
gl_FragCoord在屏幕坐标中,因此要获得规范化的坐标,需要除以视口的宽度和高度.您可以使用统一变量将信息传递给着色器,因为没有内置变量.
gl_FragCoord is in screen coordinates, so to get normalized coords you need to divide by the viewport width and height. You can use a uniform variable to pass that information to the shader, since there is no built in variable for it.
这篇关于GLSL:gl_FragCoord问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!