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
// Take a look at the license at the top of the repository in the LICENSE file.

use std::fmt;

use glib::translate::*;

use crate::{Matrix, Point3D, Vec3, Vec4};

impl Matrix {
    /// Initializes a [`Matrix`][crate::Matrix] from the values of an affine
    /// transformation matrix.
    ///
    /// The arguments map to the following matrix layout:
    ///
    ///
    ///
    /// **⚠️ The following code is in plain ⚠️**
    ///
    /// ```plain
    ///   ⎛ xx  yx ⎞   ⎛  a   b  0 ⎞
    ///   ⎜ xy  yy ⎟ = ⎜  c   d  0 ⎟
    ///   ⎝ x0  y0 ⎠   ⎝ tx  ty  1 ⎠
    /// ```
    ///
    /// This function can be used to convert between an affine matrix type
    /// from other libraries and a [`Matrix`][crate::Matrix].
    /// ## `xx`
    /// the xx member
    /// ## `yx`
    /// the yx member
    /// ## `xy`
    /// the xy member
    /// ## `yy`
    /// the yy member
    /// ## `x_0`
    /// the x0 member
    /// ## `y_0`
    /// the y0 member
    ///
    /// # Returns
    ///
    /// the initialized matrix
    #[doc(alias = "graphene_matrix_init_from_2d")]
    #[doc(alias = "init_from_2d")]
    pub fn from_2d(xx: f64, yx: f64, xy: f64, yy: f64, x_0: f64, y_0: f64) -> Self {
        assert_initialized_main_thread!();
        unsafe {
            let mut mat = Self::uninitialized();
            ffi::graphene_matrix_init_from_2d(mat.to_glib_none_mut().0, xx, yx, xy, yy, x_0, y_0);
            mat
        }
    }

    /// Initializes a [`Matrix`][crate::Matrix] with the given array of floating
    /// point values.
    /// ## `v`
    /// an array of at least 16 floating
    ///  point values
    ///
    /// # Returns
    ///
    /// the initialized matrix
    #[doc(alias = "graphene_matrix_init_from_float")]
    #[doc(alias = "init_from_float")]
    pub fn from_float(v: [f32; 16]) -> Self {
        assert_initialized_main_thread!();
        unsafe {
            let mut mat = Self::uninitialized();
            ffi::graphene_matrix_init_from_float(mat.to_glib_none_mut().0, v.as_ptr() as *const _);
            mat
        }
    }

    /// Initializes a [`Matrix`][crate::Matrix] with the given four row
    /// vectors.
    /// ## `v0`
    /// the first row vector
    /// ## `v1`
    /// the second row vector
    /// ## `v2`
    /// the third row vector
    /// ## `v3`
    /// the fourth row vector
    ///
    /// # Returns
    ///
    /// the initialized matrix
    #[doc(alias = "graphene_matrix_init_from_vec4")]
    #[doc(alias = "init_from_vec4")]
    pub fn from_vec4(v0: &Vec4, v1: &Vec4, v2: &Vec4, v3: &Vec4) -> Self {
        assert_initialized_main_thread!();
        unsafe {
            let mut mat = Self::uninitialized();
            ffi::graphene_matrix_init_from_vec4(
                mat.to_glib_none_mut().0,
                v0.to_glib_none().0,
                v1.to_glib_none().0,
                v2.to_glib_none().0,
                v3.to_glib_none().0,
            );
            mat
        }
    }

    /// Initializes a [`Matrix`][crate::Matrix] compatible with [`Frustum`][crate::Frustum].
    ///
    /// See also: [`Frustum::from_matrix()`][crate::Frustum::from_matrix()]
    /// ## `left`
    /// distance of the left clipping plane
    /// ## `right`
    /// distance of the right clipping plane
    /// ## `bottom`
    /// distance of the bottom clipping plane
    /// ## `top`
    /// distance of the top clipping plane
    /// ## `z_near`
    /// distance of the near clipping plane
    /// ## `z_far`
    /// distance of the far clipping plane
    ///
    /// # Returns
    ///
    /// the initialized matrix
    #[doc(alias = "graphene_matrix_init_frustum")]
    #[doc(alias = "init_frustum")]
    pub fn new_frustum(
        left: f32,
        right: f32,
        bottom: f32,
        top: f32,
        z_near: f32,
        z_far: f32,
    ) -> Self {
        assert_initialized_main_thread!();
        unsafe {
            let mut mat = Self::uninitialized();
            ffi::graphene_matrix_init_frustum(
                mat.to_glib_none_mut().0,
                left,
                right,
                bottom,
                top,
                z_near,
                z_far,
            );
            mat
        }
    }

