跳到主要内容
← ShadowMap

ShadowMap

Shadow Map - Render Passes

shader-learning 自学第 4 课:Shadow Map - Render Passes

实时渲染 · 网格 GLSL

第 4 课:Shadow Map - Render Passes

实现

uniform vec2 iResolution;
uniform int iDepthPass;

// Already available:
// attribute vec3 position;
// attribute vec2 uv;

attribute vec4 color;
attribute int id;

flat varying int vId;
varying vec3 vLightDir;
varying vec3 vNormal;
varying vec4 vColor;
varying vec2 vUv;

mat4 getLightProjection() {
  float ratio = iResolution.x / iResolution.y;
  float size = 2.0;
  float left = -size * ratio;
  float right = size * ratio;
  float top = size;
  float bottom = -size;
  float far = 8.0;
  float near = 0.1;

  mat4 lightProjection;

  lightProjection[0][0] = 2.0 / (right - left);
  lightProjection[1][0] = 0.0;
  lightProjection[2][0] = 0.0;
  lightProjection[3][0] = -(right + left) / (right - left);

  lightProjection[0][1] = 0.0;
  lightProjection[1][1] = 2.0 / (top - bottom);
  lightProjection[2][1] = 0.0;
  lightProjection[3][1] = -(top + bottom) / (top - bottom);

  lightProjection[0][2] = 0.0;
  lightProjection[1][2] = 0.0;
  lightProjection[2][2] = -2.0 / (far - near);
  lightProjection[3][2] = -(far + near) / (far - near);

  lightProjection[0][3] = 0.0;
  lightProjection[1][3] = 0.0;
  lightProjection[2][3] = 0.0;
  lightProjection[3][3] = 1.0;

  return lightProjection;
}
void main() {

  vec3 lightDir = normalize(vec3(-0.5, -0.8, 0.0));
  vec3 lightPos = vec3(1.5, 2.4, 0.0);
  vec3 worldUp = vec3(0.0,1.0,0.0);
  vec3 vectorRight = normalize(cross(worldUp,-lightDir));
  vec3 vectorUp = normalize(cross(-lightDir, vectorRight));

  mat4 lightView = transpose(mat4(
    vec4(vectorRight, 0.0),
    vec4(vectorUp, 0.0),
    vec4(-lightDir, 0.0),
    vec4(vec3(0.0), 1.0)
  ));

  mat4 translate = transpose(mat4(
    vec4(1.0, 0.0, 0.0, -lightPos.x),
    vec4(0.0, 1.0, 0.0, -lightPos.y),
    vec4(0.0, 0.0, 1.0, -lightPos.z),
    vec4(vec3(0.0), 1.0)
  ));

  lightView *= translate;

  mat4 projView;
  if(iDepthPass == 1){
    projView = getLightProjection() * lightView;
  }else{
    projView = projectionMatrix * viewMatrix;
  }

  gl_Position = projView * modelMatrix * vec4(position, 1.0);

  vId = id;
  vLightDir = lightDir;
  vNormal = mat3(modelMatrix) * normal;
  vColor = color;
  vUv = uv;
}