extends Node2D

class_name Occluder

const MAX_LENGTH = 200
const EPSILON = 0.1
const DEBUG = false

var ignore_sides = [false, false, false, false]
var size = Vector2(32, 32)
var origin = null
var polygon: PoolVector2Array = [Vector2.ZERO, Vector2(size.x, 0), Vector2(size.x, size.y), Vector2(0, size.y)]

func _draw():
	if polygon == null:
		return

	if origin == null:
		return
		
	var player_position =  origin.global_position - global_position
	
	# Find what edges is the players looking at
	var edges = [
		player_position.y < 0, # TOP
		player_position.x > size.x*2, # RIGHT
		player_position.y > size.y*2, # BOTTOM
		player_position.x < 0 # LEFT
	]

	for current in range(0, polygon.size()):
		var next = (current + 1) % polygon.size()

		if not ignore_sides[current] and not edges[current]:
			var points = [
				(polygon[current] * 2.1 - origin.global_position + global_position) * MAX_LENGTH,
				polygon[current], polygon[next],
				(polygon[next] * 2.1 - origin.global_position + global_position) * MAX_LENGTH
			]
			draw_polygon(points, [Color.black])
			if DEBUG:
				draw_polyline(points, Color.rebeccapurple)
		else:
			if DEBUG:
				if ignore_sides[current]:
					draw_line(polygon[current], polygon[next], Color.red, 1)
				else:
					draw_line(polygon[current], polygon[next], Color.yellow, 2)

func _process(_delta):
	update()
	z_index = 999
