#include "bitmap_glyph_atlas.h"

#include "interface/image_interface.h"

glyph_atlas_result_t bitmap_glyph_atlas::create_glyph(const char_key_t& in_key) {
	const auto& glyph_index = in_key.glyph_index;
	const auto& font      = in_key.font_face;
	const auto& font_size = in_key.font_size;

	glyph_atlas_result_t result{};

	font->set_font_size(font_size);

	// 获取字形的位图数据
	auto bitmap = font->get_glyph_image(glyph_index);
	if (!bitmap) {
		result.reason = glyph_atlas_reason_t::glyph_not_found;
		return result;
	}

	// 从图集分配空间，添加2像素的padding防止纹理采样时的边缘混合问题
	const auto& region = atlas_->allocate_region(bitmap->get_size(), { 2, 2 });
	if (!region) {
		result.reason = glyph_atlas_reason_t::atlas_full;
		return result;
	}

	// 更新图集，将位图数据上传到纹理
	atlas_->update_region(bitmap->data, bitmap->get_data_size(), region->rect);

	// 缓存结果以便未来复用
	add_to_cache(in_key, *region);

	result.reason = glyph_atlas_reason_t::success;
	result.region = *region;

	return result;
}
