micro_games_kit/
assets.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
use crate::game::GameSubsystem;
use anput::world::World;
use core::str;
use fontdue::Font;
use image::{GenericImage, GenericImageView, RgbaImage};
use keket::{
    database::{
        handle::AssetHandle,
        path::{AssetPath, AssetPathStatic},
        AssetDatabase,
    },
    fetch::{
        container::{ContainerAssetFetch, ContainerPartialFetch},
        AssetFetch,
    },
    protocol::{
        bytes::BytesAssetProtocol, group::GroupAssetProtocol, text::TextAssetProtocol,
        AssetProtocol,
    },
};
use kira::sound::static_sound::StaticSoundData;
use serde::{Deserialize, Serialize};
use spitfire_glow::renderer::GlowTextureFormat;
use std::{
    borrow::Cow,
    collections::HashMap,
    error::Error,
    io::{Cursor, Read, Write},
    ops::Range,
    path::Path,
};

pub fn name_from_path<'a>(path: &'a AssetPath<'a>) -> &'a str {
    path.meta_items()
        .find(|(key, _)| *key == "as")
        .map(|(_, value)| value)
        .unwrap_or(path.path())
}

pub fn make_database(fetch: impl AssetFetch) -> AssetDatabase {
    AssetDatabase::default()
        .with_protocol(BytesAssetProtocol)
        .with_protocol(TextAssetProtocol)
        .with_protocol(GroupAssetProtocol)
        .with_protocol(ShaderAssetProtocol)
        .with_protocol(TextureAssetProtocol)
        .with_protocol(FontAssetProtocol)
        .with_protocol(SoundAssetProtocol)
        .with_fetch(fetch)
}

pub fn make_memory_database(package: &[u8]) -> Result<AssetDatabase, Box<dyn Error>> {
    Ok(make_database(ContainerAssetFetch::new(
        AssetPackage::decode(package)?,
    )))
}

pub fn make_directory_database(
    directory: impl AsRef<Path>,
) -> Result<AssetDatabase, Box<dyn Error>> {
    Ok(make_database(ContainerAssetFetch::new(
        AssetPackage::from_directory(directory)?,
    )))
}

#[derive(Debug, Default, Serialize, Deserialize)]
struct AssetPackageRegistry {
    mappings: HashMap<String, Range<usize>>,
}

#[derive(Default)]
pub struct AssetPackage {
    registry: AssetPackageRegistry,
    content: Vec<u8>,
}

impl AssetPackage {
    pub fn from_directory(directory: impl AsRef<Path>) -> Result<Self, Box<dyn Error>> {
        fn visit_dirs(
            dir: &Path,
            root: &str,
            registry: &mut AssetPackageRegistry,
            content: &mut Cursor<Vec<u8>>,
        ) -> std::io::Result<()> {
            if dir.is_dir() {
                for entry in std::fs::read_dir(dir)? {
                    let entry = entry?;
                    let path = entry.path();
                    let name = path.file_name().unwrap().to_str().unwrap();
                    let name = if root.is_empty() {
                        name.to_owned()
                    } else {
                        format!("{}/{}", root, name)
                    };
                    if path.is_dir() {
                        visit_dirs(&path, &name, registry, content)?;
                    } else {
                        let bytes = std::fs::read(path)?;
                        let start = content.position() as usize;
                        content.write_all(&bytes)?;
                        let end = content.position() as usize;
                        registry.mappings.insert(name, start..end);
                    }
                }
            }
            Ok(())
        }

        let directory = directory.as_ref();
        let mut registry = AssetPackageRegistry::default();
        let mut content = Cursor::new(Vec::default());
        visit_dirs(directory, "", &mut registry, &mut content)?;
        Ok(AssetPackage {
            registry,
            content: content.into_inner(),
        })
    }

    pub fn decode(bytes: &[u8]) -> Result<Self, Box<dyn Error>> {
        let mut stream = Cursor::new(bytes);
        let mut size = 0usize.to_be_bytes();
        stream.read_exact(&mut size)?;
        let size = usize::from_be_bytes(size);
        let mut registry = vec![0u8; size];
        stream.read_exact(&mut registry)?;
        let registry = toml::from_str(str::from_utf8(&registry)?)?;
        let mut content = Vec::default();
        stream.read_to_end(&mut content)?;
        Ok(Self { registry, content })
    }

    pub fn encode(&self) -> Result<Vec<u8>, Box<dyn Error>> {
        let mut stream = Cursor::new(Vec::default());
        let registry = toml::to_string(&self.registry)?;
        let registry = registry.as_bytes();
        stream.write_all(&registry.len().to_be_bytes())?;
        stream.write_all(registry)?;
        stream.write_all(&self.content)?;
        Ok(stream.into_inner())
    }

