Skip to main content

AssetRef

Struct AssetRef 

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

A reference to an asset in the asset database.

AssetRef encapsulates a reference to an asset, identified by its path, with an optional handle that can be lazily resolved or explicitly set.

Implementations§

Source§

impl AssetRef

Source

pub fn new(path: impl Into<AssetPathStatic>) -> Self

Creates a new AssetRef with the given asset path.

§Arguments
  • path: The path to the asset.
§Returns

An instance of AssetRef.

Examples found in repository?
examples/ingame.rs (line 80)
62    fn default() -> Self {
63        Self {
64            context: Default::default(),
65            timer: Instant::now(),
66            assets: AssetDatabase::default()
67                // Text protocol for shader sources.
68                .with_protocol(TextAssetProtocol)
69                // Group protocol for loading many assets at once.
70                .with_protocol(GroupAssetProtocol)
71                // Custom shader protocol.
72                .with_protocol(BundleAssetProtocol::new("shader", ShaderAssetProcessor))
73                // Custom texture protocol.
74                .with_protocol(BundleAssetProtocol::new("texture", TextureAssetProcessor))
75                // Load all data from file system asynchronously.
76                .with_fetch(DeferredAssetFetch::new(
77                    FileAssetFetch::default().with_root("resources"),
78                )),
79            // Stored asset references for cached asset handles.
80            image_shader: AssetRef::new("shader://image.shader"),
81            ferris_texture: AssetRef::new("texture://ferris.png"),
82        }
83    }
Source

pub fn new_resolved( path: impl Into<AssetPathStatic>, handle: AssetHandle, ) -> Self

Creates a new resolved AssetRef with the given asset path and handle.

§Arguments
  • path: The path to the asset.
  • handle: The resolved handle for the asset.
§Returns

A resolved instance of AssetRef.

Source

pub fn invalidate(&self) -> Result<(), Box<dyn Error>>

Invalidates the asset handle, making the AssetRef unresolved.

§Returns

An error if the handle could not be invalidated.

Source

pub fn path(&self) -> &AssetPathStatic

Gets the asset path associated with this reference.

§Returns

A reference to the asset path.

Examples found in repository?
examples/10_references.rs (line 68)
60    fn process_bytes(
61        &mut self,
62        bytes: Vec<u8>,
63    ) -> Result<BundleWithDependencies<Self::Bundle>, Box<dyn Error>> {
64        let asset = serde_json::from_slice::<CustomAsset>(&bytes)?;
65        let dependency = asset
66            .next
67            .as_ref()
68            .map(|reference| reference.path().clone());
69        Ok(BundleWithDependencies::new((asset,)).maybe_dependency(dependency))
70    }
More examples
Hide additional examples
examples/ingame.rs (line 233)
228    fn process_bytes(
229        &mut self,
230        bytes: Vec<u8>,
231    ) -> Result<BundleWithDependencies<Self::Bundle>, Box<dyn Error>> {
232        let asset = serde_json::from_slice::<ShaderAssetInfo>(&bytes)?;
233        let vertex = asset.vertex.path().clone();
234        let fragment = asset.fragment.path().clone();
235
236        println!("* Shader asset processed: {asset:#?}");
237        Ok(BundleWithDependencies::new((asset,))
238            .dependency(vertex)
239            .dependency(fragment))
240    }
241
242    fn maintain(&mut self, storage: &mut World) -> Result<(), Box<dyn Error>> {
243        let mut commands = CommandBuffer::default();
244        let mut lookup = storage.lookup_access::<true, &String>();
245
246        // We scan for decoded shader info and if dependencies are loaded,
247        // then turn them into shader asset.
248        for (entity, info, dependencies) in
249            storage.query::<true, (Entity, &ShaderAssetInfo, &Relation<AssetDependency>)>()
250        {
251            if dependencies
252                .entities()
253                .all(|entity| storage.has_entity_component::<String>(entity))
254            {
255                let vertex = lookup
256                    .access(storage.find_by::<true, _>(info.vertex.path()).unwrap())
257                    .unwrap()
258                    .to_owned();
259                let fragment = lookup
260                    .access(storage.find_by::<true, _>(info.fragment.path()).unwrap())
261                    .unwrap()
262                    .to_owned();
263
264                let asset = ShaderAsset { vertex, fragment };
265                commands.command(InsertCommand::new(entity, (asset,)));
266                commands.command(RemoveCommand::<(ShaderAssetInfo,)>::new(entity));
267            }
268        }
269        drop(lookup);
270
271        commands.execute(storage);
272
273        Ok(())
274    }
Source

pub fn handle(&self) -> Result<AssetHandle, Box<dyn Error>>

Gets the resolved handle for the asset.

§Returns

The resolved AssetHandle, or an error if it has not been resolved.

Source

pub fn resolve<'a>( &'a self, database: &'a AssetDatabase, ) -> Result<AssetResolved<'a>, Box<dyn Error>>

Resolves the asset handle using the asset database, if not already resolved.

§Arguments
  • database: Reference to the AssetDatabase to resolve the asset.
§Returns

A resolved AssetResolved object, or an error if resolution fails.

