pybevy_math 0.2.1

Math types (Vec2, Vec3, Vec4, Quat, Mat3, Mat4) for PyBevy
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
use bevy::math::{Affine2, Mat2, Vec2};
use pybevy_core::{FromBorrowedStorage, ValueStorage};
use pyo3::{basic::CompareOp, exceptions::PyTypeError, prelude::*};

use super::{mat3::PyMat3, vec2::PyVec2};

#[pyclass(name = "Affine2")]
#[derive(Debug, Clone, PartialEq)]
pub struct PyAffine2 {
    storage: ValueStorage<Affine2>,
}

impl From<PyAffine2> for Affine2 {
    #[inline(always)]
    fn from(py: PyAffine2) -> Self {
        py.storage.get().unwrap()
    }
}

impl From<&PyAffine2> for Affine2 {
    #[inline(always)]
    fn from(py: &PyAffine2) -> Self {
        py.storage.get().unwrap()
    }
}

impl From<Affine2> for PyAffine2 {
    #[inline(always)]
    fn from(affine: Affine2) -> Self {
        PyAffine2::from_affine2(affine)
    }
}

impl FromBorrowedStorage<ValueStorage<Affine2>> for PyAffine2 {
    fn from_borrowed(storage: ValueStorage<Affine2>) -> Self {
        PyAffine2 { storage }
    }
}

impl PyAffine2 {
    #[inline(always)]
    pub fn from_affine2(affine: Affine2) -> Self {
        PyAffine2 {
            storage: ValueStorage::owned(affine),
        }
    }

    #[inline(always)]
    pub const fn affine2(affine: Affine2) -> Self {
        PyAffine2 {
            storage: ValueStorage::owned(affine),
        }
    }

    #[inline(always)]
    fn as_ref(&self) -> PyResult<&Affine2> {
        Ok(self.storage.as_ref()?)
    }

    #[inline(always)]
    fn as_mut(&mut self) -> PyResult<&mut Affine2> {
        Ok(self.storage.as_mut()?)
    }

    #[inline(always)]
    pub fn get(&self) -> Affine2 {
        self.storage.get().unwrap()
    }

    pub const IDENTITY: PyAffine2 = PyAffine2::affine2(Affine2::IDENTITY);
    pub const ZERO: PyAffine2 = PyAffine2::affine2(Affine2::ZERO);
    pub const NAN: PyAffine2 = PyAffine2::affine2(Affine2::NAN);
}

#[pymethods]
impl PyAffine2 {
    #[staticmethod]
    #[pyo3(name = "IDENTITY")]
    pub fn identity() -> Self {
        Self::affine2(Affine2::IDENTITY)
    }
    #[staticmethod]
    #[pyo3(name = "ZERO")]
    pub fn zero() -> Self {
        Self::affine2(Affine2::ZERO)
    }
    #[staticmethod]
    #[pyo3(name = "NAN")]
    pub fn nan() -> Self {
        Self::affine2(Affine2::NAN)
    }

    #[new]
    #[pyo3(signature = (matrix2 = None, translation = None))]
    pub fn new(matrix2: Option<PyMat2>, translation: Option<PyVec2>) -> Self {
        let m2 = matrix2.map(|m| m.into()).unwrap_or(Mat2::IDENTITY);
        let t = translation.map(|v| v.into()).unwrap_or(Vec2::ZERO);
        PyAffine2::from_affine2(Affine2::from_mat2_translation(m2, t))
    }

    #[staticmethod]
    pub fn from_cols(x_axis: PyVec2, y_axis: PyVec2, z_axis: PyVec2) -> Self {
        PyAffine2::from_affine2(Affine2::from_cols(
            x_axis.into(),
            y_axis.into(),
            z_axis.into(),
        ))
    }

    #[staticmethod]
    pub fn from_scale(scale: PyVec2) -> Self {
        PyAffine2::from_affine2(Affine2::from_scale(scale.into()))
    }

    #[staticmethod]
    pub fn from_angle(angle: f32) -> Self {
        PyAffine2::from_affine2(Affine2::from_angle(angle))
    }

    #[staticmethod]
    pub fn from_translation(translation: PyVec2) -> Self {
        PyAffine2::from_affine2(Affine2::from_translation(translation.into()))
    }

    #[staticmethod]
    pub fn from_scale_angle_translation(scale: PyVec2, angle: f32, translation: PyVec2) -> Self {
        PyAffine2::from_affine2(Affine2::from_scale_angle_translation(
            scale.into(),
            angle,
            translation.into(),
        ))
    }

