跳到主要内容
← Grass

Grass

Grass - Flattening Map

shader-learning 自学第 11 课:Grass - Flattening Map

实时渲染 · 网格 GLSL

第 11 课:Grass - Flattening Map

实现

uniform vec2 iResolution;

varying vec3 vNormal;
varying vec3 vPos;

mat4 getOrhtoProjection() {
  // Apply the ratio for visual demo.
  // Before generating the map you need to remove it.
  float ratio = iResolution.x / iResolution.y;
  float size = 3.5;
  float left = -size * ratio;
  float right = size * ratio;
  float top = size;
  float bottom = -size;
  float far = 8.0;
  float near = 0.1;

  mat4 projection;

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

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

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

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

  return projection;
}

mat4 getOrthoView() {
  vec3 viewPos = vec3(0.0, 5.0, 0.0);

  vec3 front = vec3(0.0, 1.0, 0.0);
  vec3 up = vec3(0.0, 0.0, -1.0);
  vec3 right = normalize(cross(up, front));
  vec3 fixedUp = normalize(cross(front, right));

  // column major
  mat4 view;

  // row 0 = dot(right, vertex_pos)
  view[0][0] = right.x;
  view[1][0] = right.y;
  view[2][0] = right.z;
  view[3][0] = -dot(viewPos, right);

  // row 1 = dot(fixedUp, vertex_pos)
  view[0][1] = fixedUp.x;
  view[1][1] = fixedUp.y;
  view[2][1] = fixedUp.z;
  view[3][1] = -dot(viewPos, fixedUp);

  // row 2 = dot(-front, vertex_pos)
  view[0][2] = front.x;
  view[1][2] = front.y;
  view[2][2] = front.z;
  view[3][2] = -dot(viewPos, front);

  //row 3
  view[0][3] = 0.0;
  view[1][3] = 0.0;
  view[2][3] = 0.0;
  view[3][3] = 1.0;

  return view;
}

void main() {
  vNormal = normalize(position);

  vec4 worldPos =  modelMatrix * vec4(position, 1.0);
  vPos = worldPos.xyz;

  gl_Position = getOrhtoProjection() * getOrthoView() * worldPos;
}