Skip to main content

mln_engine/text/
atlas.rs

1//! Where images and glyphs are in an atlas.
2
3use mln_style::image::{ImageContent, ImageStretches, Impl, TextFit};
4
5/// A rectangle of an atlas, in pixels.
6#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, mln_wire::Wire)]
7pub struct RectU16 {
8    pub x: u16,
9    pub y: u16,
10    pub w: u16,
11    pub h: u16,
12}
13
14/// An image's place in an atlas.
15#[derive(Clone, Debug, PartialEq, mln_wire::Wire)]
16pub struct ImagePosition {
17    pub padded_rect: RectU16,
18    pub pixel_ratio: f32,
19    pub sdf: bool,
20    pub stretch_x: ImageStretches,
21    pub stretch_y: ImageStretches,
22    pub content: Option<ImageContent>,
23    pub text_fit_width: Option<TextFit>,
24    pub text_fit_height: Option<TextFit>,
25}
26
27impl ImagePosition {
28    pub const PADDING: u16 = 1;
29
30    #[must_use]
31    pub fn new(rect: RectU16, image: &Impl) -> Self {
32        ImagePosition {
33            padded_rect: rect,
34            pixel_ratio: image.pixel_ratio,
35            sdf: image.sdf,
36            stretch_x: image.stretch_x.clone(),
37            stretch_y: image.stretch_y.clone(),
38            content: image.content,
39            text_fit_width: image.text_fit_width,
40            text_fit_height: image.text_fit_height,
41        }
42    }
43
44    /// The top-left corner inside the padding; the sums are computed in `i32`
45    /// and narrowed to `u16`, as in C++.
46    #[must_use]
47    pub fn tl(&self) -> [u16; 2] {
48        [
49            (i32::from(self.padded_rect.x) + i32::from(Self::PADDING)) as u16,
50            (i32::from(self.padded_rect.y) + i32::from(Self::PADDING)) as u16,
51        ]
52    }
53
54    #[must_use]
55    pub fn br(&self) -> [u16; 2] {
56        [
57            (i32::from(self.padded_rect.x) + i32::from(self.padded_rect.w) - i32::from(Self::PADDING)) as u16,
58            (i32::from(self.padded_rect.y) + i32::from(self.padded_rect.h) - i32::from(Self::PADDING)) as u16,
59        ]
60    }
61
62    #[must_use]
63    pub fn tlbr(&self) -> [u16; 4] {
64        let tl = self.tl();
65        let br = self.br();
66        [tl[0], tl[1], br[0], br[1]]
67    }
68
69    #[must_use]
70    pub fn display_size(&self) -> [f32; 2] {
71        [
72            (i32::from(self.padded_rect.w) - i32::from(Self::PADDING) * 2) as f32 / self.pixel_ratio,
73            (i32::from(self.padded_rect.h) - i32::from(Self::PADDING) * 2) as f32 / self.pixel_ratio,
74        ]
75    }
76}
77
78/// The places of the images of a layout, by id.
79pub type ImagePositions = mln_style::hash::HashMap<String, ImagePosition>;