extends Module


var enabled := true

var pos_x_register_index:int
var pos_y_register_index:int
var pos_z_register_index:int

func _ready() -> void:
	if Terrain.instance == null:
		print("No terrain to get clicks from")

func set_registers(index:int)->int:
	pos_x_register_index = index
	pos_y_register_index = index+1
	pos_z_register_index = index+2
	return 3

func _unhandled_input(event: InputEvent) -> void:
	if not enabled: return
	if event is InputEventMouseButton and event.is_pressed():
		var button_event = event as InputEventMouseButton
		if button_event.button_index == MOUSE_BUTTON_LEFT:
			set_click_registers()
		elif button_event.button_index == MOUSE_BUTTON_RIGHT:
			pass

func set_click_registers()->void:
	var mouse_pos_2d := get_viewport().get_mouse_position()
	var current_camera := get_viewport().get_camera_3d()
	var origin := current_camera.project_ray_origin(mouse_pos_2d)
	var dir := current_camera.project_ray_normal(mouse_pos_2d)
	var res := Terrain.instance.get_voxel_tool().raycast(origin, dir, 100)
	var registers := cpu.cobor_vm.get_registers()
	registers[pos_x_register_index] = res.previous_position.x
	registers[pos_y_register_index] = res.previous_position.y
	registers[pos_z_register_index] = res.previous_position.z
	cpu.cobor_vm.set_registers(cpu.register_size, registers)
