/* "Sunny Sky"
 * adapted from https://www.shadertoy.com/view/wt2Gzc
 */
// NOTE: Shader automatically converted from Godot Engine 4.2.2.stable's ProceduralSkyMaterial.

shader_type sky;

uniform vec3 sun_color : source_color = vec3(1.0, 1.0, 1.0);
uniform vec3 sky_color : source_color = vec3(0.0, 0.0, 0.0);

uniform float threshold: hint_range(0.0, 1.0) = 0.3;
uniform float speed = 0.02;
uniform float rotation = 4.0;

//uniform sampler2D base_noise: repeat_enable;
uniform sampler3D base_noise: repeat_enable;


float noise3d(vec3 x) {
	return texture(base_noise, x).r;
}

// Fractal Brownian Noise
// see https://github.com/MaxBittker/glsl-fractal-brownian-noise/blob/master/3d.glsl
float fbm3d(vec3 x, const in int it) {
	float v = 0.0;
	float a = 0.5;
	vec3 shift = vec3(100.0);

	for (int i = 0; i < 32; i++) {
		if (i < it) {
			v += a * noise3d(x);
			x = x * 2.0 + shift;
			a *= 0.5;
		}
	}

	return v;
}

float luminance(vec3 color) {
	return 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b;
}

void sky() {
	if (EYEDIR.y > 0.0) {
		float t = TIME * -speed;

		vec2 uv = (EYEDIR.xz * 0.3);
		vec2 st = vec2(
			length(uv) * 1.5,
			atan(uv.y, uv.x)
		);

		st.y += st.x * rotation;

		float x = fbm3d(
			vec3(
				sin(st.y),
				cos(st.y),
				pow(st.x, 0.3) + t * 0.1
			),
			3
		);
		float y = fbm3d(
			vec3(
				sin(1.0 - st.y),
				cos(1.0 - st.y),
				pow(st.x, 0.5) + t * 0.1
			),
			4
		);

		float r = fbm3d(
			vec3(
				x,
				y,
				st.x + t * 0.3
			),
			5
		);

		r = fbm3d(
			vec3(
				r - x,
				r - y,
				r + t * 0.3
			),
			6
		);

		float c = (r + st.x * 5.0) / 6.0;
		COLOR.rgb = c < threshold ? sun_color : sky_color;
	}
}
