#version 330 core

uniform sampler2D bumpmap;
uniform sampler2D diffuse;
uniform sampler2D flow;
uniform sampler2D foam;
uniform float time;

in vec3 normal;
in vec3 ec_pos;
in vec2 uv;
in vec2 offset;

layout (location = 0) out vec4 diffuse_specular;
layout (location = 1) out vec4 normal_depth;

#include <tangentspace_include.frag>

void main()
{
	const vec3 diff = vec3(53.f/255.0, 62.0/255.0, 93.0/255.0);
	const vec3 refr = vec3(53.f/255.0, 62.0/255.0, 93.0/255.0);
	const vec3 refl = vec3(83.f/255.0, 92.0/255.0, 113.0/255.0)*0.5;
	const vec3 ld = vec3(0.0, 0.0, 1.0);
	//vec3 ld = normalize(vec3(0.0, -0.2, 1.0));
	
	//float time = 0.5;//ec_pos.x*ec_pos.z;

	// pseudo water flow
	//vec3 f = texture(flow, uv*(1.0/64.0)).rgb;
	vec3 f = texture(flow, uv*(1.0/16.0)).rgb;
	vec2 flow_uv = f.rg*2.0 - vec2(1.0);
	float flow_offset0 = mod(time, 1.0);
	float flow_offset1 = mod(time + 0.5, 1.0);
	float cycle_offset = f.b;

	float phase0 = cycle_offset*0.5 + flow_offset0;
	float phase1 = cycle_offset*0.5 + flow_offset1;

	// make waves
	vec3 bump0 = texture(bumpmap, uv*1.0+flow_uv*phase0).rgb*2.0 - vec3(1.0);
	vec3 bump1 = texture(bumpmap, uv*1.0+flow_uv*phase1).rgb*2.0 - vec3(1.0);
	vec3 bump2 = texture(bumpmap, uv*16.0+offset).rgb*2.0 - vec3(1.0);
	float k = abs( 0.5 - flow_offset0 ) / 0.5;
	vec3 n = normalize(mix(bump0, bump1, k) + bump2*0.25);
	//n = normalize( mix(normal, normalize(n + n2*0.25), 0.5) );
/*
	vec3 fm1 = texture(foam, uv*16.0 + flow_uv*phase1).rrr;
	vec3 fm2 = texture(foam, uv.yx*16.0 + flow_uv*phase0).rrr;
	vec3 fm = mix(fm1, fm1, k);
	vec3 fm = mix(fm1, fm1, k);
*/

	// fake lighting
	float lit = pow(max(dot(n, ld), 0.0), 5.0);
	
	vec3 r = normalize(refract(vec3(0.0,0.0,-1.0), n, 0.33));
	float rf = pow(max(dot(r, ld), 0.0), 1.0);

	vec3 r2 = normalize( reflect(vec3(0.0,0.0,-1.0), n) );
	float rf2 = pow(max(dot(r2, ld), 0.0), 32.0);

	vec3 r3 = reflect(vec3(0.0, 0.0, 1.0), n);
	vec2 refr_uv = r3.xy*(1.0/64.0);
	vec4 grnd = texture(diffuse, uv*2.0 + refr_uv);

	//vec3 fm = texture(foam, uv*16.0 + refr_uv).rrr;
	vec3 fm = texture(foam, uv*vec2(8.0,10.0) + refr_uv*1.0).rrr;

	vec3 water = diff*lit + refr*rf + /*refl*rf2 +*/ fm*rf2;
	//vec3 water = fm;

	//float alpha = min(lit + rf + rf2, 1.0);
	float alpha = clamp(lit + rf + rf2, 0.0, 1.0)*0.9;// * grnd.a;
	diffuse_specular.rgb = grnd.rgb*0.5 + water;
	diffuse_specular.a = alpha;

	vec3 t, b;
	per_fragment_tangent_space(ec_pos, uv, t, b);
	mat3 mr = mat3(t, b, normalize(normal));
	n = mr * n;

	normal_depth.rgb = n*alpha;
	normal_depth.a = alpha;
}
