gemini_engine/primitives/
triangle.rs1use crate::core::{CanDraw, ColChar, Vec2D};
2
3use super::Line;
4
5pub struct Triangle {
7 pub corners: [Vec2D; 3],
9 pub fill_char: ColChar,
11}
12
13impl Triangle {
14 #[must_use]
16 pub const fn new(pos0: Vec2D, pos1: Vec2D, pos2: Vec2D, fill_char: ColChar) -> Self {
17 Self::with_array([pos0, pos1, pos2], fill_char)
18 }
19
20 #[must_use]
22 pub const fn with_array(corners: [Vec2D; 3], fill_char: ColChar) -> Self {
23 Self { corners, fill_char }
24 }
25}
26
27impl CanDraw for Triangle {
28 fn draw_to(&self, canvas: &mut impl crate::core::Canvas) {
29 let mut corners = self.corners;
30 corners.sort_unstable_by_key(|k| k.y);
31 let (x0, y0) = corners[0].into();
32 let (x1, y1) = corners[1].into();
33 let (x2, y2) = corners[2].into();
34
35 let mut x01 = super::interpolate(y0, x0, y1, x1);
36 let x12 = super::interpolate(y1, x1, y2, x2);
37 let x02 = super::interpolate(y0, x0, y2, x2);
38
39 x01.pop();
41 let x01_12 = [x01, x12].concat();
42
43 let m = (x01_12.len() as f64 / 2.0).floor() as usize;
44 let (x_left, x_right) = if x02[m] < x01_12[m] {
45 (x02, x01_12)
46 } else {
47 (x01_12, x02)
48 };
49
50 for (i, y) in (y0..y2).enumerate() {
51 for x in x_left[i]..x_right[i] {
52 canvas.plot(Vec2D::new(x, y), self.fill_char);
53 }
54 }
55
56 Line::new(corners[0], corners[1], self.fill_char).draw_to(canvas);
58 Line::new(corners[1], corners[2], self.fill_char).draw_to(canvas);
59 Line::new(corners[2], corners[0], self.fill_char).draw_to(canvas);
60 }
61}