path_finding/
node.rs

1use std::cmp::Eq;
2use std::cmp::PartialEq;
3use std::hash::{Hash, Hasher};
4
5use crate::graph::Edge;
6
7#[derive(Clone)]
8pub struct Node {
9    pub id: usize,
10    pub edges: Vec<Edge>,
11}
12
13impl Node {
14    pub fn from(id: usize, edges: Vec<Edge>) -> Node {
15        return Node {
16            id,
17            edges,
18        };
19    }
20}
21
22#[derive(Clone)]
23pub struct Vec3 {
24    pub x: f32,
25    pub y: f32,
26    pub z: f32,
27}
28
29impl PartialEq for Vec3 {
30    fn eq(&self, other: &Self) -> bool {
31        return (self.x - other.x).abs() <= f32::EPSILON
32            && (self.y - other.y).abs() <= f32::EPSILON
33            && (self.z - other.z).abs() <= f32::EPSILON;
34    }
35}
36
37
38impl Hash for Vec3 {
39    fn hash<H: Hasher>(&self, state: &mut H) {
40        let precision = 1e6;
41        let x_int = (self.x * precision).round() as i32;
42        let y_int = (self.y * precision).round() as i32;
43        let z_int = (self.z * precision).round() as i32;
44
45        x_int.hash(state);
46        y_int.hash(state);
47        z_int.hash(state);
48    }
49}
50
51impl Eq for Vec3 {}
52
53impl Vec3 {
54    pub fn zeroed() -> Vec3 {
55        return Vec3 {
56            x: 0.0,
57            y: 0.0,
58            z: 0.0,
59        };
60    }
61
62    pub fn from(x: f32, y: f32, z: f32) -> Vec3 {
63        return Vec3 {
64            x,
65            y,
66            z,
67        };
68    }
69
70    pub fn euclidean_dist(&self, o: &Vec3) -> f32 {
71        return ((o.x - self.x).powf(2.0) +
72            (o.y - self.y).powf(2.0) +
73            (o.z - self.z).powf(2.0)).sqrt();
74    }
75
76    pub fn manhattan_dist(&self, o: &Vec3) -> f32 {
77        return (o.x - self.x).abs() + (o.y - self.y).abs() + (o.z - self.z).abs();
78    }
79}
80
81#[test]
82fn create_node_should_succeed() {
83    let node = Node::from(1, vec![]);
84
85    assert_eq!(1, node.id);
86    assert!(node.edges.is_empty());
87}
88
89#[test]
90fn create_zeroed_position_should_succeed() {
91    let position = Vec3::zeroed();
92
93    assert_eq!(0.0, position.x);
94    assert_eq!(0.0, position.y);
95    assert_eq!(0.0, position.z);
96}
97
98#[test]
99fn create_position_should_succeed() {
100    let position = Vec3::from(0.1, 0.2, 0.3);
101
102    assert_eq!(0.1, position.x);
103    assert_eq!(0.2, position.y);
104    assert_eq!(0.3, position.z);
105}
106
107#[test]
108fn test_euclidean_distance() {
109    let position1 = Vec3::from(0.0, 0.0, 0.0);
110    let position2 = Vec3::from(1.0, 1.0, 1.0);
111
112    let dist = position1.euclidean_dist(&position2);
113    assert_eq!(1.7320508, dist);
114}
115
116#[test]
117fn test_manhattan_distance() {
118    let position1 = Vec3::from(0.0, 0.0, 0.0);
119    let position2 = Vec3::from(1.0, 1.0, 1.0);
120
121    let dist = position1.manhattan_dist(&position2);
122    assert_eq!(3.0, dist);
123}