Skip to content

Instantly share code, notes, and snippets.

@giuliano-macedo
Last active November 18, 2021 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giuliano-macedo/9c0775fbb6d04b12454e9e3e48e4fc6a to your computer and use it in GitHub Desktop.
Save giuliano-macedo/9c0775fbb6d04b12454e9e3e48e4fc6a to your computer and use it in GitHub Desktop.
Quadratic bézier function in rust (not the most performant, focused in readability)
use std::fmt;
#[derive(Debug, Clone, Copy)]
struct Point {
x: f64,
y: f64,
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}, {}", self.x, self.y)
}
}
impl Point {
fn new(x: f64, y: f64) -> Self {
Self { x: x, y: y }
}
}
#[derive(Debug)]
struct QuadraticBezier {
p0: Point,
p1: Point,
p2: Point,
}
impl QuadraticBezier {
fn new(p0: Point, p1: Point, p2: Point) -> Self {
Self {
p0: p0,
p1: p1,
p2: p2,
}
}
fn compute(&self, time: f64) -> Point {
let a = walk_line(self.p0, self.p1, time);
let b = walk_line(self.p1, self.p2, time);
walk_line(a, b, time)
}
}
fn walk_line(start: Point, end: Point, time: f64) -> Point {
let dx = end.x - start.x;
let dy = end.y - start.y;
Point {
x: start.x + (time * dx),
y: start.y + (time * dy),
}
}
fn main() {
let bezier = QuadraticBezier::new(Point::new(0., 0.), Point::new(0., 2.), Point::new(2., 2.));
let precision = 100;
for i in 0..(precision + 1) {
let t = (i as f64) / (precision as f64);
println!("{}", bezier.compute(t));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment