Int / Floor

Task

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

scss 复制代码
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.

根据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():

glsl 复制代码
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

glsl 复制代码
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);
}

效果

练习

Int / Floor

最后

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

相关推荐
IT_陈寒1 小时前
Redis缓存击穿把我整不会了,原来还有这手操作
前端·人工智能·后端
idcu2 小时前
深入 Lyt.js 组件系统:L2 渲染引擎层的核心
前端·typescript
这是程序猿2 小时前
Spring Boot自动配置详解
java·大数据·前端
文心快码BaiduComate2 小时前
干货|Comate Harness Engineering工程实践指南
前端·后端·程序员
还有多久拿退休金2 小时前
一张栈的图,治好你面试答不出 script 阻塞的病
前端·javascript
光辉GuangHui2 小时前
Agent Skill 也需要测试:如何搭建 Skill 评估框架
前端·后端·llm
To_OC2 小时前
我终于搞懂 Claude Code 核心逻辑!90%的人都用错了模式
前端·ai编程
蓝宝石的傻话2 小时前
Headless浏览器的隐形陷阱:为什么你的AI自动化工具抓不到页面早期错误?
前端
irving同学462382 小时前
Node 后端实战:JWT 认证与生产级错误处理
前端·后端
莽夫搞战术3 小时前
【Google Stitch】AI原生画布重新定义设计,让想法变成可交互界面
前端·人工智能·ui