extends RigidBody

var _my_patch = "res://oscScene/osc-node.pd"
var _my_id = 0
export (float, 0, 100) var audible_range_max = 10.0

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

	# relocate randomly
	look_at_from_position(Vector3(randf()*60 - 30, randf()*2 + 1, randf()*60 - 30), Vector3.FORWARD, Vector3.UP)

	# send a 'individual' bang.
	Global._gdpd.start_message(1)
	Global._gdpd.add_symbol('bang') # there's no 'add_bang', only 'add_symbol' => add_symbol('bang') is a pseudo-bang
	Global._gdpd.finish_list("fromGodot" + String(_my_id)) # send msg. individually ($0)

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

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
	# (check)
#	print(str(_my_id) +" : ("+ str(distance) +","+ str(angle) +")")
	# 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