    pub fn paths(&self) -> impl Iterator<Item = &str> {
        self.registry.mappings.keys().map(|key| key.as_str())
    }
}

impl ContainerPartialFetch for AssetPackage {
    fn load_bytes(&mut self, path: AssetPath) -> Result<Vec<u8>, Box<dyn Error>> {
        if let Some(range) = self.registry.mappings.get(path.path()).cloned() {
            if range.end <= self.content.len() {
                Ok(self.content[range].to_owned())
            } else {
                Err(format!(
                    "Asset: `{}` out of content bounds! Bytes range: {:?}, content byte size: {}",
                    path,
                    range,
                    self.content.len()
                )
                .into())
            }
        } else {
            Err(format!("Asset: `{}` not present in package!", path).into())
        }
    }
}

impl std::fmt::Debug for AssetPackage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AssetPackage")
            .field("registry", &self.registry)
            .finish_non_exhaustive()
    }
}

pub struct ShaderAsset {
    pub vertex: Cow<'static, str>,
    pub fragment: Cow<'static, str>,
}

impl ShaderAsset {
    pub fn new(vertex: &'static str, fragment: &'static str) -> Self {
        Self {
            vertex: vertex.into(),
            fragment: fragment.into(),
        }
    }
}

pub struct ShaderAssetSubsystem;

impl GameSubsystem for ShaderAssetSubsystem {
    fn run(&mut self, context: crate::context::GameContext, _: f32) {
        for entity in context.assets.storage.added().iter_of::<ShaderAsset>() {
            if let Some((path, asset)) = context
                .assets
                .storage
                .lookup_one::<true, (&AssetPathStatic, &ShaderAsset)>(entity)
            {
                context.draw.shaders.insert(
                    name_from_path(&path).to_owned().into(),
                    context
                        .graphics
                        .shader(asset.vertex.trim(), asset.fragment.trim())
                        .unwrap(),
                );
            }
        }
        for entity in context.assets.storage.removed().iter_of::<ShaderAsset>() {
            if let Some(path) = context
                .assets
                .storage
                .lookup_one::<true, &AssetPathStatic>(entity)
            {
                context.draw.shaders.remove(name_from_path(&path));
            }
        }
    }
}

pub struct ShaderAssetProtocol;

impl AssetProtocol for ShaderAssetProtocol {
    fn name(&self) -> &str {
        "shader"
    }

    fn process_bytes(
        &mut self,
        handle: AssetHandle,
        storage: &mut World,
        bytes: Vec<u8>,
    ) -> Result<(), Box<dyn Error>> {
        enum Mode {
            Vertex,
            Fragment,
        }

        let mut vertex = String::default();
        let mut fragment = String::default();
        let mut mode = Mode::Vertex;
        for line in std::str::from_utf8(&bytes)?.lines() {
            let trimmed = line.trim();
            if let Some(comment) = trimmed.strip_prefix("///") {
                let comment = comment.trim().to_lowercase();
                if comment == "[vertex]" {
                    mode = Mode::Vertex;
                    continue;
                }
                if comment == "[fragment]" {
                    mode = Mode::Fragment;
                    continue;
                }
            }
            match mode {
                Mode::Vertex => {
                    vertex.push_str(line);
                    vertex.push('\n');
                }
                Mode::Fragment => {
                    fragment.push_str(line);
                    fragment.push('\n');
                }
            }
        }

        storage.insert(
            handle.entity(),
            (ShaderAsset {
                vertex: vertex.into(),
                fragment: fragment.into(),
            },),
        )?;

        Ok(())
    }
}

pub struct TextureAsset {
    pub image: RgbaImage,
    pub cols: u32,
    pub rows: u32,
}

pub struct TextureAssetSubsystem;

impl GameSubsystem for TextureAssetSubsystem {
    fn run(&mut self, context: crate::context::GameContext, _: f32) {
        for entity in context.assets.storage.added().iter_of::<TextureAsset>() {
            if let Some((path, asset)) = context
                .assets
                .storage
                .lookup_one::<true, (&AssetPathStatic, &TextureAsset)>(entity)
            {
                let pages = asset.cols * asset.rows;
                context.draw.textures.insert(
                    name_from_path(&path).to_owned().into(),
                    context
                        .graphics
                        .texture(
                            asset.image.width(),
                            asset.image.height() / pages,
                            pages,
                            GlowTextureFormat::Rgba,
                            Some(asset.image.as_raw()),
                        )
                        .unwrap(),
                );
            }
        }
        for entity in context.assets.storage.removed().iter_of::<TextureAsset>() {
            if let Some(path) = context
                .assets
                .storage
                .lookup_one::<true, &AssetPathStatic>(entity)
            {
                context.draw.textures.remove(name_from_path(&path));
            }
        }
    }
}

