Skip to content

Commit adbb53b

Browse files
authored
Return an error when direct-nested-loading a subasset (#18213)
# Objective - Prevents #18291. - Previously, attempting to direct-nested-load a subasset would return the root of the nested-loaded asset. This is most problematic when doing direct-nested-**untyped**-loads of subassets, where you may not even realize you're dealing with the entirely wrong asset (at least with typed loads, *most of the time* the root asset has a different type from the subasset, and so at least you'd get an error that the types don't match). ## Solution - We now return an error when doing these kinds of loads. Note an alternative would be to "solve" this problem, by just looking up the appropriate subasset after doing the nested load. However there's two problems: 1) we don't know which subassets of the root asset are necessary for the subasset we are looking up (so any handles in that subasset may never get registered), 2) a solution will likely hamper attempts to resolve #18010. AFAICT, no one has complained about this issue, so it doesn't seem critical to fix this for now. ## Testing - Added a test to ensure this returns an error. I also checked that the error before this was just a mismatched type error, meaning it was trying to pass off the root asset type `CoolText` as the subasset type `SubText` (which would have worked had I not been using typed loads).
1 parent f245490 commit adbb53b

File tree

3 files changed

+103
-17
lines changed

3 files changed

+103
-17
lines changed

crates/bevy_asset/src/lib.rs

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1823,6 +1823,83 @@ mod tests {
18231823
});
18241824
}
18251825

1826+
// This test is not checking a requirement, but documenting a current limitation. We simply are
1827+
// not capable of loading subassets when doing nested immediate loads.
1828+
#[test]
1829+
fn error_on_nested_immediate_load_of_subasset() {
1830+
let mut app = App::new();
1831+
1832+
let dir = Dir::default();
1833+
dir.insert_asset_text(
1834+
Path::new("a.cool.ron"),
1835+
r#"(
1836+
text: "b",
1837+
dependencies: [],
1838+
embedded_dependencies: [],
1839+
sub_texts: ["A"],
1840+
)"#,
1841+
);
1842+
dir.insert_asset_text(Path::new("empty.txt"), "");
1843+
1844+
app.register_asset_source(
1845+
AssetSourceId::Default,
1846+
AssetSource::build()
1847+
.with_reader(move || Box::new(MemoryAssetReader { root: dir.clone() })),
1848+
)
1849+
.add_plugins((
1850+
TaskPoolPlugin::default(),
1851+
LogPlugin::default(),
1852+
AssetPlugin::default(),
1853+
));
1854+
1855+
app.init_asset::<CoolText>()
1856+
.init_asset::<SubText>()
1857+
.register_asset_loader(CoolTextLoader);
1858+
1859+
struct NestedLoadOfSubassetLoader;
1860+
1861+
impl AssetLoader for NestedLoadOfSubassetLoader {
1862+
type Asset = TestAsset;
1863+
type Error = crate::loader::LoadDirectError;
1864+
type Settings = ();
1865+
1866+
async fn load(
1867+
&self,
1868+
_: &mut dyn Reader,
1869+
_: &Self::Settings,
1870+
load_context: &mut LoadContext<'_>,
1871+
) -> Result<Self::Asset, Self::Error> {
1872+
// We expect this load to fail.
1873+
load_context
1874+
.loader()
1875+
.immediate()
1876+
.load::<SubText>("a.cool.ron#A")
1877+
.await?;
1878+
Ok(TestAsset)
1879+
}
1880+
1881+
fn extensions(&self) -> &[&str] {
1882+
&["txt"]
1883+
}
1884+
}
1885+
1886+
app.init_asset::<TestAsset>()
1887+
.register_asset_loader(NestedLoadOfSubassetLoader);
1888+
1889+
let asset_server = app.world().resource::<AssetServer>().clone();
1890+
let handle = asset_server.load::<TestAsset>("empty.txt");
1891+
1892+
run_app_until(&mut app, |_world| match asset_server.load_state(&handle) {
1893+
LoadState::Loading => None,
1894+
LoadState::Failed(err) => {
1895+
let error_message = format!("{err}");
1896+
assert!(error_message.contains("Requested to load an asset path (a.cool.ron#A) with a subasset, but this is unsupported"), "what? \"{error_message}\"");
1897+
Some(())
1898+
}
1899+
state => panic!("Unexpected asset state: {state:?}"),
1900+
});
1901+
}
1902+
18261903
// validate the Asset derive macro for various asset types
18271904
#[derive(Asset, TypePath)]
18281905
pub struct TestAsset;

