1use crate::aes::Aesthetic;
2use crate::coord::Coord;
3use crate::data::DataFrame;
4use crate::position::identity::PositionIdentity;
5use crate::position::Position;
6use crate::render::backend::{DrawBackend, RectStyle};
7use crate::render::RenderError;
8use crate::scale::ScaleSet;
9use crate::stat::identity::StatIdentity;
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15pub struct GeomTile {
17 pub fill: (u8, u8, u8),
18 pub color: (u8, u8, u8),
19 pub alpha: f64,
20 pub width: f64,
21 pub height: f64,
22 pub line_width: f64,
23}
24
25impl Default for GeomTile {
26 fn default() -> Self {
27 GeomTile {
28 fill: (97, 156, 255),
29 color: (50, 50, 50),
30 alpha: 1.0,
31 width: 1.0,
32 height: 1.0,
33 line_width: 0.5,
34 }
35 }
36}
37
38impl Geom for GeomTile {
39 fn draw(
40 &self,
41 data: &DataFrame,
42 coord: &dyn Coord,
43 scales: &ScaleSet,
44 _theme: &Theme,
45 backend: &mut dyn DrawBackend,
46 ) -> Result<(), RenderError> {
47 let x_col = data
48 .column("x")
49 .ok_or(RenderError::MissingAesthetic("x".into()))?;
50 let y_col = data
51 .column("y")
52 .ok_or(RenderError::MissingAesthetic("y".into()))?;
53 let fill_col = data.column("fill");
54
55 let plot_area = backend.plot_area();
56 let x_scale = scales.get(&Aesthetic::X);
57 let y_scale = scales.get(&Aesthetic::Y);
58
59 let half_w = self.width / 2.0;
60 let half_h = self.height / 2.0;
61
62 for i in 0..data.nrows() {
63 let cx = x_col[i].as_f64().unwrap_or(0.0);
64 let cy = y_col[i].as_f64().unwrap_or(0.0);
65
66 let nxmin = x_scale
67 .map(|s| s.map(&crate::data::Value::Float(cx - half_w)))
68 .unwrap_or(0.0);
69 let nxmax = x_scale
70 .map(|s| s.map(&crate::data::Value::Float(cx + half_w)))
71 .unwrap_or(0.0);
72 let nymin = y_scale
73 .map(|s| s.map(&crate::data::Value::Float(cy - half_h)))
74 .unwrap_or(0.0);
75 let nymax = y_scale
76 .map(|s| s.map(&crate::data::Value::Float(cy + half_h)))
77 .unwrap_or(0.0);
78
79 let (left, top) = coord.transform((nxmin, nymax), &plot_area);
80 let (right, bottom) = coord.transform((nxmax, nymin), &plot_area);
81
82 let fill_color = fill_col
83 .and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[i]))
84 .unwrap_or(self.fill);
85
86 backend.draw_rect(
87 (left, top.min(bottom)),
88 (right, top.max(bottom)),
89 &RectStyle {
90 fill: Some(fill_color),
91 stroke: Some(self.color),
92 stroke_width: self.line_width,
93 alpha: self.alpha,
94 clip: true,
95 },
96 )?;
97 }
98
99 Ok(())
100 }
101
102 fn required_aes(&self) -> Vec<Aesthetic> {
103 vec![Aesthetic::X, Aesthetic::Y]
104 }
105
106 fn default_stat(&self) -> Box<dyn Stat> {
107 Box::new(StatIdentity)
108 }
109
110 fn default_position(&self) -> Box<dyn Position> {
111 Box::new(PositionIdentity)
112 }
113
114 fn default_params(&self) -> GeomParams {
115 GeomParams::default()
116 }
117
118 fn name(&self) -> &str {
119 "tile"
120 }
121
122 fn set_series_color(&mut self, color: (u8, u8, u8)) {
123 self.fill = color;
124 }
125}