Skip to main content

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::{Render, Texture};
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::<Texture>::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 = Texture;
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!(?name, "convert from png");
64        let dynamic_image = image::load_from_memory_with_format(octets, image::ImageFormat::Png)
65            .expect("Failed to load image");
66
67        debug!(?name, "creating texture");
68        let wgpu_texture = mireforge_wgpu_sprites::load_texture_from_memory(
69            &device_info.device,
70            &device_info.queue,
71            dynamic_image,
72            name.value(),
73        );
74
75        {
76            let mireforge_render_wgpu = resources.fetch_mut::<Render>();
77            let wgpu_material =
78                mireforge_render_wgpu.texture_resource_from_texture(&wgpu_texture, name.value());
79
80            let image_assets = resources.fetch_mut::<Assets<Texture>>();
81            image_assets.set_raw(id, wgpu_material);
82            debug!(?id, ?name, "texture inserted");
83        }
84
85        Ok(())
86    }
87}