    #[staticmethod]
    pub fn from_mat2(matrix2: PyMat2) -> Self {
        PyAffine2::from_affine2(Affine2::from_mat2(matrix2.into()))
    }

    #[staticmethod]
    pub fn from_mat2_translation(matrix2: PyMat2, translation: PyVec2) -> Self {
        PyAffine2::from_affine2(Affine2::from_mat2_translation(
            matrix2.into(),
            translation.into(),
        ))
    }

    pub fn to_scale_angle_translation(&self) -> PyResult<(PyVec2, f32, PyVec2)> {
        let (scale, angle, translation) = self.as_ref()?.to_scale_angle_translation();
        Ok((scale.into(), angle, translation.into()))
    }

    #[getter]
    pub fn matrix2(&self) -> PyResult<PyMat2> {
        Ok(self.as_ref()?.matrix2.into())
    }

    #[setter]
    pub fn set_matrix2(&mut self, value: PyMat2) -> PyResult<()> {
        self.as_mut()?.matrix2 = value.into();
        Ok(())
    }

    #[getter]
    pub fn translation(&self) -> PyResult<PyVec2> {
        Ok(self.as_ref()?.translation.into())
    }

    #[setter]
    pub fn set_translation(&mut self, value: PyVec2) -> PyResult<()> {
        self.as_mut()?.translation = value.into();
        Ok(())
    }

    pub fn inverse(&self) -> PyResult<PyAffine2> {
        Ok(PyAffine2::from_affine2(self.as_ref()?.inverse()))
    }

    pub fn transform_point2(&self, point: PyVec2) -> PyResult<PyVec2> {
        Ok(self.as_ref()?.transform_point2(point.into()).into())
    }

    pub fn transform_vector2(&self, vector: PyVec2) -> PyResult<PyVec2> {
        Ok(self.as_ref()?.transform_vector2(vector.into()).into())
    }

    pub fn is_finite(&self) -> PyResult<bool> {
        Ok(self.as_ref()?.is_finite())
    }

    pub fn is_nan(&self) -> PyResult<bool> {
        Ok(self.as_ref()?.is_nan())
    }

    pub fn into_mat3(&self) -> PyResult<PyMat3> {
        let affine = self.as_ref()?;
        let mat3: bevy::math::Mat3 = (*affine).into();
        Ok(mat3.into())
    }

    fn __mul__(&self, other: &PyAffine2) -> PyResult<PyAffine2> {
        Ok(PyAffine2::from_affine2(self.get() * other.get()))
    }

    fn __repr__(&self) -> PyResult<String> {
        let a = self.as_ref()?;
        Ok(format!(
            "Affine2(matrix2={:?}, translation={:?})",
            a.matrix2, a.translation
        ))
    }

    fn __richcmp__(&self, other: &Bound<'_, PyAny>, op: CompareOp) -> PyResult<bool> {
        if let Ok(other_affine) = other.extract::<PyAffine2>() {
            match op {
                CompareOp::Eq => Ok(self.get() == other_affine.get()),
                CompareOp::Ne => Ok(self.get() != other_affine.get()),
                _ => Err(PyTypeError::new_err("Unsupported comparison operation")),
            }
        } else {
            Err(PyTypeError::new_err(
                "Can only compare Affine2 with another Affine2",
            ))
        }
    }
}

#[pyclass(name = "Mat2")]
#[derive(Debug, Clone, PartialEq)]
pub struct PyMat2 {
    storage: ValueStorage<Mat2>,
}

impl From<PyMat2> for Mat2 {
    #[inline(always)]
    fn from(py: PyMat2) -> Self {
        py.storage.get().unwrap()
    }
}

impl From<&PyMat2> for Mat2 {
    #[inline(always)]
    fn from(py: &PyMat2) -> Self {
        py.storage.get().unwrap()
    }
}

impl From<Mat2> for PyMat2 {
    #[inline(always)]
    fn from(mat: Mat2) -> Self {
        PyMat2::from_mat2(mat)
    }
}

impl PyMat2 {
    #[inline(always)]
    pub fn from_mat2(mat: Mat2) -> Self {
        PyMat2 {
            storage: ValueStorage::owned(mat),
        }
    }

    #[inline(always)]
    pub const fn mat2(mat: Mat2) -> Self {
        PyMat2 {
            storage: ValueStorage::owned(mat),
        }
    }

