Fract - Grid

168 阅读1分钟

Task

Write a shader that draws a grid. Each cell in the grid should be 50x50 pixels in size, with a margin of 10 pixels between cells.

编写一个绘制网格的着色器。网格中的每个单元格应为50x50像素大小,单元格之间的间距为10像素。

Requirements

The shader should avoid using branching or conditional statements in its code, and instead rely on the fract and step functions to determine the color of each pixel.

着色器应避免在其代码中使用分支或条件语句,而是依靠fractstep函数来确定每个像素的颜色。

Theory

把一个单元格和一个间距做为一个整体, 开始10像素作为间距,[10, 60]作为单元格,宽和高使用同样的处理方式,使用step处理各自区域之间的值。

Answer

void main() {
  float cellSize = 50.0f;
  float margin = 10.0f;
  vec2 cell = gl_FragCoord.xy/(cellSize + margin);
  float x = step(margin / (cellSize + margin), fract(cell.x));
  float y = step(margin / (cellSize + margin), fract(cell.y));

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

效果

image.png

练习

Fract - Grid

最后

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