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
//! # Spatial
//!
//! The `spatial` module provides the [`Vec2`] struct to specify positions on the terminal screen
//! and the [`Direction`] enum to specify and provide utility methods for relative directions.

use num::cast::ToPrimitive;
use std::cmp::Ordering;
use std::convert::TryFrom;
use std::error::Error;
use std::fmt;
use std::fmt::{Display, Formatter};
use std::ops::{
    Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub, SubAssign,
};

/// Represents a two-dimensional spatial vector.
///
/// It is generally used as a position vector, representing a point on the
/// [`Canvas`](crate::terminal::Canvas). In the terminal, the origin is (by default) set at the
/// top-left corner with `y` increasing downwards, i.e., counting from top to bottom.
///
/// At times, it is also used as a size. The differences are shown in the example below.
///
/// ## Example
///
/// ```rust
/// # use ruscii::spatial::Vec2;
/// # use ruscii::terminal::{Canvas, VisualElement};
/// #
/// let mut canvas = Canvas::new(
///     Vec2::xy(20, 20),  // (20, 20) is used as a size here.
///     &VisualElement::default()
/// );
/// let a = Vec2::xy(20, 20);  // (20, 20) is used as a position here
/// let b = Vec2::xy(19, 19);  // and (19, 19) as a position here.
///
/// assert!(canvas.contains(b));  // b is a valid point on the Canvas.
/// assert!(!canvas.contains(a));  // The bottom-right corner is actually (19, 19).
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Vec2 {
    pub x: i32,
    pub y: i32,
}

impl Vec2 {
    /// Constructs a [`Vec2`] representing (0, 0).
    pub fn zero() -> Vec2 {
        Vec2 { x: 0, y: 0 }
    }

    /// Constructs a [`Vec2`] with the given `x`- and `y`-coordinates.
    pub fn xy<T1: ToPrimitive, T2: ToPrimitive>(x: T1, y: T2) -> Vec2 {
        Vec2 {
            x: x.to_i32().unwrap(),
            y: y.to_i32().unwrap(),
        }
    }

    /// Constructs a [`Vec2`] with the given `x`-coordinate and a `y`-coordinate of 0.
    pub fn x<T: ToPrimitive>(x: T) -> Vec2 {
        Vec2 {
            x: x.to_i32().unwrap(),
            y: 0,
        }
    }

    /// Constructs a [`Vec2`] with the given `y`-coordinate and an `x`-coordinate of 0.
    pub fn y<T: ToPrimitive>(y: T) -> Vec2 {
        Vec2 {
            x: 0,
            y: y.to_i32().unwrap(),
        }
    }

    /// Sets the [`Vec2`] object to (0, 0).
    pub fn clear(&mut self) {
        self.x = 0;
        self.y = 0;
    }
}

impl Display for Vec2 {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

impl Add for Vec2 {
    type Output = Vec2;

