// simple vertex shader
//http://www.jayconrod.com/cgi/view_post.py?34
#version 120

const float pi = 3.14159;
const float waterHeight = 1.0;
uniform float time;
varying vec3 normal;
const int numWaves=3;
const float amplitude[8] = float[8](1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0);
const float wavelength[8] = amplitude;
const float speed[8] = amplitude;
const vec2 direction[8] = vec2[8](vec2(1.0,1.0),vec2(0.1,1.5),vec2(-0.5,3.0),vec2(1.0,1.3),vec2(1.0,1.4),vec2(1.0,1.5),vec2(1.0,1.6),vec2(0.2,1.7));

float wave(int i, float x, float y) {
    float frequency = 2*pi/wavelength[i];
    float phase = speed[i] * frequency;
    float theta = dot(direction[i], vec2(x, y));
    return amplitude[i] * sin(theta * frequency + time * phase);
}

float waveHeight(float x, float y) {
    float height = 0.0;
    for (int i = 0; i < numWaves; ++i)
        height += wave(i, x, y);
    return height;
}

float dWavedx(int i, float x, float y) {
    float frequency = 2*pi/wavelength[i];
    float phase = speed[i] * frequency;
    float theta = dot(direction[i], vec2(x, y));
    float A = amplitude[i] * direction[i].x * frequency;
    return A * cos(theta * frequency + time * phase);
}

float dWavedy(int i, float x, float y) {
    float frequency = 2*pi/wavelength[i];
    float phase = speed[i] * frequency;
    float theta = dot(direction[i], vec2(x, y));
    float A = amplitude[i] * direction[i].y * frequency;
    return A * cos(theta * frequency + time * phase);
}

vec3 waveNormal(float x, float y) {
    float dx = 0.0;
    float dy = 0.0;
    for (int i = 0; i < numWaves; ++i) {
        dx += dWavedx(i, x, y);
        dy += dWavedy(i, x, y);
    }
    vec3 n = vec3(-dx, -dy, 1.0);
    return normalize(n);
}
void main()
{
        gl_Position    = gl_ModelViewProjectionMatrix * gl_Vertex;
        gl_FrontColor  = gl_Color;
        gl_TexCoord[0] = gl_MultiTexCoord0;
        gl_Position.y += 0.1*waveHeight(gl_Position.x, gl_Position.y);
        normal = waveNormal(gl_Position.x, gl_Position.y);
}