    #[inline(always)]
    fn as_ref(&self) -> PyResult<&Mat2> {
        Ok(self.storage.as_ref()?)
    }

    #[inline(always)]
    pub fn get(&self) -> Mat2 {
        self.storage.get().unwrap()
    }
}

#[pymethods]
impl PyMat2 {
    #[classattr]
    pub const IDENTITY: PyMat2 = PyMat2::mat2(Mat2::IDENTITY);

    #[classattr]
    pub const ZERO: PyMat2 = PyMat2::mat2(Mat2::ZERO);

    #[classattr]
    pub const NAN: PyMat2 = PyMat2::mat2(Mat2::NAN);

    #[new]
    #[pyo3(signature = (x_axis = None, y_axis = None))]
    pub fn new(x_axis: Option<PyVec2>, y_axis: Option<PyVec2>) -> Self {
        let x = x_axis.map(|v| v.into()).unwrap_or(Vec2::X);
        let y = y_axis.map(|v| v.into()).unwrap_or(Vec2::Y);
        PyMat2::from_mat2(Mat2::from_cols(x, y))
    }

    #[staticmethod]
    pub fn from_cols(x_axis: PyVec2, y_axis: PyVec2) -> Self {
        PyMat2::from_mat2(Mat2::from_cols(x_axis.into(), y_axis.into()))
    }

    #[staticmethod]
    pub fn from_angle(angle: f32) -> Self {
        PyMat2::from_mat2(Mat2::from_angle(angle))
    }

    #[staticmethod]
    pub fn from_scale_angle(scale: PyVec2, angle: f32) -> Self {
        PyMat2::from_mat2(Mat2::from_scale_angle(scale.into(), angle))
    }

    #[staticmethod]
    pub fn from_diagonal(diagonal: PyVec2) -> Self {
        PyMat2::from_mat2(Mat2::from_diagonal(diagonal.into()))
    }

    pub fn col(&self, index: usize) -> PyResult<PyVec2> {
        Ok(self.as_ref()?.col(index).into())
    }

    pub fn row(&self, index: usize) -> PyResult<PyVec2> {
        Ok(self.as_ref()?.row(index).into())
    }

    #[getter]
    pub fn x_axis(&self) -> PyResult<PyVec2> {
        Ok(self.as_ref()?.x_axis.into())
    }

    #[getter]
    pub fn y_axis(&self) -> PyResult<PyVec2> {
        Ok(self.as_ref()?.y_axis.into())
    }

    pub fn transpose(&self) -> PyResult<PyMat2> {
        Ok(PyMat2::from_mat2(self.as_ref()?.transpose()))
    }

    pub fn determinant(&self) -> PyResult<f32> {
        Ok(self.as_ref()?.determinant())
    }

    pub fn inverse(&self) -> PyResult<PyMat2> {
        Ok(PyMat2::from_mat2(self.as_ref()?.inverse()))
    }

    pub fn mul_vec2(&self, rhs: PyVec2) -> PyResult<PyVec2> {
        Ok(self.as_ref()?.mul_vec2(rhs.into()).into())
    }

    pub fn is_finite(&self) -> PyResult<bool> {
        Ok(self.as_ref()?.is_finite())
    }

    pub fn is_nan(&self) -> PyResult<bool> {
        Ok(self.as_ref()?.is_nan())
    }

    fn __mul__(&self, other: &Bound<'_, PyAny>) -> PyResult<PyMat2> {
        if let Ok(scalar) = other.extract::<f32>() {
            Ok(PyMat2::from_mat2(self.get() * scalar))
        } else if let Ok(other_mat) = other.extract::<PyMat2>() {
            Ok(PyMat2::from_mat2(self.get() * other_mat.get()))
        } else {
            Err(PyTypeError::new_err("Unsupported operand type for *"))
        }
    }

    fn __add__(&self, other: &PyMat2) -> PyResult<PyMat2> {
        Ok(PyMat2::from_mat2(self.get() + other.get()))
    }

    fn __sub__(&self, other: &PyMat2) -> PyResult<PyMat2> {
        Ok(PyMat2::from_mat2(self.get() - other.get()))
    }

    fn __neg__(&self) -> PyResult<PyMat2> {
        Ok(PyMat2::from_mat2(-self.get()))
    }

    fn __repr__(&self) -> PyResult<String> {
        let m = self.as_ref()?;
        Ok(format!(
            "Mat2(x_axis={:?}, y_axis={:?})",
            m.x_axis, m.y_axis
        ))
    }

