burbomath 0.0.1

Burbokop's rust math library
Documentation
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
use super::{Complex, One, Point, Rect, Size, Two, Vector, Zero};
use core::{
    fmt::Debug,
    ops::{Add, Div, Mul, Neg, Not, Sub},
};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Matrix<T>([T; 9]);

pub mod indices {
    /// horizontal scale factor
    pub const SCALE_X: usize = 0;
    /// horizontal skew factor
    pub const SKEW_X: usize = 1;
    /// horizontal translation
    pub const TRANS_X: usize = 2;
    /// vertical skew factor
    pub const SKEW_Y: usize = 3;
    /// vertical scale factor
    pub const SCALE_Y: usize = 4;
    /// vertical translation
    pub const TRANS_Y: usize = 5;
    /// input x perspective factor
    pub const PERSP0: usize = 6;
    /// input y perspective factor
    pub const PERSP1: usize = 7;
    /// perspective bias
    pub const PERSP2: usize = 8;
}

impl<T> Matrix<T> {
    /**
     * @brief identity - create identity matrix
     *  | 1  0  0 |
     *  | 0  1  0 |
     *  | 0  0  1 |
     * @return identity matrix
     */
    pub fn identity() -> Self
    where
        T: Zero + One,
    {
        Self([
            T::one(),
            T::zero(),
            T::zero(),
            T::zero(),
            T::one(),
            T::zero(),
            T::zero(),
            T::zero(),
            T::one(),
        ])
    }

    /**
     * @brief scale - create scale matrix
     *  | x  0  0 |
     *  | 0  y  0 |
     *  | 0  0  1 |
     * @param x - horizontal scale factor
     * @param y - vertical scale factor
     * @return Matrix with scale
     */
    pub fn scale(x: T, y: T) -> Self
    where
        T: Zero + One,
    {
        Self([
            x,
            T::zero(),
            T::zero(),
            T::zero(),
            y,
            T::zero(),
            T::zero(),
            T::zero(),
            T::one(),
        ])
    }

    /**
     * @brief translate - create translate matrix
     *  | 1  0  x |
     *  | 0  1  y |
     *  | 0  0  1 |
     * @param x - horizontal translation
     * @param y - vertical translation
     * @return Matrix with translation
     */
    pub fn translate(offset: Vector<T>) -> Self
    where
        T: Zero + One + Clone,
    {
        Self([
            T::one(),
            T::zero(),
            offset.x().clone(),
            T::zero(),
            T::one(),
            offset.y().clone(),
            T::zero(),
            T::zero(),
            T::one(),
        ])
    }

    /**
     * @brief rotate - create translate matrix from radians
     *  | cos(θ) -sin(θ)   0 |
     *  | sin(θ)  cos(θ)   0 |
     *  |   0       0      1 |
     * @param rad
     * @return Matrix with rotation
     */
    pub fn rotate(rotor: Complex<T>) -> Self
    where
        T: Zero + One + Clone + Neg<Output = T>,
    {
        Self([
            rotor.real().clone(),
            -rotor.imag().clone(),
            T::zero(),
            rotor.imag().clone(),
            rotor.real().clone(),
            T::zero(),
            T::zero(),
            T::zero(),
            T::one(),
        ])
    }

    pub fn scale_x(&self) -> &T {
        &self.0[indices::SCALE_X]
    }

    pub fn scale_y(&self) -> &T {
        &self.0[indices::SCALE_Y]
    }

    pub fn average_scale(&self) -> T
    where
        T: Two + Clone + Add<Output = T> + Div<Output = T>,
    {
        (self.0[indices::SCALE_X].clone() + self.0[indices::SCALE_Y].clone()) / T::two()
    }

    pub fn translation(&self) -> Vector<T>
    where
        T: Clone,
    {
        (
            self.0[indices::TRANS_X].clone(),
            self.0[indices::TRANS_Y].clone(),
        )
            .into()
    }

    pub fn rotation(&self) -> Complex<T>
    where
        T: Div<Output = T> + Neg<Output = T> + Clone,
    {
        (
            self.0[indices::SCALE_X].clone() / self.0[indices::SCALE_Y].clone(),
            -self.0[indices::SKEW_X].clone() / self.0[indices::SKEW_Y].clone(),
        )
            .into()
    }

