Skip to main content

ResourceManager

Struct ResourceManager 

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

Resource manager controls loading and lifetime of resource in the engine. Resource manager can hold resources of arbitrary types via type erasure mechanism.

§Built-in Resources

Built-in resources are special kinds of resources, whose data is packed in the executable (i.e. via include_bytes macro). Such resources reference the data that cannot be “loaded” from external source. To support such kind of resource the manager provides built_in_resources hash map where you can register your own built-in resource and access existing ones.

§Internals

It is a simple wrapper over ResourceManagerState that can be shared (cloned). In other words, it is just a strong reference to the inner state.

Implementations§

Source§

impl ResourceManager

Source

pub fn new(io: Arc<dyn ResourceIo>, task_pool: Arc<TaskPool>) -> ResourceManager

Creates a resource manager with default settings and loaders.

Source

pub fn state(&self) -> MutexGuard<'_, RawMutex, ResourceManagerState>

Returns a guarded reference to the internal state of resource manager. This is blocking method and it may deadlock if used incorrectly (trying to get the state lock one more time when there’s an existing lock in the same thread, multi-threading-related deadlock and so on).

Source

pub fn try_get_state( &self, timeout: Duration, ) -> Option<MutexGuard<'_, RawMutex, ResourceManagerState>>

Returns a guarded reference to the internal state of resource manager. This method will try to acquire the state lock for the given time and if it fails, returns None.

Source

pub async fn registry_is_loaded(&self) -> bool

The resource manager keeps a registry of available resources, and this registry must be loaded before any resources may be requested. This async method returns once the registry loading is complete and it returns true if the loading was successful. It returns false if loading failed.

Source

pub fn resource_io(&self) -> Arc<dyn ResourceIo>

Returns the ResourceIo used by this resource manager

Source

pub fn task_pool(&self) -> Arc<TaskPool>

Returns the task pool used by this resource manager.

Source

pub fn registry_folder(&self) -> PathBuf

Returns an absolute path to the registry folder (absolute version of ./data by default).

Source

pub fn register_built_in_resource<T>( &self, resource: BuiltInResource<T>, ) -> Option<UntypedBuiltInResource>

Registers a new built-in resource, so it becomes accessible via Self::request.

Source

pub fn try_find<T>(&self, path: impl AsRef<Path>) -> Option<Resource<T>>

The same as Self::find, but returns None if type UUID of T does not match the actual type UUID of the resource.

§Panic

This method does not panic.

Source

pub fn find<T>(&self, path: impl AsRef<Path>) -> Resource<T>

Find the resource for the given path without loading the resource. A new unloaded resource is created if one does not already exist. If the path is not in the registry then a new UUID is generated and the path is added to the registry. If the resource is not already loading, then it will be returned in the ResourceState::Unloaded state, and Self::request_resource may be used to begin the loading process.

§Panic

This method will panic if type UUID of T does not match the actual type UUID of the resource. If this is undesirable, use Self::try_find instead.

Source

pub fn find_uuid<T>(&self, uuid: Uuid) -> Resource<T>

Find the resource for the given UUID without loading the resource. If the resource is not already loading, then it will be returned in the ResourceState::Unloaded state, and Self::request_resource may be used to begin the loading process.

§Panic

This method will panic if type UUID of T does not match the actual type UUID of the resource. If this is undesirable, use Self::try_find instead.

Source

pub fn request<T>(&self, path: impl AsRef<Path>) -> Resource<T>

Requests a resource of the given type located at the given path. This method is non-blocking, instead it immediately returns the typed resource wrapper. Loading of the resource is managed automatically in a separate thread (or thread pool) on PC, and JS micro-task (the same thread) on WebAssembly.

§Type Guarantees

There’s no strict guarantees that the requested resource will be of the requested type. This is because the resource system is fully async and does not have access to type information in most cases. Initial type checking is not very reliable and can be “fooled” pretty easily, simply because it just checks if there’s a registered loader for a specific extension.

§Sharing

If the resource at the given path is already was requested (no matter in which state the actual resource is), this method will return the existing instance. This way the resource manager guarantees that the actual resource data will be loaded once, and it can be shared.

§Waiting

If you need to wait until the resource is loaded, use .await on the result of the method. Every resource implements Future trait and can be used in async contexts.

§Resource state

Keep in mind, that the resource itself is a small state machine. It could be in three main states:

Actual resource state can be fetched by Resource::state method. If you know for sure that the resource is already loaded, then you can use Resource::data_ref to obtain a reference to the actual resource data. Keep in mind, that this method will panic if the resource non in Ok state.

§Panic

This method will panic, if type UUID of T does not match the actual type UUID of the resource. If this is undesirable, use Self::try_request instead.

Source

pub fn request_resource<T>(&self, resource: &mut Resource<T>)

Requests that given resource should begin loading, if not already loading or loaded. This method is non-blocking, instead it modifies the given resource and returns. Loading of the resource is managed automatically in a separate thread (or thread pool) on PC, and JS micro-task (the same thread) on WebAssembly.

§Type Guarantees

There’s no strict guarantees that the requested resource will be of the requested type. This is because the resource system is fully async and does not have access to type information in most cases. Initial type checking is not very reliable and can be “fooled” pretty easily, simply because it just checks if there’s a registered loader for a specific extension.

§Sharing

If a resource with given resource’s UUID was already requested (no matter in which state the actual resource is), this method will modify the given resource to be a shared reference to the already loading resource. This way the resource manager guarantees that the actual resource data will be loaded once, and it can be shared.

§Resource state

Keep in mind, that the resource itself is a small state machine. It could be in these states:

