shader_type canvas_item;

uniform sampler2D texture1: filter_linear, source_color;
uniform sampler2D texture2: filter_linear, source_color;
uniform sampler3D ripples: repeat_enable, filter_linear;
uniform float transition = 0;
uniform float time = 0;
uniform float warp;
uniform float ridge_sharpness;
uniform float ridge_shine = 0;
uniform float vignette_start;
uniform float vignette_fade;
uniform float vignette_distort = 0;
uniform float vignette_gradient = 1;

vec3 hmap_normal(sampler3D hmap, vec3 uv) {
	float eps = 0.03;
	float z = texture(hmap, uv).z;
	return normalize(vec3(
		(texture(hmap, uv + vec3(eps, 0, 0)).z - z) / eps,
		(texture(hmap, uv + vec3(0, eps, 0)).z - z) / eps,
		-1
	));
}

void fragment() {
	float tr = transition;

	//vec3 normal = texture(ripples, UV + vec2(TIME * time_scale, 0)).xyz;
	vec3 time_uv = vec3(UV.x, UV.y, time);
	vec3 center = hmap_normal(ripples, time_uv);
	vec3 right = hmap_normal(ripples, time_uv + vec3(ridge_sharpness, 0, 0));
	vec3 up = hmap_normal(ripples, time_uv + vec3(0, ridge_sharpness, 0));
	vec3 left = hmap_normal(ripples, time_uv + vec3(-ridge_sharpness, 0, 0));
	vec3 down = hmap_normal(ripples, time_uv + vec3(0, -ridge_sharpness, 0));

	vec3 normal = (center + left + right + up + down) / 5.0f;
	vec3 edge_normal = (center + left - right + up - down) / 5.0f;

	float ridge_shine_factor = pow(length(edge_normal.xy), 3) * 0.7f;
	vec2 warp_uv = UV + normal.xy * (warp + 0.05f * tr);
	float vig = pow(max(length(warp_uv - vec2(0.5f)) - vignette_start, 0) / (1.0f - vignette_start), vignette_gradient);

	vec2 vig_uv = warp_uv - (vignette_distort + 1.0f * tr) * vig * normalize(warp_uv - vec2(0.5f));
	vec4 col1 = texture(texture1, vig_uv).rgba;
	vec4 col2 = texture(texture2, vig_uv).rgba;
	vec4 col = mix(col1, (col1 + col2) / 2.0f, tr);

	col.rgb += vec3((ridge_shine + 5.0f * tr) * ridge_shine_factor);
	col.rgb = mix(col.rgb, vec3(1.0f), (vignette_fade + 2.0f * tr) * (vig + 0.02f * tr));
	COLOR.rgb = col.rgb;
}
