 
 
 [FragmentShader]
+#line 194
 
 in data {
 	vec3 worldPos;

}

// lighting
float diffuse(vec3 n,vec3 l,float p) {
    return pow(dot(n,l) * 0.4 + 0.6,p);
}
float specular(vec3 n,vec3 l,vec3 e,float s) {    
    float nrm = (s + 8.0) / (3.1415 * 8.0);
    return pow(max(dot(reflect(e,n),l),0.0),s) * nrm;
}

// sky
vec3 getSkyColor(vec3 e) {
    e.y = max(e.y,0.0);
    return vec3(pow(1.0-e.y,2.0), 1.0-e.y, 0.6+(1.0-e.y)*0.4);
}

// sea

    	uv *= octave_m; freq *= 1.9; amp *= 0.22;
        choppy = mix(choppy,1.0,0.2);
    }
    return -h;
}

vec3 getSeaColor(float height, vec3 normal, vec3 dirToLight, vec3 dirToCamera) {  
    
    vec3 color = vec3(0);
    
    float fresnel = clamp(1.0 - dot(normal,-dirToCamera), 0.0, 1.0);
    fresnel = pow(fresnel,3.0) * 0.65;        
    vec3 reflected = getSkyColor(reflect(dirToCamera,normal));    
    vec3 refracted = SEA_BASE + diffuse(normal,dirToLight,80.0) * SEA_WATER_COLOR * 0.12; 
	color += mix(refracted,reflected,fresnel);    
    
	//color += getSkyColor(reflect(dirToCamera,normal));

    float dist = length(i.worldPos);
    //dist = 100;
    float atten = max(1.0 - dist * 0.001, 0.0); 
    color += SEA_WATER_COLOR * (-height) * 0.18 * atten;
    
    color += vec3(specular(normal,dirToLight,dirToCamera,60.0));
    
    return color;
}


vec3 getNormal(vec2 uv, float eps) {
    vec3 normal;
    normal.y = map_detailed(uv); 
    normal.x = map_detailed(vec2(uv.x+eps,uv.y)) - normal.y;
    normal.z = map_detailed(vec2(uv.x,uv.y+eps)) - normal.y;
    normal.y = eps;
    return normalize(normal);
}




vec3 normalMap(vec3 normal) {
	vec3 N = i.normal;
	vec3 T = i.tangent;
	vec3 T2 = T - N * dot(N, T); // Gram-Schmidt orthogonalization of T
	vec3 B = normalize(cross(N,T2));
	//if (dot(B2, B) < 0) B2 *= -1;
	mat3 normalMatrix = mat3(T,B,N); // column0, column1, column2		
	return normalMatrix * normal;
}


void main()
{

	const float startAtCameraDist = 5000;

	const vec3 defaultColor = vec3(0.5,0.7,1);

	vec3 color = defaultColor;	

	float dist = length(i.worldPos);

	if(dist < startAtCameraDist) {

		//mainImage(color, gl_FragCoord.xy);

		vec2 uv = i.uv*100000;
		float height = map(uv);
		vec3 normal = getNormal(uv, 100 * EPSILON_NRM);

		//normal = vec3(0,1,0);
		//normal = normalMap(normal);



		vec3 dirToCamera = normalize(vec3(0) - i.worldPos);
		vec3 dirToLight = vec3(0,1,0);
		color = getSeaColor(height, normal, dirToLight, dirToCamera);

		color = mix(defaultColor, color, smoothstep(startAtCameraDist, startAtCameraDist/2, dist));
	}

	//DEBUG
	//color = vec3(height);
	//color = normal;	

	color = pow(color,vec3(engine.gammaCorrectionTextureRead));
	vec4 color4 = vec4(color, 0.5);
	out_color = color4;

}

