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::binhex::{HexLattice, StatBinHex};
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15fn fallback_hex_size(xs: impl Iterator<Item = f64>, ys: impl Iterator<Item = f64>) -> (f64, f64) {
32 let res_x = super::continuous_bar_half_width(xs, 2.0, 1.0);
33 let res_y = super::continuous_bar_half_width(ys, 2.0, 1.0);
34 (2.0 * res_x, 2.0 * res_y / 3.0_f64.sqrt())
35}
36
37pub struct GeomHex {
43 pub color: (u8, u8, u8),
44 pub alpha: f64,
45 pub line_width: f64,
46}
47
48impl Default for GeomHex {
49 fn default() -> Self {
50 GeomHex {
51 color: (50, 50, 50),
52 alpha: 1.0,
53 line_width: 0.2,
54 }
55 }
56}
57
58impl GeomHex {
59 pub fn color(mut self, color: (u8, u8, u8)) -> Self {
60 self.color = color;
61 self
62 }
63
64 pub fn linewidth(mut self, width: f64) -> Self {
66 self.line_width = width;
67 self
68 }
69}
70
71impl Geom for GeomHex {
72 fn draw(
73 &self,
74 data: &DataFrame,
75 coord: &dyn Coord,
76 scales: &ScaleSet,
77 _theme: &Theme,
78 backend: &mut dyn DrawBackend,
79 ) -> Result<(), RenderError> {
80 let x_col = data
81 .column("x")
82 .ok_or(RenderError::MissingAesthetic("x".into()))?;
83 let y_col = data
84 .column("y")
85 .ok_or(RenderError::MissingAesthetic("y".into()))?;
86 let fill_col = data.column("fill");
87 let width_col = data.column("width");
88 let height_col = data.column("height");
89
90 let plot_area = backend.plot_area();
91 let x_scale = scales.get(&Aesthetic::X);
92 let y_scale = scales.get(&Aesthetic::Y);
93
94 let (fallback_w, fallback_h) = fallback_hex_size(
95 x_col.iter().filter_map(|v| v.as_f64()),
96 y_col.iter().filter_map(|v| v.as_f64()),
97 );
98
99 for i in 0..data.nrows() {
100 let (Some(cx), Some(cy)) = (x_col[i].as_f64(), y_col[i].as_f64()) else {
101 continue;
102 };
103 let width = width_col
104 .and_then(|wc| wc[i].as_f64())
105 .filter(|w| w.is_finite() && *w > 0.0)
106 .unwrap_or(fallback_w);
107 let height = height_col
108 .and_then(|hc| hc[i].as_f64())
109 .filter(|h| h.is_finite() && *h > 0.0)
110 .unwrap_or(fallback_h);
111
112 let fill_color = fill_col
113 .and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[i]))
114 .unwrap_or((97, 156, 255));
115
116 super::set_mark(
117 backend,
118 fill_col.map(|c| format!("n = {}", super::tip_value(&c[i]))),
119 None,
120 None,
121 fill_col.and_then(|c| super::raw_value(&c[i])),
122 );
123 super::set_row_extras(backend, data, i);
124
125 let verts_data = HexLattice::new(width, height, (cx, cy)).vertices(0, 0);
128 let vertices: Vec<(f64, f64)> = verts_data
129 .iter()
130 .map(|&(vx, vy)| {
131 let nx = x_scale
132 .map(|s| s.map(&crate::data::Value::Float(vx)))
133 .unwrap_or(0.0);
134 let ny = y_scale
135 .map(|s| s.map(&crate::data::Value::Float(vy)))
136 .unwrap_or(0.0);
137 coord.transform((nx, ny), &plot_area)
138 })
139 .collect();
140
141 backend.draw_polygon(
142 &vertices,
143 &RectStyle {
144 fill: Some(fill_color),
145 stroke: Some(self.color),
146 stroke_width: self.line_width,
147 alpha: self.alpha,
148 clip: true,
149 },
150 )?;
151 }
152 super::clear_mark(backend);
153 super::clear_row_extras(backend);
154
155 Ok(())
156 }
157
158 fn required_aes(&self) -> Vec<Aesthetic> {
159 vec![Aesthetic::X, Aesthetic::Y]
160 }
161
162 fn default_stat(&self) -> Box<dyn Stat> {
163 Box::new(StatBinHex::default())
164 }
165
166 fn default_position(&self) -> Box<dyn Position> {
167 Box::new(PositionIdentity)
168 }
169
170 fn default_params(&self) -> GeomParams {
171 GeomParams::default()
172 }
173
174 fn name(&self) -> &str {
175 "hex"
176 }
177}
178
179#[cfg(test)]
180mod tests {
181 use super::fallback_hex_size;
182 use crate::data::Value;
183 use crate::prelude::*;
184
185 #[test]
188 fn fallback_size_is_twice_the_resolution_scaled_for_the_lattice() {
189 let (w, h) = fallback_hex_size([0.0, 2.0].into_iter(), [0.0, 3.0].into_iter());
190 assert!((w - 4.0).abs() < 1e-9, "w={w}");
191 let expected_h = 2.0 * 3.0 / 3.0_f64.sqrt();
192 assert!(
193 (h - expected_h).abs() < 1e-9,
194 "h={h}, expected={expected_h}"
195 );
196 }
197
198 #[test]
199 fn fallback_size_gives_regular_hexagons_on_a_square_lattice() {
200 let w_lattice = 5.0;
205 let res_x = w_lattice / 2.0;
206 let res_y = w_lattice * 3.0_f64.sqrt() / 2.0;
207 let (w, h) = fallback_hex_size([0.0, res_x].into_iter(), [0.0, res_y].into_iter());
208 assert!((w - w_lattice).abs() < 1e-9, "w={w}");
209 assert!((h - w_lattice).abs() < 1e-9, "h={h}");
210 }
211
212 #[test]
220 #[cfg(feature = "sf")]
221 fn geom_hex_without_width_height_columns_draws_regular_hexagons() {
222 let res_x = 5.0;
226 let res_y = res_x * 3.0_f64.sqrt();
227 let svg = GGPlot::new(vec![
228 ("x".into(), vec![Value::Float(0.0), Value::Float(res_x)]),
229 ("y".into(), vec![Value::Float(0.0), Value::Float(res_y)]),
230 ])
231 .aes(Aes::new().x("x").y("y"))
232 .geom_hex_with(GeomHex::default())
233 .stat(crate::stat::identity::StatIdentity)
234 .coord_sf()
235 .render_svg_native_with_size(400, 400)
236 .unwrap();
237
238 assert!(!svg.contains("NaN"));
239 let poly = svg.split("<polygon").nth(1).expect("a hex polygon");
240 let points_attr = poly
241 .split("points=\"")
242 .nth(1)
243 .unwrap()
244 .split('"')
245 .next()
246 .unwrap();
247 let pts: Vec<(f64, f64)> = points_attr
248 .split(' ')
249 .map(|p| {
250 let mut it = p.split(',');
251 let x: f64 = it.next().unwrap().parse().unwrap();
252 let y: f64 = it.next().unwrap().parse().unwrap();
253 (x, y)
254 })
255 .collect();
256 assert_eq!(pts.len(), 6);
257 let edge =
258 |a: (f64, f64), b: (f64, f64)| ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt();
259 let edges: Vec<f64> = (0..6).map(|i| edge(pts[i], pts[(i + 1) % 6])).collect();
260 let first = edges[0];
261 for e in &edges {
262 assert!((e - first).abs() < 0.05, "edges should be equal: {edges:?}");
263 }
264 }
265
266 #[test]
269 fn color_and_linewidth_builders_change_the_rendered_outline() {
270 let svg = GGPlot::new(vec![
271 ("x".into(), vec![Value::Float(0.0), Value::Float(1.0)]),
272 ("y".into(), vec![Value::Float(0.0), Value::Float(1.0)]),
273 ])
274 .aes(Aes::new().x("x").y("y"))
275 .geom_hex_with(GeomHex::default().color((10, 20, 30)).linewidth(3.0))
276 .render_svg_native_with_size(200, 200)
277 .unwrap();
278 assert!(svg.contains("stroke=\"#0A141E\""));
279 assert!(svg.contains("stroke-width=\"3.00\""));
280 }
281
282 #[test]
285 fn a_row_with_non_numeric_position_is_skipped() {
286 let svg = GGPlot::new(vec![
287 (
288 "x".into(),
289 vec![Value::Float(0.0), Value::Na, Value::Float(5.0)],
290 ),
291 (
292 "y".into(),
293 vec![Value::Float(0.0), Value::Float(1.0), Value::Float(5.0)],
294 ),
295 ])
296 .aes(Aes::new().x("x").y("y"))
297 .geom_hex_with(GeomHex::default())
298 .stat(crate::stat::identity::StatIdentity)
299 .render_svg_native_with_size(200, 200)
300 .unwrap();
301 assert!(!svg.contains("NaN"));
302 assert_eq!(svg.matches("<polygon").count(), 2);
303 }
304}