From 9724f0d0fe318615e4ed79b1600dd4557a2378eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Manuel=20Tom=C3=A1s?= Date: Thu, 7 Jan 2021 20:14:15 -0300 Subject: Visualize polynomials using sdl --- src/main.rs | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 61 insertions(+), 3 deletions(-) (limited to 'src/main.rs') diff --git a/src/main.rs b/src/main.rs index 1e4f704..13f13da 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,63 @@ +use poly::Poly; +use poly::Number; +use poly::Lerp; + +use sdl2::pixels::Color; +use sdl2::event::Event; +use sdl2::keyboard::Keycode; +use sdl2::rect::Rect; + +use std::thread; +use std::time::Duration; + +fn eval_poly(p: &Poly, t: Number) -> Number { + let mut r = 0.0; + for i in 0..p.len() { + r += p[i] * t.powi(i as i32); + } + r +} + fn main() { - let a = poly::Lerp::new(vec![1.0, 5.0, 8.0, 3.0, 10.0]); - println!("{:?}", a); - println!("{:?}", poly::lp(a)); + let a = Lerp::new(vec![100.0, 200.0, 300.0, 500.0]); + let b = Lerp::new(vec![400.0, 140.0, 500.0, 300.0]); + let pa = poly::lp(a); + let pb = poly::lp(b); + + let sdl_context = sdl2::init().unwrap(); + let video_subsystem = sdl_context.video().unwrap(); + + let window = video_subsystem.window("rust-sdl2 demo", 800, 600) + .position_centered() + .build() + .unwrap(); + + let mut canvas = window.into_canvas().build().unwrap(); + + let mut event_pump = sdl_context.event_pump().unwrap(); + 'running: loop { + canvas.set_draw_color(Color::RGB(20, 20, 20)); + canvas.clear(); + for event in event_pump.poll_iter() { + match event { + Event::Quit {..} | + Event::KeyDown { keycode: Some(Keycode::Escape), .. } => { + break 'running + }, + _ => {} + } + } + + for t in 0..800 { + let x = eval_poly(&pa, t as Number / 800.0); + let y = eval_poly(&pb, t as Number / 800.0); + canvas.set_draw_color(Color::RGB(180, 20, 20)); + canvas.fill_rect(Rect::new(t, x as i32, 5, 5)).unwrap(); + canvas.set_draw_color(Color::RGB(20, 180, 20)); + canvas.fill_rect(Rect::new(t, y as i32, 5, 5)).unwrap(); + } + + canvas.present(); + thread::sleep(Duration::new(0, 1_000_000_000u32 / 60)); + } } -- cgit v1.2.3