1 use plotters::prelude::*;
2
snowflake_iter(points: &[(f64, f64)]) -> Vec<(f64, f64)>3 fn snowflake_iter(points: &[(f64, f64)]) -> Vec<(f64, f64)> {
4 let mut ret = vec![];
5 for i in 0..points.len() {
6 let (start, end) = (points[i], points[(i + 1) % points.len()]);
7 let t = ((end.0 - start.0) / 3.0, (end.1 - start.1) / 3.0);
8 let s = (
9 t.0 * 0.5 - t.1 * (0.75f64).sqrt(),
10 t.1 * 0.5 + (0.75f64).sqrt() * t.0,
11 );
12 ret.push(start);
13 ret.push((start.0 + t.0, start.1 + t.1));
14 ret.push((start.0 + t.0 + s.0, start.1 + t.1 + s.1));
15 ret.push((start.0 + t.0 * 2.0, start.1 + t.1 * 2.0));
16 }
17 ret
18 }
19
main() -> Result<(), Box<dyn std::error::Error>>20 fn main() -> Result<(), Box<dyn std::error::Error>> {
21 let root =
22 BitMapBackend::new("plotters-doc-data/snowflake.png", (1024, 768)).into_drawing_area();
23
24 root.fill(&WHITE)?;
25
26 let mut chart = ChartBuilder::on(&root)
27 .caption("Koch's Snowflake", ("sans-serif", 50))
28 .build_cartesian_2d(-2.0..2.0, -1.5..1.5)?;
29
30 let mut snowflake_vertices = {
31 let mut current: Vec<(f64, f64)> = vec![
32 (0.0, 1.0),
33 ((3.0f64).sqrt() / 2.0, -0.5),
34 (-(3.0f64).sqrt() / 2.0, -0.5),
35 ];
36 for _ in 0..6 {
37 current = snowflake_iter(¤t[..]);
38 }
39 current
40 };
41
42 chart.draw_series(std::iter::once(Polygon::new(
43 snowflake_vertices.clone(),
44 &RED.mix(0.2),
45 )))?;
46 snowflake_vertices.push(snowflake_vertices[0]);
47 chart.draw_series(std::iter::once(PathElement::new(snowflake_vertices, &RED)))?;
48
49 Ok(())
50 }
51 #[test]
entry_point()52 fn entry_point() {
53 main().unwrap()
54 }
55