catbox3d/src/lib.rs

94 lines
2 KiB
Rust
Raw Normal View History

use std::cell::Cell;
2022-03-06 13:08:05 -06:00
use sdl2::{
render::Canvas,
video::{Window, WindowBuildError},
2022-03-06 14:23:10 -06:00
IntegerOrSdlError,
2022-03-06 13:08:05 -06:00
};
2022-03-06 10:55:10 -06:00
pub use sdl2::event::Event;
2022-03-06 13:08:05 -06:00
pub use sdl2::keyboard::Keycode;
pub use sdl2::pixels::Color;
2022-03-06 14:23:10 -06:00
#[macro_export]
macro_rules! cloned {
($thing:ident => $e:expr) => {
let $thing = $thing.clone();
$e
};
($($thing:ident),* => $e:expr) => {
$( let $thing = $thing.clone(); )*
$e
}
}
#[derive(Debug)]
2022-03-06 10:55:10 -06:00
pub struct CatboxError(String);
impl From<WindowBuildError> for CatboxError {
fn from(e: WindowBuildError) -> Self {
CatboxError(format!("{}", e))
2022-03-06 10:25:42 -06:00
}
}
2022-03-06 10:55:10 -06:00
impl From<String> for CatboxError {
fn from(e: String) -> Self {
CatboxError(e)
}
}
impl From<IntegerOrSdlError> for CatboxError {
fn from(e: IntegerOrSdlError) -> Self {
CatboxError(format!("{}", e))
}
}
pub type Result<T> = std::result::Result<T, CatboxError>;
pub struct Game {
pub title: String,
pub width: u32,
pub height: u32,
2022-03-06 13:08:05 -06:00
stopped: Cell<bool>,
2022-03-06 10:55:10 -06:00
}
impl Game {
pub fn new(title: &str, width: u32, height: u32) -> Self {
Self {
title: title.to_string(),
width,
height,
2022-03-06 13:08:05 -06:00
stopped: Cell::new(false),
2022-03-06 10:55:10 -06:00
}
}
2022-03-06 14:23:10 -06:00
pub fn run<F: FnMut(&mut Canvas<Window>, Vec<Event>)>(&self, mut func: F) -> Result<()> {
2022-03-06 10:55:10 -06:00
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;
2022-03-06 13:08:05 -06:00
let window = video_subsystem
.window(&self.title, self.width, self.height)
2022-03-06 10:55:10 -06:00
.position_centered()
.build()?;
let mut canvas = window.into_canvas().build()?;
let mut event_pump = sdl_context.event_pump()?;
loop {
if self.stopped.get() {
break;
}
let events = event_pump.poll_iter().collect::<Vec<Event>>();
func(&mut canvas, events);
2022-03-06 10:55:10 -06:00
canvas.present();
}
Ok(())
}
pub fn terminate(&self) {
self.stopped.set(true);
}
2022-03-06 13:08:05 -06:00
}