bevy_asset

Struct AssetServer

Source
pub struct AssetServer { /* private fields */ }
Expand description

Loads and tracks the state of Asset values from a configured AssetReader. This can be used to kick off new asset loads and retrieve their current load states.

The general process to load an asset is:

  1. Initialize a new Asset type with the AssetServer via AssetApp::init_asset, which will internally call AssetServer::register_asset and set up related ECS Assets storage and systems.
  2. Register one or more AssetLoaders for that asset with AssetApp::init_asset_loader
  3. Add the asset to your asset folder (defaults to assets).
  4. Call AssetServer::load with a path to your asset.

AssetServer can be cloned. It is backed by an Arc so clones will share state. Clones can be freely used in parallel.

Implementations§

Source§

impl AssetServer

Source

pub fn new( sources: AssetSources, mode: AssetServerMode, watching_for_changes: bool, ) -> Self

Create a new instance of AssetServer. If watch_for_changes is true, the AssetReader storage will watch for changes to asset sources and hot-reload them.

Source

pub fn new_with_meta_check( sources: AssetSources, mode: AssetServerMode, meta_check: AssetMetaCheck, watching_for_changes: bool, ) -> Self

Create a new instance of AssetServer. If watch_for_changes is true, the AssetReader storage will watch for changes to asset sources and hot-reload them.

Source

pub fn get_source<'a>( &'a self, source: impl Into<AssetSourceId<'a>>, ) -> Result<&'a AssetSource, MissingAssetSourceError>

Retrieves the AssetSource for the given source.

Source

pub fn watching_for_changes(&self) -> bool

Returns true if the AssetServer watches for changes.

Source

pub fn register_loader<L: AssetLoader>(&self, loader: L)

Registers a new AssetLoader. AssetLoaders must be registered before they can be used.

Source

pub fn register_asset<A: Asset>(&self, assets: &Assets<A>)

Registers a new Asset type. Asset types must be registered before assets of that type can be loaded.

Source

pub async fn get_asset_loader_with_extension( &self, extension: &str, ) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForExtensionError>

Returns the registered AssetLoader associated with the given extension, if it exists.

Source

pub async fn get_asset_loader_with_type_name( &self, type_name: &str, ) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeNameError>

Returns the registered AssetLoader associated with the given std::any::type_name, if it exists.

Source

pub async fn get_path_asset_loader<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForExtensionError>

Retrieves the default AssetLoader for the given path, if one can be found.

Source

pub async fn get_asset_loader_with_asset_type_id<'a>( &self, type_id: TypeId, ) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeIdError>

Retrieves the default AssetLoader for the given Asset TypeId, if one can be found.

Source

pub async fn get_asset_loader_with_asset_type<'a, A: Asset>( &self, ) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeIdError>

Retrieves the default AssetLoader for the given Asset type, if one can be found.

Source

pub fn load<'a, A: Asset>(&self, path: impl Into<AssetPath<'a>>) -> Handle<A>

Begins loading an Asset of type A stored at path. This will not block on the asset load. Instead, it returns a “strong” Handle. When the Asset is loaded (and enters LoadState::Loaded), it will be added to the associated Assets resource.

