Skip to content

Fill out some missing docs for bevy_assets #17829

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/bevy_asset/src/assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ impl AssetIndexAllocator {
/// [`AssetPath`]: crate::AssetPath
#[derive(Asset, TypePath)]
pub struct LoadedUntypedAsset {
/// The handle to the loaded asset.
#[dependency]
pub handle: UntypedHandle,
}
Expand Down Expand Up @@ -629,6 +630,7 @@ impl<'a, A: Asset> Iterator for AssetsMutIterator<'a, A> {
}
}

/// An error returned when an [`AssetIndex`] has an invalid generation.
#[derive(Error, Debug)]
#[error("AssetIndex {index:?} has an invalid generation. The current generation is: '{current_generation}'.")]
pub struct InvalidGenerationError {
Expand Down
3 changes: 3 additions & 0 deletions crates/bevy_asset/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use core::fmt::Debug;
/// For an untyped equivalent, see [`UntypedAssetLoadFailedEvent`].
#[derive(Event, Clone, Debug)]
pub struct AssetLoadFailedEvent<A: Asset> {
/// The stable identifier of the asset that failed to load.
pub id: AssetId<A>,
/// The asset path that was attempted.
pub path: AssetPath<'static>,
Expand All @@ -25,6 +26,7 @@ impl<A: Asset> AssetLoadFailedEvent<A> {
/// An untyped version of [`AssetLoadFailedEvent`].
#[derive(Event, Clone, Debug)]
pub struct UntypedAssetLoadFailedEvent {
/// The stable identifier of the asset that failed to load.
pub id: UntypedAssetId,
/// The asset path that was attempted.
pub path: AssetPath<'static>,
Expand All @@ -43,6 +45,7 @@ impl<A: Asset> From<&AssetLoadFailedEvent<A>> for UntypedAssetLoadFailedEvent {
}

/// Events that occur for a specific loaded [`Asset`], such as "value changed" events and "dependency" events.
#[expect(missing_docs, reason = "Documenting the id fields is unhelpful.")]
#[derive(Event, Reflect)]
pub enum AssetEvent<A: Asset> {
/// Emitted whenever an [`Asset`] is added.
Expand Down
1 change: 1 addition & 0 deletions crates/bevy_asset/src/folder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use bevy_reflect::TypePath;
/// [`AssetPath`]: crate::AssetPath
#[derive(Asset, TypePath)]
pub struct LoadedFolder {
/// The handles of all assets stored in the folder.
#[dependency]
pub handles: Vec<UntypedHandle>,
}
9 changes: 8 additions & 1 deletion crates/bevy_asset/src/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,9 @@ impl<A: Asset> From<&mut Handle<A>> for UntypedAssetId {
/// See [`Handle`] for more information.
#[derive(Clone)]
pub enum UntypedHandle {
/// A strong handle, which will keep the referenced [`Asset`] alive until all strong handles are dropped.
Strong(Arc<StrongHandle>),
/// A weak handle, which does not keep the referenced [`Asset`] alive.
Weak(UntypedAssetId),
}

Expand Down Expand Up @@ -528,7 +530,12 @@ pub enum UntypedAssetConversionError {
#[error(
"This UntypedHandle is for {found:?} and cannot be converted into a Handle<{expected:?}>"
)]
TypeIdMismatch { expected: TypeId, found: TypeId },
TypeIdMismatch {
/// The expected [`TypeId`] of the [`Handle`] being converted to.
expected: TypeId,
/// The [`TypeId`] of the [`UntypedHandle`] being converted from.
found: TypeId,
},
}

#[cfg(test)]
Expand Down
28 changes: 24 additions & 4 deletions crates/bevy_asset/src/id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,20 @@ pub enum AssetId<A: Asset> {
///
/// [`Assets`]: crate::Assets
Index {
/// The unstable, opaque index of the asset.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment sent me down a giant rabbit whole lol.

I get that opaque means that there is some data known to the compiler but not to the user. I don't really know what unstable means in this context though.

Maybe it's worth linking to the AssetIndex struct for users to read more?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Opaque means you can't "see inside" it, or e.g. do arithmetic with it, but only use it by giving it to APIs. The compiler helps us enforce this but that's not a requirement for using the term.

Unstable means you can't expect to get the same index between restarts of the application, so it doesn't make sense to serialize it for example.

In all cases I can think of where doc links are rendered you'd also have the type right there, so a link is probably redundant.

index: AssetIndex,
/// A marker to store the type information of the asset.
#[reflect(ignore)]
marker: PhantomData<fn() -> A>,
},
/// A stable-across-runs / const asset identifier. This will only be used if an asset is explicitly registered in [`Assets`]
/// with one.
///
/// [`Assets`]: crate::Assets
Uuid { uuid: Uuid },
Uuid {
/// The UUID provided during asset registration.
uuid: Uuid,
},
}

impl<A: Asset> AssetId<A> {
Expand Down Expand Up @@ -165,12 +170,22 @@ pub enum UntypedAssetId {
/// explicitly registered that way.
///
/// [`Assets`]: crate::Assets
Index { type_id: TypeId, index: AssetIndex },
Index {
/// An identifier that records the underlying asset type.
type_id: TypeId,
/// The unstable, opaque index of the asset.
index: AssetIndex,
},
/// A stable-across-runs / const asset identifier. This will only be used if an asset is explicitly registered in [`Assets`]
/// with one.
///
/// [`Assets`]: crate::Assets
Uuid { type_id: TypeId, uuid: Uuid },
Uuid {
/// An identifier that records the underlying asset type.
type_id: TypeId,
/// The UUID provided during asset registration.
uuid: Uuid,
},
}

impl UntypedAssetId {
Expand Down Expand Up @@ -404,7 +419,12 @@ impl<A: Asset> TryFrom<UntypedAssetId> for AssetId<A> {
pub enum UntypedAssetIdConversionError {
/// Caused when trying to convert an [`UntypedAssetId`] into an [`AssetId`] of the wrong type.
#[error("This UntypedAssetId is for {found:?} and cannot be converted into an AssetId<{expected:?}>")]
TypeIdMismatch { expected: TypeId, found: TypeId },
TypeIdMismatch {
/// The [`TypeId`] of the asset that we are trying to convert to.
expected: TypeId,
/// The [`TypeId`] of the asset that we are trying to convert from.
found: TypeId,
},
}

#[cfg(test)]
Expand Down
1 change: 1 addition & 0 deletions crates/bevy_asset/src/io/embedded/embedded_watcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pub struct EmbeddedWatcher {
}

impl EmbeddedWatcher {
/// Creates a new `EmbeddedWatcher` that watches for changes to the embedded assets in the given `dir`.
Copy link
Contributor

@Carter0 Carter0 Feb 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really think you need this. The comment above the struct is better. I guess you might want it for the future lints though.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah this is lint-proofing.

pub fn new(
dir: Dir,
root_paths: Arc<RwLock<HashMap<Box<Path>, PathBuf>>>,
Expand Down
3 changes: 3 additions & 0 deletions crates/bevy_asset/src/io/embedded/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ use std::path::{Path, PathBuf};
#[cfg(feature = "embedded_watcher")]
use alloc::borrow::ToOwned;

/// The name of the `embedded` [`AssetSource`],
/// as stored in the [`AssetSourceBuilders`] resource.
pub const EMBEDDED: &str = "embedded";
Copy link
Contributor

@Carter0 Carter0 Feb 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does "embedding" an asset in this context mean? I looked at the example and it didn't really explain it either.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It means putting the asset inside the game executable file, in contrast to other assets that are normally loaded from disk to memory when needed. It's normally only used for small engine-related assets so you can use them without having them in your own asset directory.

It sounds like the example could use a line or 2 describing that.


/// A [`Resource`] that manages "rust source files" in a virtual in memory [`Dir`], which is intended
Expand Down Expand Up @@ -77,6 +79,7 @@ impl EmbeddedAssetRegistry {
self.dir.remove_asset(full_path)
}

/// Registers the [`EMBEDDED`] [`AssetSource`] with the given [`AssetSourceBuilders`].
pub fn register_source(&self, sources: &mut AssetSourceBuilders) {
let dir = self.dir.clone();
let processed_dir = self.dir.clone();
Expand Down
5 changes: 4 additions & 1 deletion crates/bevy_asset/src/io/file/file_watcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ use std::path::{Path, PathBuf};
use tracing::error;

/// An [`AssetWatcher`] that watches the filesystem for changes to asset files in a given root folder and emits [`AssetSourceEvent`]
/// for each relevant change. This uses [`notify_debouncer_full`] to retrieve "debounced" filesystem events.
/// for each relevant change.
///
/// This uses [`notify_debouncer_full`] to retrieve "debounced" filesystem events.
/// "Debouncing" defines a time window to hold on to events and then removes duplicate events that fall into this window.
/// This introduces a small delay in processing events, but it helps reduce event duplicates. A small delay is also necessary
/// on some systems to avoid processing a change event before it has actually been applied.
Expand All @@ -27,6 +29,7 @@ pub struct FileWatcher {
}

impl FileWatcher {
/// Creates a new [`FileWatcher`] that watches for changes to the asset files in the given `path`.
pub fn new(
path: PathBuf,
sender: Sender<AssetSourceEvent>,
Expand Down
5 changes: 2 additions & 3 deletions crates/bevy_asset/src/io/file/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,14 @@ impl FileAssetReader {
}
}

/// A writer for the local filesystem.
pub struct FileAssetWriter {
root_path: PathBuf,
}

impl FileAssetWriter {
/// Creates a new `FileAssetIo` at a path relative to the executable's directory, optionally
/// Creates a new [`FileAssetWriter`] at a path relative to the executable's directory, optionally
/// watching for changes.
///
/// See `get_base_path` below.
pub fn new<P: AsRef<Path> + core::fmt::Debug>(path: P, create_root: bool) -> Self {
let root_path = get_base_path().join(path.as_ref());
if create_root {
Expand Down
8 changes: 8 additions & 0 deletions crates/bevy_asset/src/io/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,26 +132,34 @@ impl<'a> PartialEq for AssetSourceId<'a> {
/// and whether or not the source is processed.
#[derive(Default)]
pub struct AssetSourceBuilder {
/// The [`ErasedAssetReader`] to use on the unprocessed asset.
pub reader: Option<Box<dyn FnMut() -> Box<dyn ErasedAssetReader> + Send + Sync>>,
/// The [`ErasedAssetWriter`] to use on the unprocessed asset.
pub writer: Option<Box<dyn FnMut(bool) -> Option<Box<dyn ErasedAssetWriter>> + Send + Sync>>,
/// The [`AssetWatcher`] to use for unprocessed assets, if any.
pub watcher: Option<
Box<
dyn FnMut(crossbeam_channel::Sender<AssetSourceEvent>) -> Option<Box<dyn AssetWatcher>>
+ Send
+ Sync,
>,
>,
/// The [`ErasedAssetReader`] to use for processed assets.
Copy link
Contributor

@Carter0 Carter0 Feb 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might be worth linking to this somewhere? That way people know what processing is. https://github.com/bevyengine/bevy/blob/main/crates/bevy_asset/src/processor/mod.rs

pub processed_reader: Option<Box<dyn FnMut() -> Box<dyn ErasedAssetReader> + Send + Sync>>,
/// The [`ErasedAssetWriter`] to use for processed assets.
pub processed_writer:
Option<Box<dyn FnMut(bool) -> Option<Box<dyn ErasedAssetWriter>> + Send + Sync>>,
/// The [`AssetWatcher`] to use for processed assets, if any.
pub processed_watcher: Option<
Box<
dyn FnMut(crossbeam_channel::Sender<AssetSourceEvent>) -> Option<Box<dyn AssetWatcher>>
+ Send
+ Sync,
>,
>,
/// The warning message to display when watching an unprocessed asset fails.
pub watch_warning: Option<&'static str>,
/// The warning message to display when watching a processed asset fails.
pub processed_watch_warning: Option<&'static str>,
}

Expand Down
8 changes: 8 additions & 0 deletions crates/bevy_asset/src/processor/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,10 @@ pub struct ProcessorTransactionLog {
/// An error that occurs when reading from the [`ProcessorTransactionLog`] fails.
#[derive(Error, Debug)]
Copy link
Contributor

@Carter0 Carter0 Feb 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also might be worth linking to this above the ProcessorTransactionLog
struct. https://github.com/bevyengine/bevy/blob/main/crates/bevy_asset/src/processor/mod.rs

pub enum ReadLogError {
/// An invalid log line was encountered, consisting of the contained string.
#[error("Encountered an invalid log line: '{0}'")]
InvalidLine(String),
/// A file-system-based error occurred while reading the log file.
#[error("Failed to read log file: {0}")]
Io(#[from] futures_io::Error),
}
Expand All @@ -51,21 +53,27 @@ pub struct WriteLogError {
/// An error that occurs when validating the [`ProcessorTransactionLog`] fails.
#[derive(Error, Debug)]
pub enum ValidateLogError {
/// An error that could not be recovered from. All assets will be reprocessed.
#[error("Encountered an unrecoverable error. All assets will be reprocessed.")]
UnrecoverableError,
/// A [`ReadLogError`].
#[error(transparent)]
ReadLogError(#[from] ReadLogError),
/// Duplicated process asset transactions occurred.
#[error("Encountered a duplicate process asset transaction: {0:?}")]
EntryErrors(Vec<LogEntryError>),
}

/// An error that occurs when validating individual [`ProcessorTransactionLog`] entries.
#[derive(Error, Debug)]
pub enum LogEntryError {
/// A duplicate process asset transaction occurred for the given asset path.
#[error("Encountered a duplicate process asset transaction: {0}")]
DuplicateTransaction(AssetPath<'static>),
/// A transaction was ended that never started for the given asset path.
#[error("A transaction was ended that never started {0}")]
EndedMissingTransaction(AssetPath<'static>),
/// An asset started processing but never finished at the given asset path.
#[error("An asset started processing but never finished: {0}")]
UnfinishedTransaction(AssetPath<'static>),
}
Expand Down
2 changes: 2 additions & 0 deletions crates/bevy_asset/src/render_asset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ bitflags::bitflags! {
#[reflect(opaque)]
#[reflect(Serialize, Deserialize, Hash, PartialEq, Debug)]
pub struct RenderAssetUsages: u8 {
/// The bit flag for the main world.
const MAIN_WORLD = 1 << 0;
/// The bit flag for the render world.
const RENDER_WORLD = 1 << 1;
}
}
Expand Down
14 changes: 13 additions & 1 deletion crates/bevy_asset/src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1737,6 +1737,10 @@ impl RecursiveDependencyLoadState {

/// An error that occurs during an [`Asset`] load.
#[derive(Error, Debug, Clone)]
#[expect(
missing_docs,
reason = "Adding docs to the variants would not add information beyond the error message and the names"
)]
pub enum AssetLoadError {
#[error("Requested handle of type {requested:?} for asset '{path}' does not match actual asset type '{actual_asset_name}', which used loader '{loader_name}'")]
RequestedHandleTypeMismatch {
Expand Down Expand Up @@ -1798,6 +1802,7 @@ pub enum AssetLoadError {
},
}

/// An error that can occur during asset loading.
#[derive(Error, Debug, Clone)]
#[error("Failed to load asset '{path}' with asset loader '{loader_name}': {error}")]
pub struct AssetLoaderError {
Expand All @@ -1807,11 +1812,13 @@ pub struct AssetLoaderError {
}

impl AssetLoaderError {
/// The path of the asset that failed to load.
pub fn path(&self) -> &AssetPath<'static> {
&self.path
}
}

/// An error that occurs while resolving an asset added by `add_async`.
#[derive(Error, Debug, Clone)]
#[error("An error occurred while resolving an asset added by `add_async`: {error}")]
pub struct AddAsyncError {
Expand All @@ -1829,13 +1836,15 @@ pub struct MissingAssetLoaderForExtensionError {
#[derive(Error, Debug, Clone, PartialEq, Eq)]
#[error("no `AssetLoader` found with the name '{type_name}'")]
pub struct MissingAssetLoaderForTypeNameError {
type_name: String,
/// The type name that was not found.
pub type_name: String,
}

/// An error that occurs when an [`AssetLoader`] is not registered for a given [`Asset`] [`TypeId`].
#[derive(Error, Debug, Clone, PartialEq, Eq)]
#[error("no `AssetLoader` found with the ID '{type_id:?}'")]
pub struct MissingAssetLoaderForTypeIdError {
/// The type ID that was not found.
pub type_id: TypeId,
}

Expand Down Expand Up @@ -1866,10 +1875,13 @@ const UNTYPED_SOURCE_SUFFIX: &str = "--untyped";
/// An error when attempting to wait asynchronously for an [`Asset`] to load.
#[derive(Error, Debug, Clone)]
pub enum WaitForAssetError {
/// The asset is not being loaded; waiting for it is meaningless.
#[error("tried to wait for an asset that is not being loaded")]
NotLoaded,
/// The asset failed to load.
#[error(transparent)]
Failed(Arc<AssetLoadError>),
/// A dependency of the asset failed to load.
#[error(transparent)]
DependencyFailed(Arc<AssetLoadError>),
}
1 change: 1 addition & 0 deletions crates/bevy_asset/src/transformer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ pub struct IdentityAssetTransformer<A: Asset> {
}

impl<A: Asset> IdentityAssetTransformer<A> {
/// Creates a new [`IdentityAssetTransformer`] with the correct internal [`PhantomData`] field.
pub const fn new() -> Self {
Self {
_phantom: PhantomData,
Expand Down