fennel_core/resources/
font.rs

1use anyhow::bail;
2use std::{
3    path::PathBuf,
4    rc::Rc,
5};
6
7use crate::{graphics::Graphics, resources::LoadableResource};
8
9/// Font asset
10pub struct Font {
11    /// Filesystem path to the font.
12    pub path: PathBuf,
13    /// Font family name
14    pub family_name: String,
15    /// Internal name
16    name: String,
17    /// Point size
18    pub size: f32,
19    /// Smart pointer to sdl3's `Font`
20    pub buffer: Rc<sdl3::ttf::Font<'static>>,
21}
22
23/// Font asset to be able to use fonts of various sizes
24pub struct DummyFont {
25    /// Filesystem path to the font.
26    pub path: PathBuf,
27    /// Internal name
28    name: String,
29}
30
31impl LoadableResource for DummyFont {
32    fn load(
33        path: PathBuf,
34        name: String,
35        _graphics: &mut Graphics,
36        _size: Option<f32>,
37    ) -> anyhow::Result<Box<dyn LoadableResource>>
38    where
39        Self: Sized, {
40
41        Ok(Box::new(Self {
42            path,
43            name,
44        }))
45    }
46
47    fn name(&self) -> String {
48        self.name.to_string()
49    }
50}
51impl LoadableResource for Font {
52    // TODO: improve font internal naming, it's quite confusing as of now
53    fn load(
54        path: PathBuf,
55        name: String,
56        graphics: &mut Graphics,
57        size: Option<f32>,
58    ) -> anyhow::Result<Box<dyn LoadableResource>>
59    where
60        Self: Sized,
61    {
62        if size.is_none() {
63            bail!("no font size was provided");
64        }
65        let font = graphics.ttf_context.load_font(&path, size.unwrap())?;
66        Ok(Box::new(Self {
67            path,
68            family_name: font
69                .face_family_name()
70                .expect("failed to get font family name"),
71            name,
72            size: size.unwrap(),
73            buffer: Rc::new(font),
74        }))
75    }
76
77    fn name(&self) -> String {
78        self.name.to_string()
79    }
80}