shader_type canvas_item;
render_mode unshaded;

uniform vec4 viewport_rect;
uniform sampler2D occlusion_mask;
uniform vec4 occlusion_rect;
uniform float cell_div = 0.03125; // 1/cell_size = 1/32
uniform float diffusion = 0.3;
uniform float scale_factor = 0.5;

float tile_at(vec2 coord, vec2 camera_tile_offset, vec2 occlusion_div) {
	return texture(occlusion_mask, (coord * cell_div - occlusion_rect.xy) * occlusion_div + camera_tile_offset).r;
}

void fragment() {
	vec2 occlusion_div = 1.0 / occlusion_rect.zw;
	vec2 camera_offset = viewport_rect.xy * scale_factor;
	vec2 camera_tile_offset = camera_offset * cell_div * occlusion_div;

	vec2 coords = UV.xy * viewport_rect.zw * scale_factor;
	float tile = tile_at(coords, camera_tile_offset, occlusion_div);
	
	vec4 ray_coords = vec4(0,0, viewport_rect.zw/2.) * scale_factor;
	vec2 ray_dir = normalize(ray_coords.zw - ray_coords.xy);
	if (int(coords.x+camera_offset.x) % 32 < 1 || int(coords.y+camera_offset.y) % 32 < 1) {
		COLOR = vec4(1);
	} else if (distance(coords, ray_coords.xy) < 10.0 || distance(coords, ray_coords.zw) < 10.) {
		COLOR = vec4(0,1,0,1);
	} else if (tile >= diffusion) {
		COLOR = vec4(1,0,0,1);
	} else {
		COLOR = texture(SCREEN_TEXTURE, SCREEN_UV);
	}
}