shader_type spatial;
render_mode blend_mix, depth_draw_opaque, cull_back, diffuse_burley, specular_schlick_ggx, sss_mode_skin;

uniform vec3 color_1: source_color = vec3(0.0, 0.03, 0.1);
uniform vec3 color_2: source_color = vec3(0.0, 0.1, 0.3);
uniform vec3 emission_color: source_color = vec3(0.25, 0.88, 1.0);

uniform float pixellation = 50.0;

uniform float roughness: hint_range(0.0, 1.0) = 0.15;
uniform float specular_contribution = 0.8;
uniform float emission_strength = 0.05;

// Used ONLY by the gunk, does not affect the gunk mask.
uniform vec2 uv_scale = vec2(1.0);

uniform float time_scale = 1.0;

uniform float edge_bleed = 0.1;

uniform sampler2D gunk_mask;

uniform highp sampler3D gunk_noise;
uniform highp sampler3D gunk_normal_map;


float hardstep(float value) {
	float x = clamp(value, 0.0, 1.0);
	return 0.5 * tanh( (20.0 * x - 10.0) * inversesqrt(x - x * x) ) + 0.5;
}

void fragment() {
	vec2 local_uv = floor(UV * uv_scale * pixellation) / pixellation;

	// wave
	vec3 uvt = vec3(local_uv.x, local_uv.y, TIME * time_scale);
	uvt.x += sin(uvt.y * 1.54 * PI + uvt.z) * cos(uvt.y * 1.31 * PI + uvt.z);
	uvt.y += cos(uvt.x * 1.74 * PI + uvt.z) * -sin(uvt.y * 1.64 * PI + uvt.z);


	float value = texture(gunk_noise, uvt).r;
	vec3 color = mix(color_1, color_2, value);

	ALBEDO = color.rgb;
	ROUGHNESS = value * roughness;
	EMISSION = (1.0 - value) * emission_color * emission_strength;
	SPECULAR = 0.5 * inversesqrt(specular_contribution);
	NORMAL_MAP = texture(gunk_normal_map, uvt).xyz;

	float mask = texture(gunk_mask, UV).r;

	// soften edges
	NORMAL_MAP *= smoothstep(1.0, 0.0, mask);

	/*
	// Hard edge
	if(mask + edge_bleed < 0.5) {
		ALPHA = 1.0;
	} else {
		ALPHA = 0.0;
	}
	*/

	// Hardish edge
	ALPHA = hardstep(1.0 - mask + edge_bleed);
}