@tool
extends Node

const TEXTURE_DIR := "res://terrain/jajce/textures"


func _ready() -> void:
	if not Engine.is_editor_hint():
		return
	call_deferred("generate")


func generate() -> void:
	var dir := DirAccess.open(TEXTURE_DIR)
	if not dir:
		DirAccess.make_dir_recursive_absolute(ProjectSettings.globalize_path(TEXTURE_DIR))

	_generate_texture("dirt_path_albedo.png", Color("#8b7355"), Color("#c4a882"), 101)
	_generate_texture("riverbank_stone_albedo.png", Color("#5a6b7a"), Color("#8a9baa"), 102)
	_generate_texture("compacted_ground_albedo.png", Color("#a0845c"), Color("#d4b896"), 103)

	print("[TerrainTextureGenerator] Generated 3 terrain textures")


func _generate_texture(file_name: String, dark: Color, light: Color, seed_val: int) -> void:
	seed(seed_val)
	var grid_size := 16
	var grid: Array[float] = []
	grid.resize(grid_size * grid_size)
	for i in grid_size * grid_size:
		grid[i] = float(randi() % 1000) / 1000.0

	var image := Image.create_empty(256, 256, false, Image.FORMAT_RGBA8)
	var cells := grid_size - 1
	for y in 256:
		var gyf := float(y) / 256.0 * cells
		var gy := clampi(gyf, 0, cells)
		var fy := gyf - gy
		var gy1 := mini(gy + 1, cells)
		for x in 256:
			var gxf := float(x) / 256.0 * cells
			var gx := clampi(gxf, 0, cells)
			var fx := gxf - gx
			var gx1 := mini(gx + 1, cells)

			var v00 := grid[gy * grid_size + gx]
			var v10 := grid[gy * grid_size + gx1]
			var v01 := grid[gy1 * grid_size + gx]
			var v11 := grid[gy1 * grid_size + gx1]

			var vx0 := lerpf(v00, v10, fx)
			var vx1 := lerpf(v01, v11, fx)
			var value := lerpf(vx0, vx1, fy)

			var color := dark.lerp(light, value)
			color.a = 1.0
			image.set_pixel(x, y, color)

	image.generate_mipmaps()
	var err := image.save_png(TEXTURE_DIR.path_join(file_name))
	if err != OK:
		push_error("Failed to save texture: ", file_name, " error: ", err)
