# Hurry Curry! - a game about cooking
# Copyright (C) 2026 Hurry Curry! Contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, version 3 of the License only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
class_name GrassMesher
extends FloorMesher

const GRASS_MESH: Mesh = preload("res://map/tiles/grass_side.tres")
var multimesh_instance := MultiMeshInstance3D.new()

var no_grass_tiles: Dictionary[String, Vector2i] = {}

func _init(mesh: MeshInstance3D) -> void:
	super(mesh)
	mesh_instance.add_child(multimesh_instance)

func add_tile(pos: Vector2i, use_no_grass: bool = false):
	super(pos)
	if use_no_grass:
		no_grass_tiles[str(pos)] = pos

func remove_tile(pos: Vector2i):
	super(pos)
	no_grass_tiles.erase(str(pos))

func flush() -> void:
	super()
	var random = RandomNumberGenerator.new()
	random.seed = "gr4ss".hash()

	var multimesh := MultiMesh.new()
	multimesh.mesh = GRASS_MESH
	multimesh.transform_format = MultiMesh.TRANSFORM_3D
	multimesh.instance_count = tiles.size() * Settings.read("graphics.grass_amount")
	var t := tiles.values()
	var no_grass := no_grass_tiles.values()
	for i in multimesh.instance_count:
		var p: Vector2i = t[i / Settings.read("graphics.grass_amount")]
		if p in no_grass: continue
		var origin := Vector3(random.randf_range(-.5, .5), 0.25, random.randf_range(-.5, .5)) + Vector3(p.x + 0.5, 0.0, p.y + 0.5)
		var basis_ := (Basis(Vector3(0, 1, 0), random.randf_range(0, PI)) * Basis(Vector3(1, 0, 0), PI/2)).scaled(Vector3(0.75, 0.5, 0.75))
		multimesh.set_instance_transform(i, Transform3D(basis_, origin))

	multimesh_instance.multimesh = multimesh
