@tool
extends MeshInstance3D
@export var update=false

var height = Array()
var grid
var lng_w
var lat_l = 111.321
var v_step
var h_step

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	_getHeights()
	_widthOfLongitude(51)
	v_step = grid / lat_l
	h_step = ((lng_w/1000) / lat_l) * v_step
	_generateTerrain()


func _getHeights():
	if FileAccess.file_exists("res://N51E007.hgt"):
		var file = FileAccess.open("res://N51E007.hgt", FileAccess.READ)
		file.big_endian = true
		var size = file.get_length()
		grid = int(sqrt(size/2))
		#uv_step = 1 / grid
		for x in range(0, grid):
			var row = Array()
			for y in range(0, grid):
				row.append(file.get_16())
			height.append(row)
		height.reverse()


func _widthOfLongitude(lng):
	var dm = cos(deg_to_rad(lng)) * lat_l
	lng_w = round(dm * 1000)


func _generateTerrain():
	var a_mesh = ArrayMesh.new()
	var verts := PackedVector3Array()
	var indices := PackedInt32Array()
	var normals := PackedVector3Array()
	var curind = 0
	
	for x in range(0, grid-2):
		for y in range(0, grid-2):
			var xp = x*h_step
			var yp = y*v_step
			var v1 = Vector3(xp, _getHeight(x, y), -yp)
			var v2 = Vector3(xp, _getHeight(x, y+1), -yp-v_step)
			var v3 = Vector3(xp+h_step, _getHeight(x+1, y), -yp)
			
			var side1 = v2-v1
			var side2 = v2-v3
			var normal1 = side1.cross(side2)
			
			var v4 = Vector3(xp, _getHeight(x, y+1), -yp-v_step)
			var v5 = Vector3(xp+h_step, _getHeight(x+1, y+1), -yp-v_step)
			var v6 = Vector3(xp+h_step, _getHeight(x+1, y), -yp)
			
			var side3 = v5-v4
			var side4 = v5-v6
			var normal2 = side3.cross(side4)
			
			verts.append(v1)
			verts.append(v2)
			verts.append(v3)
			verts.append(v4)
			verts.append(v5)
			verts.append(v6)
			
			normals.append(normal1)
			normals.append(normal1)
			normals.append(normal1)
			normals.append(normal2)
			normals.append(normal2)
			normals.append(normal2)
			
			indices.append(curind+0)
			indices.append(curind+1)
			indices.append(curind+2)
			indices.append(curind+3)
			indices.append(curind+4)
			indices.append(curind+5)
			curind = curind+6
	
	var array = []
	array.resize(Mesh.ARRAY_MAX)
	array[Mesh.ARRAY_VERTEX] = verts
	array[Mesh.ARRAY_INDEX] = indices
	array[Mesh.ARRAY_NORMAL] = normals
	a_mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, array)
	mesh = a_mesh



func _getHeight(x, y):
	return height[y][x]


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	pass
