Skip to main content

glory_render/
graphic.rs

1//! Finite vector geometry. No host markup, fonts, resources or GPU objects.
2use crate::Error;
3use glory_style::Color;
4
5pub const MAX_GRAPHIC_COMMANDS: usize = 256;
6pub const MAX_GRAPHIC_COORDINATE: f64 = 1_000_000.0;
7
8#[derive(Clone, Copy, Debug, PartialEq)]
9pub struct GraphicPoint {
10    pub x: f64,
11    pub y: f64,
12}
13impl GraphicPoint {
14    pub const fn new(x: f64, y: f64) -> Self {
15        Self { x, y }
16    }
17    fn validate(self) -> Result<(), Error> {
18        if [self.x, self.y]
19            .into_iter()
20            .any(|value| !value.is_finite() || value.abs() > MAX_GRAPHIC_COORDINATE)
21        {
22            return Err(Error::InvalidProps(
23                "graphic coordinates must be finite and within +/-1000000",
24            ));
25        }
26        Ok(())
27    }
28}
29#[derive(Clone, Copy, Debug, PartialEq)]
30pub enum PathCommand {
31    Move(GraphicPoint),
32    Line(GraphicPoint),
33    Cubic {
34        first: GraphicPoint,
35        second: GraphicPoint,
36        end: GraphicPoint,
37    },
38    Close,
39}
40#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
41pub enum StrokeCap {
42    #[default]
43    Butt,
44    Round,
45    Square,
46}
47#[derive(Clone, Copy, Debug, PartialEq)]
48pub struct GraphicStroke {
49    pub color: Color,
50    pub width: f64,
51    pub cap: StrokeCap,
52}
53
54#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
55pub enum GraphicFit {
56    #[default]
57    Contain,
58    Stretch,
59}
60
61/// One nonzero-winding path, contained by default or explicitly stretched.
62/// Geometry is clipped to that box. Multiple colors are separate semantic nodes.
63#[derive(Clone, Debug, PartialEq)]
64pub struct GraphicProps {
65    pub width: f64,
66    pub height: f64,
67    pub fit: GraphicFit,
68    pub commands: Vec<PathCommand>,
69    pub fill: Option<Color>,
70    pub stroke: Option<GraphicStroke>,
71    /// `None` explicitly decorates the graphic; text must not be announced twice.
72    pub alternative: Option<String>,
73    pub animation: Option<crate::GraphicAnimation>,
74    pub transition: Option<crate::GraphicTransition>,
75}
76impl Default for GraphicProps {
77    fn default() -> Self {
78        Self {
79            width: 24.0,
80            height: 24.0,
81            fit: GraphicFit::Contain,
82            commands: Vec::new(),
83            fill: None,
84            stroke: None,
85            alternative: None,
86            animation: None,
87            transition: None,
88        }
89    }
90}
91impl GraphicProps {
92    pub(crate) fn transition_from(&self, previous: &Self) -> Result<(), Error> {
93        if self.transition.is_some()
94            && !crate::GraphicTransition::compatible(&previous.commands, &self.commands)
95        {
96            return Err(Error::InvalidProps(
97                "graphic transition requires compatible command topology",
98            ));
99        }
100        Ok(())
101    }
102    pub fn validate(&self) -> Result<(), Error> {
103        if let Some(transition) = self.transition {
104            transition.validate()?;
105            if self.animation.is_some() {
106                return Err(Error::InvalidProps(
107                    "graphic animation and transition are mutually exclusive",
108                ));
109            }
110        }
111        if let Some(animation) = self.animation {
112            animation.validate()?;
113        }
114        if [self.width, self.height].into_iter().any(|value| {
115            !value.is_finite() || !(0.000001..=MAX_GRAPHIC_COORDINATE).contains(&value)
116        }) {
117            return Err(Error::InvalidProps(
118                "graphic viewport dimensions must be finite and in 0.000001..=1000000",
119            ));
120        }
121        if self.commands.len() > MAX_GRAPHIC_COMMANDS {
122            return Err(Error::InvalidProps(
123                "graphic path exceeds its 256 command budget",
124            ));
125        }
126        if self
127            .alternative
128            .as_ref()
129            .is_some_and(|text| text.trim().is_empty() || text.len() > 1024)
130        {
131            return Err(Error::InvalidProps(
132                "graphic alternative must be nonempty and at most 1024 UTF-8 bytes",
133            ));
134        }
135        if self.stroke.is_some_and(|stroke| {
136            !stroke.width.is_finite() || !(0.000001..=10000.0).contains(&stroke.width)
137        }) {
138            return Err(Error::InvalidProps(
139                "graphic stroke width must be finite and in 0.000001..=10000",
140            ));
141        }
142        let mut open = false;
143        for command in &self.commands {
144            match command {
145                PathCommand::Move(point) => {
146                    point.validate()?;
147                    open = true;
148                }
149                PathCommand::Line(point) => {
150                    if !open {
151                        return Err(Error::InvalidProps(
152                            "graphic segments require a preceding Move",
153                        ));
154                    }
155                    point.validate()?;
156                }
157                PathCommand::Cubic { first, second, end } => {
158                    if !open {
159                        return Err(Error::InvalidProps(
160                            "graphic segments require a preceding Move",
161                        ));
162                    }
163                    first.validate()?;
164                    second.validate()?;
165                    end.validate()?;
166                }
167                PathCommand::Close => {
168                    if !open {
169                        return Err(Error::InvalidProps(
170                            "graphic Close requires an open subpath",
171                        ));
172                    }
173                    open = false;
174                }
175            }
176        }
177        Ok(())
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184    fn point() -> GraphicPoint {
185        GraphicPoint::new(1.0, 2.0)
186    }
187    #[test]
188    fn every_command_checks_order_and_all_coordinates() {
189        let mut props = GraphicProps::default();
190        for command in [
191            PathCommand::Line(point()),
192            PathCommand::Cubic {
193                first: point(),
194                second: point(),
195                end: point(),
196            },
197            PathCommand::Close,
198        ] {
199            props.commands = vec![command];
200            assert!(props.validate().is_err());
201        }
202        for value in [
203            f64::NAN,
204            f64::INFINITY,
205            f64::NEG_INFINITY,
206            1_000_001.0,
207            -1_000_001.0,
208        ] {
209            for bad in [GraphicPoint::new(value, 0.0), GraphicPoint::new(0.0, value)] {
210                for command in [
211                    PathCommand::Move(bad),
212                    PathCommand::Line(bad),
213                    PathCommand::Cubic {
214                        first: bad,
215                        second: point(),
216                        end: point(),
217                    },
218                    PathCommand::Cubic {
219                        first: point(),
220                        second: bad,
221                        end: point(),
222                    },
223                    PathCommand::Cubic {
224                        first: point(),
225                        second: point(),
226                        end: bad,
227                    },
228                ] {
229                    props.commands = vec![PathCommand::Move(point()), command];
230                    assert!(props.validate().is_err());
231                }
232            }
233        }
234        props.commands = vec![
235            PathCommand::Move(point()),
236            PathCommand::Line(point()),
237            PathCommand::Cubic {
238                first: point(),
239                second: point(),
240                end: point(),
241            },
242            PathCommand::Close,
243            PathCommand::Move(point()),
244        ];
245        props.validate().unwrap();
246        props.commands.push(PathCommand::Close);
247        props.commands.push(PathCommand::Close);
248        assert!(props.validate().is_err());
249    }
250    #[test]
251    fn viewport_stroke_alternative_and_command_budgets_are_independent() {
252        for value in [0.0, -1.0, f64::NAN, f64::INFINITY, 0.0000001, 1_000_001.0] {
253            assert!(
254                GraphicProps {
255                    width: value,
256                    ..Default::default()
257                }
258                .validate()
259                .is_err()
260            );
261            assert!(
262                GraphicProps {
263                    height: value,
264                    ..Default::default()
265                }
266                .validate()
267                .is_err()
268            );
269        }
270        for width in [0.0, -1.0, f64::NAN, f64::INFINITY, 0.0000001, 10001.0] {
271            assert!(
272                GraphicProps {
273                    stroke: Some(GraphicStroke {
274                        color: Color(0, 0, 0, 255),
275                        width,
276                        cap: StrokeCap::Butt
277                    }),
278                    ..Default::default()
279                }
280                .validate()
281                .is_err()
282            );
283        }
284        for cap in [StrokeCap::Butt, StrokeCap::Round, StrokeCap::Square] {
285            GraphicProps {
286                stroke: Some(GraphicStroke {
287                    color: Color(0, 0, 0, 255),
288                    width: 1.0,
289                    cap,
290                }),
291                ..Default::default()
292            }
293            .validate()
294            .unwrap();
295        }
296        for alternative in ["".to_string(), " ".to_string(), "x".repeat(1025)] {
297            assert!(
298                GraphicProps {
299                    alternative: Some(alternative),
300                    ..Default::default()
301                }
302                .validate()
303                .is_err()
304            );
305        }
306        let mut props = GraphicProps {
307            commands: vec![PathCommand::Move(point()); 256],
308            ..Default::default()
309        };
310        props.validate().unwrap();
311        props.commands.push(PathCommand::Move(point()));
312        assert!(props.validate().is_err());
313    }
314}