use bevy_asset::{AssetEvent, AssetId, Assets, RenderAssetUsages};
use bevy_ecs::{event::EventReader, resource::Resource, system::ResMut};
use bevy_image::prelude::*;
use bevy_math::{IVec2, UVec2};
use bevy_platform::collections::HashMap;
use bevy_reflect::TypePath;
use wgpu_types::{Extent3d, TextureDimension, TextureFormat};
use crate::{error::TextError, Font, FontAtlas, FontSmoothing, GlyphAtlasInfo};
#[derive(Debug, Default, Resource)]
pub struct FontAtlasSets {
pub(crate) sets: HashMap<AssetId<Font>, FontAtlasSet>,
}
impl FontAtlasSets {
pub fn get(&self, id: impl Into<AssetId<Font>>) -> Option<&FontAtlasSet> {
let id: AssetId<Font> = id.into();
self.sets.get(&id)
}
pub fn get_mut(&mut self, id: impl Into<AssetId<Font>>) -> Option<&mut FontAtlasSet> {
let id: AssetId<Font> = id.into();
self.sets.get_mut(&id)
}
}
pub fn remove_dropped_font_atlas_sets(
mut font_atlas_sets: ResMut<FontAtlasSets>,
mut font_events: EventReader<AssetEvent<Font>>,
) {
for event in font_events.read() {
if let AssetEvent::Removed { id } = event {
font_atlas_sets.sets.remove(id);
}
}
}
#[derive(Debug, Hash, PartialEq, Eq)]
pub struct FontAtlasKey(pub u32, pub FontSmoothing);
#[derive(Debug, TypePath)]
pub struct FontAtlasSet {
font_atlases: HashMap<FontAtlasKey, Vec<FontAtlas>>,
}
impl Default for FontAtlasSet {
fn default() -> Self {
FontAtlasSet {
font_atlases: HashMap::with_capacity_and_hasher(1, Default::default()),
}
}
}
impl FontAtlasSet {
pub fn iter(&self) -> impl Iterator<Item = (&FontAtlasKey, &Vec<FontAtlas>)> {
self.font_atlases.iter()
}
pub fn has_glyph(&self, cache_key: cosmic_text::CacheKey, font_size: &FontAtlasKey) -> bool {
self.font_atlases
.get(font_size)
.is_some_and(|font_atlas| font_atlas.iter().any(|atlas| atlas.has_glyph(cache_key)))
}
pub fn add_glyph_to_atlas(
&mut self,
texture_atlases: &mut Assets<TextureAtlasLayout>,
textures: &mut Assets<Image>,
font_system: &mut cosmic_text::FontSystem,
swash_cache: &mut cosmic_text::SwashCache,
layout_glyph: &cosmic_text::LayoutGlyph,
font_smoothing: FontSmoothing,
) -> Result<GlyphAtlasInfo, TextError> {
let physical_glyph = layout_glyph.physical((0., 0.), 1.0);
let font_atlases = self
.font_atlases
.entry(FontAtlasKey(
physical_glyph.cache_key.font_size_bits,
font_smoothing,
))
.or_insert_with(|| {
vec![FontAtlas::new(
textures,
texture_atlases,
UVec2::splat(512),
font_smoothing,
)]
});
let (glyph_texture, offset) = Self::get_outlined_glyph_texture(
font_system,
swash_cache,
&physical_glyph,
font_smoothing,
)?;
let mut add_char_to_font_atlas = |atlas: &mut FontAtlas| -> Result<(), TextError> {
atlas.add_glyph(
textures,
texture_atlases,
physical_glyph.cache_key,
&glyph_texture,
offset,
)
};
if !font_atlases
.iter_mut()
.any(|atlas| add_char_to_font_atlas(atlas).is_ok())
{
let glyph_max_size: u32 = glyph_texture
.texture_descriptor
.size
.height
.max(glyph_texture.width());
let containing = (1u32 << (32 - glyph_max_size.leading_zeros())).max(512);
font_atlases.push(FontAtlas::new(
textures,
texture_atlases,
UVec2::splat(containing),
font_smoothing,
));
font_atlases.last_mut().unwrap().add_glyph(
textures,
texture_atlases,
physical_glyph.cache_key,
&glyph_texture,
offset,
)?;
}
Ok(self
.get_glyph_atlas_info(physical_glyph.cache_key, font_smoothing)
.unwrap())
}
pub fn get_glyph_atlas_info(
&mut self,
cache_key: cosmic_text::CacheKey,
font_smoothing: FontSmoothing,
) -> Option<GlyphAtlasInfo> {
self.font_atlases
.get(&FontAtlasKey(cache_key.font_size_bits, font_smoothing))
.and_then(|font_atlases| {
font_atlases.iter().find_map(|atlas| {
atlas
.get_glyph_index(cache_key)
.map(|location| GlyphAtlasInfo {
location,
texture_atlas: atlas.texture_atlas.id(),
texture: atlas.texture.id(),
})
})
})
}
pub fn len(&self) -> usize {
self.font_atlases.len()
}
pub fn is_empty(&self) -> bool {
self.font_atlases.len() == 0
}
pub fn get_outlined_glyph_texture(
font_system: &mut cosmic_text::FontSystem,
swash_cache: &mut cosmic_text::SwashCache,
physical_glyph: &cosmic_text::PhysicalGlyph,
font_smoothing: FontSmoothing,
) -> Result<(Image, IVec2), TextError> {
let image = swash_cache
.get_image_uncached(font_system, physical_glyph.cache_key)
.ok_or(TextError::FailedToGetGlyphImage(physical_glyph.cache_key))?;
let cosmic_text::Placement {
left,
top,
width,
height,
} = image.placement;
let data = match image.content {
cosmic_text::SwashContent::Mask => {
if font_smoothing == FontSmoothing::None {
image
.data
.iter()
.flat_map(|a| [255, 255, 255, if *a > 127 { 255 } else { 0 }])
.collect()
} else {
image
.data
.iter()
.flat_map(|a| [255, 255, 255, *a])
.collect()
}
}
cosmic_text::SwashContent::Color => image.data,
cosmic_text::SwashContent::SubpixelMask => {
todo!()
}
};
Ok((
Image::new(
Extent3d {
width,
height,
depth_or_array_layers: 1,
},
TextureDimension::D2,
data,
TextureFormat::Rgba8UnormSrgb,
RenderAssetUsages::MAIN_WORLD,
),
IVec2::new(left, top),
))
}
}