In case the file path contains a hashtag (#), the path must be specified using Path or AssetPath because otherwise the hashtag would be interpreted as separator between the file path and the label. For example:

// `#path` is a label.
asset_server.load("some/file#path");

// `#path` is part of the file name.
asset_server.load(Path::new("some/file#path"));

Furthermore, if you need to load a file with a hashtag in its name and a label, you can manually construct an AssetPath.

asset_server.load(AssetPath::from_path(Path::new("some/file#path")).with_label("subasset"));

You can check the asset’s load state by reading AssetEvent events, calling AssetServer::load_state, or checking the Assets storage to see if the Asset exists yet.

The asset load will fail and an error will be printed to the logs if the asset stored at path is not of type A.

Source

pub fn load_acquire<'a, A: Asset, G: Send + Sync + 'static>( &self, path: impl Into<AssetPath<'a>>, guard: G, ) -> Handle<A>

Begins loading an Asset of type A stored at path while holding a guard item. The guard item is dropped when either the asset is loaded or loading has failed.

This function returns a “strong” Handle. When the Asset is loaded (and enters LoadState::Loaded), it will be added to the associated Assets resource.

The guard item should notify the caller in its Drop implementation. See example multi_asset_sync. Synchronously this can be a Arc<AtomicU32> that decrements its counter, asynchronously this can be a Barrier. This function only guarantees the asset referenced by the Handle is loaded. If your asset is separated into multiple files, sub-assets referenced by the main asset might still be loading, depend on the implementation of the AssetLoader.

Additionally, you can check the asset’s load state by reading AssetEvent events, calling AssetServer::load_state, or checking the Assets storage to see if the Asset exists yet.

The asset load will fail and an error will be printed to the logs if the asset stored at path is not of type A.

Source

pub fn load_with_settings<'a, A: Asset, S: Settings>( &self, path: impl Into<AssetPath<'a>>, settings: impl Fn(&mut S) + Send + Sync + 'static, ) -> Handle<A>

Begins loading an Asset of type A stored at path. The given settings function will override the asset’s AssetLoader settings. The type S must match the configured AssetLoader::Settings or settings changes will be ignored and an error will be printed to the log.

Source

pub fn load_acquire_with_settings<'a, A: Asset, S: Settings, G: Send + Sync + 'static>( &self, path: impl Into<AssetPath<'a>>, settings: impl Fn(&mut S) + Send + Sync + 'static, guard: G, ) -> Handle<A>

Begins loading an Asset of type A stored at path while holding a guard item. The guard item is dropped when either the asset is loaded or loading has failed.

This function only guarantees the asset referenced by the Handle is loaded. If your asset is separated into multiple files, sub-assets referenced by the main asset might still be loading, depend on the implementation of the AssetLoader.

The given settings function will override the asset’s AssetLoader settings. The type S must match the configured AssetLoader::Settings or settings changes will be ignored and an error will be printed to the log.

Source

pub async fn load_untyped_async<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Result<UntypedHandle, AssetLoadError>

Asynchronously load an asset that you do not know the type of statically. If you do know the type of the asset, you should use AssetServer::load. If you don’t know the type of the asset, but you can’t use an async method, consider using AssetServer::load_untyped.

Source

pub fn load_untyped<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Handle<LoadedUntypedAsset>

Load an asset without knowing its type. The method returns a handle to a LoadedUntypedAsset.

Once the LoadedUntypedAsset is loaded, an untyped handle for the requested path can be retrieved from it.

use bevy_asset::{Assets, Handle, LoadedUntypedAsset};
use bevy_ecs::system::{Res, Resource};

#[derive(Resource)]
struct LoadingUntypedHandle(Handle<LoadedUntypedAsset>);

fn resolve_loaded_untyped_handle(loading_handle: Res<LoadingUntypedHandle>, loaded_untyped_assets: Res<Assets<LoadedUntypedAsset>>) {
    if let Some(loaded_untyped_asset) = loaded_untyped_assets.get(&loading_handle.0) {
        let handle = loaded_untyped_asset.handle.clone();
        // continue working with `handle` which points to the asset at the originally requested path
    }
}

This indirection enables a non blocking load of an untyped asset, since I/O is required to figure out the asset type before a handle can be created.

Source

pub fn reload<'a>(&self, path: impl Into<AssetPath<'a>>)

Kicks off a reload of the asset stored at the given path. This will only reload the asset if it currently loaded.

Source

pub fn add<A: Asset>(&self, asset: A) -> Handle<A>

Queues a new asset to be tracked by the AssetServer and returns a Handle to it. This can be used to track dependencies of assets created at runtime.

After the asset has been fully loaded by the AssetServer, it will show up in the relevant Assets storage.

Source

pub fn add_async<A: Asset, E: Error + Send + Sync + 'static>( &self, future: impl Future<Output = Result<A, E>> + Send + 'static, ) -> Handle<A>

Queues a new asset to be tracked by the AssetServer and returns a Handle to it. This can be used to track dependencies of assets created at runtime.

After the asset has been fully loaded, it will show up in the relevant Assets storage.

Source

pub fn load_folder<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Handle<LoadedFolder>

Loads all assets from the specified folder recursively. The LoadedFolder asset (when it loads) will contain handles to all assets in the folder. You can wait for all assets to load by checking the LoadedFolder’s RecursiveDependencyLoadState.

Loading the same folder multiple times will return the same handle. If the file_watcher feature is enabled, LoadedFolder handles will reload when a file in the folder is removed, added or moved. This includes files in subdirectories and moving, adding, or removing complete subdirectories.

Source

