bevy_embedded_assets

repository·main·Indexed 42 days ago

https://github.com/vleue/bevy_embedded_assets

A Bevy plugin that embeds asset folders directly into the compiled binary to simplify distribution and releases. It provides the EmbeddedAssetPlugin for integration with Bevy's asset system via various PluginModes (AutoLoad, ReplaceDefault, and ReplaceAndFallback), as well as the EmbeddedAssetReader for accessing raw asset bytes outside of the ECS environment.

Tokens
2.3K
Snippets
10
Records
11
Agent score
50%

What's inside bevy_embedded_assets

  1. Configure EmbeddedAssetPlugin modes

    main

    The EmbeddedAssetPlugin operates in one of three modes, which determine how assets are accessed and where they are sourced from:

    • PluginMode::AutoLoad: Embeds the asset folder and makes it available via the embedded:// source.
    • PluginMode::ReplaceDefault: Embeds the asset folder and makes it available through the default asset source.
    • PluginMode::ReplaceAndFallback: Embeds the asset folder and makes it available through the default asset source. If an asset is not found at runtime, it falls back to the default source for the current platform.
    // Example of configuring a specific mode
    EmbeddedAssetPlugin::new(PluginMode::ReplaceDefault)
  2. Install and initialize EmbeddedAssetPlugin

    main

    To embed your asset folder inside your binary for easier releases, add EmbeddedAssetPlugin to your Bevy App. You should typically add it alongside DefaultPlugins.

    use bevy::prelude::*;
    use bevy_embedded_assets::EmbeddedAssetPlugin;
    
    fn main() {
        App::new().add_plugins((EmbeddedAssetPlugin::default(), DefaultPlugins));
    }
  3. Retrieve embedded assets directly with `EmbeddedAssetReader`

    main

    If you need to access embedded assets outside of the standard Bevy ECS environment (e.g., in a non-ECS system or a standalone utility), you can use EmbeddedAssetReader. This allows you to bypass the Handle<T> pattern and load raw bytes directly from the embedded registry.

    Note: This functionality is only available when the default-source cargo feature is enabled.

    To use it, call EmbeddedAssetReader::preloaded() to initialize a reader containing all assets found by the build script, then use load_path_sync() to retrieve a DataReader.

    use bevy_embedded_assets::{DataReader, EmbeddedAssetReader};
    use std::path::Path;
    
    fn some_bevy_system() {
        // Initialize the reader with all embedded assets
        let embedded: EmbeddedAssetReader = EmbeddedAssetReader::preloaded();
        
        // Load an asset synchronously by path
        // Assumes 'image.png' was included during build
        let reader: DataReader = embedded.load_path_sync(&Path::new("image.png")).unwrap();
        
        // Access the raw bytes via the .0 field
        let image_data: Vec<u8> = reader.0.to_vec();
        
        // Use the data...
    }
  4. Use EmbeddedAssetPlugin to embed assets

    main

    The EmbeddedAssetPlugin allows you to embed your asset folder directly into your Bevy application binary. This is particularly useful for platforms like WebAssembly (WASM) where file system access is limited.

    Depending on the PluginMode you choose, assets are accessed either via a specific URI prefix or by replacing the default asset loading behavior.

    # use bevy::prelude::*;
    # use bevy_embedded_assets::{EmbeddedAssetPlugin, PluginMode};
    # #[derive(Asset, TypePath)]
    # pub struct MyAsset;
    # fn main() {
    # let mut app = App::new();
    app.add_plugins((EmbeddedAssetPlugin::default(), DefaultPlugins));
    # app.init_asset::<MyAsset>();
    # let asset_server: Mut<'_, AssetServer> = app.world_mut().resource_mut::<AssetServer>();
    # let handle: Handle<MyAsset> = asset_server.load("embedded://example_asset.test");
    # }
  5. Check Bevy compatibility versions

    main

    Ensure your version of bevy_embedded_assets is compatible with your version of bevy. Use the following mapping:

    Bevy Versionbevy_embedded_assets Version
    mainmain
    0.190.16
    0.180.15
    0.170.14
    0.160.13
    0.150.12
    0.140.11
    0.130.10
    0.120.9
    0.110.8
    0.100.7
    0.90.6
    0.80.4
    0.70.3
    0.60.2
    0.50.1
  6. Use `EmbeddedAssetReader::preloaded()` to load all assets

    main

    The preloaded() method creates an EmbeddedAssetReader that is automatically populated with all assets discovered by the crate's build script. This is the primary way to access the embedded filesystem without manual registration.

    let embedded = EmbeddedAssetReader::preloaded();
  7. Synchronously load an asset path with `load_path_sync`

    main

    The load_path_sync method searches the embedded registry for an asset matching the provided &Path.

    • Returns: Ok(DataReader) containing the asset bytes if found.
    • Errors: Returns AssetReaderError::NotFound if the path does not exist in the embedded registry.
    let reader = embedded.load_path_sync(Path::new("path/to/asset.png"))?;
  8. EmbeddedAssetPlugin struct reference

    main

    The main plugin used to enable embedded assets in a Bevy application.

    #[allow(clippy::module_name_repetitions)]
    #[derive(Default, Debug, Clone)]
    pub struct EmbeddedAssetPlugin {
        /// How this plugin should behave.
        pub mode: PluginMode,
    }
  9. PluginMode enum reference

    main

    The PluginMode enum defines how the EmbeddedAssetPlugin integrates with Bevy's asset system.

    #[derive(Debug, Clone, Default)]
    #[allow(missing_copy_implementations)]
    pub enum PluginMode {
        /// Embed the assets folder and make the files available through the `embedded://` source.
        #[default]
        AutoLoad,
    
        /// Replace the default asset source with an embedded source.
        ///
        /// In this mode, listing files in a directory will work in wasm.
        #[cfg(feature = "default-source")]
        ReplaceDefault,
    
        /// Replace the default asset source with an embedded source. If a file is not present at build
        /// time, fallback to the default source for the current platform.
        ///
        /// In this mode, listing files in a directory will work in wasm.
        #[cfg(feature = "default-source")]
        ReplaceAndFallback {
            /// The default file path to use (relative to the project root). `"assets"` is the
            /// standard value in Bevy.
            path: String,
        },
    }
  10. Access raw asset bytes with `DataReader`

    main

    A DataReader is a lightweight wrapper around a &'static [u8] slice representing the raw bytes of an embedded asset. It is returned by EmbeddedAssetReader::load_path_sync().

    To access the underlying byte slice, use the public field .0.

    // Assuming 'reader' is a DataReader
    let bytes: &[u8] = reader.0;