    /// Initializes a [`Matrix`][crate::Matrix] with the identity matrix.
    ///
    /// # Returns
    ///
    /// the initialized matrix
    #[doc(alias = "graphene_matrix_init_identity")]
    #[doc(alias = "init_identity")]
    pub fn new_identity() -> Self {
        assert_initialized_main_thread!();
        unsafe {
            let mut mat = Self::uninitialized();
            ffi::graphene_matrix_init_identity(mat.to_glib_none_mut().0);
            mat
        }
    }

    /// Initializes a [`Matrix`][crate::Matrix] so that it positions the "camera"
    /// at the given `eye` coordinates towards an object at the `center`
    /// coordinates. The top of the camera is aligned to the direction
    /// of the `up` vector.
    ///
    /// Before the transform, the camera is assumed to be placed at the
    /// origin, looking towards the negative Z axis, with the top side of
    /// the camera facing in the direction of the Y axis and the right
    /// side in the direction of the X axis.
    ///
    /// In theory, one could use `self` to transform a model of such a camera
    /// into world-space. However, it is more common to use the inverse of
    /// `self` to transform another object from world coordinates to the view
    /// coordinates of the camera. Typically you would then apply the
    /// camera projection transform to get from view to screen
    /// coordinates.
    /// ## `eye`
    /// the vector describing the position to look from
    /// ## `center`
    /// the vector describing the position to look at
    /// ## `up`
    /// the vector describing the world's upward direction; usually,
    ///  this is the [`Vec3::y_axis()`][crate::Vec3::y_axis()] vector
    ///
    /// # Returns
    ///
    /// the initialized matrix
    #[doc(alias = "graphene_matrix_init_look_at")]
    #[doc(alias = "init_look_at")]
    pub fn new_look_at(eye: &Vec3, center: &Vec3, up: &Vec3) -> Self {
        assert_initialized_main_thread!();
        unsafe {
            let mut mat = Self::uninitialized();
            ffi::graphene_matrix_init_look_at(
                mat.to_glib_none_mut().0,
                eye.to_glib_none().0,
                center.to_glib_none().0,
                up.to_glib_none().0,
            );
            mat
        }
    }

    /// Initializes a [`Matrix`][crate::Matrix] with an orthographic projection.
    /// ## `left`
    /// the left edge of the clipping plane
    /// ## `right`
    /// the right edge of the clipping plane
    /// ## `top`
    /// the top edge of the clipping plane
    /// ## `bottom`
    /// the bottom edge of the clipping plane
    /// ## `z_near`
    /// the distance of the near clipping plane
    /// ## `z_far`
    /// the distance of the far clipping plane
    ///
    /// # Returns
    ///
    /// the initialized matrix
    #[doc(alias = "graphene_matrix_init_ortho")]
    #[doc(alias = "init_ortho")]
    pub fn new_ortho(
        left: f32,
        right: f32,
        top: f32,
        bottom: f32,
        z_near: f32,
        z_far: f32,
    ) -> Self {
        assert_initialized_main_thread!();
        unsafe {
            let mut mat = Self::uninitialized();
            ffi::graphene_matrix_init_ortho(
                mat.to_glib_none_mut().0,
                left,
                right,
                top,
                bottom,
                z_near,
                z_far,
            );
            mat
        }
    }

    /// Initializes a [`Matrix`][crate::Matrix] with a perspective projection.
    /// ## `fovy`
    /// the field of view angle, in degrees
    /// ## `aspect`
    /// the aspect value
    /// ## `z_near`
    /// the near Z plane
    /// ## `z_far`
    /// the far Z plane
    ///
    /// # Returns
    ///
    /// the initialized matrix
    #[doc(alias = "graphene_matrix_init_perspective")]
    #[doc(alias = "init_perspective")]
    pub fn new_perspective(fovy: f32, aspect: f32, z_near: f32, z_far: f32) -> Self {
        assert_initialized_main_thread!();
        unsafe {
            let mut mat = Self::uninitialized();
            ffi::graphene_matrix_init_perspective(
                mat.to_glib_none_mut().0,
                fovy,
                aspect,
                z_near,
                z_far,
            );
            mat
        }
    }