crates/bevy_asset/src/loader.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -359,10 +359,14 @@ impl<A: Asset> From<CompleteLoadedAsset<A>> for CompleteErasedLoadedAsset {
359359
/// [`NestedLoader::load`]: crate::NestedLoader::load
360360
/// [immediately]: crate::Immediate
361361
#[derive(Error, Debug)]
362-
#[error("Failed to load dependency {dependency:?} {error}")]
363-
pub struct LoadDirectError {
364-
pub dependency: AssetPath<'static>,
365-
pub error: AssetLoadError,
362+
pub enum LoadDirectError {
363+
#[error("Requested to load an asset path ({0:?}) with a subasset, but this is unsupported. See issue #18291")]
364+
RequestedSubasset(AssetPath<'static>),
365+
#[error("Failed to load dependency {dependency:?} {error}")]
366+
LoadError {
367+
dependency: AssetPath<'static>,
368+
error: AssetLoadError,
369+
},
366370
}
367371

368372
/// An error that occurs while deserializing [`AssetMeta`].
@@ -621,7 +625,7 @@ impl<'a> LoadContext<'a> {
621625
self.populate_hashes,
622626
)
623627
.await
624-
.map_err(|error| LoadDirectError {
628+
.map_err(|error| LoadDirectError::LoadError {
625629
dependency: path.clone(),
626630
error,
627631
})?;

crates/bevy_asset/src/loader_builders.rs

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -387,13 +387,16 @@ impl<'builder, 'reader, T> NestedLoader<'_, '_, T, Immediate<'builder, 'reader>>
387387
path: &AssetPath<'static>,
388388
asset_type_id: Option<TypeId>,
389389
) -> Result<(Arc<dyn ErasedAssetLoader>, CompleteErasedLoadedAsset), LoadDirectError> {
390+
if path.label().is_some() {
391+
return Err(LoadDirectError::RequestedSubasset(path.clone()));
392+
}
390393
let (mut meta, loader, mut reader) = if let Some(reader) = self.mode.reader {
391394
let loader = if let Some(asset_type_id) = asset_type_id {
392395
self.load_context
393396
.asset_server
394397
.get_asset_loader_with_asset_type_id(asset_type_id)
395398
.await
396-
.map_err(|error| LoadDirectError {
399+
.map_err(|error| LoadDirectError::LoadError {
397400
dependency: path.clone(),
398401
error: error.into(),
399402
})?
@@ -402,7 +405,7 @@ impl<'builder, 'reader, T> NestedLoader<'_, '_, T, Immediate<'builder, 'reader>>
402405
.asset_server
403406
.get_path_asset_loader(path)
404407
.await
405-
.map_err(|error| LoadDirectError {
408+
.map_err(|error| LoadDirectError::LoadError {
406409
dependency: path.clone(),
407410
error: error.into(),
408411
})?
@@ -415,7 +418,7 @@ impl<'builder, 'reader, T> NestedLoader<'_, '_, T, Immediate<'builder, 'reader>>
415418
.asset_server
416419
.get_meta_loader_and_reader(path, asset_type_id)
417420
.await
418-
.map_err(|error| LoadDirectError {
421+
.map_err(|error| LoadDirectError::LoadError {
419422
dependency: path.clone(),
420423
error,
421424
})?;
@@ -453,15 +456,17 @@ impl NestedLoader<'_, '_, StaticTyped, Immediate<'_, '_>> {
453456
self.load_internal(&path, Some(TypeId::of::<A>()))
454457
.await
455458
.and_then(move |(loader, untyped_asset)| {
456-
untyped_asset.downcast::<A>().map_err(|_| LoadDirectError {
457-
dependency: path.clone(),
458-
error: AssetLoadError::RequestedHandleTypeMismatch {
459-
path,
460-
requested: TypeId::of::<A>(),
461-
actual_asset_name: loader.asset_type_name(),
462-
loader_name: loader.type_name(),
463-
},
464-
})
459+
untyped_asset
460+
.downcast::<A>()
461+
.map_err(|_| LoadDirectError::LoadError {
462+
dependency: path.clone(),
463+
error: AssetLoadError::RequestedHandleTypeMismatch {
464+
path,
465+
requested: TypeId::of::<A>(),
466+
actual_asset_name: loader.asset_type_name(),
467+
loader_name: loader.type_name(),
468+
},
469+
})
465470
})
466471
}
467472
}

0 commit comments

Comments
 (0)