Clamp

116 阅读1分钟

Task

Write a GLSL program that draws a diagonal line from the bottom left corner of the texture to the top right corner. The line should have a width of 0.2 in normalized coordinates and be colored in (1.0, 0.3, 0.3). Additionally, ensure that the line is limited to values between 0.25 and 0.75 in Y coordinate.

编写一个GLSL程序,该程序绘制一条从纹理左下角到右上角的对角线。要求如下:

  • 线条在归一化坐标系中的宽度为 0.2
  • 线条颜色为 (1.0, 0.3, 0.3)
  • 此外,请确保该线条只在Y坐标

Theory

函数介绍

float clamp(float value, float minVal, float maxVal)

clamp 将一个值限制在一个闭区间 [min, max] 内,如果小于minVal则返回minVal,如果大于maxVal则返回maxVal,否则返回value

  • value: 你想要限制的原始值。
  • minVal: 区间的下限(最小值)。
  • maxVal: 区间的上限(最大值)。

Answer

uniform vec2 iResolution;

void main() {
  vec2 uv = gl_FragCoord.xy / iResolution.xy;

  float lineWidth = 0.2;
  vec3  lineColor = vec3(1.0, 0.3, 0.3);
  float value = clamp(uv.x, 0.25, 0.75);
  // 获得当前点的y坐标,用来下面进行判断颜色用,如果当前点的y坐标大于线条宽度的一半则舍弃这个点
  float dist  = abs(uv.y - value); 
  float line  = 1.0 - step(lineWidth * 0.5, dist);
  
  gl_FragColor = vec4(lineColor * line, 1.0);
}


效果

image.png

练习

Clamp

最后

如果你觉得这篇文章有用,记得点赞、关注、收藏,学Shader更轻松!!