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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! Provides the [`Slicer`] trait and slicers types that determine the order and pattern in which
//! data is produced by an interator over a [`CellMap`].
//!
//! [`CellMap`]: crate::CellMap

// ------------------------------------------------------------------------------------------------
// IMPORTS
// ------------------------------------------------------------------------------------------------

use nalgebra::{Point2, Vector2};
use ndarray::{s, Array2, ArrayView2, ArrayViewMut2};
use serde::Serialize;

use crate::{
    cell_map::Bounds, extensions::Point2Ext, map_metadata::CellMapMetadata, CellMap, Error, Layer,
};

// ------------------------------------------------------------------------------------------------
// TRAITS
// ------------------------------------------------------------------------------------------------

/// Trait which allows a [`CellMapIter`] or [`CellMapIterMut`] struct to determine what shape the
/// data in the iteration should be produced in. For example:
///
/// - [`Cells`] produces data in each cell in `(x, y)` order, x increasing most rapidly.
/// - [`Windows`] produces rectangular views in `(x, y`) order, x increasing most rapidly.
/// - [`Line`] produces cells along the line connecting two positions in the parent frame.
///
/// [`Slicer`]s are designed to be used in iterators, so after a `.slice` or `.slice_mut` the user
/// shall call [`Slicer::advance()`] on the type.
///
/// [`CellMapIter`]: crate::iterators::CellMapIter
/// [`CellMapIterMut`]: crate::iterators::CellMapIterMut
pub trait Slicer<'a, L, T>
where
    L: Layer,
{
    /// The non-mutable output type for the data of this [`Slicer`].
    type Output;

    /// The mutable output type for the data of this [`Slicer`].
    type OutputMut;

    /// Perform the slice on the given `data` layer, or `None` if the slicer has reached the end of
    /// its data.
    fn slice(&self, data: &'a Array2<T>) -> Option<Self::Output>;

    /// Perform a mutable slice on the given `data` layer, or `None` if the slicer has reached the
    /// end of its data.
    fn slice_mut(&self, data: &'a mut Array2<T>) -> Option<Self::OutputMut>;

    /// Advance the [`Slicer`] to the next index.
    fn advance(&mut self);

    /// Return the current index of the [`Slicer`], or `None` if the slicer has reached the end of
    /// its data.
    fn index(&self) -> Option<Point2<usize>>;

    /// Resets the index of this [`Slicer`] so that it can be used on the next layer in the
    /// iteration. The `layer` input is used for slicers which need to monitor which layer they are
    /// on.
    fn reset(&mut self, layer: Option<L>);
}

/// Rectangular bounds in an XY plane. Lower bound is inclusive, upper exclusive.
pub(crate) type RectBounds = Vector2<(usize, usize)>;

/// A [`Slicer`] which produces cells in `(x, y)` order inside a layer, with `x` increasing most
/// rapidly.
#[derive(Debug, Clone, Copy)]
pub struct Cells {
    bounds: RectBounds,
    index: Point2<usize>,
}

/// A [`Slicer`] which produces rectangular views into a layer in `(x, y)` order, increasing `x`
/// most rapidly. A boundary of the `semi_width` of the window around the outside edge of the map
/// is used to prevent indexing outside the map.
#[derive(Debug, Clone, Copy)]
pub struct Windows {
    bounds: RectBounds,
    index: Point2<usize>,
    semi_width: Vector2<usize>,
}

/// A [`Slicer`] which produces cells along the line connecting two points in the parent frame.
///
/// This slicer will uses the algorithm described in
/// [here](https://theshoemaker.de/2016/02/ray-casting-in-2d-grids/), meaning that all cells the
/// line intersects will be yielded only once.
#[derive(Debug, Clone)]
#[allow(missing_copy_implementations)]
pub struct Line {
    bounds: Bounds,
    map_meta: CellMapMetadata,

    start_parent: Point2<f64>,
    end_parent: Point2<f64>,

    dir: Vector2<f64>,
    dir_sign: Vector2<f64>,

    start_map: Point2<f64>,
    end_map: Point2<f64>,
    current_map: Option<Point2<f64>>,

    end_index: Point2<usize>,

    #[cfg(feature = "debug_iters")]
    step_report_file: std::sync::Arc<std::fs::File>,
}

#[derive(Debug, Clone, Copy, Serialize)]
struct LineStepData {
    start_parent: Point2<f64>,
    end_parent: Point2<f64>,

    dir: Vector2<f64>,
    dir_sign: Vector2<f64>,

    start_map: Point2<f64>,
    end_map: Point2<f64>,
    current_map: Option<Point2<f64>>,

    end_index: Point2<usize>,

    delta: Vector2<f64>,
}

// ------------------------------------------------------------------------------------------------
// IMPLS
// ------------------------------------------------------------------------------------------------

impl Cells {
    pub(crate) fn from_map<L: Layer, T>(map: &CellMap<L, T>) -> Self {
        let cells = map.num_cells();
        Self {
            bounds: Vector2::new((0, cells.x), (0, cells.y)),
            index: Point2::new(0, 0),
        }
    }
}

impl<'a, L, T> Slicer<'a, L, T> for Cells
where
    L: Layer,
    T: 'a,
{
    type Output = &'a T;
    type OutputMut = &'a mut T;

    fn slice(&self, data: &'a Array2<T>) -> Option<Self::Output> {
        data.get(self.index.as_array2_index())
    }

    fn slice_mut(&self, data: &'a mut Array2<T>) -> Option<Self::OutputMut> {
        data.get_mut(self.index.as_array2_index())
    }

    fn advance(&mut self) {
        self.index.x += 1;

        if !self.index.in_bounds(&self.bounds) {
            self.index.y += 1;
            self.index.x = self.bounds.x.0;
        }
    }

    fn index(&self) -> Option<Point2<usize>> {
        if self.index.in_bounds(&self.bounds) {
            Some(self.index)
        } else {
            None
        }
    }

    fn reset(&mut self, _layer: Option<L>) {
        self.index = Point2::new(self.bounds.x.0, self.bounds.y.0);
    }
}

impl Windows {
    pub(crate) fn from_map<L: Layer, T>(
        map: &CellMap<L, T>,
        semi_width: Vector2<usize>,
    ) -> Result<Self, Error> {
        let cells = map.num_cells();

        if semi_width.x * 2 + 1 > cells.x || semi_width.y * 2 + 1 > cells.y {
            Err(Error::WindowLargerThanMap(
                semi_width * 2 + Vector2::new(1, 1),
                cells,
            ))
        } else {
            let bounds = Vector2::new(
                (semi_width.x, cells.x - semi_width.x),
                (semi_width.y, cells.y - semi_width.y),
            );

            Ok(Self {
                bounds,
                index: Point2::new(bounds.x.0, bounds.y.0),
                semi_width,
            })
        }
    }
}

impl<'a, L, T> Slicer<'a, L, T> for Windows
where
    L: Layer,
    T: 'a,
{
    type Output = ArrayView2<'a, T>;
    type OutputMut = ArrayViewMut2<'a, T>;

    fn slice(&self, data: &'a Array2<T>) -> Option<Self::Output> {
        if self.index.in_bounds(&self.bounds) {
            let x0 = self.index.x - self.semi_width.x;
            let x1 = self.index.x + self.semi_width.x + 1;
            let y0 = self.index.y - self.semi_width.y;
            let y1 = self.index.y + self.semi_width.y + 1;
            Some(data.slice(s![y0..y1, x0..x1]))
        } else {
            None
        }
    }

    fn slice_mut(&self, data: &'a mut Array2<T>) -> Option<Self::OutputMut> {
        if self.index.in_bounds(&self.bounds) {
            let x0 = self.index.x - self.semi_width.x;
            let x1 = self.index.x + self.semi_width.x + 1;
            let y0 = self.index.y - self.semi_width.y;
            let y1 = self.index.y + self.semi_width.y + 1;
            Some(data.slice_mut(s![y0..y1, x0..x1]))
        } else {
            None
        }
    }

    fn advance(&mut self) {
        self.index.x += 1;

        if !self.index.in_bounds(&self.bounds) {
            self.index.y += 1;
            self.index.x = self.bounds.x.0;
        }
    }

    fn index(&self) -> Option<Point2<usize>> {
        if self.index.in_bounds(&self.bounds) {
            Some(self.index)
        } else {
            None
        }
    }

    fn reset(&mut self, _layer: Option<L>) {
        self.index = Point2::new(self.bounds.x.0, self.bounds.y.0);
    }
}

impl Line {
    pub(crate) fn from_map<L: Layer, T>(
        map_meta: CellMapMetadata,
        start_parent: Point2<f64>,
        end_parent: Point2<f64>,
    ) -> Result<Self, Error> {
        // Calculate start and end points in map frame, note these aren't cell indices, instead
        // they are floating point positions within the map frame, which we get by not casting the
        // output of the `to_parent` transforms to usize.
        let start_map = map_meta.to_parent.inverse_transform_point(&start_parent);
        let end_map = map_meta.to_parent.inverse_transform_point(&end_parent);

        // Get map edges in floating point for bounds check
        let map_x_bounds = (
            map_meta.cell_bounds.x.0 as f64,
            map_meta.cell_bounds.x.1 as f64,
        );
        let map_y_bounds = (
            map_meta.cell_bounds.y.0 as f64,
            map_meta.cell_bounds.y.1 as f64,
        );

        // Check start and end points are inside the map
        if start_map.x < map_x_bounds.0
            || start_map.x > map_x_bounds.1
            || start_map.y < map_y_bounds.0
            || start_map.y > map_y_bounds.1
        {
            return Err(Error::PositionOutsideMap(
                "Line::Start".into(),
                start_parent,
            ));
        }

        if end_map.x < map_x_bounds.0
            || end_map.x > map_x_bounds.1
            || end_map.y < map_y_bounds.0
            || end_map.y > map_y_bounds.1
        {
            return Err(Error::PositionOutsideMap("Line::End".into(), start_parent));
        }

        // Calculate direction vector
        let dir = end_map - start_map;

        // Get the direction sign
        let dir_sign = dir.map(|v| if v < 0.0 { 0.0 } else { 1.0 });

        // Get the cell index of the end point
        let end_cell = map_meta
            .index(end_parent)
            .ok_or_else(|| Error::PositionOutsideMap("Line::End".into(), end_parent))?;

        Ok(Self {
            bounds: map_meta.cell_bounds,
            map_meta,
            start_parent,
            end_parent,
            dir,
            dir_sign,
            start_map,
            end_map,
            current_map: Some(start_map),
            end_index: end_cell,
            #[cfg(feature = "debug_iters")]
            step_report_file: std::sync::Arc::new(
                std::fs::OpenOptions::new()
                    .create(true)
                    .truncate(true)
                    .write(true)
                    .open("line_step_report.json")
                    .unwrap(),
            ),
        })
    }

    /// Gets the current cell index to yield, or `None` if at the end of the line
    fn get_current_index(&self) -> Option<Point2<usize>> {
        // Current will be inside the map, since start and end were confirmed to be inside the map
        // at construction, so simply cast, then convert from bounds to index
        let current_map_isize = self.current_map?.map(|e| e as isize);
        self.map_meta.cell_bounds.get_index(current_map_isize)
    }
}

impl<'a, L, T> Slicer<'a, L, T> for Line
where
    L: Layer,
    T: 'a,
{
    type Output = &'a T;

    type OutputMut = &'a mut T;

    fn slice(&self, data: &'a Array2<T>) -> Option<Self::Output> {
        // Get the index
        let index = self.get_current_index()?;

        data.get(index.as_array2_index())
    }

    fn slice_mut(&self, data: &'a mut Array2<T>) -> Option<Self::OutputMut> {
        // Get the index
        let index = self.get_current_index()?;

        data.get_mut(index.as_array2_index())
    }

    fn advance(&mut self) {
        // Get the index of the current position, or just return if we're at the end
        let curr_index = match self.get_current_index() {
            Some(i) => i,
            None => return,
        };

        // Calculate the param value, i.e. how far along the line we are. This will be used to
        // check if we are beyond the end of the line
        let param = (self.current_map.unwrap() - self.start_map).norm()
            / (self.end_map - self.start_map).norm();

        // Calculate the changes in the line parameter needed to reach the next x and y grid line
        // respectively. Also add on the cell boundary precision to ensure that we will actually
        // move over the cell boundary line.
        let delta_param: Vector2<f64> = ((curr_index.cast() + self.dir_sign)
            - self.current_map.unwrap())
        .component_div(&self.dir)
            + Vector2::from_element(self.map_meta.cell_boundary_precision);

        // Whichever component of delta is smaller is what we need to advance along the line by.
        let delta = delta_param.x.min(delta_param.y);

        // If any of param + delta is > 1, the next point would be beyond the end of the line, so
        // we should end here
        if delta + param > 1.0 {
            self.current_map = None;
        }
        // Otherwise, move current to current + dir*delta
        else {
            self.current_map = Some(self.current_map.unwrap() + (self.dir * delta));
        }

        // Write new step report to file
        #[cfg(feature = "debug_iters")]
        {
            use std::io::Write;

            let rpt = LineStepData {
                start_parent: self.start_parent,
                end_parent: self.end_parent,
                dir: self.dir,
                dir_sign: self.dir_sign,
                start_map: self.start_map,
                end_map: self.end_map,
                current_map: self.current_map,
                end_index: self.end_index,
                delta: delta_param,
            };

            let val = serde_json::to_string_pretty(&rpt).unwrap();

            writeln!(
                std::sync::Arc::<std::fs::File>::get_mut(&mut self.step_report_file).unwrap(),
                "{},",
                val
            )
            .unwrap();
        }
    }

    fn index(&self) -> Option<Point2<usize>> {
        self.get_current_index()
    }

    fn reset(&mut self, _layer: Option<L>) {
        self.current_map = Some(self.start_map)
    }
}