shader_type spatial;
render_mode unshaded;

uniform vec4 color_low: source_color = vec4(0.0, 0.0, 0.0, 1.0);
uniform vec4 color_hi: source_color = vec4(1.0, 1.0, 1.0, 1.0);

uniform float threshold: hint_range(0.0, 1.0) = 0.5;
uniform float contrast: hint_range(0.0, 1.0) = 1.0;
uniform float offset: hint_range(-1.0, 1.0) = 0.0;

uniform sampler2D screen_texture: hint_screen_texture;

float linearSRGB(float channel) {
	if (channel <= 0.04045) {
		return channel / 12.92;
	} else {
		return pow(((channel + 0.055) / 1.055), 2.4);
	}
}

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

void fragment() {
	vec4 screen_color = texture(screen_texture, SCREEN_UV).rgba;

	float Y = luminance(screen_color.rgb);

	// adjust contrast & offset
	Y = clamp((Y - 0.5 + offset) * contrast + 0.5, 0.0, 1.0);

	vec4 color = Y > threshold ? color_hi : color_low;
	ALBEDO.rgb = color.rgb;
	ALPHA = color.a;
}