pub fn get_load_states( &self, id: impl Into<UntypedAssetId>, ) -> Option<(LoadState, DependencyLoadState, RecursiveDependencyLoadState)>

Retrieves all loads states for the given asset id.

Source

pub fn get_load_state(&self, id: impl Into<UntypedAssetId>) -> Option<LoadState>

Retrieves the main LoadState of a given asset id.

Note that this is “just” the root asset load state. To check if an asset and its recursive dependencies have loaded, see AssetServer::is_loaded_with_dependencies.

Source

pub fn get_recursive_dependency_load_state( &self, id: impl Into<UntypedAssetId>, ) -> Option<RecursiveDependencyLoadState>

Retrieves the RecursiveDependencyLoadState of a given asset id.

Source

pub fn load_state(&self, id: impl Into<UntypedAssetId>) -> LoadState

Retrieves the main LoadState of a given asset id.

Source

pub fn recursive_dependency_load_state( &self, id: impl Into<UntypedAssetId>, ) -> RecursiveDependencyLoadState

Retrieves the RecursiveDependencyLoadState of a given asset id.

Source

pub fn is_loaded_with_dependencies(&self, id: impl Into<UntypedAssetId>) -> bool

Returns true if the asset and all of its dependencies (recursive) have been loaded.

Source

pub fn get_handle<'a, A: Asset>( &self, path: impl Into<AssetPath<'a>>, ) -> Option<Handle<A>>

Returns an active handle for the given path, if the asset at the given path has already started loading, or is still “alive”.

Source

pub fn get_id_handle<A: Asset>(&self, id: AssetId<A>) -> Option<Handle<A>>

Get a Handle from an AssetId.

This only returns Some if id is derived from a Handle that was loaded through an AssetServer, otherwise it returns None.

Consider using Assets::get_strong_handle in the case the Handle comes from Assets::add.

Source

pub fn get_id_handle_untyped(&self, id: UntypedAssetId) -> Option<UntypedHandle>

Get an UntypedHandle from an UntypedAssetId. See AssetServer::get_id_handle for details.

Source

pub fn is_managed(&self, id: impl Into<UntypedAssetId>) -> bool

Returns true if the given id corresponds to an asset that is managed by this AssetServer. Otherwise, returns false.

Source

pub fn get_path_id<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Option<UntypedAssetId>

Returns an active untyped asset id for the given path, if the asset at the given path has already started loading, or is still “alive”. Returns the first ID in the event of multiple assets being registered against a single path.

§See also

get_path_ids for all handles.

Source

pub fn get_path_ids<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Vec<UntypedAssetId>

Returns all active untyped asset IDs for the given path, if the assets at the given path have already started loading, or are still “alive”. Multiple IDs will be returned in the event that a single path is used by multiple AssetLoader’s.

Source

pub fn get_handle_untyped<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Option<UntypedHandle>

Returns an active untyped handle for the given path, if the asset at the given path has already started loading, or is still “alive”. Returns the first handle in the event of multiple assets being registered against a single path.

§See also

get_handles_untyped for all handles.

Source

pub fn get_handles_untyped<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Vec<UntypedHandle>

Returns all active untyped handles for the given path, if the assets at the given path have already started loading, or are still “alive”. Multiple handles will be returned in the event that a single path is used by multiple AssetLoader’s.

Source

pub fn get_path_and_type_id_handle( &self, path: &AssetPath<'_>, type_id: TypeId, ) -> Option<UntypedHandle>

Returns an active untyped handle for the given path and TypeId, if the asset at the given path has already started loading, or is still “alive”.

Source

pub fn get_path(&self, id: impl Into<UntypedAssetId>) -> Option<AssetPath<'_>>

Returns the path for the given id, if it has one.

Source

pub fn mode(&self) -> AssetServerMode

Returns the AssetServerMode this server is currently in.

Source

pub fn preregister_loader<L: AssetLoader>(&self, extensions: &[&str])

Pre-register a loader that will later be added.

Assets loaded with matching extensions will be blocked until the real loader is added.

Trait Implementations§

Source§

impl Clone for AssetServer

Source§

fn clone(&self) -> AssetServer

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for AssetServer

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Resource for AssetServer
where Self: Send + Sync + 'static,

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> TypeData for T
where T: 'static + Send + Sync + Clone,

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ConditionalSend for T
where T: Send,

Source§

impl<T> Settings for T
where T: 'static + Send + Sync,