#version 330 core

#ifdef GL_ES
precision mediump float;
#endif

#extension GL_OES_standard_derivatives : enable

uniform float time;
uniform vec2 resolution;



// halfspace discard uniforms: ////////////////////////////////

in vec4 aPos;

uniform int iside=0; // 0=>noDiscard

uniform vec3 eyePos;

uniform vec3  port1;
uniform vec3  port2;

// halfspace discard uniforms end /////////////////////////////







float hashS( vec2 p ) {
	float h = dot(p,vec2(127.1,311.7));	
    return fract(sin(h)*43758.5453123);
}

float noiseS( in vec2 p ) {
    const vec2 modifier = vec2(1.0, 0.0);
    vec2 i = floor( p );
    vec2 f = fract( p );	
	vec2 u = f*f*(3.0-2.0*f);
    return -1.0+2.0*mix( mix( hashS( i + modifier.yy ), 
                     hashS( i + modifier.xy ), u.x),
                mix( hashS( i + modifier.yx ), 
                     hashS( i + modifier.xx ), u.x), u.y);
 }
                     
float sea_octave(vec2 uv, float choppy) {
    uv += noiseS(uv);        
    vec2 wv = 1.0-abs(sin(uv));
    vec2 swv = abs(cos(uv));    
    wv = mix(wv,swv,wv);
    return pow(1.0-pow(wv.x * wv.y,0.65),choppy);
}

float seatime = 1.0 + time * 0.8;
mat2 octave_m = mat2(1.6,1.2,-1.2,1.6);

float heightwater(vec2 uv) {
    float freq = 0.16;
    float amp = 0.6;
    uv *= 2.1;
    uv.x *= 0.75;
    float choppy = 4.0;
    
    float d, h = 0.0;    
    for(int i = 0; i < 7; i++) {        
    	d = sea_octave((uv+seatime)*freq,choppy);
    	d += sea_octave((uv-seatime)*freq,choppy);
        h += d * amp;        
    	uv *= octave_m; freq *= 1.9; amp *= 0.22;
        choppy = mix(choppy,1.0,0.2);
    }
    return h *0.5;
}


in vec2 mypos;
out vec4 fragColor;

void main( void ) {

	//vec2 position = ( gl_FragCoord.xy / resolution.xy ) + mouse / 4.0;
	vec2 position = mypos/20.0 ;

	position.x *= resolution.x / resolution.y;
	float color = heightwater(position * 12.0);

	fragColor = vec4(color);

	fragColor.a = 1.0;


	// fastrgv:  my halfspace-discard addendum:
	vec3 cP1 =  port1 - eyePos;
	vec3 cP2 =  port2 - eyePos;
	vec3 vP0 = aPos.xyz - eyePos;
	float PRAD = 0.85; // larger, but synched with adagate.adb
	float FOV1 = atan(PRAD/length(cP1));
	float FOV2 = atan(PRAD/length(cP2));
	vec3 nP1 = normalize(cP1);
	vec3 nP2 = normalize(cP2);
	vec3 nP0 = normalize(vP0);
	float d1=dot(nP0,nP1);
	float d2=dot(nP0,nP2);
	float a1=acos(d1);
	float a2=acos(d2);
	if( iside != 0 ) {
		if( (iside==2) && (a1>FOV1) ) discard;
		if( (iside==1) && (a2>FOV2) ) discard;
	}


}