    fn __richcmp__(&self, other: &Bound<'_, PyAny>, op: CompareOp) -> PyResult<bool> {
        if let Ok(other_mat) = other.extract::<PyMat2>() {
            match op {
                CompareOp::Eq => Ok(self.get() == other_mat.get()),
                CompareOp::Ne => Ok(self.get() != other_mat.get()),
                _ => Err(PyTypeError::new_err("Unsupported comparison operation")),
            }
        } else {
            Err(PyTypeError::new_err(
                "Can only compare Mat2 with another Mat2",
            ))
        }
    }
}

#[cfg(test)]
mod tests {
    use bevy::math::{Affine2, Mat2, Vec2};

    use super::*;

    #[test]
    fn test_pyaffine2_identity() {
        let py_identity = PyAffine2::IDENTITY;
        assert_eq!(py_identity.get(), Affine2::IDENTITY);
    }

    #[test]
    fn test_pyaffine2_from_translation() {
        let translation = Vec2::new(10.0, 20.0);
        let py_affine = PyAffine2::from_translation(PyVec2::from_vec2(translation));
        let expected = Affine2::from_translation(translation);
        assert_eq!(py_affine.get(), expected);
    }

    #[test]
    fn test_pyaffine2_from_scale() {
        let scale = Vec2::new(2.0, 3.0);
        let py_affine = PyAffine2::from_scale(PyVec2::from_vec2(scale));
        let expected = Affine2::from_scale(scale);
        assert_eq!(py_affine.get(), expected);
    }

    #[test]
    fn test_pyaffine2_from_angle() {
        let angle = std::f32::consts::PI / 4.0;
        let py_affine = PyAffine2::from_angle(angle);
        let expected = Affine2::from_angle(angle);
        assert_eq!(py_affine.get(), expected);
    }

    #[test]
    fn test_pyaffine2_inverse() {
        let translation = Vec2::new(5.0, 10.0);
        let py_affine = PyAffine2::from_translation(PyVec2::from_vec2(translation));
        let inverse = py_affine.inverse().unwrap();
        let expected = Affine2::from_translation(translation).inverse();
        assert_eq!(inverse.get(), expected);
    }

    #[test]
    fn test_pyaffine2_transform_point2() {
        let scale = Vec2::new(2.0, 2.0);
        let translation = Vec2::new(1.0, 1.0);
        let py_affine = PyAffine2::from_scale_angle_translation(
            PyVec2::from_vec2(scale),
            0.0,
            PyVec2::from_vec2(translation),
        );
        let point = Vec2::new(1.0, 1.0);
        let result = py_affine
            .transform_point2(PyVec2::from_vec2(point))
            .unwrap();
        // scale(2,2) * (1,1) + translation(1,1) = (3,3)
        assert_eq!(result.get(), Vec2::new(3.0, 3.0));
    }

    #[test]
    fn test_pyaffine2_roundtrip() {
        let bevy_affine =
            Affine2::from_scale_angle_translation(Vec2::new(2.0, 3.0), 1.0, Vec2::new(10.0, 20.0));
        let py_affine: PyAffine2 = bevy_affine.into();
        let back: Affine2 = py_affine.into();
        assert_eq!(bevy_affine, back);
    }

    #[test]
    fn test_pymat2_identity() {
        let py_identity = PyMat2::IDENTITY;
        assert_eq!(py_identity.get(), Mat2::IDENTITY);
    }

    #[test]
    fn test_pymat2_from_angle() {
        let angle = std::f32::consts::PI / 2.0;
        let py_mat = PyMat2::from_angle(angle);
        let expected = Mat2::from_angle(angle);
        assert_eq!(py_mat.get(), expected);
    }

    #[test]
    fn test_pymat2_inverse() {
        let mat = Mat2::from_diagonal(Vec2::new(2.0, 4.0));
        let py_mat = PyMat2::from_mat2(mat);
        let inverse = py_mat.inverse().unwrap();
        assert_eq!(inverse.get(), mat.inverse());
    }

    #[test]
    fn test_pymat2_mul_vec2() {
        let mat = Mat2::from_diagonal(Vec2::new(2.0, 3.0));
        let py_mat = PyMat2::from_mat2(mat);
        let vec = Vec2::new(1.0, 1.0);
        let result = py_mat.mul_vec2(PyVec2::from_vec2(vec)).unwrap();
        assert_eq!(result.get(), Vec2::new(2.0, 3.0));
    }
}