pythagore_wasm/
force_2d.rs

1use wasm_bindgen::prelude::wasm_bindgen;
2use pythagore::{self as py, force};
3
4#[wasm_bindgen]
5#[derive(Copy, Clone, Debug)]
6pub struct Force2D {
7    force: py::Force2D<f64>,
8}
9
10#[wasm_bindgen]
11impl Force2D {
12    /// Creates a new force from given coordinates
13    #[wasm_bindgen(constructor)]
14    pub fn new(dx: f64, dy: f64) -> Force2D {
15        Force2D { force: force![dx, dy] }
16    }
17
18    /// Creates a new null force (same as `new Force2D(0, 0)`)
19    pub fn null() -> Force2D {
20        Force2D { force: py::Force2D::null() }
21    }
22
23    pub fn equals(&self, other: &Force2D) -> bool {
24        self.force == other.force
25    }
26
27    pub fn add(&self, other: &Force2D) -> Force2D {
28        (self.force + other.force).into()
29    }
30
31    pub fn sub(&self, other: &Force2D) -> Force2D {
32        (self.force - other.force).into()
33    }
34
35    pub fn dot(&self, other: &Force2D) -> f64 {
36        self.force * other.force
37    }
38
39    pub fn dot_scalar(&self, scalar: f64) -> Force2D {
40        (self.force * scalar).into()
41    }
42
43    pub fn div_scalar(&self, scalar: f64) -> Force2D {
44        (self.force / scalar).into()
45    }
46
47    // Properties
48    #[wasm_bindgen(getter)]
49    pub fn dx(&self) -> f64 {
50        *self.force.dx()
51    }
52
53    #[wasm_bindgen(setter)]
54    pub fn set_dx(&mut self, x: f64) {
55        *self.force.dx_mut() = x;
56    }
57
58    #[wasm_bindgen(getter)]
59    pub fn dy(&self) -> f64 {
60        *self.force.dy()
61    }
62
63    #[wasm_bindgen(setter)]
64    pub fn set_dy(&mut self, y: f64) {
65        *self.force.dy_mut() = y;
66    }
67
68    #[wasm_bindgen(getter)]
69    pub fn norm(&self) -> f64 {
70        self.force.norm()
71    }
72
73    #[wasm_bindgen(getter)]
74    pub fn manhattan_norm(&self) -> f64 {
75        self.force.manhattan_norm()
76    }
77
78    #[wasm_bindgen(getter)]
79    pub fn square_norm(&self) -> f64 {
80        self.force.square_norm()
81    }
82
83    #[wasm_bindgen(getter)]
84    pub fn unit(&self) -> Force2D {
85        self.force.unit().into()
86    }
87}
88
89impl PartialEq for Force2D {
90    #[inline]
91    fn eq(&self, other: &Force2D) -> bool {
92        self.equals(other)
93    }
94}
95
96// Utils
97impl AsRef<py::Force2D<f64>> for Force2D {
98    fn as_ref(&self) -> &py::Force2D<f64> {
99        &self.force
100    }
101}
102
103impl AsMut<py::Force2D<f64>> for Force2D {
104    fn as_mut(&mut self) -> &mut py::Force2D<f64> {
105        &mut self.force
106    }
107}
108
109impl From<py::Force2D<f64>> for Force2D {
110    fn from(force: py::Force2D<f64>) -> Self {
111        Force2D { force }
112    }
113}