diff --git a/src/lib.rs b/src/lib.rs index e47a5fd..3827e79 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -53,10 +53,10 @@ use std::{cell::Cell, path::Path}; use sdl2::{ image::ImageRWops, rect::Rect, - render::{Canvas, TextureValueError}, + render::{Canvas, TextureValueError, TextureCreator}, rwops::RWops, surface::Surface, - video::{Window, WindowBuildError}, + video::{Window, WindowBuildError, WindowContext}, EventPump, IntegerOrSdlError, }; @@ -175,8 +175,8 @@ impl Sprite { /// s.draw(canvas); /// # }); /// ``` - pub fn draw(&mut self, canvas: &mut Canvas) -> Result<()> { - let creator = canvas.texture_creator(); + pub fn draw(&mut self, ctx: &mut Context) -> Result<()> { + let (creator, canvas) = ctx.inner(); let text = creator.create_texture_from_surface(&self.surf)?; canvas.fill_rect(None)?; @@ -235,6 +235,33 @@ impl Sprite { } } +pub struct Context { + canvas: Canvas, + texture_creator: TextureCreator, +} + +impl Context { + pub fn new(canvas: Canvas) -> Self { + let creator = canvas.texture_creator(); + Self { + canvas, + texture_creator: creator, + } + } + + pub fn canvas(&mut self) -> &mut Canvas { + &mut self.canvas + } + + pub fn inner(&mut self) -> (&TextureCreator, &mut Canvas) { + (&self.texture_creator, &mut self.canvas) + } + + pub fn update(&mut self) { + self.canvas.present(); + } +} + /// Representation of the game. pub struct Game { /// The title that the window displays. @@ -274,7 +301,7 @@ impl Game { /// // Game logic goes here /// }); /// ``` - pub fn run, &mut Events)>(&self, mut func: F) -> Result<()> { + pub fn run(&self, mut func: F) -> Result<()> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; @@ -285,18 +312,20 @@ impl Game { .vulkan() .build()?; - let mut canvas = window.into_canvas().build()?; + let canvas = window.into_canvas().build()?; let event_pump = sdl_context.event_pump()?; let mut events = Events { pump: event_pump }; + let mut ctx = Context::new(canvas); + loop { if self.stopped.get() { break; } - func(&mut canvas, &mut events); - canvas.present(); + func(&mut ctx, &mut events); + ctx.update(); } Ok(()) diff --git a/src/main.rs b/src/main.rs index 7fdf991..389b615 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,7 +5,7 @@ fn main() { let mut i = 0.0; let mut s = Sprite::new("duck.png", 500, 400).unwrap(); - game.run(|canvas, event_pump| { + game.run(|ctx, event_pump| { i = (i + 1.0) % 360.0; let (start_x, start_y) = s.position(); @@ -39,7 +39,7 @@ fn main() { } } - s.draw(canvas).unwrap(); + s.draw(ctx).unwrap(); }) .unwrap(); }