Mod

Task

Create a pattern of alternating black and red columns, with 9 columns of each color. Then, hide every third column that is colored red.
创建一个黑色和红色交替出现的图案,红黑两种颜色各有9列。并且,每隔3列隐藏一列。

Requirements

The shader should avoid using branching or conditional statements in its code, and instead rely on the mod and step functions to determine the color of each pixel.
着色器应避免在其代码中使用分支或条件语句,而是依靠mod和step函数来确定每个像素的颜色。

Theory

mod函数用于计算两个数字除法运算的余数。

函数

float mod(float x, float y);

该mod函数有两个参数:

  • •被除数:被除数
  • •除数:被除数除以的数。

该函数返回除法运算的余数。

与模运算符的比较

该mod函数的工作原理与许多编程语言中的模运算符 ( %) 类似。但是,在处理负数的方式上存在一些差异。在 GLSL 中,该mod函数始终返回非负结果。

示例

正数的基本用法:

scss 复制代码
float result = mod(10.0, 3.0); // Result will be 1.0 (10 / 3 has a remainder of 1)

处理负数:

scss 复制代码
float result = mod(-10.0, 3.0); // Result will be 2.0 (-10 / 3 has a remainder of 2)

实际应用

  • 创建重复图案: 通过使用 mod 功能,您可以创建无缝、重复的纹理或图案。

  • 动画: 可以通过将值包装在一定范围内来实现循环动画。

  • 网格系统: 用于创建基于网格的效果或将屏幕划分为多个部分。

Answer

glsl 复制代码
uniform vec2 iResolution;

void main() {
  // Normalized pixel coordinates (from 0 to 1)
  vec2 uv = gl_FragCoord.xy / iResolution.xy;
  
  uv *= 9.0;
  float x = fract(uv.x);
  float hide = 1.0;
  hide = step(1.0, mod(uv.x + 1.0, 3.0)) ;
  x = step(0.5, x * hide);

  gl_FragColor = vec4(x, 0.0, 0.0, 1.0);
}

效果

练习

Mod

最后

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

相关推荐
卸任7 小时前
Vibe coding工具使用心得
前端·ai编程
brien98 小时前
为什么模型标称 1M,Google Antigravity 聊到 256K 却突然失忆?我们给它做了个原生行内监控圆环
前端
修炼的dance8 小时前
录屏关键帧间隔多少合适?六档实测,2秒到10秒小了75.6%
前端
Lank_M8 小时前
关键帧从1秒拉到10秒,录屏小87.3%,摄像头小10.8%
前端
补码缩写8 小时前
用 ffprobe 拆录屏,八成字节在 29 个关键帧上
前端
百思不得小李8 小时前
一个复杂的动态表单是如何实现的
前端·设计模式
陈随易9 小时前
Cmder 停更 17 个月,2.0 支持 Windows Terminal
前端·后端·程序员
风骏时光牛马9 小时前
前沿视界
前端
kyriewen9 小时前
我扫了 814 个依赖,97 个还敢要 Node 10
前端·javascript·程序员
陈随易9 小时前
3000 万人在用的翻译插件,重写一遍就是一门生意
前端·后端·程序员