#version 120
#define LIGHT_SOURCES 2
const float pi = 3.14159;
const float waterHeight = 0.1;
uniform float time;
varying vec3 waterNormal, oldNormal;
varying float height;
const int numWaves=8;
const float amplitude[8] = float[8](0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8);
const float wavelength[8] = amplitude;
const float speed[8] = float[8](0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2);
const vec2 direction[8] = vec2[8](vec2(1.0,1.0),vec2(0.1,1.5),vec2(-0.5,3.0),vec2(0.0,-1.5),vec2(-1.0,1.4),vec2(-0.7,1.5),vec2(1.0,1.9),vec2(0.3,1.2));


varying vec3 normal, lightDir[LIGHT_SOURCES], eyeVec;
varying float att[LIGHT_SOURCES];

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_FrontColor  = gl_Color;
        oldNormal = gl_NormalMatrix * gl_Normal;
        vec3 vVertex = vec3(gl_ModelViewMatrix * gl_Vertex);
        eyeVec = -vVertex;
        for(int i=0;i<LIGHT_SOURCES;i++){
            lightDir[i] = vec3(gl_LightSource[i].position.xyz - vVertex);                
            float d = length(lightDir[i]);
        
            att[i] = 1.0 / ( gl_LightSource[i].constantAttenuation + 
            (gl_LightSource[i].linearAttenuation*d) + 
            (gl_LightSource[i].quadraticAttenuation*d*d) );
        }
        gl_TexCoord[0] = gl_MultiTexCoord0;
        gl_Position    = gl_ModelViewProjectionMatrix * gl_Vertex;
        height= waveHeight(gl_TexCoord[0].x,gl_TexCoord[0].y);
        waterNormal = waveNormal(gl_TexCoord[0].x,gl_TexCoord[0].y);
        normal = (0.75*(0.9*oldNormal+0.1*waterNormal))+(0.25*(oldNormal*waterNormal)); 
                //cross(oldNormal,waterNormal);
}
