extends Spatial

var Chunk = preload("res://chunk.tscn")
onready var Player = $"../Player"

var resolution = 512
var scaleFact = 1000
var radius = 1737.4*scaleFact
var renderDistance = 0.2

var chunkIndex = {}

# Called when the node enters the scene tree for the first time.
func _ready():
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	var playerSpos = Player.getSpos()
	var playerChunkPos = Vector2(int(playerSpos.x), int(playerSpos.y))
	var playerInterChunkPos = Vector2(playerSpos.x - playerChunkPos.x, playerSpos.y - playerChunkPos.y)
	
	var dir = Vector2()
	
	if playerInterChunkPos.x < renderDistance:
		dir = dir+Vector2(-1,0)
	elif playerInterChunkPos.x > 1-renderDistance:
		dir = dir+Vector2(1,0)
	
	if playerInterChunkPos.y < renderDistance:
		dir = dir+Vector2(0,-1)
	elif playerInterChunkPos.y > 1-renderDistance:
		dir = dir+Vector2(0,1)
		
	add_chunk(playerChunkPos+dir)
	add_chunk(playerChunkPos+Vector2(0,dir.y))
	add_chunk(playerChunkPos+Vector2(dir.x,0))
	
	#for i in [Vector2(1,0),Vector2(1,1),Vector2(0,1),Vector2(-1,0),Vector2(0,-1),Vector2(-1,-1),Vector2(1,-1),Vector2(-1,1)]:
	#	var dist = Vector2(playerSpos.x, playerSpos.y).distance_to(playerChunkPos+i)
	#	if dist < renderDistance:
	#		add_chunk(playerChunkPos+i)


func add_chunk(chunkPos = Vector2()):
	var lat = int(chunkPos.x)
	var lon = int(chunkPos.y)
	if chunkIndex.has(lon) and chunkIndex[lon].has(lat):
		return
	var chunk = Chunk.instance()
	chunk.setParams(lat,lat+1,lon,lon+1,resolution,radius,scaleFact)
	#moontile.scale=Vector3(1000,1000,1000)
	.add_child(chunk)
	if not chunkIndex.has(lon):
		chunkIndex[lon]={}
	chunkIndex[lon][lat] = chunk

func remove_chunk(chunkPos = Vector2()):
	var lat = int(chunkPos.x)
	var lon = int(chunkPos.y)
	if chunkIndex.has(lon) and chunkIndex[lon].has(lat):
		chunkIndex[lon][lat].queue_free()
		chunkIndex[lon].delete(lat)

