1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
mod bb;
mod core;
mod polygon;

pub use bb::BB;
pub use core::{Calc, OutOfBoundsMode, Point, PtF, PtI, Shape};
pub use polygon::Polygon;
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
pub enum GeoFig {
    BB(BB),
    Poly(Polygon),
}

impl GeoFig {
    pub fn contains<P>(&self, point: P) -> bool
    where
        P: Into<PtF>,
    {
        match self {
            Self::BB(bb) => bb.contains(point),
            Self::Poly(poly) => poly.contains(point),
        }
    }
    pub fn distance_to_boundary(&self, point: PtF) -> f32 {
        match self {
            Self::BB(bb) => bb.distance_to_boundary(point),
            Self::Poly(poly) => poly.distance_to_boundary(point),
        }
    }
    pub fn is_contained_in_image(&self, shape: Shape) -> bool {
        match self {
            Self::BB(bb) => bb.is_contained_in_image(shape),
            Self::Poly(poly) => poly.is_contained_in_image(shape),
        }
    }
    pub fn max_squaredist(&self, other: &Self) -> (PtI, PtI, i64) {
        match self {
            Self::BB(bb) => match other {
                GeoFig::BB(bb_other) => bb.max_squaredist(bb_other.points_iter()),
                GeoFig::Poly(poly_other) => bb.max_squaredist(poly_other.points_iter()),
            },
            Self::Poly(poly) => match other {
                GeoFig::BB(bb_other) => poly.max_squaredist(bb_other.points_iter()),
                GeoFig::Poly(poly_other) => poly.max_squaredist(poly_other.points_iter()),
            },
        }
    }
    pub fn has_overlap(&self, other: &BB) -> bool {
        match self {
            Self::BB(bb) => bb.has_overlap(other),
            Self::Poly(poly) => poly.has_overlap(other),
        }
    }
    pub fn translate(self, p: Point<i32>, shape: Shape, oob_mode: OutOfBoundsMode) -> Option<Self> {
        match self {
            Self::BB(bb) => bb.translate(p.x, p.y, shape, oob_mode).map(GeoFig::BB),
            Self::Poly(poly) => poly.translate(p.x, p.y, shape, oob_mode).map(GeoFig::Poly),
        }
    }
    pub fn enclosing_bb(&self) -> BB {
        match self {
            Self::BB(bb) => *bb,
            Self::Poly(poly) => poly.enclosing_bb(),
        }
    }
    pub fn follow_movement(
        self,
        from: PtF,
        to: PtF,
        shape: Shape,
        oob_mode: OutOfBoundsMode,
    ) -> Option<Self> {
        let x_shift: i32 = (to.x - from.x) as i32;
        let y_shift: i32 = (to.y - from.y) as i32;
        self.translate(
            Point {
                x: x_shift,
                y: y_shift,
            },
            shape,
            oob_mode,
        )
    }

    pub fn points_normalized(&self, w: f32, h: f32) -> Vec<PtF> {
        fn convert(iter: impl Iterator<Item = PtI>, w: f32, h: f32) -> Vec<PtF> {
            iter.map(<PtI as Into<PtF>>::into)
                .map(|p| Point {
                    x: p.x / w,
                    y: p.y / h,
                })
                .collect()
        }
        match self {
            GeoFig::BB(bb) => convert(bb.points_iter(), w, h),
            GeoFig::Poly(poly) => convert(poly.points_iter(), w, h),
        }
    }
}
impl Default for GeoFig {
    fn default() -> Self {
        Self::BB(BB::default())
    }
}

pub fn zoom_box_mouse_wheel(zoom_box: Option<BB>, shape_orig: Shape, y_delta: f32) -> Option<BB> {
    let current_zb = if let Some(zb) = zoom_box {
        zb
    } else {
        BB::from_arr(&[0, 0, shape_orig.w, shape_orig.h])
    };
    let clip_val = 1.0;
    let y_delta_clipped = if y_delta > 0.0 {
        y_delta.min(clip_val)
    } else {
        y_delta.max(-clip_val)
    };
    let factor = 1.0 - y_delta_clipped * 0.1;

    Some(current_zb.center_scale(factor, shape_orig))
}