Examples found in repository?
examples/10_references.rs (line 46)
42    fn contents(&self, database: &AssetDatabase) -> String {
43        let mut result = self.content.as_str().to_owned();
44        if let Some(next) = self.next.as_ref() {
45            result.push(' ');
46            if let Ok(resolved) = next.resolve(database) {
47                result.push_str(&resolved.access::<&Self>().contents(database));
48            }
49        }
50        result
51    }
More examples
Hide additional examples
examples/ingame.rs (line 110)
102    fn on_redraw(&mut self, graphics: &mut Graphics<Vertex>, _: &mut AppControl) {
103        // Process assets periotically.
104        if self.timer.elapsed().as_secs_f32() > DELTA_TIME {
105            self.timer = Instant::now();
106            self.process_assets(graphics);
107        }
108
109        // Do not render unless we have shader loaded.
110        let Ok(image_shader) = self.image_shader.resolve(&self.assets) else {
111            return;
112        };
113        let Some(image_shader) = image_shader
114            .access_checked::<&AsyncHandle<Shader>>()
115            .map(|handle| handle.to_ref())
116        else {
117            return;
118        };
119
120        // Begin drawing objects.
121        self.context.begin_frame(graphics);
122        self.context.push_shader(&image_shader);
123        self.context.push_blending(GlowBlending::Alpha);
124
125        // Draw sprite only if texture asset is loaded.
126        if let Ok(texture) = self.ferris_texture.resolve(&self.assets)
127            && let Some(texture) = texture
128                .access_checked::<&AsyncHandle<Texture>>()
129                .map(|handle| handle.to_ref())
130        {
131            Sprite::single(SpriteTexture::new("u_image".into(), texture))
132                .pivot(0.5.into())
133                .draw(&mut self.context, graphics);
134        }
135
136        // Commit drawn objects.
137        self.context.end_frame();
138    }
examples/17_smart_references.rs (line 19)
8fn main() -> Result<(), Box<dyn Error>> {
9    /* ANCHOR: main */
10    let mut database = AssetDatabase::default()
11        .with_protocol(TextAssetProtocol)
12        .with_fetch(FileAssetFetch::default().with_root("resources"));
13
14    /* ANCHOR: smart_reference */
15    // Load asset and mark its first reference.
16    let first = SmartAssetRef::new("text://lorem.txt", &mut database)?;
17    println!(
18        "Lorem Ipsum: {}",
19        first.resolve(&database)?.access::<&String>()
20    );
21    database.maintain()?;
22    assert_eq!(database.storage.len(), 1);
23    assert_eq!(
24        first
25            .resolve(&database)?
26            .access::<&AssetReferenceCounter>()
27            .counter(),
28        1
29    );
30
31    // Clone the asset and mark its second reference.
32    let second = first.clone();
33    database.maintain()?;
34    assert_eq!(database.storage.len(), 1);
35    assert_eq!(
36        second
37            .resolve(&database)?
38            .access::<&AssetReferenceCounter>()
39            .counter(),
40        2
41    );
42
43    // Ensure asset again from scratch and mark its third reference.
44    let third = SmartAssetRef::new("text://lorem.txt", &mut database)?;
45    database.maintain()?;
46    assert_eq!(database.storage.len(), 1);
47    assert_eq!(
48        third
49            .resolve(&database)?
50            .access::<&AssetReferenceCounter>()
51            .counter(),
52        3
53    );
54
55    // Drop the first reference and expect 2 references.
56    drop(first);
57    database.maintain()?;
58    assert_eq!(database.storage.len(), 1);
59    assert_eq!(
60        third
61            .resolve(&database)?
62            .access::<&AssetReferenceCounter>()
63            .counter(),
64        2
65    );
66
67    // Drop the second reference and expect 1 reference.
68    drop(second);
69    database.maintain()?;
70    assert_eq!(database.storage.len(), 1);
71    assert_eq!(
72        third
73            .resolve(&database)?
74            .access::<&AssetReferenceCounter>()
75            .counter(),
76        1
77    );
78
79    // Drop the third reference and expect no references and asset no more existing.
80    drop(third);
81    database.maintain()?;
82    assert_eq!(database.storage.len(), 0);
83    /* ANCHOR_END: smart_reference */
84    /* ANCHOR_END: main */
85
86    Ok(())
87}
Source

pub fn ensure<'a>( &'a self, database: &'a mut AssetDatabase, ) -> Result<AssetResolved<'a>, Box<dyn Error>>

Ensures existence of the asset with handle using the asset database.

§Arguments
  • database: Reference to the AssetDatabase to ensure the asset.
§Returns

An ensured AssetResolved object, or an error if resolution fails.

Trait Implementations§

Source§

impl Clone for AssetRef

Source§

fn clone(&self) -> Self

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 AssetRef

Source§

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

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

impl Default for AssetRef

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for AssetRef

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<AssetPath<'static>> for AssetRef

Source§

fn from(path: AssetPathStatic) -> Self

Converts to this type from the input type.
Source§

impl From<AssetRef> for AssetPathStatic

Source§

fn from(value: AssetRef) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for AssetRef

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for AssetRef

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for AssetRef

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

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

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> Finalize for T

Source§

unsafe fn finalize_raw(data: *mut ())

Safety Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Initialize for T
where T: Default,

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

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,