Shader #10 : 水玉模様

f:id:zonu_a0:20210609054831p:plain

Shadertoy

www.shadertoy.com

ソースコード

Image

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    // ピクセルの座標
    vec2 pixel = fragCoord.xy;
    
    // 1マスの大きさ
    float squareSize = 0.1 * iResolution.y;
    
    // 左下からいくつめのマスか
    float squareX = floor(pixel.x / squareSize);
    float squareY = floor(pixel.y / squareSize);
    
    //  x+yが奇数になるマスを白くする
    float white = fract((squareX + squareY) / 2.0) * 2.0;
    
    // マスの左下が(0,0),右上が(1,1)となるように座標を変換 
    vec2 pos = vec2(fract(pixel.x / squareSize), fract(pixel.y / squareSize));
    
    // 白いマスを円形に切り抜く
    vec2 center = vec2(0.5, 0.5);
    vec2 diff = pos - center;
    float radian = 0.3;
    white = white * step(length(diff), radian);
    
    // ピクセルの色を設定
    fragColor = vec4(white, white, white, 1.0);
}

解説

    // ピクセルの座標
    vec2 pixel = fragCoord.xy;
    
    // 1マスの大きさ
    float squareSize = 0.1 * iResolution.y;
    
    // 左下からいくつめのマスか
    float squareX = floor(pixel.x / squareSize);
    float squareY = floor(pixel.y / squareSize);
    
    //  x+yが奇数になるマスを白くする
    float white = fract((squareX + squareY) / 2.0) * 2.0;
  • ここまでは #9 と同じ

Shader #9 : 市松模様 - zonu's memo

  • 市松模様の白いマスごとに、マスの中心基準で円形に切り抜くことで水玉模様を作る
    // マスの左下が(0,0),右上が(1,1)となるように座標を変換 
    vec2 pos = vec2(fract(pixel.x / squareSize), fract(pixel.y / squareSize));

  • pos =pixelがあるマスの左下を(0,0), 右上を(1,1)とした時の座標
    // 白いマスを円形に切り抜く
    vec2 center = vec2(0.5, 0.5);
    vec2 diff = pos - center;
    float radian = 0.3;
    white = white * step(length(diff), radian);
  • center = マスの中心座標 点(0,0)と点(1,1)の中心点
  • diff = マスの中での、中心とピクセルの距離
  • radian = マスの中に描画する円の半径
    • 0.5でマスの各辺と円がぴったり接するような円になる
  • white = 円内であれば1.0, そうでないなら0.0
    • 既に white市松模様になっており、この処理で白いマスを円形にくりぬいている
    // ピクセルの色を設定
    fragColor = vec4(white, white, white, 1.0);
  • 描画色を決定