    /*
     * @brief apply_affine_to_point
     * @return vector (x, y) multiplied by matrix
     *               | A B C |
     * @param self - | D E F |
     *               | G H I |
     *              | x |
     * @param rhs - | y |
     *              | 1 |
     *
     *                       |A B C| |x|                               Ax+By+C   Dx+Ey+F
     * @return Matrix * pt = |D E F| |y| = |Ax+By+C Dx+Ey+F Gx+Hy+I| = ------- , -------
     *                       |G H I| |1|                               Gx+Hy+I   Gx+Hy+I
     */
    fn apply_affine_to_point<'a>(&'a self, rhs: &Point<T>) -> Point<T>
    where
        T: One + Clone + Div<Output = T>,
        &'a Matrix<T>: Mul<[T; 3], Output = [T; 3]>,
    {
        let result = self * [rhs.x().clone(), rhs.y().clone(), T::one()];
        (
            result[0].clone() / result[2].clone(),
            result[1].clone() / result[2].clone(),
        )
            .into()
    }

    fn apply_affine_to_rect<'a>(&'a self, rhs: &Rect<T>) -> Rect<T>
    where
        T: One + Add<Output = T> + Sub<Output = T> + Div<Output = T> + Clone + PartialOrd,
        &'a Matrix<T>: Mul<[T; 3], Output = [T; 3]>,
    {
        return Rect::aabb_from_points(
            [
                self.apply_affine_to_point(&rhs.left_top()),
                self.apply_affine_to_point(&rhs.right_top()),
                self.apply_affine_to_point(&rhs.right_bottom()),
                self.apply_affine_to_point(&rhs.left_bottom()),
            ]
            .into_iter(),
        )
        .unwrap();
    }

    /*
     * @brief apply_affine_without_translation
     * @return vector (x, y) multiplied by matrix, treating matrix translation as zero.
     *               | A B 0 |
     * @param self - | D E 0 |
     *               | G H I |
     *              | x |
     * @param rhs - | y |
     *              | 1 |
     *
     *            |A B 0| |x|                            Ax+By     Dx+Ey
     * @return -  |D E 0| |y| = |Ax+By Dx+Ey Gx+Hy+I| = ------- , -------
     *            |G H I| |1|                           Gx+Hy+I   Gx+Hy+I
     */
    pub fn apply_affine_without_translation<'a>(&'a self, rhs: &Point<T>) -> Point<T>
    where
        T: Zero + One + Div<Output = T> + Clone + Add<Output = T> + Mul<Output = T>,
        &'a Matrix<T>: Mul<[T; 3], Output = [T; 3]>,
    {
        let result = Self([
            self.a().clone(),
            self.b().clone(),
            T::zero(),
            self.d().clone(),
            self.e().clone(),
            T::zero(),
            self.g().clone(),
            self.h().clone(),
            self.i().clone(),
        ]) * &[rhs.x().clone(), rhs.y().clone(), T::one()];
        (
            result[0].clone() / result[2].clone(),
            result[1].clone() / result[2].clone(),
        )
            .into()
    }

    /**
     * @brief apply_only_scale - apply only affine scale to size object
     */
    fn apply_only_scale(&self, rhs: &Size<T>) -> Size<T>
    where
        T: Clone + Mul<Output = T>,
    {
        (
            rhs.w().clone() * self.a().clone(),
            rhs.h().clone() * self.e().clone(),
        )
            .into()
    }

    /**
     * @brief transposed
     * @return returns matrix reflected about the main diagonal
     */
    fn transposed(&self) -> Self
    where
        T: Clone,
    {
        return Self([
            self.a().clone(),
            self.d().clone(),
            self.g().clone(),
            self.b().clone(),
            self.e().clone(),
            self.h().clone(),
            self.c().clone(),
            self.f().clone(),
            self.i().clone(),
        ]);
    }

    fn minor<const I: usize, const J: usize>(&self) -> [T; 4]
    where
        T: Default + Clone,
    {
        let side_len = 3;

        assert!(I < side_len && J < side_len);
        let mut pos: usize = 0;
        let mut result: [T; 4] = Default::default();
        for y in 0..side_len {
            for x in 0..side_len {
                if x != I && y != J {
                    result[pos] = self.0[x + y * side_len].clone();
                    pos += 1;
                }
            }
        }
        return result;
    }

    /**
     * @brief det2x2 - determinant of 2x2 matrix
     * @return
     */
    fn det2x2(data: [T; 4]) -> T
    where
        T: Clone + Mul<Output = T> + Sub<Output = T>,
    {
        return data[0].clone() * data[3].clone() - data[1].clone() * data[2].clone();
    }

    /**
     * @brief det - determinant
     * @return
     */
    fn det(&self) -> T
    where
        T: Clone + Mul<Output = T> + Add<Output = T> + Sub<Output = T>,
    {
        return self.a().clone() * self.e().clone() * self.i().clone()
            + self.b().clone() * self.f().clone() * self.g().clone()
            + self.c().clone() * self.d().clone() * self.h().clone()
            - self.c().clone() * self.e().clone() * self.g().clone()
            - self.b().clone() * self.d().clone() * self.i().clone()
            - self.a().clone() * self.f().clone() * self.h().clone();
    }

    fn a(&self) -> &T {
        return &self.0[0];
    }
    fn b(&self) -> &T {
        return &self.0[1];
    }
    fn c(&self) -> &T {
        return &self.0[2];
    }
    fn d(&self) -> &T {
        return &self.0[3];
    }
    fn e(&self) -> &T {
        return &self.0[4];
    }
    fn f(&self) -> &T {
        return &self.0[5];
    }
    fn g(&self) -> &T {
        return &self.0[6];
    }
    fn h(&self) -> &T {
        return &self.0[7];
    }
    fn i(&self) -> &T {
        return &self.0[8];
    }
}

