line drawing works well, room for optimization

This commit is contained in:
Joe Ardent 2025-09-05 15:43:03 -07:00
parent ba91baa302
commit 635585dd09
2 changed files with 20 additions and 9 deletions

View file

@ -57,13 +57,24 @@ fn main() {
.unwrap(); .unwrap();
} }
fn line(a: Point, b: Point, fb: &mut TGAImage, color: TGAColor) { fn line(mut a: Point, mut b: Point, fb: &mut TGAImage, color: TGAColor) {
let mut t = 0.0; let is_steep = (a.x - b.x).abs() < (a.y - b.y).abs();
let step = 0.02; if is_steep {
while t < 1.0 { std::mem::swap(&mut a.x, &mut a.y);
let x = (a.x as f32 + (b.x - a.x) as f32 * t).round_ties_even() as u32; std::mem::swap(&mut b.x, &mut b.y);
}
if a.x > b.x {
std::mem::swap(&mut a.x, &mut b.x);
std::mem::swap(&mut a.y, &mut b.y);
}
for x in (a.x)..b.x {
let t = (x - a.x) as f32 / (b.x - a.x) as f32;
let y = (a.y as f32 + (b.y - a.y) as f32 * t).round_ties_even() as u32; let y = (a.y as f32 + (b.y - a.y) as f32 * t).round_ties_even() as u32;
fb.set(x, y, color); if is_steep {
t += step; fb.set(y, x as u32, color);
} else {
fb.set(x as u32, y, color);
}
} }
} }

View file

@ -31,8 +31,8 @@ impl Sub for Point {
fn sub(self, rhs: Self) -> Self::Output { fn sub(self, rhs: Self) -> Self::Output {
Self { Self {
x: self.x.saturating_sub(rhs.x), x: self.x - rhs.x,
y: self.y.saturating_sub(rhs.y), y: self.y - rhs.y,
} }
} }
} }