pathfinder/map/
mod.rs

1/*!
2Functions to manage large numbers of placable entities.
3 */
4
5extern crate image;
6
7use super::*;
8use image::Rgba;
9use std::cmp;
10
11pub mod gif;
12pub mod network;
13
14/**
15Returns the underlaying image used for the Map struct.
16*/
17pub fn gen_map<T: Location + Draw + MinMax>(
18    list: &[T],
19) -> (image::ImageBuffer<Rgba<u8>, Vec<u8>>, (Coordinate)) {
20    let (min, max) = min_max(&list);
21    let diff = max - min;
22    let add = Coordinate::new(-min.x, -min.y);
23    let image = gen_canvas(diff.x as u32, diff.y as u32);
24    (image, add)
25}
26
27/**
28Finds the min and max of a list and returns (min, max).
29
30the min and max use the size of the Draw trait to enlarge the are the min, max occupy.
31*/
32fn min_max<T: Location + Draw + MinMax>(list: &[T]) -> (Coordinate, Coordinate) {
33    let mut size: i16 = consts::DEFAULT_SIZE as i16;
34    let mut min = coordinate!();
35    let mut max = coordinate!();
36
37    for item in list {
38        size = cmp::max(size, item.size() as i16);
39        let (imin, imax) = item.min_max();
40
41        max.x = cmp::max(max.x, imax.x);
42        min.x = cmp::min(min.x, imin.x);
43        max.y = cmp::max(max.y, imax.y);
44        min.y = cmp::min(min.y, imin.y);
45    }
46
47    let size = coordinate!(size / 4);
48    (min - size, max + size)
49}
50
51/**
52Generates a canvas from the image crate.
53*/
54fn gen_canvas(w: u32, h: u32) -> image::ImageBuffer<Rgba<u8>, Vec<u8>> {
55    image::DynamicImage::new_rgba8(w, h).to_rgba()
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61    #[test]
62    fn test_gen_canvas() {
63        let image = gen_canvas(50, 50);
64        assert_eq!(image.width(), 50);
65        assert_eq!(image.height(), 50);
66    }
67
68    #[test]
69    fn test_gen_canvas_2() {
70        let image = gen_canvas(0, 0);
71        assert_eq!(image.width(), 0);
72        assert_eq!(image.height(), 0);
73    }
74
75    #[test]
76    fn test_min_max() {
77        let nodes = Node::from_list(&[(-50, 50), (50, -50), (0, 25), (25, 0)]);
78        let (min, max) = min_max(&nodes);
79        assert_eq!(min, Coordinate::new(-55, -55));
80        assert_eq!(max, Coordinate::new(55, 55));
81    }
82
83    #[test]
84    fn test_min_max_2() {
85        let nodes = Node::from_list(&[(-9999, 50), (50, -50), (0, 25), (9999, 0)]);
86        let (min, max) = min_max(&nodes);
87        assert_eq!(min, Coordinate::new(-10004, -55));
88        assert_eq!(max, Coordinate::new(10004, 55));
89    }
90}