/// https://d138zd1ktt9iqe.cloudfront.net/media/seo_landing_files/multiplication-of-matrices-of-order-3-x-3-1627879219.png
impl<T> Mul for &Matrix<T>
where
    T: Clone + Mul<Output = T> + Add<Output = T>,
{
    type Output = Matrix<T>;

    fn mul(self, rhs: Self) -> Self::Output {
        let l = &self.0;
        let r = &rhs.0;

        Matrix([
            (l[0].clone() * r[0].clone()
                + l[1].clone() * r[3].clone()
                + l[2].clone() * r[6].clone()),
            (l[0].clone() * r[1].clone()
                + l[1].clone() * r[4].clone()
                + l[2].clone() * r[7].clone()),
            (l[0].clone() * r[2].clone()
                + l[1].clone() * r[5].clone()
                + l[2].clone() * r[8].clone()),
            (l[3].clone() * r[0].clone()
                + l[4].clone() * r[3].clone()
                + l[5].clone() * r[6].clone()),
            (l[3].clone() * r[1].clone()
                + l[4].clone() * r[4].clone()
                + l[5].clone() * r[7].clone()),
            (l[3].clone() * r[2].clone()
                + l[4].clone() * r[5].clone()
                + l[5].clone() * r[8].clone()),
            (l[6].clone() * r[0].clone()
                + l[7].clone() * r[3].clone()
                + l[8].clone() * r[6].clone()),
            (l[6].clone() * r[1].clone()
                + l[7].clone() * r[4].clone()
                + l[8].clone() * r[7].clone()),
            (l[6].clone() * r[2].clone()
                + l[7].clone() * r[5].clone()
                + l[8].clone() * r[8].clone()),
        ])
    }
}

impl<T> Mul<&Matrix<T>> for Matrix<T>
where
    T: Clone + Mul<Output = T> + Add<Output = T>,
{
    type Output = Matrix<T>;

    fn mul(self, rhs: &Matrix<T>) -> Self::Output {
        let l = &self.0;
        let r = &rhs.0;

        Matrix([
            (l[0].clone() * r[0].clone()
                + l[1].clone() * r[3].clone()
                + l[2].clone() * r[6].clone()),
            (l[0].clone() * r[1].clone()
                + l[1].clone() * r[4].clone()
                + l[2].clone() * r[7].clone()),
            (l[0].clone() * r[2].clone()
                + l[1].clone() * r[5].clone()
                + l[2].clone() * r[8].clone()),
            (l[3].clone() * r[0].clone()
                + l[4].clone() * r[3].clone()
                + l[5].clone() * r[6].clone()),
            (l[3].clone() * r[1].clone()
                + l[4].clone() * r[4].clone()
                + l[5].clone() * r[7].clone()),
            (l[3].clone() * r[2].clone()
                + l[4].clone() * r[5].clone()
                + l[5].clone() * r[8].clone()),
            (l[6].clone() * r[0].clone()
                + l[7].clone() * r[3].clone()
                + l[8].clone() * r[6].clone()),
            (l[6].clone() * r[1].clone()
                + l[7].clone() * r[4].clone()
                + l[8].clone() * r[7].clone()),
            (l[6].clone() * r[2].clone()
                + l[7].clone() * r[5].clone()
                + l[8].clone() * r[8].clone()),
        ])
    }
}

impl<T> Mul<&[T; 3]> for &Matrix<T>
where
    T: Clone + Mul<Output = T> + Add<Output = T>,
{
    type Output = [T; 3];

    fn mul(self, rhs: &[T; 3]) -> Self::Output {
        let x = &rhs[0];
        let y = &rhs[1];
        let z = &rhs[2];
        [
            (self.a().clone() * x.clone()
                + self.b().clone() * y.clone()
                + self.c().clone() * z.clone()),
            (self.d().clone() * x.clone()
                + self.e().clone() * y.clone()
                + self.f().clone() * z.clone()),
            (self.g().clone() * x.clone()
                + self.h().clone() * y.clone()
                + self.i().clone() * z.clone()),
        ]
    }
}

