跳到主要内容
← Signed Distance Field

Signed Distance Field

SDF Rotation 2

shader-learning 自学第 10 课:SDF Rotation 2

实时渲染 · 2D 片段 GLSL

第 10 课:SDF Rotation 2

实现

uniform vec2 iResolution;
uniform float iTime;

const vec3 shapeColor      = vec3(1.0, 0.3, 0.3);
const vec3 backgroundColor = vec3(0.12);

float sdfCircle(vec2 center, float r, vec2 pos) {
  return distance(center, pos) - r;
}

float drawPental(vec2 uv) {
  float r  = iResolution.y * 0.3;

  vec2 center0 = iResolution * vec2(0.0, 0.0);

  vec2 center1 = iResolution * vec2(-0.03, 0.0) + vec2(+r, +r);
  vec2 center2 = iResolution * vec2(+0.03, 0.0) + vec2(-r, +r);

  float c0 = sdfCircle(center0, r * 0.3, uv);

  float c1 = sdfCircle(center1, r, uv);
  float c2 = sdfCircle(center2, r, uv);

  return min(max(c1, c2), c0);
}

mat2 rotation(float theta){
  return transpose(mat2(
    vec2(cos(theta),-sin(theta)),
    vec2(sin(theta),cos(theta))
  ));
}

void main() {
  vec2 uv = gl_FragCoord.xy;

  // make 0 the center
  uv.x -= iResolution.x * 0.5;
  uv.y -= iResolution.y * 0.5;


  float time = sin(iTime) * 0.5 + 0.5;
  float t = 1.0;
  int steps = 20;
  float twoPI = 3.14 * 2.0;
  for (int i = 0; i < steps; i++) {
    float maxangle = twoPI / float(steps) * float(i);
    float angle = clamp(time * twoPI, 0.0, maxangle);
    float ti = drawPental(rotation(angle)* uv);
    t = min(t, ti);
  }
  t = clamp(t, 0.0, 1.0);

  gl_FragColor = vec4(mix(shapeColor, backgroundColor, t), 1.0);
}