1use plotters::prelude::*;
2
3fn 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
20const OUT_FILE_NAME: &'static str = "plotters-doc-data/animation.gif";
21fn main() -> Result<(), Box<dyn std::error::Error>> {
22 let root = BitMapBackend::gif(OUT_FILE_NAME, (800, 600), 1_000)?.into_drawing_area();
23
24 for i in 0..8 {
25 root.fill(&WHITE)?;
26
27 let mut chart = ChartBuilder::on(&root)
28 .caption(
29 format!("Koch's Snowflake (n_iter = {})", i),
30 ("sans-serif", 50),
31 )
32 .build_cartesian_2d(-2.0..2.0, -1.5..1.5)?;
33
34 let mut snowflake_vertices = {
35 let mut current: Vec<(f64, f64)> = vec![
36 (0.0, 1.0),
37 ((3.0f64).sqrt() / 2.0, -0.5),
38 (-(3.0f64).sqrt() / 2.0, -0.5),
39 ];
40 for _ in 0..i {
41 current = snowflake_iter(¤t[..]);
42 }
43 current
44 };
45
46 chart.draw_series(std::iter::once(Polygon::new(
47 snowflake_vertices.clone(),
48 &RED.mix(0.2),
49 )))?;
50
51 snowflake_vertices.push(snowflake_vertices[0]);
52 chart.draw_series(std::iter::once(PathElement::new(snowflake_vertices, &RED)))?;
53
54 root.present()?;
55 }
56
57 println!("Result has been saved to {}", OUT_FILE_NAME);
58
59 Ok(())
60}
61
62#[test]
63fn entry_point() {
64 main().unwrap()
65}
66