@tool
extends MeshInstance3D
const SHADER = preload("res://nodes/tools/wireframe_aabb.gdshader")

var color : Color = Color(0.0, 1.0, 0.0)

func _enter_tree():
	if Engine.is_editor_hint():
		var parent = get_parent()
		if parent != null and parent is MeshInstance3D:
			var aabb = parent.get_aabb()
			var material = ShaderMaterial.new()
			material.set_shader(SHADER)
			material.set_shader_parameter("color", Vector3(color.r, color.g, color.b))
			draw_aabb(aabb, material)
		else:
			print("no parent or no mesh instance parent found")

func draw_aabb(aabb:AABB, material:Material):
	
	mesh = ImmediateMesh.new()
	mesh.surface_begin(Mesh.PRIMITIVE_LINES, material)
	
	#bottom
	mesh.surface_add_vertex(aabb.position)
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(1, 0, 0))
	
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(1, 0, 0))
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(1, 0, 1))
	
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(1, 0, 1))
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(0, 0, 1))
	
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(0, 0, 1))
	mesh.surface_add_vertex(aabb.position)
	
	#top
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(0, 1, 0))
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(1, 1, 0))
	
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(1, 1, 0))
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(1, 1, 1))
	
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(1, 1, 1))
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(0, 1, 1))
	
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(0, 1, 1))
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(0, 1, 0))
	
	#sides
	mesh.surface_add_vertex(aabb.position)
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(0, 1, 0))
	
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(1, 0, 0))
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(1, 1, 0))
	
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(1, 0, 1))
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(1, 1, 1))
	
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(0, 0, 1))
	mesh.surface_add_vertex(aabb.position + aabb.size * Vector3(0, 1, 1))
	
	mesh.surface_end()
