console_display/
drawing.rs

1use core::f32;
2use std::marker::PhantomData;
3
4use num_traits::NumCast;
5
6use crate::{
7    pixel::Pixel,
8    widget::DynamicWidget,
9};
10
11/// Defines a fill for a drawable.
12#[const_trait]
13pub trait FillType {}
14
15/// Defines no fill on a drawable, e.g. only outline.
16#[derive(PartialEq, Eq, Debug)]
17pub struct NoFill;
18impl const FillType for NoFill {}
19
20/// Defines flat fill on a drawable.
21#[derive(PartialEq, Eq, Debug)]
22pub struct Filled;
23impl const FillType for Filled {}
24
25/// Defines an object that you can draw on and query pixels from.
26#[const_trait]
27pub trait DynamicCanvas<S: Pixel>: DynamicWidget {
28    type A: NumCast;
29    /// Returns a bool representing the state of the pixel at the specified coordinate.
30    ///
31    /// # Examples
32    ///
33    /// ```
34    /// #![allow(incomplete_features)]
35    /// #![feature(generic_const_exprs)]
36    ///
37    /// use console_display::{
38    ///     console_display::DynamicConsoleDisplay,
39    ///     display_driver::DisplayDriver,
40    ///     pixel::monochrome_pixel::SinglePixel,
41    ///     pixel_display::DynamicPixelDisplay,
42    ///     drawing::DynamicCanvas
43    /// };
44    ///
45    /// let disp: DisplayDriver<DynamicPixelDisplay<SinglePixel>> = DisplayDriver::new(
46    ///     DynamicPixelDisplay::<SinglePixel>::build_from_data(
47    ///         6,
48    ///         6,
49    ///         &vec![
50    ///             true, true, true, true,  true, true, // 0
51    ///             true, true, true, true,  true, true, // 1
52    ///             true, true, true, false, true, true, //-2-
53    ///             true, true, true, true,  true, true, // 3
54    ///             true, true, true, true,  true, true, // 4
55    ///             true, true, true, true,  true, true, // 5
56    ///         ] //  0     1     2   --3--    4     5
57    ///     ).expect("Could not construct display.")
58    /// );
59    /// // Replace with actual error handling
60    ///
61    /// let pixel = disp.pixel(3, 2);
62    ///
63    /// assert_eq!(pixel, Ok(false));
64    ///
65    /// let pixel = disp.pixel(5, 6);
66    ///
67    /// assert!(matches!(pixel, Err(_)));
68    /// ```
69    ///
70    /// # Errors
71    ///
72    /// Returns an error if the pixel coordinates are out of bounds.
73    ///
74    /// # Panics
75    ///
76    /// If the index of a subpixel is out of bounds.
77    /// This should not happen and is subject to change in the future.
78    fn pixel(&self, x: Self::A, y: Self::A) -> Result<S::U, String>
79    where
80        [(); S::WIDTH * S::HEIGHT]:;
81
82    /// Set a pixel at the specified coordinate with a given value.
83    ///
84    /// # Errors
85    ///
86    /// Returns an error if the pixel coordinates are out of bounds.
87    ///
88    /// # Panics
89    ///
90    /// If the index of a subpixel is out of bounds.
91    /// This should not happen and is subject to change in the future.
92    fn set_pixel(
93        &mut self,
94        x: Self::A,
95        y: Self::A,
96        value: S::U,
97    ) -> Result<(), String>
98    where
99        [(); S::WIDTH * S::HEIGHT]:;
100
101    /// Draw a drawable/shape onto a canvas with the specified pixel type/brush.
102    /// Convenience method for inversing `DynamicDrawable::draw` by using double dispatch.
103    fn draw<D: [const] DynamicDrawable<N>, const N: usize>(
104        &mut self,
105        drawable: &D,
106        value: S::U,
107    ) where
108        Self: Sized,
109        [(); S::WIDTH * S::HEIGHT]:,
110    {
111        drawable.draw(self, value);
112    }
113}
114
115/// Defines an object that can be drawn onto a canvas.
116#[const_trait]
117pub trait DynamicDrawable<const N: usize> {
118    /// Draws the drawable onto a canvas with the specified pixel type/brush.
119    fn draw<T: DynamicCanvas<S>, S: Pixel>(
120        &self,
121        display: &mut T,
122        value: S::U,
123    ) where
124        [(); S::WIDTH * S::HEIGHT]:;
125
126    /// Transforms the drawable by applying a function to all coordinate pairs that define it.
127    /// Returns a new transformed drawable.
128    #[must_use]
129    fn transform<F: [const] Fn((f32, f32)) -> (f32, f32)>(
130        &self,
131        transform: F,
132    ) -> Self;
133}
134
135/// Defines a line primitive by two endpoints.
136#[derive(PartialEq, Debug)]
137pub struct Line {
138    pub x1: f32,
139    pub y1: f32,
140    pub x2: f32,
141    pub y2: f32,
142}
143
144impl DynamicDrawable<2> for Line {
145    fn draw<T: DynamicCanvas<S>, S: Pixel>(
146        &self,
147        display: &mut T,
148        value: S::U,
149    ) where
150        [(); S::WIDTH * S::HEIGHT]:,
151    {
152        let dx = self.x2 - self.x1;
153        let dy = self.y2 - self.y1;
154
155        let steps: f32 = dx.abs().max(dy.abs());
156        let x_inc = dx / steps;
157        let y_inc = dy / steps;
158
159        let mut x = self.x1;
160        let mut y = self.y1;
161
162        #[allow(clippy::cast_possible_truncation)]
163        #[allow(clippy::cast_sign_loss)]
164        for _ in 0..=steps.round() as usize {
165            if x > -0.5 && y > -0.5 {
166                let x = NumCast::from(x.round());
167                let y = NumCast::from(y.round());
168                if let Some(x) = x &&
169                    let Some(y) = y
170                {
171                    let _ = display.set_pixel(x, y, value);
172                }
173            }
174            x += x_inc;
175            y += y_inc;
176        }
177    }
178
179    fn transform<F: Fn((f32, f32)) -> (f32, f32)>(
180        &self,
181        transform: F,
182    ) -> Self {
183        let trans_p1 = transform((self.x1, self.y1));
184        let trans_p2 = transform((self.x2, self.y2));
185        Self {
186            x1: trans_p1.0,
187            y1: trans_p1.1,
188            x2: trans_p2.0,
189            y2: trans_p2.1,
190        }
191    }
192}
193
194/// Defines a Rectangle by two corners.
195#[derive(PartialEq, Debug)]
196pub struct Rectangle<FILL: FillType> {
197    pub x1: f32,
198    pub y1: f32,
199    pub x2: f32,
200    pub y2: f32,
201    pub fill: PhantomData<FILL>,
202}
203
204impl DynamicDrawable<2> for Rectangle<NoFill> {
205    fn draw<T: DynamicCanvas<S>, S: Pixel>(
206        &self,
207        display: &mut T,
208        value: S::U,
209    ) where
210        [(); S::WIDTH * S::HEIGHT]:,
211    {
212        let lines = [
213            Line {
214                x1: self.x1,
215                y1: self.y1,
216                x2: self.x2,
217                y2: self.y1,
218            },
219            Line {
220                x1: self.x1,
221                y1: self.y2,
222                x2: self.x2,
223                y2: self.y2,
224            },
225            Line {
226                x1: self.x1,
227                y1: self.y1,
228                x2: self.x1,
229                y2: self.y2,
230            },
231            Line {
232                x1: self.x2,
233                y1: self.y1,
234                x2: self.x2,
235                y2: self.y2,
236            },
237        ];
238
239        for line in lines {
240            line.draw(display, value);
241        }
242    }
243
244    fn transform<F: Fn((f32, f32)) -> (f32, f32)>(
245        &self,
246        transform: F,
247    ) -> Self {
248        let trans_p1 = transform((self.x1, self.y1));
249        let trans_p2 = transform((self.x2, self.y2));
250        Self {
251            x1: trans_p1.0,
252            y1: trans_p1.1,
253            x2: trans_p2.0,
254            y2: trans_p2.1,
255            fill: PhantomData::<NoFill>,
256        }
257    }
258}
259
260impl DynamicDrawable<2> for Rectangle<Filled> {
261    fn draw<T: DynamicCanvas<S>, S: Pixel>(
262        &self,
263        display: &mut T,
264        value: S::U,
265    ) where
266        [(); S::WIDTH * S::HEIGHT]:,
267    {
268        #[allow(clippy::cast_possible_truncation)]
269        for x in self.x1.round() as i32..=self.x2.round() as i32 {
270            let line = Line {
271                x1: x as f32,
272                y1: self.y1,
273                x2: x as f32,
274                y2: self.y2,
275            };
276            line.draw(display, value);
277        }
278    }
279
280    fn transform<F: Fn((f32, f32)) -> (f32, f32)>(
281        &self,
282        transform: F,
283    ) -> Self {
284        let trans_p1 = transform((self.x1, self.y1));
285        let trans_p2 = transform((self.x2, self.y2));
286        Self {
287            x1: trans_p1.0,
288            y1: trans_p1.1,
289            x2: trans_p2.0,
290            y2: trans_p2.1,
291            fill: PhantomData::<Filled>,
292        }
293    }
294}
295
296// TODO: Check correctness of implementation
297/// Defines a Circle by its midpoint and two vectors from the midpoint to the circumference.
298#[derive(PartialEq, Debug)]
299pub struct Ellipse<FILL: FillType> {
300    pub midpoint_x: f32,
301    pub midpoint_y: f32,
302    pub x1: f32,
303    pub y1: f32,
304    pub x2: f32,
305    pub y2: f32,
306    pub num_points: u32,
307    pub fill: PhantomData<FILL>,
308}
309
310impl DynamicDrawable<3> for Ellipse<NoFill> {
311    fn draw<T: DynamicCanvas<S>, S: Pixel>(
312        &self,
313        display: &mut T,
314        value: S::U,
315    ) where
316        [(); S::WIDTH * S::HEIGHT]:,
317    {
318        let first_point;
319        let mut last_point;
320        let x = self.midpoint_x + self.x1;
321        let y = self.midpoint_y + self.y1;
322        let x = NumCast::from(x.round());
323        let y = NumCast::from(y.round());
324        if let Some(x) = x &&
325            let Some(y) = y
326        {
327            first_point = (x, y);
328            last_point = (x, y);
329        }
330        else {
331            return;
332        }
333
334        for i in 1..self.num_points {
335            let angle =
336                f32::consts::TAU / self.num_points as f32 * i as f32;
337            let x = self.x2.mul_add(
338                f32::sin(angle),
339                self.x1.mul_add(f32::cos(angle), self.midpoint_x),
340            );
341            let y = self.y2.mul_add(
342                f32::sin(angle),
343                self.y1.mul_add(f32::cos(angle), self.midpoint_y),
344            );
345            let x = NumCast::from(x.round());
346            let y = NumCast::from(y.round());
347            if let Some(x) = x &&
348                let Some(y) = y
349            {
350                display.draw(
351                    &Line {
352                        x1: last_point.0,
353                        y1: last_point.1,
354                        x2: x,
355                        y2: y,
356                    },
357                    value,
358                );
359                last_point = (x, y);
360            }
361            else {
362                return;
363            }
364        }
365
366        display.draw(
367            &Line {
368                x1: last_point.0,
369                y1: last_point.1,
370                x2: first_point.0,
371                y2: first_point.1,
372            },
373            value,
374        );
375    }
376
377    fn transform<F: Fn((f32, f32)) -> (f32, f32)>(
378        &self,
379        transform: F,
380    ) -> Self {
381        let trans_mid = transform((self.midpoint_x, self.midpoint_y));
382        let trans_p1 = transform((self.x1, self.y1));
383        let trans_p2 = transform((self.x2, self.y2));
384        Self {
385            midpoint_x: trans_mid.0,
386            midpoint_y: trans_mid.1,
387            x1: trans_p1.0,
388            y1: trans_p1.1,
389            x2: trans_p2.0,
390            y2: trans_p2.1,
391            num_points: self.num_points,
392            fill: PhantomData::<NoFill>,
393        }
394    }
395}
396
397#[cfg(test)]
398mod tests {
399    mod line {
400        use crate::drawing::{
401            DynamicDrawable,
402            Line,
403        };
404
405        #[test]
406        fn transform() {
407            let expected = Line {
408                x1: 1.,
409                y1: 1.,
410                x2: 3.,
411                y2: 3.,
412            };
413            let line = Line {
414                x1: 0.,
415                y1: 1.,
416                x2: 2.,
417                y2: 3.,
418            };
419            let transform = line.transform(|(x, y)| (x + 1., y));
420            assert_eq!(expected, transform);
421        }
422    }
423
424    mod rectagle {
425        use std::marker::PhantomData;
426
427        use crate::drawing::{
428            DynamicDrawable,
429            NoFill,
430            Rectangle,
431        };
432
433        #[test]
434        fn transform() {
435            let expected = Rectangle {
436                x1: -10.,
437                y1: -10.,
438                x2: 10.,
439                y2: 10.,
440                fill: PhantomData::<NoFill>,
441            };
442            let rect = Rectangle {
443                x1: 0.,
444                y1: 0.,
445                x2: 10.,
446                y2: 20.,
447                fill: PhantomData::<NoFill>,
448            };
449            let transform = rect.transform(|(x, y)| {
450                (if x == 0. { -10. } else { x }, y - 10.)
451            });
452            assert_eq!(expected, transform);
453        }
454    }
455}