summaryrefslogtreecommitdiff
path: root/src/geometry.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/geometry.rs')
-rw-r--r--src/geometry.rs24
1 files changed, 24 insertions, 0 deletions
diff --git a/src/geometry.rs b/src/geometry.rs
index 6f7f658..64414e0 100644
--- a/src/geometry.rs
+++ b/src/geometry.rs
@@ -1,4 +1,5 @@
use std::ops::*;
+use std::f64;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Vec2d {
@@ -35,6 +36,29 @@ impl Vec2d {
y: self.y / mag
}
}
+
+ pub fn dot(&self, other: Vec2d) -> f64 {
+ (self.x * other.x) + (self.y * other.y)
+ }
+}
+
+pub struct LineSegment {
+ pub start: Vec2d,
+ pub end: Vec2d
+}
+
+impl LineSegment {
+ pub fn distance(&self, other: Vec2d) -> f64 {
+ let length_squared = self.start.distance_squared(self.end);
+ if length_squared == 0.0 {
+ return self.start.distance(other);
+ }
+
+ let t = f64::max(0., f64::min(1., (other - self.start).dot(self.end - self.start) / length_squared));
+ let projection = self.start + (self.end - self.start) * t;
+ other.distance(projection)
+ }
+
}
impl Add for Vec2d {