/// shape of the image that fits into the window
pub fn shape_scaled(shape_unscaled: Shape, shape_win: Shape) -> (f32, f32) {
    let w_ratio = shape_unscaled.w as f32 / shape_win.w as f32;
    let h_ratio = shape_unscaled.h as f32 / shape_win.h as f32;
    let ratio = w_ratio.max(h_ratio);
    let w_new = shape_unscaled.w as f32 / ratio;
    let h_new = shape_unscaled.h as f32 / ratio;
    (w_new, h_new)
}
/// shape without scaling to window
pub fn shape_unscaled(zoom_box: &Option<BB>, shape_orig: Shape) -> Shape {
    zoom_box.map_or(shape_orig, |z| z.shape())
}
pub fn pos_transform<F>(
    pos: PtF,
    shape_orig: Shape,
    shape_win: Shape,
    zoom_box: &Option<BB>,
    transform: F,
) -> PtF
where
    F: Fn(f32, f32, f32, f32) -> f32,
{
    let unscaled = shape_unscaled(zoom_box, shape_orig);
    let (w_scaled, h_scaled) = shape_scaled(unscaled, shape_win);

    let (x_off, y_off) = match zoom_box {
        Some(c) => (c.x, c.y),
        _ => (0, 0),
    };

    let (x, y) = pos.into();
    let x_tf = transform(x, w_scaled, unscaled.w as f32, x_off as f32);
    let y_tf = transform(y, h_scaled, unscaled.h as f32, y_off as f32);
    (x_tf, y_tf).into()
}
#[cfg(test)]
pub fn make_test_bbs() -> Vec<BB> {
    vec![
        BB {
            x: 0,
            y: 0,
            w: 10,
            h: 10,
        },
        BB {
            x: 5,
            y: 5,
            w: 10,
            h: 10,
        },
        BB {
            x: 9,
            y: 9,
            w: 10,
            h: 10,
        },
    ]
}
#[cfg(test)]
pub fn make_test_geos() -> Vec<GeoFig> {
    make_test_bbs()
        .into_iter()
        .map(|bb| GeoFig::BB(bb))
        .collect()
}

#[test]
fn test_polygon() {
    let bbs = make_test_bbs();
    let poly = Polygon::from(bbs[2]);
    assert_eq!(poly.enclosing_bb(), bbs[2]);
    let corners = bbs[0].points_iter().collect::<Vec<_>>();
    let ebb = BB::from_vec(&corners).unwrap();
    let poly = Polygon::from(ebb);
    assert_eq!(poly.enclosing_bb(), ebb);
}

#[test]
fn test_zb() {
    fn test(zb: Option<BB>, y_delta: f32, reference_coords: &[u32; 4]) {
        println!("y_delta {}", y_delta);
        let shape = Shape::new(200, 100);
        let zb_new = zoom_box_mouse_wheel(zb, shape, y_delta);
        assert_eq!(zb_new, Some(BB::from_arr(reference_coords)));
    }
    test(None, 1.0, &[10, 5, 180, 90]);
    test(None, -1.0, &[0, 0, 200, 100]);
}

#[test]
fn test_bb() {
    let bb = BB {
        x: 10,
        y: 10,
        w: 10,
        h: 10,
    };
    assert!(!bb.contains((20u32, 20u32)));
    assert!(bb.contains((10u32, 10u32)));
    assert!(bb.corner(0).equals((10, 10)));
    assert!(bb.corner(1).equals((10, 19)));
    assert!(bb.corner(2).equals((19, 19)));
    assert!(bb.corner(3).equals((19, 10)));
    assert!(bb.opposite_corner(0).equals((19, 19)));
    assert!(bb.opposite_corner(1).equals((19, 10)));
    assert!(bb.opposite_corner(2).equals((10, 10)));
    assert!(bb.opposite_corner(3).equals((10, 19)));
    for (c, i) in bb.points_iter().zip(0..4) {
        assert_eq!(c, bb.corner(i));
    }
    let shape = Shape::new(100, 100);
    let bb1 = bb.translate(1, 1, shape, OutOfBoundsMode::Deny);
    assert_eq!(
        bb1,
        Some(BB {
            x: 11,
            y: 11,
            w: 10,
            h: 10
        })
    );
    let shape = Shape::new(100, 100);
    let bb1 = bb.shift_max(1, 1, shape);
    assert_eq!(
        bb1,
        Some(BB {
            x: 10,
            y: 10,
            w: 11,
            h: 11
        })
    );
    let bb1 = bb.shift_max(100, 1, shape);
    assert_eq!(bb1, None);
    let bb1 = bb.shift_max(-1, -2, shape);
    assert_eq!(
        bb1,
        Some(BB {
            x: 10,
            y: 10,
            w: 9,
            h: 8
        })
    );
    let bb1 = bb.shift_max(-100, -200, shape);
    assert_eq!(bb1, None);
    let bb_moved = bb
        .follow_movement(
            (5, 5).into(),
            (6, 6).into(),
            Shape::new(100, 100),
            OutOfBoundsMode::Deny,
        )
        .unwrap();
    assert_eq!(bb_moved, BB::from_arr(&[11, 11, 10, 10]));
}

