~starkingdoms/starkingdoms

ref: d024fde6beb37c38cb2f0c7088a828aaa6b2a09d starkingdoms/crates/client/src/rendering/assets_native.rs -rw-r--r-- 2.1 KiB
d024fde6 — ghostly_zsh oh shut up cargo.lock 8 months ago
                                                                                
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
use std::io::Read;

use bevy_ecs::system::Resource;
use resvg::{tiny_skia, usvg};

#[derive(Debug, Clone)]
pub struct ImgData {
    pub bytes: Vec<u8>,
    pub width: u32,
    pub height: u32,
}

#[derive(Resource)]
pub struct Assets {}
impl Assets {
    pub fn new() -> Self {
        Assets {}
    }
    pub fn get(&self, local_path: impl Into<String>) -> Option<ImgData> {
        let local_path = local_path.into();
        let bytes = std::fs::read(format!("src/assets/{}", local_path)).unwrap();
        if local_path.ends_with(".svg") {
            let opt = usvg::Options {
                default_size: usvg::Size::from_wh(20.0, 20.0).unwrap(),
                ..Default::default()
            };
            let tree = usvg::Tree::from_data(&bytes, &opt)
                .expect(&format!("Couldn't parse svg {}", local_path));
            let tree_size = tree.size().to_int_size();
            let size = usvg::Size::from_wh(200.0, 200.0).unwrap().to_int_size();
            assert!(size.width() > 0 && size.height() > 0);
            let mut pixmap = tiny_skia::Pixmap::new(size.width(), size.height())
                .expect("Failed to construct pixmap");
            resvg::render(
                &tree,
                tiny_skia::Transform::from_scale(
                    (size.width() as f32) / (tree_size.height() as f32),
                    (size.height() as f32) / (tree_size.height() as f32),
                ),
                &mut pixmap.as_mut(),
            );
            let data = ImgData {
                bytes: pixmap.data().to_vec(),
                width: size.width(),
                height: size.height(),
            };

            Some(data)
        } else if local_path.ends_with(".png") {
            let img = image::load_from_memory(&bytes).unwrap();
            let rgba = img.to_rgba8();
            let data = ImgData {
                bytes: rgba.bytes().map(|byte| byte.unwrap()).collect::<Vec<u8>>(),
                width: rgba.width(),
                height: rgba.height(),
            };
            Some(data)
        } else {
            panic!("Unsupported sprite type");
        }
    }
}