impl<T> Mul<&[T; 3]> for Matrix<T>
where
    T: Clone + Mul<Output = T> + Add<Output = T>,
{
    type Output = [T; 3];

    fn mul(self, rhs: &[T; 3]) -> Self::Output {
        let x = &rhs[0];
        let y = &rhs[1];
        let z = &rhs[2];
        [
            (self.a().clone() * x.clone()
                + self.b().clone() * y.clone()
                + self.c().clone() * z.clone()),
            (self.d().clone() * x.clone()
                + self.e().clone() * y.clone()
                + self.f().clone() * z.clone()),
            (self.g().clone() * x.clone()
                + self.h().clone() * y.clone()
                + self.i().clone() * z.clone()),
        ]
    }
}

impl<T> Mul<[T; 3]> for &Matrix<T>
where
    T: Clone + Mul<Output = T> + Add<Output = T>,
{
    type Output = [T; 3];

    fn mul(self, rhs: [T; 3]) -> Self::Output {
        let x = &rhs[0];
        let y = &rhs[1];
        let z = &rhs[2];
        [
            (self.a().clone() * x.clone()
                + self.b().clone() * y.clone()
                + self.c().clone() * z.clone()),
            (self.d().clone() * x.clone()
                + self.e().clone() * y.clone()
                + self.f().clone() * z.clone()),
            (self.g().clone() * x.clone()
                + self.h().clone() * y.clone()
                + self.i().clone() * z.clone()),
        ]
    }
}

impl<'a, T> Mul<&Point<T>> for &'a Matrix<T>
where
    T: One + Clone + Div<Output = T>,
    &'a Matrix<T>: Mul<[T; 3], Output = [T; 3]>,
{
    type Output = Point<T>;

    fn mul(self, rhs: &Point<T>) -> Self::Output {
        self.apply_affine_to_point(rhs)
    }
}

impl<T> Mul<&Size<T>> for &Matrix<T>
where
    T: Clone + Mul<Output = T>,
{
    type Output = Size<T>;

    fn mul(self, rhs: &Size<T>) -> Self::Output {
        self.apply_only_scale(rhs)
    }
}

impl<'a, T> Mul<&Rect<T>> for &'a Matrix<T>
where
    T: One + Add<Output = T> + Sub<Output = T> + Div<Output = T> + Clone + PartialOrd,
    &'a Matrix<T>: Mul<[T; 3], Output = [T; 3]>,
{
    type Output = Rect<T>;

    fn mul(self, rhs: &Rect<T>) -> Self::Output {
        self.apply_affine_to_rect(rhs)
    }
}

/**
 * @brief Not - invert matrix
 * @return inverted matrix if it is invertable else None
 */
impl<T> Not for &Matrix<T>
where
    T: Clone
        + Zero
        + PartialEq
        + Default
        + Mul<Output = T>
        + Add<Output = T>
        + Sub<Output = T>
        + Div<Output = T>
        + Neg<Output = T>,
{
    type Output = Option<Matrix<T>>;

    fn not(self) -> Self::Output {
        let det = self.det();
        if det == T::zero() {
            return None;
        }
        let t = self.transposed();
        Some(Matrix([
            Matrix::det2x2(t.minor::<0, 0>()) / det.clone(),
            -Matrix::det2x2(t.minor::<1, 0>()) / det.clone(),
            Matrix::det2x2(t.minor::<2, 0>()) / det.clone(),
            -Matrix::det2x2(t.minor::<0, 1>()) / det.clone(),
            Matrix::det2x2(t.minor::<1, 1>()) / det.clone(),
            -Matrix::det2x2(t.minor::<2, 1>()) / det.clone(),
            Matrix::det2x2(t.minor::<0, 2>()) / det.clone(),
            -Matrix::det2x2(t.minor::<1, 2>()) / det.clone(),
            Matrix::det2x2(t.minor::<2, 2>()) / det.clone(),
        ]))
    }
}

impl Matrix<f32> {
    pub fn as_f64(self) -> Matrix<f64> {
        Matrix(self.0.map(|x| x as f64))
    }
}

impl Matrix<f64> {
    pub fn as_f32(self) -> Matrix<f32> {
        Matrix(self.0.map(|x| x as f32))
    }
}

impl<T> From<Matrix<T>> for [T; 9] {
    fn from(value: Matrix<T>) -> Self {
        value.0
    }
}