跳到主要内容
← Ray Tracing

Ray Tracing

Ray-plane intersection

shader-learning 自学第 2 课:Ray-plane intersection

实时渲染 · 2D 片段 GLSL

第 2 课:Ray-plane intersection

实现

uniform vec2 iResolution;
uniform float iTime;

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

vec3 rotateY(vec3 position, float angle) {
  float x = +position.x * cos(angle) + position.z * sin(angle);
  float z = -position.x * sin(angle) + position.z * cos(angle);
  return vec3(x, position.y, z);
}

void main() {
  vec2 uv = gl_FragCoord.xy / iResolution.xy;
  uv = uv * 2.0 - 1.0;
  uv.x *= iResolution.x / iResolution.y;
  vec4 rayOrigin = vec4(0.0, 0.0, 2.0, 1.0);
  vec4 rayDir = vec4(normalize(vec3(uv, -1.0)), 0.0);

  // Plane normal
  vec3 N = normalize(rotateY(vec3(0.0, 0.0, 1.0), iTime));

  // Point on the plane
  vec3 P = rotateY(vec3(-1.0, 1.0, 0.0), iTime);

  float D = dot(P, N);
  vec4 L = vec4(N, -D);
  float t = - (dot(L, rayOrigin) / dot(L, rayDir));

  vec3 point = rayOrigin.xyz + rayDir.xyz * t;
  point = rotateY(point, -iTime);

  vec3 color = shapeColor;
  color *= step(-1.0, point.x);
  color *= 1.0 - step(1.0, point.x);
  color *= step(-1.0, point.y);
  color *= 1.0 - step(1.0, point.y);

  gl_FragColor = vec4(color, 1.0);
}