shader_type spatial;
render_mode unshaded, cull_disabled, shadows_disabled;

// Cinder Caldera lava (env_lava.gd): slow flowing molten rock - a dark crust broken into drifting plates (Voronoi in
// world XZ, scrolled along the flow) over glowing orange-yellow cracks, bright pulsing edges near the banks
// (UV.y = 0 / 1 at the banks). Over-bright (HDR) so the bloom picks it up.
uniform vec3 hot : source_color = vec3(1.0, 0.55, 0.12);
uniform vec3 hotter : source_color = vec3(1.0, 0.9, 0.45);
uniform vec3 crust : source_color = vec3(0.16, 0.06, 0.05);
uniform float glow = 1.8;
uniform vec2 flow = vec2(0.35, 0.0);

varying vec3 wpos;

void vertex() {
	wpos = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
}

vec2 h22(vec2 p) {
	p = vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3)));
	return fract(sin(p) * 43758.5453);
}

float edge(vec2 q) {
	vec2 i = floor(q);
	vec2 f = fract(q);
	float d1 = 8.0;
	float d2 = 8.0;
	for (int y = -1; y <= 1; y++) {
		for (int x = -1; x <= 1; x++) {
			vec2 g = vec2(float(x), float(y));
			float d = length(g + h22(i + g) - f);
			if (d < d1) {
				d2 = d1;
				d1 = d;
			} else if (d < d2) {
				d2 = d;
			}
		}
	}
	return d2 - d1;
}

void fragment() {
	vec2 p = wpos.xz * 0.45 - flow * TIME;
	float e = edge(p);
	float e2 = edge(p * 2.3 + 11.0 - flow * TIME * 0.7);
	float crack = 1.0 - smoothstep(0.015, 0.07, e);
	crack = max(crack, (1.0 - smoothstep(0.01, 0.045, e2)) * 0.5);
	float bank = 1.0 - smoothstep(0.0, 0.1, min(UV.y, 1.0 - UV.y));
	float pulse = 0.85 + 0.15 * sin(TIME * 2.0 + wpos.x * 0.3 + wpos.z * 0.2);
	vec3 molten = mix(hot, hotter, crack * 0.6) * pulse;
	vec3 col = mix(crust, molten, clamp(crack + bank * 0.8, 0.0, 1.0));
	// unshaded: brightness above 1 in ALBEDO is what the HDR bloom picks up
	ALBEDO = col + molten * clamp(crack + bank * 0.7, 0.0, 1.0) * (glow - 1.0) * 0.5;
}
