From: Tomas Wenström Date: Tue, 5 Jan 2021 15:32:22 +0000 (+0100) Subject: Moved main loop to App X-Git-Url: http://dolda2000.com/gitweb/?p=kaka%2Frust-sdl-test.git;a=commitdiff_plain;h=6ba7aef184300a81cb7fb9533e926f663c0f806f Moved main loop to App --- diff --git a/src/boll.rs b/src/boll.rs index 64be265..b8e21a7 100644 --- a/src/boll.rs +++ b/src/boll.rs @@ -4,9 +4,9 @@ use sdl2::rect::Rect; use sdl2::render::Canvas; use sdl2::video::Window; -use {SCREEN_HEIGHT, SCREEN_WIDTH}; use common::Point2D; use sdl2::gfx::primitives::DrawRenderer; +use {SCREEN_HEIGHT, SCREEN_WIDTH}; pub trait Boll { fn update(&mut self); @@ -45,7 +45,8 @@ impl Boll for SquareBoll { canvas.set_draw_color(Color::RGBA( 255 - std::cmp::min(255, (self.vel.length() * 25.0) as u8), (255.0 * (self.pos.x / SCREEN_WIDTH as f64)) as u8, - (255.0 * (self.pos.y / SCREEN_HEIGHT as f64)) as u8, 128 + (255.0 * (self.pos.y / SCREEN_HEIGHT as f64)) as u8, + 128, )); let mut r = Rect::new(0, 0, size, size); r.center_on(Point::new(self.pos.x as i32, self.pos.y as i32)); @@ -53,7 +54,6 @@ impl Boll for SquareBoll { } } - pub struct CircleBoll { pub boll: SquareBoll, } @@ -61,10 +61,7 @@ pub struct CircleBoll { impl CircleBoll { pub fn new(pos: Point2D, vel: Point2D) -> CircleBoll { CircleBoll { - boll: SquareBoll { - pos, - vel, - } + boll: SquareBoll { pos, vel }, } } } @@ -76,11 +73,13 @@ impl Boll for CircleBoll { fn draw(&self, canvas: &mut Canvas, size: u32) { let val = 255 - std::cmp::min(255, (self.boll.vel.length() * 20.0) as u8); - canvas.filled_circle(self.boll.pos.x as i16, self.boll.pos.y as i16, size as i16, Color::RGBA( - val, - val, - val, - 128, - )).unwrap(); + canvas + .filled_circle( + self.boll.pos.x as i16, + self.boll.pos.y as i16, + size as i16, + Color::RGBA(val, val, val, 128), + ) + .unwrap(); } } diff --git a/src/common.rs b/src/common.rs index f5ebb6e..283640e 100644 --- a/src/common.rs +++ b/src/common.rs @@ -2,7 +2,9 @@ use std::ops::{Add, AddAssign, Mul}; #[macro_export] macro_rules! point { - ( $x:expr, $y:expr ) => { Point2D { x:$x, y:$y } }; + ( $x:expr, $y:expr ) => { + Point2D { x: $x, y: $y } + }; } #[derive(Debug, Copy, Clone, PartialEq)] @@ -17,11 +19,14 @@ impl Point2D { } } -impl> Add for Point2D { +impl> Add for Point2D { type Output = Point2D; fn add(self, rhs: Point2D) -> Self::Output { - Point2D { x: self.x + rhs.x, y: self.y + rhs.y } + Point2D { + x: self.x + rhs.x, + y: self.y + rhs.y, + } } } @@ -38,16 +43,19 @@ pub struct Rect { pub height: T, } -impl + Copy> Rect { +impl + Copy> Rect { #[allow(dead_code)] pub fn area(&self) -> T { - self.width * self.height + self.width * self.height } } impl From<(T, T)> for Rect { fn from(item: (T, T)) -> Self { - Rect { width: item.0, height: item.1 } + Rect { + width: item.0, + height: item.1, + } } } @@ -75,7 +83,7 @@ mod tests { #[test] fn area_for_rect_of_multipliable_type() { let r: Rect<_> = (30, 20).into(); // the Into trait uses the From trait - assert_eq!(r.area(), 30 * 20); + assert_eq!(r.area(), 30 * 20); // let a = Rect::from(("a".to_string(), "b".to_string())).area(); // this doesn't work, because area() is not implemented for String } } diff --git a/src/game/app.rs b/src/game/app.rs index 362af2e..4e0f97b 100644 --- a/src/game/app.rs +++ b/src/game/app.rs @@ -1,21 +1,28 @@ +use boll::*; +use common::{Point2D, Rect}; +use point; // defined in common, but loaded from main... use rand::Rng; use sdl2::event::Event; -use sdl2::{EventPump, VideoSubsystem}; +use sdl2::event::WindowEvent; +use sdl2::gfx::primitives::DrawRenderer; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; +use sdl2::rect::Rect as SDLRect; use sdl2::render::BlendMode; use sdl2::render::Canvas; +use sdl2::video::FullscreenType; use sdl2::video::{SwapInterval, Window}; - -use ::{SCREEN_HEIGHT, SCREEN_WIDTH}; -use boll::*; -use common::{Point2D, Rect}; +use sdl2::{EventPump, VideoSubsystem}; use sprites::SpriteManager; -use NS_PER_FRAME; -use point; // defined in common, but loaded from main... +use std::f32::consts::PI; +use time::PreciseTime; +use {SCREEN_HEIGHT, SCREEN_WIDTH}; pub type Nanoseconds = u64; +const FPS: u32 = 60; +const NS_PER_FRAME: u32 = 1_000_000_000 / FPS; + #[derive(Default)] pub struct AppBuilder { resolution: Rect, @@ -25,34 +32,39 @@ pub struct AppBuilder { impl AppBuilder { pub fn with_resolution(mut self, width: u16, height: u16) -> Self { - self.resolution = Rect { width, height }; - self + self.resolution = Rect { width, height }; + self } pub fn with_state(mut self, state: Box) -> Self { - self.state = Some(state); - self + self.state = Some(state); + self } pub fn with_title(mut self, title: &str) -> Self { - self.title = Some(title.to_string()); - self + self.title = Some(title.to_string()); + self } pub fn build(self) -> Result { let context = sdl2::init().unwrap(); sdl2::image::init(sdl2::image::InitFlag::PNG)?; - let video = context.video()?; + let video = context.video()?; - self.print_video_display_modes(&video); + self.print_video_display_modes(&video); let window = video - .window(&self.title.unwrap(), self.resolution.width.into(), self.resolution.height.into()) + .window( + &self.title.unwrap(), + self.resolution.width.into(), + self.resolution.height.into(), + ) .position_centered() - // .fullscreen() - // .fullscreen_desktop() + // .fullscreen() + // .fullscreen_desktop() .opengl() - .build().unwrap(); + .build() + .unwrap(); context.mouse().show_cursor(false); let mut canvas = window.into_canvas().build().unwrap(); @@ -61,7 +73,7 @@ impl AppBuilder { canvas.clear(); canvas.present(); - video.gl_set_swap_interval(SwapInterval::VSync)?; + video.gl_set_swap_interval(SwapInterval::VSync)?; let event_pump = context.event_pump()?; let sprites = SpriteManager::new(canvas.texture_creator()); @@ -75,19 +87,39 @@ impl AppBuilder { } fn print_video_display_modes(&self, video: &VideoSubsystem) { - println!("video subsystem: {:?}", video); - println!("current_video_driver: {:?}", video.current_video_driver()); - for display in 0..video.num_video_displays().unwrap() { - println!("=== display {} - {} ===", display, video.display_name(display).unwrap()); - println!(" display_bounds: {:?}", video.display_bounds(display).unwrap()); - println!(" num_display_modes: {:?}", video.num_display_modes(display).unwrap()); - println!(" desktop_display_mode: {:?}", video.desktop_display_mode(display).unwrap()); - println!(" current_display_mode: {:?}", video.current_display_mode(display).unwrap()); - for mode in 0..video.num_display_modes(display).unwrap() { - println!(" {:2}: {:?}", mode, video.display_mode(display, mode).unwrap()); - } - } - println!("swap interval: {:?}", video.gl_get_swap_interval()); + println!("video subsystem: {:?}", video); + println!("current_video_driver: {:?}", video.current_video_driver()); + for display in 0..video.num_video_displays().unwrap() { + println!( + "=== display {} - {} ===", + display, + video.display_name(display).unwrap() + ); + println!( + " display_bounds: {:?}", + video.display_bounds(display).unwrap() + ); + println!( + " num_display_modes: {:?}", + video.num_display_modes(display).unwrap() + ); + println!( + " desktop_display_mode: {:?}", + video.desktop_display_mode(display).unwrap() + ); + println!( + " current_display_mode: {:?}", + video.current_display_mode(display).unwrap() + ); + for mode in 0..video.num_display_modes(display).unwrap() { + println!( + " {:2}: {:?}", + mode, + video.display_mode(display, mode).unwrap() + ); + } + } + println!("swap interval: {:?}", video.gl_get_swap_interval()); } } @@ -100,7 +132,7 @@ pub struct App { impl App { pub fn new() -> AppBuilder { - Default::default() + Default::default() } pub fn load_sprites(&mut self, sprites: &[(&str, &str)]) { @@ -108,6 +140,205 @@ impl App { self.sprites.load(name, file); } } + + pub fn start(&mut self) { + let mut frame_count: u64 = 0; + let mut fps_time = PreciseTime::now(); + let mut last_time = PreciseTime::now(); + + let mut mario_angle = 0.0; + + 'running: loop { + self.canvas.set_draw_color(Color::RGB(0, 0, 0)); + self.canvas.clear(); + { + let blocks = 20; + let size = 32; + let offset = point!( + (SCREEN_WIDTH as i32 - (blocks + 1) * size) / 2, + (SCREEN_HEIGHT as i32 - (blocks + 1) * size) / 2 + ); + let block = self.sprites.get("block"); + for i in 0..blocks { + self.canvas + .copy( + block, + None, + SDLRect::new((i) * size + offset.x, offset.y, size as u32, size as u32), + ) + .unwrap(); + self.canvas + .copy( + block, + None, + SDLRect::new( + (blocks - i) * size + offset.x, + (blocks) * size + offset.y, + size as u32, + size as u32, + ), + ) + .unwrap(); + self.canvas + .copy( + block, + None, + SDLRect::new( + offset.x, + (blocks - i) * size + offset.y, + size as u32, + size as u32, + ), + ) + .unwrap(); + self.canvas + .copy( + block, + None, + SDLRect::new( + (blocks) * size + offset.x, + (i) * size + offset.y, + size as u32, + size as u32, + ), + ) + .unwrap(); + } + } + { + let size = 64; + let offset = point!( + (SCREEN_WIDTH as i32 - size) / 2, + (SCREEN_HEIGHT as i32 - size) / 2 + ); + let radius = 110.0 + size as f32 * 0.5; + let angle = (mario_angle as f32 - 90.0) * PI / 180.0; + let offset2 = point!((angle.cos() * radius) as i32, (angle.sin() * radius) as i32); + self.canvas + .copy_ex( + self.sprites.get("mario"), + None, + SDLRect::new( + offset.x + offset2.x, + offset.y + offset2.y, + size as u32, + size as u32, + ), + mario_angle, + sdl2::rect::Point::new(size / 2, size / 2), + false, + false, + ) + .unwrap(); + mario_angle += 1.0; + if mario_angle >= 360.0 { + mario_angle -= 360.0 + } + } + { + let p = point!((SCREEN_WIDTH / 2) as i16, (SCREEN_HEIGHT / 2) as i16); + self.canvas + .circle(p.x, p.y, 100, Color::RGB(255, 255, 255)) + .unwrap(); + self.canvas + .aa_circle(p.x, p.y, 110, Color::RGB(255, 255, 255)) + .unwrap(); + self.canvas + .ellipse(p.x, p.y, 50, 100, Color::RGB(255, 255, 255)) + .unwrap(); + self.canvas + .aa_ellipse(p.x, p.y, 110, 55, Color::RGB(255, 255, 255)) + .unwrap(); + } + + // window.gl_swap_window(); + for event in self.event_pump.poll_iter() { + match event { + Event::Quit { .. } + | Event::KeyDown { + keycode: Some(Keycode::Escape), + .. + } => { + break 'running; + } + Event::KeyDown { + keycode: Some(Keycode::F11), + .. + } => { + match self.canvas.window().fullscreen_state() { + FullscreenType::Off => self + .canvas + .window_mut() + .set_fullscreen(FullscreenType::Desktop), + _ => self.canvas.window_mut().set_fullscreen(FullscreenType::Off), + } + .unwrap(); + } + Event::Window { + win_event: WindowEvent::Resized(x, y), + .. + } => { + println!("window resized({}, {})", x, y) + } + Event::Window { + win_event: WindowEvent::Maximized, + .. + } => { + println!("window maximized") + } + Event::Window { + win_event: WindowEvent::Restored, + .. + } => { + println!("window restored") + } + Event::Window { + win_event: WindowEvent::Enter, + .. + } => { + println!("window enter") + } + Event::Window { + win_event: WindowEvent::Leave, + .. + } => { + println!("window leave") + } + Event::Window { + win_event: WindowEvent::FocusGained, + .. + } => { + println!("window focus gained") + } + Event::Window { + win_event: WindowEvent::FocusLost, + .. + } => { + println!("window focus lost") + } + _ => self.state.on_event(event), + } + } + + let duration = + last_time.to(PreciseTime::now()).num_nanoseconds().unwrap() as Nanoseconds; + last_time = PreciseTime::now(); + self.state.update(duration); + self.state.render(&mut self.canvas); + self.canvas.present(); + + frame_count += 1; + if frame_count == FPS as u64 { + let duration = fps_time.to(PreciseTime::now()).num_nanoseconds().unwrap() as f64 + / 1_000_000_000.0; + println!("fps: {}", frame_count as f64 / duration); + frame_count = 0; + fps_time = PreciseTime::now(); + } + } + + self.state.leave(); + } } pub trait AppState { @@ -147,7 +378,10 @@ impl ActiveState { fn add_boll(&mut self) { let mut rng = rand::thread_rng(); self.bolls.push(Box::new(SquareBoll { - pos: point!(rng.gen_range(0, SCREEN_WIDTH) as f64, rng.gen_range(0, SCREEN_HEIGHT) as f64), + pos: point!( + rng.gen_range(0, SCREEN_WIDTH) as f64, + rng.gen_range(0, SCREEN_HEIGHT) as f64 + ), vel: point!(rng.gen_range(-2.0, 2.0), rng.gen_range(-2.0, 2.0)), })); } @@ -160,8 +394,8 @@ impl AppState for ActiveState { } match dt { - ns if ns < (NS_PER_FRAME - 90_0000) as u64 => { self.change_boll_count(100) } - ns if ns > (NS_PER_FRAME + 90_0000) as u64 => { self.change_boll_count(-100) } + ns if ns < (NS_PER_FRAME - 90_0000) as u64 => self.change_boll_count(100), + ns if ns > (NS_PER_FRAME + 90_0000) as u64 => self.change_boll_count(-100), _ => {} } } @@ -178,14 +412,18 @@ impl AppState for ActiveState { fn on_event(&mut self, event: Event) { match event { - Event::KeyDown { keycode: Some(Keycode::KpPlus), .. } => { self.boll_size = std::cmp::min(self.boll_size + 1, 32) } - Event::KeyDown { keycode: Some(Keycode::KpMinus), .. } => { self.boll_size = std::cmp::max(self.boll_size - 1, 1) } - Event::MouseMotion { x, y, .. } => { - self.bolls.push(Box::new(CircleBoll::new( - point!(x as f64, y as f64), - point!(0.0, 0.0), - ))) - } + Event::KeyDown { + keycode: Some(Keycode::KpPlus), + .. + } => self.boll_size = std::cmp::min(self.boll_size + 1, 32), + Event::KeyDown { + keycode: Some(Keycode::KpMinus), + .. + } => self.boll_size = std::cmp::max(self.boll_size - 1, 1), + Event::MouseMotion { x, y, .. } => self.bolls.push(Box::new(CircleBoll::new( + point!(x as f64, y as f64), + point!(0.0, 0.0), + ))), _ => {} } } diff --git a/src/game/mod.rs b/src/game/mod.rs index 02c0277..309be62 100644 --- a/src/game/mod.rs +++ b/src/game/mod.rs @@ -1 +1 @@ -pub mod app; \ No newline at end of file +pub mod app; diff --git a/src/main.rs b/src/main.rs index 217918c..877d367 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,124 +2,26 @@ extern crate rand; extern crate sdl2; extern crate time; -use std::f32::consts::PI; - -use sdl2::event::Event; -use sdl2::event::WindowEvent; -use sdl2::gfx::primitives::DrawRenderer; -use sdl2::keyboard::Keycode; -use sdl2::pixels::Color; -use sdl2::rect::Rect; -use sdl2::video::FullscreenType; -use time::PreciseTime; - use game::app::*; -use common::Point2D; mod game; -#[macro_use] mod common; +#[macro_use] +mod common; mod boll; mod sprites; const SCREEN_WIDTH: u32 = 1280; const SCREEN_HEIGHT: u32 = (SCREEN_WIDTH as f64 * (1440.0 / 2560.0)) as u32; -const FPS: u32 = 60; -const NS_PER_FRAME: u32 = 1_000_000_000 / FPS; fn main() { println!("starting..."); let mut app = App::new() - .with_resolution(SCREEN_WIDTH as u16, SCREEN_HEIGHT as u16) - .with_state(Box::new(ActiveState::new())) - .with_title("SDL test") - .build() - .unwrap(); - app.load_sprites(&[ - ("block", "res/block.bmp"), - ("mario", "res/mario-trans.png"), - ]); - - let mut frame_count: u64 = 0; - let mut fps_time = PreciseTime::now(); - let mut last_time = PreciseTime::now(); - - let mut mario_angle = 0.0; - - 'running: loop { - app.canvas.set_draw_color(Color::RGB(0, 0, 0)); - app.canvas.clear(); - { - let blocks = 20; - let size = 32; - let offset = point!((SCREEN_WIDTH as i32 - (blocks + 1) * size) / 2, (SCREEN_HEIGHT as i32 - (blocks + 1) * size) / 2); - let block = app.sprites.get("block"); - for i in 0..blocks { - app.canvas.copy(block, None, Rect::new((i) * size + offset.x, offset.y, size as u32, size as u32)).unwrap(); - app.canvas.copy(block, None, Rect::new((blocks - i) * size + offset.x, (blocks) * size + offset.y, size as u32, size as u32)).unwrap(); - app.canvas.copy(block, None, Rect::new(offset.x, (blocks - i) * size + offset.y, size as u32, size as u32)).unwrap(); - app.canvas.copy(block, None, Rect::new((blocks) * size + offset.x, (i) * size + offset.y, size as u32, size as u32)).unwrap(); - } - } - { - let size = 64; - let offset = point!((SCREEN_WIDTH as i32 - size) / 2, (SCREEN_HEIGHT as i32 - size) / 2); - let radius = 110.0 + size as f32 * 0.5; - let angle = (mario_angle as f32 - 90.0) * PI / 180.0; - let offset2 = point!((angle.cos() * radius) as i32, (angle.sin() * radius) as i32); - app.canvas.copy_ex( - app.sprites.get("mario"), - None, Rect::new(offset.x + offset2.x, offset.y + offset2.y, size as u32, size as u32), - mario_angle, - sdl2::rect::Point::new(size / 2, size / 2), - false, false).unwrap(); - mario_angle += 1.0; - if mario_angle >= 360.0 { mario_angle -= 360.0 } - } - { - let p = point!((SCREEN_WIDTH / 2) as i16, (SCREEN_HEIGHT / 2) as i16); - app.canvas.circle(p.x, p.y, 100, Color::RGB(255, 255, 255)).unwrap(); - app.canvas.aa_circle(p.x, p.y, 110, Color::RGB(255, 255, 255)).unwrap(); - app.canvas.ellipse(p.x, p.y, 50, 100, Color::RGB(255, 255, 255)).unwrap(); - app.canvas.aa_ellipse(p.x, p.y, 110, 55, Color::RGB(255, 255, 255)).unwrap(); - } - -// window.gl_swap_window(); - for event in app.event_pump.poll_iter() { - match event { - Event::Quit { .. } | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => { - break 'running; - } - Event::KeyDown { keycode: Some(Keycode::F11), .. } => { - match app.canvas.window().fullscreen_state() { - FullscreenType::Off => app.canvas.window_mut().set_fullscreen(FullscreenType::Desktop), - _ => app.canvas.window_mut().set_fullscreen(FullscreenType::Off) - }.unwrap(); - } - Event::Window { win_event: WindowEvent::Resized(x, y), .. } => { println!("window resized({}, {})", x, y) } - Event::Window { win_event: WindowEvent::Maximized, .. } => { println!("window maximized") } - Event::Window { win_event: WindowEvent::Restored, .. } => { println!("window restored") } - Event::Window { win_event: WindowEvent::Enter, .. } => { println!("window enter") } - Event::Window { win_event: WindowEvent::Leave, .. } => { println!("window leave") } - Event::Window { win_event: WindowEvent::FocusGained, .. } => { println!("window focus gained") } - Event::Window { win_event: WindowEvent::FocusLost, .. } => { println!("window focus lost") } - _ => { app.state.on_event(event) } - } - } - - let duration = last_time.to(PreciseTime::now()).num_nanoseconds().unwrap() as Nanoseconds; - last_time = PreciseTime::now(); - app.state.update(duration); - app.state.render(&mut app.canvas); - app.canvas.present(); - - frame_count += 1; - if frame_count == FPS as u64 { - let duration = fps_time.to(PreciseTime::now()).num_nanoseconds().unwrap() as f64 / 1_000_000_000.0; - println!("fps: {}", frame_count as f64 / duration); - frame_count = 0; - fps_time = PreciseTime::now(); - } - } - - app.state.leave(); + .with_resolution(SCREEN_WIDTH as u16, SCREEN_HEIGHT as u16) + .with_state(Box::new(ActiveState::new())) + .with_title("SDL test") + .build() + .unwrap(); + app.load_sprites(&[("block", "res/block.bmp"), ("mario", "res/mario-trans.png")]); + + app.start(); } diff --git a/src/sprites.rs b/src/sprites.rs index 631f6ce..70de0c0 100644 --- a/src/sprites.rs +++ b/src/sprites.rs @@ -19,10 +19,15 @@ impl SpriteManager { } pub fn load(&mut self, name: &str, file: &str) { - self.textures.insert(name.to_string(), self.texture_creator.load_texture(file).unwrap()); + self.textures.insert( + name.to_string(), + self.texture_creator.load_texture(file).unwrap(), + ); } pub fn get(&self, name: &str) -> &Texture { - self.textures.get(name).unwrap_or_else(|| panic!("The sprite '{}' was not found", name)) + self.textures + .get(name) + .unwrap_or_else(|| panic!("The sprite '{}' was not found", name)) } }