Actual resource state can be fetched by Resource::state method. If you know for sure that the resource is already loaded, then you can use Resource::data_ref to obtain a reference to the actual resource data. Keep in mind, that this method will panic if the resource non in Ok state.

§Panic

This method will panic, if type UUID of T does not match the actual type UUID of the resource. If this is undesirable, use Self::try_request instead.

Source

pub fn add_resource<T>(&self, resource: &mut Resource<T>)

Add the given resource to the resource manager, based on the resource’s UUID, without initiating the loading of the resource. The given resource is modified to be a reference to the shared data of an existing resource with the same UUID.

Source

pub fn try_request<T>(&self, path: impl AsRef<Path>) -> Option<Resource<T>>

The same as Self::request, but returns None if type UUID of T does not match the actual type UUID of the resource.

§Panic

This method does not panic.

Source

pub fn resource_path( &self, resource: impl AsRef<UntypedResource>, ) -> Option<PathBuf>

Tries to fetch a path of the given untyped resource. The path may be missing in a few cases:

  1. The resource is in invalid state (not in ResourceState::Ok).
  2. The resource wasn’t registered in the resource registry.
  3. The resource registry wasn’t loaded.
Source

pub fn uuid_to_resource_path(&self, resource_uuid: Uuid) -> Option<PathBuf>

Tries to fetch a resource path associated with the given UUID. Returns None if there’s no resource with the given UUID.

Source

pub fn request_untyped<P>(&self, path: P) -> UntypedResource
where P: AsRef<Path>,

Same as Self::request, but returns untyped resource.

Source

pub fn update_or_load_registry(&self)

Tries to update the registry if possible on the current platform, and if not - try to load an existing one. Some platforms do not have a file system, so the registry must be prepared on a platform that does have it and then saved to be loaded later on. For example, WebAssembly platform does not have a file system and the resource manager will try to load an existing registry instead of updating it.

Source

pub fn add_loader<T>(&self, loader: T) -> Option<T>
where T: ResourceLoader,

Adds a new resource loader of the given type.

Source

pub fn register( &self, resource: UntypedResource, path: impl AsRef<Path>, ) -> Result<(), ResourceRegistrationError>

Add the given resource to the manager and registers the resource as an external resource with the given path, updating the metadata file with the resource’s UUID and updating the registry file with the resource’s path. Calling this should only be necessary after newly creating the file in the given path by saving the resource to the file, otherwise the resource’s path should already have been discovered by ResourceManager::update_or_load_registry. If the manager already has a resource with this resource’s UUID, return ResourceRegistrationError::AlreadyRegistered.

Source

pub fn is_built_in_resource_path(&self, resource: impl AsRef<Path>) -> bool

Checks whether the given resource path corresponds to a built-in resource or not.

Source

pub fn is_built_in_resource( &self, resource: impl AsRef<UntypedResource>, ) -> bool

Checks whether the given resource is a built-in resource instance or not.

Source

pub async fn make_resource_move_context( &self, src_path: impl AsRef<Path>, dest_path: impl AsRef<Path>, overwrite_existing: bool, ) -> Result<ResourceMoveContext, ResourceMovementError>

Creates a resource movement context.

Source

pub async fn can_resource_be_moved( &self, src_path: impl AsRef<Path>, dest_path: impl AsRef<Path>, overwrite_existing: bool, ) -> bool

Returns true if a resource at the src_path can be moved to the dest_path, false - otherwise. Source path must be a valid resource path, and the dest path must have a valid new directory part of the path.

Source

pub async fn move_resource_by_path( &self, src_path: impl AsRef<Path>, dest_path: impl AsRef<Path>, overwrite_existing: bool, ) -> Result<(), ResourceMovementError>

Tries to move a resource at the given path to the new path. The path of the resource must be registered in the resource registry for the resource to be moveable. This method can also be used to rename the source file of a resource.

Source

pub async fn move_resource( &self, resource: impl AsRef<UntypedResource>, new_path: impl AsRef<Path>, overwrite_existing: bool, ) -> Result<(), ResourceMovementError>

Attempts to move a resource from its current location to the new path. The resource must be registered in the resource registry to be moveable. This method can also be used to rename the source file of a resource.

Source

pub async fn reload_resources(&self)

Reloads all loaded resources. Normally it should never be called, because it is very heavy method! This method is asynchronous, it uses all available CPU power to reload resources as fast as possible.

Source

pub fn is_supported_resource(&self, path: &Path) -> bool

Checks if there’s a loader for the given resource path.

Source

pub fn is_path_in_registry(&self, path: &Path) -> bool

Checks if the given path is located inside the folder tracked by the resource registry.

Source

pub async fn try_move_folder( &self, src_dir: &Path, dest_dir: &Path, overwrite_existing: bool, ) -> Result<(), FolderMovementError>

Tries to move a folder to some other folder.

Source

pub async fn resave_native_resources(&self)

Tries to resave all the native resources registered in the resource registry. This method could be useful for assets migration to a newer version.

§Platform-specific

Does nothing on WebAssembly.

Trait Implementations§

Source§

impl Clone for ResourceManager

Source§

fn clone(&self) -> ResourceManager

Returns a duplicate 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 ResourceManager

Source§

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

Formats the value using the given formatter. Read more

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> AsyncTaskResult for T
where T: Any + Send + 'static,

Source§

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

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, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> Downcast for T
where T: Any,

Source§

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

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

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

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

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

Converts &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)

Converts &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> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

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

Source§

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

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> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Send + Sync>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

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

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be 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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<T, U> ObjectOrVariant<T> for U

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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