@tool
extends Node2D

@onready var center : Node2D = $Center
@onready var outline : Line2D = $Line2D
@export var cycle_max : float = 30.0
@export var ripple_num : int = 3
@export var speed : float = 200
@export var ripple_width : float = 3
@export var gradient : Gradient
var l_norms : Array[Vector2] = []
func _ready():
	recalc_lnorms()

func _process(delta: float) -> void:
	queue_redraw()

func recalc_lnorms():
	var polypoints : PackedVector2Array
	polypoints = outline.points.slice(0, -1)
		
	var left_neighbor : Vector2
	var right_neighbor : Vector2
	#print("Recalc set")
	for i in range(len(outline.points)):
		var p = outline.points[i]
		if i == 0:
			left_neighbor = outline.points[-2]
		else:
			left_neighbor = outline.points[i-1]
		
		if i == len(outline.points) - 1:
			right_neighbor = outline.points[1]
		else:
			right_neighbor = outline.points[i+1]
		var shift : Vector2 = ((left_neighbor - p).normalized() + (right_neighbor - p).normalized()).normalized()
		if Geometry2D.is_point_in_polygon(p + shift, polypoints):
			#print("Offset moves the point into the polygon, flip!")
			shift *= -1
		l_norms.append(shift)


func _draw() -> void:
	var ripple_line : PackedVector2Array
	ripple_line.resize(len(outline.points))
	
	var min : float = -cycle_max / ripple_num
	var max : float = cycle_max + min
	var cycle = wrapf(Time.get_ticks_msec()*speed, min, max)
	for j in range(ripple_num):
		var color = gradient.sample((cycle / cycle_max))
		for i in len(ripple_line):
			ripple_line[i] = outline.points[i] + l_norms[i] * cycle
			#print(str(outline.points[i]) + " becomes " + str(ripple_line[i]) + " because of offset " + str(l_norms[i]))
		draw_polyline(ripple_line, Color(color, .8 * (cycle_max - cycle) / cycle_max), ripple_width * (cycle_max - cycle) / cycle_max, true)
		cycle = wrapf(cycle + cycle_max / ripple_num, min, max)
	pass
