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
use crate::Axis;
use core::convert::TryFrom;
use core::ops::*;
use num_traits::float::Float;
use num_traits::Zero;
use ordered_float::NotNan;
use primitive_from::PrimitiveFrom;

///Convenience function to create a vector.
#[inline(always)]
pub const fn vec2<N>(x: N, y: N) -> Vec2<N> {
    Vec2 { x, y }
}

///Convenience function to create a vector where both component are the same.
#[inline(always)]
pub fn vec2same<N: Copy>(a: N) -> Vec2<N> {
    Vec2 { x: a, y: a }
}

impl<N: Float> AsRef<Vec2<N>> for Vec2<NotNan<N>> {
    #[inline(always)]
    fn as_ref(&self) -> &Vec2<N> {
        unsafe { &*((self as *const Self) as *const Vec2<N>) }
    }
}

impl<N: Float> AsMut<Vec2<N>> for Vec2<NotNan<N>> {
    #[inline(always)]
    fn as_mut(&mut self) -> &mut Vec2<N> {
        unsafe { &mut *((self as *mut Self) as *mut Vec2<N>) }
    }
}

///A 2D vector.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Vec2<N> {
    pub x: N,
    pub y: N,
}


#[inline(always)]
pub fn absdiff<T>(x: T, y: T) -> T
where
    T: Sub<Output = T> + PartialOrd,
{
    if x < y {
        y - x
    } else {
        x - y
    }
}


fn gen_abs<S:Neg<Output=S>+PartialOrd+Zero>(num:S)->S{
    if num<S::zero(){
        -num
    }else{
        num
    }
}
impl<S:Copy + Neg<Output=S>+PartialOrd+Zero> Vec2<S>{

    #[inline(always)]
    pub fn abs(&self)->Vec2<S>{
        vec2(gen_abs(self.x),gen_abs(self.y))   
    }   
    #[inline(always)]
    pub fn rotate_90deg_right(&self)->Vec2<S>{
        vec2(-self.y,self.x)
    }
    #[inline(always)]
    pub fn rotate_90deg_left(&self)->Vec2<S>{
        vec2(self.y,self.x)
    }

    #[inline(always)]
    pub fn split_into_components(&self)->[Vec2<S>;2]{
        [vec2(self.x,S::zero()),vec2(S::zero(),self.y)]
    }  
 
}

impl<S:Add<Output=S> + Sub<Output=S>+PartialOrd + Copy> Vec2<S>{
    #[inline(always)]
    pub fn manhattan_dis(&self,other:Vec2<S>)->S{
        (absdiff(self.x, other.x) + absdiff(self.y, other.y))
    }
    
}

impl<
        T: Copy
            + PartialOrd
            + core::ops::Sub<Output = T>
            + core::ops::Mul<Output = T>
            + core::ops::Add<Output = T>,
    > Vec2<T>
{
    ///If the point is outisde the rectangle, returns the squared distance from a point to a rectangle.
    ///If the point is inside the rectangle, it will return None.
    #[inline(always)]
    pub fn distance_squared_to_point(&self, point: Vec2<T>)->T {
        (point.x-self.x)*(point.x-self.x)+(point.y-self.y)*(point.y-self.y)
    }
}


#[test]
fn test_rotate(){

    let b=vec2(1,1).rotate_90deg_right();
    assert_eq!(b,vec2(-1,1));

    let b=vec2(1,0).rotate_90deg_right();
    assert_eq!(b,vec2(0,1));

}



impl<S: Mul<Output = S>+ Div<Output=S>+ Add<Output = S> + Copy> Vec2<S> {
    #[inline(always)]
    pub fn scale(&self,other:Vec2<S>)->Vec2<S>{
        vec2(self.x*other.x,self.y*other.y)
    }

    #[inline(always)]
    pub fn inv_scale(&self,other:Vec2<S>)->Vec2<S>{
        vec2(self.x/other.x,self.y/other.y)
    }

    #[inline(always)]
    pub fn magnitude2(&self) -> S {
        self.x * self.x + self.y * self.y
    }
    #[inline(always)]
    pub fn dot(&self, other: Vec2<S>) -> S {
        self.x * other.x + self.y * other.y
    }
}
impl<S: Float> Vec2<S> {
    #[inline(always)]
    pub fn truncate_at(&self, mag: S) -> Vec2<S> {
        if self.magnitude()>mag{
            self.normalize_to(mag)
        }else{
            *self
        }
    }

