![](/img/trans.png)
[英]In a GLSL fragment shader, how to access to texel at a specific mipmap level?
[英]How to access automatic mipmap level in GLSL fragment shader texture?
在GLSL片段着色器中對紋理進行采樣時,如何確定使用的mipmap級別?
我知道我可以使用textureLod(...)
方法手動采樣紋理的特定mipmap級別:
uniform sampler2D myTexture;
void main()
{
float mipmapLevel = 1;
vec2 textureCoord = vec2(0.5, 0.5);
gl_FragColor = textureLod(myTexture, textureCoord, mipmapLevel);
}
或者我可以允許使用texture(...)
自動選擇mipmap級別
uniform sampler2D myTexture;
void main()
{
vec2 textureCoord = vec2(0.5, 0.5);
gl_FragColor = texture(myTexture, textureCoord);
}
我更喜歡后者,因為我相信司機對合適的mipmap級別的判斷比我自己的更多。
但我想知道在自動采樣過程中使用了什么mipmap級別,以幫助我合理地對附近的像素進行采樣。 GLSL中是否有一種方法可以訪問有關自動紋理樣本使用的mipmap級別的信息?
以下是此問題的三種不同方法,具體取決於您可以使用的OpenGL功能:
正如Andon M. Coleman在評論中指出的那樣,OpenGL 4.00及以上版本的解決方案很簡單; 只需使用textureQueryLod
函數:
#version 400 uniform sampler2D myTexture; in vec2 textureCoord; // in normalized units out vec4 fragColor; void main() { float mipmapLevel = textureQueryLod(myTexture, textureCoord).x; fragColor = textureLod(myTexture, textureCoord, mipmapLevel); }
在早期版本的OpenGL(2.0+?)中,您可能能夠加載擴展,以達到類似的效果。 這種方法適用於我的情況。 注意 :方法調用在擴展中與內置( queryTextureLod
vs queryTextureLOD
)不同地大寫。
#version 330 #extension GL_ARB_texture_query_lod : enable uniform sampler2D myTexture; in vec2 textureCoord; // in normalized units out vec4 fragColor; void main() { float mipmapLevel = 3; // default in case extension is unavailable... #ifdef GL_ARB_texture_query_lod mipmapLevel = textureQueryLOD(myTexture, textureCoord).x; // NOTE CAPITALIZATION #endif fragColor = textureLod(myTexture, textureCoord, mipmapLevel); }
如果加載擴展程序不起作用,您可以使用genpfault提供的方法估計自動詳細程度 :
#version 330 uniform sampler2D myTexture; in vec2 textureCoord; // in normalized units out vec4 fragColor; // Does not take into account GL_TEXTURE_MIN_LOD/GL_TEXTURE_MAX_LOD/GL_TEXTURE_LOD_BIAS, // nor implementation-specific flexibility allowed by OpenGL spec float mip_map_level(in vec2 texture_coordinate) // in texel units { vec2 dx_vtc = dFdx(texture_coordinate); vec2 dy_vtc = dFdy(texture_coordinate); float delta_max_sqr = max(dot(dx_vtc, dx_vtc), dot(dy_vtc, dy_vtc)); float mml = 0.5 * log2(delta_max_sqr); return max( 0, mml ); // Thanks @Nims } void main() { // convert normalized texture coordinates to texel units before calling mip_map_level float mipmapLevel = mip_map_level(textureCoord * textureSize(myTexture, 0)); fragColor = textureLod(myTexture, textureCoord, mipmapLevel); }
在任何情況下,對於我的特定應用程序,我最終只是計算主機端的mipmap級別,並將其傳遞給着色器,因為自動細節級別並不是我所需要的。
從這里 :
看一下OpenGL 4.2規范章節3.9.11公式3.21。 基於導數向量的長度計算mip貼圖級別:
float mip_map_level(in vec2 texture_coordinate) { vec2 dx_vtc = dFdx(texture_coordinate); vec2 dy_vtc = dFdy(texture_coordinate); float delta_max_sqr = max(dot(dx_vtc, dx_vtc), dot(dy_vtc, dy_vtc)); return 0.5 * log2(delta_max_sqr); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.