在片段着色器中丢失纹理定义

Losing texture definition in fragment shader

我正在尝试使用片段着色器绘制参考网格,我发现在缩小时纹理失去了清晰度,正如您在此处看到的那样。有人知道为什么吗?放大看还不错

外出时四边形上的网格纹理

没有缩放的网格纹理

这是代码:

#version 330 core
uniform int multiplicationFactor;
uniform lowp float threshold;
uniform vec4 gridColor;

in vec2 vUV;

void main() {
    // multiplicationFactor scales the number of stripes
    vec2 t = vUV * multiplicationFactor;

    // the threshold constant defines the with of the lines
    if (abs(t.x - round(t.x)) <= threshold  || abs(t.y - round(t.y)) < threshold )
        gl_FragColor = gridColor;    
    else
        discard;
}

您必须计算与视口大小相关的线的距离。

添加类型为 vec2 resolution 的统一变量,其中包含视口的宽度和高度,变量 threshold 必须包含以像素为单位的线条粗细(例如 1.0):

#version 330 core

uniform int        multiplicationFactor;
uniform lowp float threshold;   // line width in pixel
uniform vec4       gridColor;
uniform vec2       resolution;  // width and height of the viewport

in vec2 vUV;

void main()
{
    float m   = float(multiplicationFactor);
    vec2 t    = vUV * m;
    vec2 dist = abs(t - round(t)) / m; 
    vec2 th   = threshold / resolution;

    if (dist.x > th.x  && dist.y > th.y)
        discard;

    gl_FragColor = gridColor;    
}