    fn add(self, other: Vec2) -> Vec2 {
        Vec2 {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

impl Sub for Vec2 {
    type Output = Vec2;

    fn sub(self, other: Vec2) -> Vec2 {
        Vec2 {
            x: self.x - other.x,
            y: self.y - other.y,
        }
    }
}

impl Mul for Vec2 {
    type Output = Vec2;

    fn mul(self, other: Vec2) -> Vec2 {
        Vec2 {
            x: self.x * other.x,
            y: self.y * other.y,
        }
    }
}

impl Div for Vec2 {
    type Output = Vec2;

    fn div(self, other: Vec2) -> Vec2 {
        Vec2 {
            x: self.x / other.x,
            y: self.y / other.y,
        }
    }
}

impl<T: ToPrimitive> Mul<T> for Vec2 {
    type Output = Vec2;

    fn mul(self, scalar: T) -> Vec2 {
        let scalar = scalar.to_i32().unwrap();
        Vec2 {
            x: self.x * scalar,
            y: self.y * scalar,
        }
    }
}

impl<T: ToPrimitive> Div<T> for Vec2 {
    type Output = Vec2;

    fn div(self, scalar: T) -> Vec2 {
        let scalar = scalar.to_i32().unwrap();
        Vec2 {
            x: self.x / scalar,
            y: self.y / scalar,
        }
    }
}

impl Neg for Vec2 {
    type Output = Vec2;

    fn neg(self) -> Vec2 {
        Vec2 {
            x: -self.x,
            y: -self.y,
        }
    }
}

impl AddAssign for Vec2 {
    fn add_assign(&mut self, other: Vec2) {
        *self = *self + other
    }
}

impl SubAssign for Vec2 {
    fn sub_assign(&mut self, other: Vec2) {
        *self = *self - other
    }
}

impl MulAssign for Vec2 {
    fn mul_assign(&mut self, other: Vec2) {
        *self = *self * other
    }
}

impl DivAssign for Vec2 {
    fn div_assign(&mut self, other: Vec2) {
        *self = *self / other
    }
}

impl<T: ToPrimitive> MulAssign<T> for Vec2 {
    fn mul_assign(&mut self, scalar: T) {
        *self = *self * scalar
    }
}

impl<T: ToPrimitive> DivAssign<T> for Vec2 {
    fn div_assign(&mut self, scalar: T) {
        *self = *self / scalar
    }
}

impl<T> Index<Vec2> for Vec<Vec<T>> {
    type Output = T;

    /// Allows indexing by a [`Vec2`] for an arbitrary nested Vec.
    ///
    /// ```rust
    /// # use ruscii::spatial::Vec2;
    /// let vec = vec![vec![1, 2], vec![3, 4], vec![5, 6]];
    /// let point = Vec2::xy(1, 1);
    /// assert_eq!(vec[point], 4)
    /// ```
    fn index(&self, index: Vec2) -> &Self::Output {
        &self[index.x as usize][index.y as usize]
    }
}

impl<T> IndexMut<Vec2> for Vec<Vec<T>> {
    fn index_mut(&mut self, index: Vec2) -> &mut Self::Output {
        &mut self[index.x as usize][index.y as usize]
    }
}

impl From<Direction> for Vec2 {
    /// Converts a [`Direction`] to a unit-length [`Vec2`] in that direction.
    ///
    /// Because terminal coordinates begin at the top line, vertical directions are inverted
    /// compared to what you may expect. More information in the example. For [`Direction::None`], a
    /// zero [`Vec2`] is returned.
    ///
    /// ## Example
    ///
    /// In the terminal, `y` increases going downward from the top. Therefore, [`Direction::Up`]
    /// is a negative vector and [`Direction::Down`] is a positive vector.
    ///
    /// ```rust
    /// # use ruscii::spatial::{Direction, Vec2};
    /// #
    /// let up = Vec2::from(Direction::Up);
    /// let down = Vec2::from(Direction::Down);
    ///
    /// assert_eq!(up, Vec2::y(-1));
    /// assert_eq!(down, Vec2::y(1));
    /// ```
    fn from(value: Direction) -> Self {
        match value {
            Direction::Up => Vec2::y(-1),
            Direction::Down => Vec2::y(1),
            Direction::Right => Vec2::x(1),
            Direction::Left => Vec2::x(-1),
            Direction::None => Vec2::zero(),
        }
    }
}

/// The relative directions in a two-dimensional coordinate system, including up, down, left,
/// right, and none.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Direction {
    Up,
    Down,
    Right,
    Left,
    None,
}

impl Direction {
    /// Returns the opposite [`Direction`].
    ///
    /// For [`Direction::None`], [`Direction::None`] is returned.
    pub fn opposite(&self) -> Direction {
        match *self {
            Direction::Up => Direction::Down,
            Direction::Down => Direction::Up,
            Direction::Right => Direction::Left,
            Direction::Left => Direction::Right,
            Direction::None => Direction::None,
        }
    }
}

impl TryFrom<Vec2> for Direction {
    type Error = TryFromVec2Error;

    /// Converts a [`Vec2`] to a [`Direction`].
    ///
    /// Because terminal coordinates begin at the top line, vertical directions are inverted
    /// compared to what you may expect. For more information, see the example.
    ///
    /// ## Errors
    ///
    /// If the given `value` is not orthogonal, i.e., one of the components is not zero,
    /// [`TryFromVec2Error`] is returned.
    ///
    /// ## Examples
    ///
    /// In the terminal, `y` increases going downward from the top. Therefore, [`Direction::Up`]
    /// is a negative vector and [`Direction::Down`] is a positive vector.
    ///
    /// ```rust
    /// # use std::convert::TryFrom;
    /// # use ruscii::spatial::{Direction, Vec2};
    /// #
    /// let negative_y = Direction::try_from(Vec2::y(-1)).unwrap();
    /// let positive_y = Direction::try_from(Vec2::y(1)).unwrap();
    ///
    /// assert_eq!(negative_y, Direction::Up);
    /// assert_eq!(positive_y, Direction::Down);
    /// ```
    ///
    /// Passing non-orthogonal vectors, that is, vectors that are neither parallel to the `x`- or
    /// `y`-axis will result in an error.
    ///
    /// ```rust,should_panic
    /// # use std::convert::TryFrom;
    /// # use ruscii::spatial::{Direction, Vec2};
    /// #
    /// Direction::try_from(Vec2::xy(1, 1)).unwrap();  // panics!
    /// ```
    fn try_from(value: Vec2) -> Result<Self, Self::Error> {
        match (value.x.cmp(&0), value.y.cmp(&0)) {
            (Ordering::Less, Ordering::Equal) => Ok(Direction::Left),
            (Ordering::Greater, Ordering::Equal) => Ok(Direction::Right),
            (Ordering::Equal, Ordering::Greater) => Ok(Direction::Down),
            (Ordering::Equal, Ordering::Less) => Ok(Direction::Up),
            (Ordering::Equal, Ordering::Equal) => Ok(Direction::None),
            _ => Err(TryFromVec2Error { value }),
        }
    }
}

#[derive(Debug)]
pub struct TryFromVec2Error {
    value: Vec2,
}

impl fmt::Display for TryFromVec2Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "displacement vector ({}, {}) is not orthogonal",
            self.value.x, self.value.y
        )
    }
}

impl Error for TryFromVec2Error {}