Step - Invert
Task
Write a shader that splits the screen into two parts: the left half should be red and the right half should be black.
编写一个着色器,将屏幕分成两部分:左半部分应为红色,右半部分应为黑色。
Requirements
The shader should avoid using branching or conditional statements in its code, and instead rely on the
step
function to determine the color of each pixel.
着色器应避免在其代码中使用分支或条件语句,而是依靠
step
函数来确定每个像素的颜色。
Theory
您可以step
通过从中减去阶跃函数结果来反转函数的结果1
。
如果输入值小于阈值,并且输入值大于或等于阈值,则函数返回。通过从中减去此结果,step
可以有效地反转输出:0.0``1.0``1.0
- • 如果原始结果是
0.0
,则反转的结果将是1.0
。 - • 如果原始结果是
1.0
,则反转的结果将是0.0
。
例子
下面是一个示例代码片段,用于说明如何step
在 GLSL 中反转函数的结果:
float invertedStep = 1.0 - step(threshold, value);
因此,如果大于或等于,invertedStep
则为,否则为。0.0``value``threshold``1.0
Answer
uniform vec2 iResolution;
void main() {
// Normalized pixel coordinates (from 0 to 1)
vec2 uv = gl_FragCoord.xy / iResolution.xy;
float result = step(0.5, 1.0 - uv.x);
gl_FragColor = vec4(result, 0.0, 0.0, 1.0);
}
效果
练习
最后
如果你觉得这篇文章有用,记得点赞、关注、收藏,学Shader更轻松!!