pub struct TextureAssetProtocol;

impl AssetProtocol for TextureAssetProtocol {
    fn name(&self) -> &str {
        "texture"
    }

    fn process_bytes(
        &mut self,
        handle: AssetHandle,
        storage: &mut World,
        bytes: Vec<u8>,
    ) -> Result<(), Box<dyn Error>> {
        let path = storage.component::<true, AssetPathStatic>(handle.entity())?;
        let mut cols = 1;
        let mut rows = 1;
        for (key, value) in path.meta_items() {
            if key == "cols" || key == "c" {
                cols = value.parse().unwrap_or(1);
            } else if key == "rows" || key == "r" {
                rows = value.parse().unwrap_or(1);
            }
        }
        let mut image = image::load_from_memory(&bytes)
            .map_err(|_| format!("Failed to load texture: {:?}", path.path()))?
            .into_rgba8();
        drop(path);
        let pages = cols * rows;
        image = if cols > 1 || rows > 1 {
            let width = image.width() / cols;
            let height = image.height() / rows;
            let mut result = RgbaImage::new(width, height * pages);
            for row in 0..rows {
                for col in 0..cols {
                    let view = image.view(col * width, row * height, width, height);
                    result
                        .copy_from(&*view, 0, (row * cols + col) * height)
                        .unwrap();
                }
            }
            result
        } else {
            image
        };

        storage.insert(handle.entity(), (TextureAsset { image, cols, rows },))?;

        Ok(())
    }
}

pub struct FontAsset {
    pub font: Font,
}

pub struct FontAssetSubsystem;

impl GameSubsystem for FontAssetSubsystem {
    fn run(&mut self, context: crate::context::GameContext, _: f32) {
        for entity in context.assets.storage.added().iter_of::<FontAsset>() {
            if let Some((path, asset)) = context
                .assets
                .storage
                .lookup_one::<true, (&AssetPathStatic, &FontAsset)>(entity)
            {
                context
                    .draw
                    .fonts
                    .insert(name_from_path(&path).to_owned(), asset.font.clone());
            }
        }
        for entity in context.assets.storage.removed().iter_of::<FontAsset>() {
            if let Some(path) = context
                .assets
                .storage
                .lookup_one::<true, &AssetPathStatic>(entity)
            {
                context.draw.fonts.remove(name_from_path(&path));
            }
        }
    }
}

pub struct FontAssetProtocol;

impl AssetProtocol for FontAssetProtocol {
    fn name(&self) -> &str {
        "font"
    }

    fn process_bytes(
        &mut self,
        handle: AssetHandle,
        storage: &mut World,
        bytes: Vec<u8>,
    ) -> Result<(), Box<dyn Error>> {
        let path = storage.component::<true, AssetPathStatic>(handle.entity())?;
        let font = Font::from_bytes(bytes, Default::default())
            .map_err(|_| format!("Failed to load font: {:?}", path.path()))?;
        drop(path);

        storage.insert(handle.entity(), (FontAsset { font },))?;

        Ok(())
    }
}

pub struct SoundAsset {
    pub data: StaticSoundData,
}

pub struct SoundAssetSubsystem;

impl GameSubsystem for SoundAssetSubsystem {
    fn run(&mut self, context: crate::context::GameContext, _: f32) {
        for entity in context.assets.storage.added().iter_of::<SoundAsset>() {
            if let Some((path, asset)) = context
                .assets
                .storage
                .lookup_one::<true, (&AssetPathStatic, &SoundAsset)>(entity)
            {
                context
                    .audio
                    .sounds
                    .insert(name_from_path(&path).to_owned(), asset.data.clone());
            }
        }
        for entity in context.assets.storage.removed().iter_of::<SoundAsset>() {
            if let Some(path) = context
                .assets
                .storage
                .lookup_one::<true, &AssetPathStatic>(entity)
            {
                context.audio.sounds.remove(name_from_path(&path));
            }
        }
    }
}

pub struct SoundAssetProtocol;

impl AssetProtocol for SoundAssetProtocol {
    fn name(&self) -> &str {
        "sound"
    }

    fn process_bytes(
        &mut self,
        handle: AssetHandle,
        storage: &mut World,
        bytes: Vec<u8>,
    ) -> Result<(), Box<dyn Error>> {
        let path = storage.component::<true, AssetPathStatic>(handle.entity())?;
        let data = StaticSoundData::from_cursor(Cursor::new(bytes))
            .map_err(|_| format!("Failed to load sound: {:?}", path.path()))?;
        drop(path);

        storage.insert(handle.entity(), (SoundAsset { data },))?;

        Ok(())
    }
}