Browse Source

add rust/vec2 project :eyes::heart:

Ethosa 3 years ago
parent
commit
f6fbcdc451

+ 8 - 0
Languages/Rust/vec2/Cargo.toml

@@ -0,0 +1,8 @@
+[package]
+name = "vec2"
+version = "0.1.0"
+edition = "2018"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]

BIN
Languages/Rust/vec2/src/main.pdb


+ 18 - 0
Languages/Rust/vec2/src/main.rs

@@ -0,0 +1,18 @@
+mod vec2;
+use vec2::build_vec2;
+
+
+fn main() {
+    let myvec1 = build_vec2(1.0, 1.0);
+    let myvec2 = build_vec2(128.0, 64.0);
+
+    println!("myvec1 vec2 [{},{}]", &myvec1.x, &myvec1.y);
+    println!("distance is {}", &myvec1.distance_to(&myvec2));
+
+    println!("sum of two vectors is {}", &myvec1 + &myvec2);
+    println!("dif of two vectors is {}", &myvec2 - &myvec1);
+    println!("mul of two vectors is {}", &myvec1 * &myvec2);
+
+    println!("length of myvec1 is {}", myvec1.length());
+    println!("norm myvec1 vector is {}", myvec1.normalized());
+}

+ 77 - 0
Languages/Rust/vec2/src/vec2.rs

@@ -0,0 +1,77 @@
+pub struct Vec2 {
+    pub x: f64,
+    pub y: f64
+}
+
+pub fn build_vec2(x: f64, y: f64) -> Vec2 {
+    // Creates vector2.
+    Vec2 {x: x, y: y}
+}
+
+impl Vec2 {
+    pub fn abs(&mut self) {
+        self.x = if self.x > 0f64 {self.x} else {-self.x};
+        self.y = if self.y > 0f64 {self.y} else {-self.y};
+    }
+
+    pub fn distance_to(&self, other: &Vec2) -> f64 {
+        // euclidean distance between two vectors.
+        ((other.x - self.x).powf(2.0) + (other.y - self.y).powf(2.0)).sqrt()
+    }
+
+    pub fn dot_product(&self, other: &Vec2) -> f64 {
+        // https://en.wikipedia.org/wiki/Dot_product
+        self.x*other.x + self.y*other.y
+    }
+
+    pub fn length(&self) -> f64 {
+        (self.x.powf(2.0) + self.y.powf(2.0)).sqrt()
+    }
+
+    pub fn normalized(&self) -> Vec2 {
+        let l = self.length();
+        if l != 0.0 {
+            return Vec2 {
+                x: self.x / l,
+                y: self.y / l
+            }
+        }
+        Vec2 {x: 0.0, y: 0.0}
+    }
+}
+
+
+impl std::fmt::Display for Vec2 {
+    // Provides vector2 string representation.
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "Vec2({}, {})", self.x, self.y)
+    }
+}
+
+// Overload operators
+impl std::ops::Add for &Vec2 {
+    // Provides vectors addition.
+    type Output = Vec2;
+
+    fn add(self, other: &Vec2) -> Vec2 {
+        Vec2 {x: self.x + other.x, y: self.y + other.y}
+    }
+}
+
+impl std::ops::Sub for &Vec2 {
+    // Provides vectors substraction.
+    type Output = Vec2;
+
+    fn sub(self, other: &Vec2) -> Vec2 {
+        Vec2 {x: self.x - other.x, y: self.y - other.y}
+    }
+}
+
+impl std::ops::Mul for &Vec2 {
+    // Provides vectors multiplication.
+    type Output = Vec2;
+
+    fn mul(self, other: &Vec2) -> Vec2 {
+        Vec2 {x: self.x * other.x, y: self.y * other.y}
+    }
+}