mireforge_material/
lib.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/mireforge/mireforge
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5pub mod prelude;
6
7use limnus_app::prelude::{App, Plugin};
8use limnus_asset_id::{AssetName, RawWeakId};
9use limnus_asset_registry::AssetRegistry;
10use limnus_assets::Assets;
11use limnus_assets_loader::{AssetLoader, ConversionError, WrappedAssetLoaderRegistry};
12use limnus_local_resource::LocalResourceStorage;
13use limnus_resource::ResourceStorage;
14use limnus_wgpu_window::BasicDeviceInfo;
15use mireforge_render_wgpu::{Material, Render};
16use tracing::debug;
17
18pub struct MaterialPlugin;
19
20impl Plugin for MaterialPlugin {
21    fn build(&self, app: &mut App) {
22        {
23            let registry = app.resource_mut::<WrappedAssetLoaderRegistry>();
24            let loader = MaterialWgpuProcessor::new();
25
26            registry.value.lock().unwrap().register_loader(loader);
27        }
28
29        app.insert_resource(Assets::<Material>::default());
30    }
31}
32
33#[derive(Default)]
34pub struct MaterialWgpuProcessor;
35
36impl MaterialWgpuProcessor {
37    #[must_use]
38    pub const fn new() -> Self {
39        Self {}
40    }
41}
42
43impl AssetLoader for MaterialWgpuProcessor {
44    type AssetType = Material;
45
46    fn convert_and_insert(
47        &self,
48        id: RawWeakId,
49        octets: &[u8],
50        resources: &mut ResourceStorage,
51        local_resources: &mut LocalResourceStorage,
52    ) -> Result<(), ConversionError> {
53        let device_info = local_resources.fetch::<BasicDeviceInfo>();
54
55        let name: AssetName;
56        {
57            let asset_container = resources.fetch::<AssetRegistry>();
58            name = asset_container
59                .name_raw(id)
60                .expect("should know about this Id");
61        }
62
63        debug!("convert from png {name}");
64        let img = image::load_from_memory_with_format(octets, image::ImageFormat::Png)
65            .expect("Failed to load image");
66        let img = img.to_rgba8();
67
68        debug!("creating texture {name}");
69        let wgpu_texture = mireforge_wgpu_sprites::load_texture_from_memory(
70            &device_info.device,
71            &device_info.queue,
72            &img,
73            name.value(),
74        );
75
76        debug!("creating material {name}");
77        {
78            let mireforge_render_wgpu = resources.fetch_mut::<Render>();
79            let wgpu_material =
80                mireforge_render_wgpu.material_from_texture(wgpu_texture, name.value());
81
82            let image_assets = resources.fetch_mut::<Assets<Material>>();
83            image_assets.set_raw(id, wgpu_material);
84        }
85
86        debug!("material complete {name}");
87
88        Ok(())
89    }
90}