#pragma once
/**
 * @file grid_allocator.h
 * @brief 网格式纹理分配算法
 */
#include "atlas_allocator.h"
#include <vector>

/**
 * @class grid_allocator
 * @brief 网格式纹理分配算法
 */
class grid_allocator : public atlas_allocator {
public:
	/**
	 * @brief 构造函数
	 * @param size 分配区域的总大小
	 * @param cell_size 单元格大小
	 */
	grid_allocator(const Eigen::Vector2i& size, const Eigen::Vector2i& cell_size);
	~grid_allocator() override = default;

	std::optional<rect_t<int32_t>> allocate(const Eigen::Vector2i& size) override;
	bool free(const rect_t<int32_t>& rect) override;
	void reset() override;
	void resize(const Eigen::Vector2i& new_size) override;
	int total_area() const override;
	int allocated_area() const override;

private:
	Eigen::Vector2i size_;
	Eigen::Vector2i cell_size_;
	Eigen::Vector2i grid_dims_;
	std::vector<bool> cells_;
	int allocated_cells_ = 0;

	// 计算网格索引
	int cell_index(int x, int y) const;

	// 查找可容纳纹理的网格起始位置
	std::optional<Eigen::Vector2i> find_free_cells(const Eigen::Vector2i& num_cells);
};