    /// Initializes `self` to represent a rotation of `angle` degrees on
    /// the axis represented by the `axis` vector.
    /// ## `angle`
    /// the rotation angle, in degrees
    /// ## `axis`
    /// the axis vector as a [`Vec3`][crate::Vec3]
    ///
    /// # Returns
    ///
    /// the initialized matrix
    #[doc(alias = "graphene_matrix_init_rotate")]
    #[doc(alias = "init_rotate")]
    pub fn new_rotate(angle: f32, axis: &Vec3) -> Self {
        assert_initialized_main_thread!();
        unsafe {
            let mut mat = Self::uninitialized();
            ffi::graphene_matrix_init_rotate(
                mat.to_glib_none_mut().0,
                angle,
                axis.to_glib_none().0,
            );
            mat
        }
    }

    /// Initializes a [`Matrix`][crate::Matrix] with the given scaling factors.
    /// ## `x`
    /// the scale factor on the X axis
    /// ## `y`
    /// the scale factor on the Y axis
    /// ## `z`
    /// the scale factor on the Z axis
    ///
    /// # Returns
    ///
    /// the initialized matrix
    #[doc(alias = "graphene_matrix_init_scale")]
    #[doc(alias = "init_scale")]
    pub fn new_scale(x: f32, y: f32, z: f32) -> Self {
        assert_initialized_main_thread!();
        unsafe {
            let mut mat = Self::uninitialized();
            ffi::graphene_matrix_init_scale(mat.to_glib_none_mut().0, x, y, z);
            mat
        }
    }

    /// Initializes a [`Matrix`][crate::Matrix] with a skew transformation
    /// with the given factors.
    /// ## `x_skew`
    /// skew factor, in radians, on the X axis
    /// ## `y_skew`
    /// skew factor, in radians, on the Y axis
    ///
    /// # Returns
    ///
    /// the initialized matrix
    #[doc(alias = "graphene_matrix_init_skew")]
    #[doc(alias = "init_skew")]
    pub fn new_skew(x_skew: f32, y_skew: f32) -> Self {
        assert_initialized_main_thread!();
        unsafe {
            let mut mat = Self::uninitialized();
            ffi::graphene_matrix_init_skew(mat.to_glib_none_mut().0, x_skew, y_skew);
            mat
        }
    }

    /// Initializes a [`Matrix`][crate::Matrix] with a translation to the
    /// given coordinates.
    /// ## `p`
    /// the translation coordinates
    ///
    /// # Returns
    ///
    /// the initialized matrix
    #[doc(alias = "graphene_matrix_init_translate")]
    #[doc(alias = "init_translate")]
    pub fn new_translate(p: &Point3D) -> Self {
        assert_initialized_main_thread!();
        unsafe {
            let mut mat = Self::uninitialized();
            ffi::graphene_matrix_init_translate(mat.to_glib_none_mut().0, p.to_glib_none().0);
            mat
        }
    }

    /// Converts a [`Matrix`][crate::Matrix] to an array of floating point
    /// values.
    ///
    /// # Returns
    ///
    ///
    /// ## `v`
    /// return location
    ///  for an array of floating point values. The array must be capable
    ///  of holding at least 16 values.
    #[doc(alias = "graphene_matrix_to_float")]
    pub fn to_float(&self) -> [f32; 16] {
        unsafe {
            let mut out = std::mem::MaybeUninit::uninit();
            ffi::graphene_matrix_to_float(self.to_glib_none().0, out.as_mut_ptr());
            out.assume_init()
        }
    }

    #[inline]
    pub fn values(&self) -> &[[f32; 4]; 4] {
        unsafe { &*(&self.inner.value as *const ffi::graphene_simd4x4f_t as *const [[f32; 4]; 4]) }
    }
}

impl fmt::Debug for Matrix {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Matrix")
            .field("values", &self.values())
            .finish()
    }
}

impl Default for Matrix {
    fn default() -> Self {
        Self::new_identity()
    }
}

#[cfg(test)]
mod tests {
    use super::Matrix;
    #[test]
    fn test_matrix_values() {
        let matrix = Matrix::new_identity();
        assert_eq!(
            matrix.values(),
            &[
                [1.0, 0.0, 0.0, 0.0],
                [0.0, 1.0, 0.0, 0.0],
                [0.0, 0.0, 1.0, 0.0],
                [0.0, 0.0, 0.0, 1.0]
            ],
        );
    }
}