fennel_engine/ecs/
sprite.rs

1use serde::{Deserialize, Serialize};
2use specs::{Join, ReadStorage, System, WriteExpect};
3
4use crate::app::App;
5
6/// A raw pointer wrapper to the application
7pub struct HostPtr(pub *mut App);
8
9unsafe impl Send for HostPtr {}
10unsafe impl Sync for HostPtr {}
11
12/// A simple renderable sprite.
13///
14/// # Fields
15/// - image: identifier or path of the image to draw
16/// - position: tuple (x, y) position on screen
17#[derive(Deserialize, Serialize)]
18pub struct Sprite {
19    pub image: String,
20    pub position: (f32, f32)
21}
22
23impl specs::Component for Sprite {
24    type Storage = specs::VecStorage<Self>;
25}
26
27/// ECS system that renders Sprite components.
28///
29/// The system reads all Sprite components from the world and obtains a mutable
30/// reference to the host App through the HostPtr resource
31pub struct RenderingSystem;
32
33impl<'a> System<'a> for RenderingSystem {
34    type SystemData = (ReadStorage<'a, Sprite>, WriteExpect<'a, HostPtr>);
35
36    fn run(&mut self, (sprites, mut host_ptr): Self::SystemData) {
37        let runtime: &mut App = unsafe { &mut *host_ptr.0 };
38        let window = &mut runtime.window;
39
40        for sprite in (&sprites).join() {
41            window.graphics.draw_image(sprite.image.clone(), sprite.position).unwrap();
42        }
43    }
44}