shader_type canvas_item;

uniform float scroll_x = 0.0;
uniform float scroll_y = 0.0;
uniform float rotation : hint_range(-360.0, 360.0) = 0.0;

uniform float globe_magnitude : hint_range(0.0, 1.0) = 1.0;

vec2 rotate(vec2 uv, vec2 pivot, float angle)
{
	mat2 r = mat2(vec2(sin(angle), -cos(angle)),
						vec2(cos(angle), sin(angle)));

	uv -= pivot;
	uv = uv * r;
	uv += pivot;
	return uv;
}

void fragment()
{
	// Original UVs from 0 to 1
	vec2 uv = UV;
	float rotationRads = (rotation + 90.0) * PI / 180.0;
	//uv.x = mod(uv.x + x_scroll, 1.0);
    //uv.y = mod(uv.y + y_scroll, 1.0);

	// Remaps UV to -1, 1, i.e. centers on the sprite
	vec2 centered_uv = uv * 2.0 - 1.0;
	centered_uv = rotate(centered_uv, vec2(0), rotationRads);

	// Radius r of length of the centered UV
	float r = length(centered_uv);
	if (r > 1.0)
	{
		discard; // clips anything past the radius of the circle
	}

	float z = sqrt(1.0 - r * r);

	vec2 sphere_uv = centered_uv / (1.0 + z);
	sphere_uv.x = mod(sphere_uv.x + scroll_x, 1.0);
    sphere_uv.y = mod(sphere_uv.y + scroll_y, 1.0);
	sphere_uv = sphere_uv * 0.5 + 0.5;


	vec2 final_uv = mix(uv, sphere_uv, globe_magnitude);

	COLOR = texture(TEXTURE, final_uv);
}