bones_asset/
network_handle.rs

1use std::marker::PhantomData;
2
3use serde::{Deserialize, Serialize};
4
5use crate::prelude::*;
6
7/// Asset handle that may be replicated over network and converted back into [`Handle`] or [`UntypedHandle`].
8#[derive(Serialize, Deserialize)]
9pub struct NetworkHandle<T> {
10    /// Content id of the asset, used to lookup asset from [`AssetServer`].
11    pub cid: Cid,
12    phantom: PhantomData<T>,
13}
14
15impl<T> NetworkHandle<T> {
16    /// Create [`NetworkHandle`] from content id ([`Cid`]).
17    pub fn from_cid(cid: Cid) -> Self {
18        Self {
19            cid,
20            phantom: PhantomData,
21        }
22    }
23
24    /// Create asset [`Handle`] by looking up [`NetworkHandle`]'s [`Cid`] in [`AssetServer`].
25    /// Panics if Cid not found in asset server.
26    pub fn into_handle(&self, asset_server: &AssetServer) -> Handle<T> {
27        asset_server.try_get_handle_from_cid(&self.cid).unwrap_or_else(||
28            panic!("Failed to lookup NetworkHandle content id: {} in AssetServer. Asset may not be loaded, or this client does not have exact copy of remote", &self.cid)
29        )
30    }
31
32    /// Convert into [`UntypedHandle`].
33    /// Panics if [`AssetServer`] fails to find handle of asset loaded with [`Cid`].
34    pub fn into_untyped_handle(&self, asset_server: &AssetServer) -> UntypedHandle {
35        asset_server
36            .try_get_untyped_handle_from_cid(&self.cid)
37            .expect("Failed to lookup NetworkHandle content id in AssetServer. Is asset loaded? Invalid Cid?")
38    }
39}