Int / Floor

118 阅读1分钟

Task

Create a shader program that generates a gradient image using an array of 5 colors. The colors are defined in the following array:

vec3 palette[5] = vec3[5]
(
    vec3(1.0, 0.0, 0.0),
    vec3(0.0, 1.0, 0.0),
    vec3(0.0, 0.0, 1.0),
    vec3(1.0, 1.0, 0.0),
    vec3(0.0, 0.0, 0.0)
);

The program should determine which color range the current pixel falls within and interpolate its color accordingly. This will result in a smooth gradient transition between the colors in the array.

image.png

根据palette提供的数组创建一个阶梯状的渐变颜色。每两个颜色之间使用线性插值的方式。

Theory

函数介绍

1. floor(x) - 数学函数

  • 定义:它返回不大于x的最大整数。
  • 举例
    • floor(3.9) -> 3.0
    • floor(3.1) -> 3.0
    • floor(-3.9) -> -4.0 (因为-4是小于-3.9的最大整数)
  • 返回类型float

2. int(x) - 类型转换函数

  • 定义:将一个浮点数转换为一个整数,丢掉小数部分。
  • 举例
    • int(3.9) -> 3
    • int(3.1) -> 3
    • int(-3.9) -> -3 (直接砍掉.9)
  • 返回类型int

任务解析

创建5级阶梯:

使用 floor():

float steps = 5.0;
float value = floor(uv.x * steps) / steps; // 结果是 {0.0, 0.2, 0.4, 0.6, 0.8}
// float value = float(int(uv.x * steps)) / steps; 或者使用int
gl_FragColor = vec4(vec3(value), 1.0); 

这样就会产生从黑到灰的5级阶梯。

Answer

uniform vec2 iResolution;

vec3 palette[5] = vec3[5] (
  vec3(1.0, 0.0, 0.0),
  vec3(0.0, 1.0, 0.0),
  vec3(0.0, 0.0, 1.0),
  vec3(1.0, 1.0, 0.0),
  vec3(0.0, 0.0, 0.0)
);

void main() {
  vec2 uv = gl_FragCoord.xy / iResolution.xy;
  float steps = 5.0;
  int index = int(uv.x * (steps - 1.0)); // 数组序号最大为4.0
  //float value = floor(uv.x * steps) / steps; // 结果是 {0.0, 0.2, 0.4, 0.6, 0.8}
  vec3 color = mix(palette[index], palette[index + 1], fract(uv.x * (steps - 1.0)));
  gl_FragColor = vec4(color, 1.0);
}

效果

image.png

练习

Int / Floor

最后

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