## MapPainter.gd
# Responsible for painting the generated map data onto a TileMapLayer in the scene.
# Handles both floor and wall tiles, using atlas coordinates for floor variety and terrain peering for walls.
class_name MapPainter
extends RefCounted

# The source ID for the floor tile in the TileSet atlas.
const FLOOR_SOURCE_ID: int = 0
# Two different atlas coordinates for floor tiles, used to create a checkerboard effect for visual variety.
const FLOOR_ATLAS_COORDS_1: Vector2i = Vector2i(3, 2)
const FLOOR_ATLAS_COORDS_2: Vector2i = Vector2i(4, 2)

# Terrain set and terrain index for wall tiles, used for Godot's terrain peering system.
const WALL_TERRAIN_SET: int = 0
const WALL_TERRAIN: int = 0

# Paints all tiles from the given MapData onto the provided TileMapLayer.
# Floors are painted with alternating atlas tiles for variety; walls are collected and painted with terrain peering.
func paint(data: MapData, layer: TileMapLayer) -> void:
	layer.clear() # Remove any existing tiles from the layer.
	var wall_cells: Array[Vector2i] = [] # Collect wall tile positions for batch painting.

	for coords: Vector2i in data.grid.keys():
		match data.grid[coords]:
			MapData.TileType.FLOOR:
				# Alternate between two floor atlas tiles for a checkerboard effect.
				var use_first: bool = ((coords.x + coords.y) % 2) == 0
				var atlas_coords: Vector2i = FLOOR_ATLAS_COORDS_1 if use_first else FLOOR_ATLAS_COORDS_2
				layer.set_cell(coords, FLOOR_SOURCE_ID, atlas_coords)
			MapData.TileType.WALL:
				# Collect wall positions for terrain peering.
				wall_cells.append(coords)

	# Use Godot's terrain peering to auto-connect wall tiles for seamless edges/corners.
	layer.set_cells_terrain_connect(wall_cells, WALL_TERRAIN_SET, WALL_TERRAIN, false)
