#version 300 es
// VERTEX SHADER
//
// Takes vertices of a unit cube, scales them up along Y according to
// aHeight, and colors them with basic diffuse shading.

#define CLEAR_COLOR vec4(0.0588235294118, 0.0588235294118, 0.0588235294118, 1.0)
#define BASE_COLOR vec3(0.6, 0.819607843137, 0.807843137255)
#define AMBIENT_LIGHT vec3(0.3, 0.3, 0.3)
#define LIGHT_DIRECTION normalize(vec3(0.85, 0.8, 0.75))
#define LIGHT_COLOR vec3(1.0, 1.0, 1.0)

precision highp float;

layout(location = 0) in vec4 aVertexPosition;
layout(location = 1) in vec3 aVertexNormal;
layout(location = 2) in float aHeight;
flat out vec4 vColor;

uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
uniform mat4 uNormalMatrix;

void main() {
  // The X position of each vertex depends on its cube's instance;
  // they should align to the X axis.
  float instanceX =
      float(gl_InstanceID * 2) * abs(aVertexPosition.x) + aVertexPosition.x;
  // To scale the boxes by their frequencies, scale vertex Y by the
  // frequency.
  float vertexY = aVertexPosition.y * aHeight;

  gl_Position = uProjectionMatrix * uModelViewMatrix *
                vec4(instanceX, vertexY, aVertexPosition.zw);

  if (aHeight == 0.0) {
    // Don't render cubes that don't currently have a height
    // (frequency = 0)
    vColor = CLEAR_COLOR;
  } else {
    // Properly shade and color any other cubes
    vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);
    float directionalLight =
        max(dot(transformedNormal.xyz, LIGHT_DIRECTION), 0.0);
    vec3 appliedColor =
        BASE_COLOR * (directionalLight * LIGHT_COLOR + AMBIENT_LIGHT);

    vColor = vec4(appliedColor.rgb, 1.0);
  }
}
