Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_asset/src/meta.rs
6598 views
1
use alloc::{
2
boxed::Box,
3
string::{String, ToString},
4
vec::Vec,
5
};
6
7
use crate::{
8
loader::AssetLoader, processor::Process, Asset, AssetPath, DeserializeMetaError,
9
VisitAssetDependencies,
10
};
11
use downcast_rs::{impl_downcast, Downcast};
12
use ron::ser::PrettyConfig;
13
use serde::{Deserialize, Serialize};
14
use tracing::error;
15
16
pub const META_FORMAT_VERSION: &str = "1.0";
17
pub type MetaTransform = Box<dyn Fn(&mut dyn AssetMetaDyn) + Send + Sync>;
18
19
/// Asset metadata that informs how an [`Asset`] should be handled by the asset system.
20
///
21
/// `L` is the [`AssetLoader`] (if one is configured) for the [`AssetAction`]. This can be `()` if it is not required.
22
/// `P` is the [`Process`] processor, if one is configured for the [`AssetAction`]. This can be `()` if it is not required.
23
#[derive(Serialize, Deserialize)]
24
pub struct AssetMeta<L: AssetLoader, P: Process> {
25
/// The version of the meta format being used. This will change whenever a breaking change is made to
26
/// the meta format.
27
pub meta_format_version: String,
28
/// Information produced by the [`AssetProcessor`] _after_ processing this asset.
29
/// This will only exist alongside processed versions of assets. You should not manually set it in your asset source files.
30
///
31
/// [`AssetProcessor`]: crate::processor::AssetProcessor
32
#[serde(skip_serializing_if = "Option::is_none")]
33
pub processed_info: Option<ProcessedInfo>,
34
/// How to handle this asset in the asset system. See [`AssetAction`].
35
pub asset: AssetAction<L::Settings, P::Settings>,
36
}
37
38
impl<L: AssetLoader, P: Process> AssetMeta<L, P> {
39
pub fn new(asset: AssetAction<L::Settings, P::Settings>) -> Self {
40
Self {
41
meta_format_version: META_FORMAT_VERSION.to_string(),
42
processed_info: None,
43
asset,
44
}
45
}
46
47
/// Deserializes the given serialized byte representation of the asset meta.
48
pub fn deserialize(bytes: &[u8]) -> Result<Self, DeserializeMetaError> {
49
Ok(ron::de::from_bytes(bytes)?)
50
}
51
}
52
53
/// Configures how an asset source file should be handled by the asset system.
54
#[derive(Serialize, Deserialize)]
55
pub enum AssetAction<LoaderSettings, ProcessSettings> {
56
/// Load the asset with the given loader and settings
57
/// See [`AssetLoader`].
58
Load {
59
loader: String,
60
settings: LoaderSettings,
61
},
62
/// Process the asset with the given processor and settings.
63
/// See [`Process`] and [`AssetProcessor`].
64
///
65
/// [`AssetProcessor`]: crate::processor::AssetProcessor
66
Process {
67
processor: String,
68
settings: ProcessSettings,
69
},
70
/// Do nothing with the asset
71
Ignore,
72
}
73
74
/// Info produced by the [`AssetProcessor`] for a given processed asset. This is used to determine if an
75
/// asset source file (or its dependencies) has changed.
76
///
77
/// [`AssetProcessor`]: crate::processor::AssetProcessor
78
#[derive(Serialize, Deserialize, Default, Debug, Clone)]
79
pub struct ProcessedInfo {
80
/// A hash of the asset bytes and the asset .meta data
81
pub hash: AssetHash,
82
/// A hash of the asset bytes, the asset .meta data, and the `full_hash` of every `process_dependency`
83
pub full_hash: AssetHash,
84
/// Information about the "process dependencies" used to process this asset.
85
pub process_dependencies: Vec<ProcessDependencyInfo>,
86
}
87
88
/// Information about a dependency used to process an asset. This is used to determine whether an asset's "process dependency"
89
/// has changed.
90
#[derive(Serialize, Deserialize, Debug, Clone)]
91
pub struct ProcessDependencyInfo {
92
pub full_hash: AssetHash,
93
pub path: AssetPath<'static>,
94
}
95
96
/// This is a minimal counterpart to [`AssetMeta`] that exists to speed up (or enable) serialization in cases where the whole [`AssetMeta`] isn't
97
/// necessary.
98
// PERF:
99
// Currently, this is used when retrieving asset loader and processor information (when the actual type is not known yet). This could probably
100
// be replaced (and made more efficient) by a custom deserializer that reads the loader/processor information _first_, then deserializes the contents
101
// using a type registry.
102
#[derive(Serialize, Deserialize)]
103
pub struct AssetMetaMinimal {
104
pub asset: AssetActionMinimal,
105
}
106
107
/// This is a minimal counterpart to [`AssetAction`] that exists to speed up (or enable) serialization in cases where the whole [`AssetAction`]
108
/// isn't necessary.
109
#[derive(Serialize, Deserialize)]
110
pub enum AssetActionMinimal {
111
Load { loader: String },
112
Process { processor: String },
113
Ignore,
114
}
115
116
/// This is a minimal counterpart to [`ProcessedInfo`] that exists to speed up serialization in cases where the whole [`ProcessedInfo`] isn't
117
/// necessary.
118
#[derive(Serialize, Deserialize)]
119
pub struct ProcessedInfoMinimal {
120
pub processed_info: Option<ProcessedInfo>,
121
}
122
123
/// A dynamic type-erased counterpart to [`AssetMeta`] that enables passing around and interacting with [`AssetMeta`] without knowing
124
/// its type.
125
pub trait AssetMetaDyn: Downcast + Send + Sync {
126
/// Returns a reference to the [`AssetLoader`] settings, if they exist.
127
fn loader_settings(&self) -> Option<&dyn Settings>;
128
/// Returns a mutable reference to the [`AssetLoader`] settings, if they exist.
129
fn loader_settings_mut(&mut self) -> Option<&mut dyn Settings>;
130
/// Serializes the internal [`AssetMeta`].
131
fn serialize(&self) -> Vec<u8>;
132
/// Returns a reference to the [`ProcessedInfo`] if it exists.
133
fn processed_info(&self) -> &Option<ProcessedInfo>;
134
/// Returns a mutable reference to the [`ProcessedInfo`] if it exists.
135
fn processed_info_mut(&mut self) -> &mut Option<ProcessedInfo>;
136
}
137
138
impl<L: AssetLoader, P: Process> AssetMetaDyn for AssetMeta<L, P> {
139
fn loader_settings(&self) -> Option<&dyn Settings> {
140
if let AssetAction::Load { settings, .. } = &self.asset {
141
Some(settings)
142
} else {
143
None
144
}
145
}
146
fn loader_settings_mut(&mut self) -> Option<&mut dyn Settings> {
147
if let AssetAction::Load { settings, .. } = &mut self.asset {
148
Some(settings)
149
} else {
150
None
151
}
152
}
153
fn serialize(&self) -> Vec<u8> {
154
ron::ser::to_string_pretty(&self, PrettyConfig::default())
155
.expect("type is convertible to ron")
156
.into_bytes()
157
}
158
fn processed_info(&self) -> &Option<ProcessedInfo> {
159
&self.processed_info
160
}
161
fn processed_info_mut(&mut self) -> &mut Option<ProcessedInfo> {
162
&mut self.processed_info
163
}
164
}
165
166
impl_downcast!(AssetMetaDyn);
167
168
/// Settings used by the asset system, such as by [`AssetLoader`], [`Process`], and [`AssetSaver`]
169
///
170
/// [`AssetSaver`]: crate::saver::AssetSaver
171
pub trait Settings: Downcast + Send + Sync + 'static {}
172
173
impl<T: 'static> Settings for T where T: Send + Sync {}
174
175
impl_downcast!(Settings);
176
177
/// The () processor should never be called. This implementation exists to make the meta format nicer to work with.
178
impl Process for () {
179
type Settings = ();
180
type OutputLoader = ();
181
182
async fn process(
183
&self,
184
_context: &mut bevy_asset::processor::ProcessContext<'_>,
185
_meta: AssetMeta<(), Self>,
186
_writer: &mut bevy_asset::io::Writer,
187
) -> Result<(), bevy_asset::processor::ProcessError> {
188
unreachable!()
189
}
190
}
191
192
impl Asset for () {}
193
194
impl VisitAssetDependencies for () {
195
fn visit_dependencies(&self, _visit: &mut impl FnMut(bevy_asset::UntypedAssetId)) {
196
unreachable!()
197
}
198
}
199
200
/// The () loader should never be called. This implementation exists to make the meta format nicer to work with.
201
impl AssetLoader for () {
202
type Asset = ();
203
type Settings = ();
204
type Error = std::io::Error;
205
async fn load(
206
&self,
207
_reader: &mut dyn crate::io::Reader,
208
_settings: &Self::Settings,
209
_load_context: &mut crate::LoadContext<'_>,
210
) -> Result<Self::Asset, Self::Error> {
211
unreachable!();
212
}
213
214
fn extensions(&self) -> &[&str] {
215
unreachable!();
216
}
217
}
218
219
pub(crate) fn meta_transform_settings<S: Settings>(
220
meta: &mut dyn AssetMetaDyn,
221
settings: &(impl Fn(&mut S) + Send + Sync + 'static),
222
) {
223
if let Some(loader_settings) = meta.loader_settings_mut() {
224
if let Some(loader_settings) = loader_settings.downcast_mut::<S>() {
225
settings(loader_settings);
226
} else {
227
error!(
228
"Configured settings type {} does not match AssetLoader settings type",
229
core::any::type_name::<S>(),
230
);
231
}
232
}
233
}
234
235
pub(crate) fn loader_settings_meta_transform<S: Settings>(
236
settings: impl Fn(&mut S) + Send + Sync + 'static,
237
) -> MetaTransform {
238
Box::new(move |meta| meta_transform_settings(meta, &settings))
239
}
240
241
pub type AssetHash = [u8; 32];
242
243
/// NOTE: changing the hashing logic here is a _breaking change_ that requires a [`META_FORMAT_VERSION`] bump.
244
pub(crate) fn get_asset_hash(meta_bytes: &[u8], asset_bytes: &[u8]) -> AssetHash {
245
let mut hasher = blake3::Hasher::new();
246
hasher.update(meta_bytes);
247
hasher.update(asset_bytes);
248
*hasher.finalize().as_bytes()
249
}
250
251
/// NOTE: changing the hashing logic here is a _breaking change_ that requires a [`META_FORMAT_VERSION`] bump.
252
pub(crate) fn get_full_asset_hash(
253
asset_hash: AssetHash,
254
dependency_hashes: impl Iterator<Item = AssetHash>,
255
) -> AssetHash {
256
let mut hasher = blake3::Hasher::new();
257
hasher.update(&asset_hash);
258
for hash in dependency_hashes {
259
hasher.update(&hash);
260
}
261
*hasher.finalize().as_bytes()
262
}
263
264