swamp_render/
api.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use crate::bm::Font;
use crate::MaterialRef;
use int_math::{URect, UVec2, Vec2, Vec3};
use monotonic_time_rs::Millis;
use std::rc::Rc;

pub trait Assets {
    fn material_png_raw(&mut self, png: &[u8], label: &str) -> MaterialRef;
    fn material_png(&mut self, name: &str) -> MaterialRef;
    fn set_prefix(&mut self, prefix: &str);
    fn frame_fixed_grid_material_png(&mut self, name: &str, grid_size: UVec2) -> FixedAtlas;
    fn bm_font(&mut self, name: &str) -> FontAndMaterialRef;
    fn now(&self) -> Millis;
}

pub trait Gfx {
    fn set_origo(&mut self, position: Vec2);
    fn sprite_atlas_frame(&mut self, position: Vec3, frame: u16, atlas: &impl FrameLookup);
    fn sprite_atlas(&mut self, position: Vec3, atlas_rect: URect, material: &MaterialRef);
    fn text_draw(&mut self, position: Vec3, text: &str, font_ref: &FontAndMaterialRef);
    fn now(&self) -> Millis;
}

pub trait FrameLookup {
    fn lookup(&self, frame: u16) -> (MaterialRef, URect);
}


pub type FontAndMaterialRef = Rc<FontAndMaterial>;

#[derive(Debug)]
pub struct FontAndMaterial {
    pub font: Font,
    pub material_ref: MaterialRef,
}


#[derive(Debug, PartialEq, Eq)]
pub struct FixedAtlas {
    material: MaterialRef,
    grid_size: UVec2,
    cell_size: UVec2,
}

impl FixedAtlas {
    pub fn new(grid_size: UVec2, material_ref: MaterialRef) -> Self {
        let cell_size = UVec2::new(
            material_ref.texture_size.x / grid_size.x,
            material_ref.texture_size.y / grid_size.y,
        );
        Self {
            material: material_ref,
            grid_size,
            cell_size,
        }
    }
}

impl FrameLookup for FixedAtlas {
    fn lookup(&self, frame: u16) -> (MaterialRef, URect) {
        let x = frame % self.cell_size.x;
        let y = frame / self.cell_size.x;

        (
            self.material.clone(),
            URect::new(
                x * self.grid_size.x,
                y * self.grid_size.y,
                self.grid_size.x,
                self.grid_size.y,
            ),
        )
    }
}