    #[inline(always)]
    pub fn normalize_to(&self, mag: S) -> Vec2<S> {
        let l = self.magnitude2().sqrt();
        (*self) * (mag / l)
    }

    #[inline(always)]
    pub fn magnitude(&self) -> S {
        self.magnitude2().sqrt()
    }
}

///Cast an array of 2 elements of primitive type to another primitive type using "as" on each element.
pub fn arr2_as<B: Copy, A: PrimitiveFrom<B>>(a: [B; 2]) -> [A; 2] {
    [PrimitiveFrom::from(a[0]), PrimitiveFrom::from(a[1])]
}

impl<B: Copy> Vec2<B> {
    pub fn inner_as<A: PrimitiveFrom<B>>(&self) -> Vec2<A> {
        vec2(PrimitiveFrom::from(self.x), PrimitiveFrom::from(self.y))
    }
}

impl<B> Vec2<B> {

    ///Get the range of one axis.
    #[inline(always)]
    pub fn get_axis(&self, axis: impl Axis) -> &B {
        if axis.is_xaxis() {
            &self.x
        } else {
            &self.y
        }
    }

    ///Get the mutable range of one axis.
    #[inline(always)]
    pub fn get_axis_mut(&mut self, axis: impl Axis) -> &mut B {
        if axis.is_xaxis() {
            &mut self.x
        } else {
            &mut self.y
        }
    }

    #[inline(always)]
    pub fn inner_into<A: From<B>>(self) -> Vec2<A> {
        let x = A::from(self.x);
        let y = A::from(self.y);
        vec2(x, y)
    }

    #[inline(always)]
    pub fn inner_try_into<A: TryFrom<B>>(self) -> Result<Vec2<A>, A::Error> {
        let x = A::try_from(self.x);
        let y = A::try_from(self.y);
        match (x, y) {
            (Ok(x), Ok(y)) => Ok(vec2(x, y)),
            (Ok(_), Err(e)) => Err(e),
            (Err(e), Ok(_)) => Err(e),
            (Err(e), Err(_)) => Err(e),
        }
    }
}


impl<S: Add<Output = S> + Copy> Add<Self> for Vec2<S> {
    type Output = Self;
    #[inline(always)]
    fn add(self, rhs: Self) -> Self {
        vec2(self.x + rhs.x, self.y + rhs.y)
    }
}

impl<S: Sub<Output = S> + Copy> Sub<Self> for Vec2<S> {
    type Output = Self;
    #[inline(always)]
    fn sub(self, rhs: Self) -> Self {
        vec2(self.x - rhs.x, self.y - rhs.y)
    }
}

impl<S: Mul<Output = S> + Copy> Mul<S> for Vec2<S> {
    type Output = Self;
    #[inline(always)]
    fn mul(self, rhs: S) -> Self {
        vec2(self.x * rhs, self.y * rhs)
    }
}

impl<S: Div<Output = S> + Copy> Div<S> for Vec2<S> {
    type Output = Self;
    #[inline(always)]
    fn div(self, rhs: S) -> Self {
        vec2(self.x / rhs, self.y / rhs)
    }
}

impl<S: DivAssign<S> + Copy> DivAssign<S> for Vec2<S> {
    #[inline(always)]
    fn div_assign(&mut self, scalar: S) {
        self.x /= scalar;
        self.y /= scalar;
    }
}
impl<S: MulAssign<S> + Copy> MulAssign<S> for Vec2<S> {
    #[inline(always)]
    fn mul_assign(&mut self, scalar: S) {
        self.x *= scalar;
        self.y *= scalar;
    }
}

impl<S: AddAssign<S> + Copy> AddAssign<Self> for Vec2<S> {
    #[inline(always)]
    fn add_assign(&mut self, rhs: Self) {
        self.x += rhs.x;
        self.y += rhs.y;
    }
}
impl<S: SubAssign<S> + Copy> SubAssign<Self> for Vec2<S> {
    #[inline(always)]
    fn sub_assign(&mut self, rhs: Self) {
        self.x -= rhs.x;
        self.y -= rhs.y;
    }
}

impl<S: Neg<Output = S>> Neg for Vec2<S> {
    type Output = Vec2<S>;

    #[inline]
    fn neg(self) -> Vec2<S> {
        vec2(-self.x, -self.y)
    }
}

impl<S: Zero + Eq + Copy> Zero for Vec2<S> {
    #[inline(always)]
    fn zero() -> Vec2<S> {
        vec2(S::zero(), S::zero())
    }

    #[inline(always)]
    fn is_zero(&self) -> bool {
        *self == Vec2::zero()
    }
}