#[test]
fn test_has_overlap() {
    let bb1 = BB::from_arr(&[5, 5, 10, 10]);
    let bb2 = BB::from_arr(&[5, 5, 10, 10]);
    assert!(bb1.has_overlap(&bb2) && bb2.has_overlap(&bb1));
    let bb2 = BB::from_arr(&[0, 0, 10, 10]);
    assert!(bb1.has_overlap(&bb2) && bb2.has_overlap(&bb1));
    let bb2 = BB::from_arr(&[0, 0, 11, 11]);
    assert!(bb1.has_overlap(&bb2) && bb2.has_overlap(&bb1));
    let bb2 = BB::from_arr(&[2, 2, 5, 5]);
    assert!(bb1.has_overlap(&bb2) && bb2.has_overlap(&bb1));
    let bb2 = BB::from_arr(&[5, 5, 9, 9]);
    assert!(bb1.has_overlap(&bb2) && bb2.has_overlap(&bb1));
    let bb2 = BB::from_arr(&[7, 7, 12, 12]);
    assert!(bb1.has_overlap(&bb2) && bb2.has_overlap(&bb1));
    let bb2 = BB::from_arr(&[17, 17, 112, 112]);
    assert!(!bb1.has_overlap(&bb2) && !bb2.has_overlap(&bb1));
    let bb2 = BB::from_arr(&[17, 17, 112, 112]);
    assert!(!bb1.has_overlap(&bb2) && !bb2.has_overlap(&bb1));
    let bb2 = BB::from_arr(&[17, 3, 112, 112]);
    assert!(!bb1.has_overlap(&bb2) && !bb2.has_overlap(&bb1));
    let bb2 = BB::from_arr(&[3, 17, 112, 112]);
    assert!(!bb1.has_overlap(&bb2) && !bb2.has_overlap(&bb1));
}

#[test]
fn test_max_corner_dist() {
    let bb1 = BB::from_arr(&[5, 5, 11, 11]);
    let bb2 = BB::from_arr(&[5, 5, 11, 11]);
    assert_eq!(
        bb1.max_squaredist(bb2.points_iter()),
        ((15, 5).into(), (5, 15).into(), 200)
    );
    let bb2 = BB::from_arr(&[6, 5, 11, 11]);
    assert_eq!(
        bb1.max_squaredist(bb2.points_iter()),
        ((5, 15).into(), (16, 5).into(), 221)
    );
    let bb2 = BB::from_arr(&[15, 15, 11, 11]);
    assert_eq!(
        bb1.max_squaredist(bb2.points_iter()),
        ((5, 5).into(), (25, 25).into(), 800)
    );
}

#[test]
fn test_intersect() {
    let bb = BB::from_arr(&[10, 15, 20, 10]);
    assert_eq!(bb.intersect(bb), bb);
    assert_eq!(
        bb.intersect(BB::from_arr(&[5, 7, 10, 10])),
        BB::from_arr(&[10, 15, 5, 2])
    );
    assert_eq!(bb.intersect_or_self(None), bb);
    assert_eq!(
        bb.intersect_or_self(Some(BB::from_arr(&[5, 7, 10, 10]))),
        BB::from_arr(&[10, 15, 5, 2])
    );
}

#[test]
fn test_into() {
    let pt: PtI = (10, 20).into();
    assert_eq!(pt, PtI { x: 10, y: 20 });
    let pt: PtF = (10i32, 20i32).into();
    assert_eq!(pt, PtF { x: 10.0, y: 20.0 });
}