@tool
extends StaticBody3D

@export var generate_mesh : bool = false : set = generate
@export var noise: NoiseTexture2D

signal clicked_on_move(position: Vector3)
signal clicked_on_look(position: Vector3)


func _on_input_event(camera: Node, event: InputEvent, position: Vector3, normal: Vector3, shape_idx: int) -> void:
	if event.is_action_pressed("mouse_move_to"):
		clicked_on_move.emit(position)
	if event.is_action_pressed("mouse_look_at"):
		clicked_on_look.emit(position)


func generate(__):
	var plane_mesh = PlaneMesh.new()
	plane_mesh.size = Vector2(500,500)
	plane_mesh.subdivide_depth = 249
	plane_mesh.subdivide_width = 249
	
	var surface_tool = SurfaceTool.new()
	surface_tool.create_from(plane_mesh,0)
	var data = surface_tool.commit_to_arrays()
	var vertices = data[ArrayMesh.ARRAY_VERTEX]
	
	var image = noise.get_image()
	for i in vertices.size():
		var vertex : Vector3 = vertices[i]
		var noise_value : float
		if vertex.distance_to(Vector3.ZERO) > 180:
			noise_value = 15
		else:
			noise_value = image.get_pixel((vertex.x*1.2)+250,(vertex.z*1.2)+250).v*15
		noise_value += randf_range(-.1,.1)
		vertices[i].y = noise_value
		#var random_offset = Vector2(randf_range(-.2,.2),randf_range(-.2,.2))
		#vertices[i].x += random_offset.x
		#vertices[i].z += random_offset.y
	data[ArrayMesh.ARRAY_VERTEX] = vertices
	
	var array_mesh = ArrayMesh.new()
	array_mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, data)
	
	surface_tool.create_from(array_mesh,0)
	surface_tool.generate_normals()
	
	$MeshInstance3D.mesh = surface_tool.commit()
	$CollisionShape3D.shape = array_mesh.create_trimesh_shape()
