extends RigidBody

var _my_patch = "res://cricketScene/cricket-node.pd"
var _my_id = 0
export (float, 0, 100) var audible_range_max = 10.0
export (Array, float) var parameters = [-7, -2, 3996, 30, 0.7]

func set_param(param):
	parameters = param

func set_color(color):
	$MeshInstance.material_override = SpatialMaterial.new()
	$MeshInstance.material_override.albedo_color = color

func relocate(center, radius_range):
	# relocate randomly into a circular zone
	var rr = radius_range[1] - radius_range[0]
	var displacement = polar2cartesian(randf()*rr+radius_range[0], randf()*2*PI)
	var loc = center + displacement
	look_at_from_position(Vector3(loc.x, randf()*2 + 1, loc.y), Vector3.FORWARD, Vector3.UP)

func _ready():
	# load patch
	_my_id = Global.load_patch(ProjectSettings.globalize_path(_my_patch))

	# listen 'player_transform_updated' event
	Events.connect("player_transform_updated", self, "_on_Events_player_transform_updated")

	# send to the patch
	Global._gdpd.start_message(6)
	Global._gdpd.add_symbol("param")
	Global._gdpd.add_float(parameters[0])
	Global._gdpd.add_float(parameters[1])
	Global._gdpd.add_float(parameters[2])
	Global._gdpd.add_float(parameters[3])
	Global._gdpd.add_float(parameters[4])
	Global._gdpd.finish_list("fromGodot" + String(_my_id))

func _on_Events_player_transform_updated(playerpos, playerheading):
	var mypos = get_global_translation()
	var mypos2d = Vector2(mypos.x, mypos.z)
	var playerpos2d = Vector2(playerpos.x, playerpos.z)
	# calculate distance
	var distance = mypos.distance_to(playerpos)
	# calculate angle
	var angle = fmod(fmod(playerpos2d.angle_to_point(mypos2d) + playerheading - PI/2, PI*2) + PI*2, PI*2)
	if angle > PI:
		angle = angle - PI*2
	# calculate gain
	var gain = max(1 - distance/audible_range_max, 0)
	# send to the patch
	Global._gdpd.start_message(3)
	Global._gdpd.add_symbol("panvol")
	Global._gdpd.add_float(gain)
	Global._gdpd.add_float(angle)
	Global._gdpd.finish_list("fromGodot" + String(_my_id))


func _exit_tree():
	Global.close_patch(_my_id)
	pass
