1use alloc::{
10 boxed::Box,
11 string::{String, ToString},
12 vec::Vec,
13};
14use futures_lite::AsyncReadExt;
15
16use crate::{
17 io::{AssetReaderError, Reader},
18 loader::AssetLoader,
19 processor::Process,
20 Asset, AssetPath, DeserializeMetaError, VisitAssetDependencies,
21};
22use downcast_rs::{impl_downcast, Downcast};
23use ron::ser::PrettyConfig;
24use serde::{Deserialize, Serialize};
25use tracing::error;
26
27pub const META_FORMAT_VERSION: &str = "1.0";
32pub type MetaTransform = Box<dyn Fn(&mut dyn AssetMetaDyn) + Send + Sync>;
33
34#[derive(Serialize, Deserialize)]
39pub struct AssetMeta<L: AssetLoader, P: Process> {
40 pub meta_format_version: String,
43 #[serde(skip_serializing_if = "Option::is_none")]
48 pub processed_info: Option<ProcessedInfo>,
49 pub asset: AssetAction<L::Settings, P::Settings>,
51}
52
53impl<L: AssetLoader, P: Process> AssetMeta<L, P> {
54 pub fn new(asset: AssetAction<L::Settings, P::Settings>) -> Self {
55 Self {
56 meta_format_version: META_FORMAT_VERSION.to_string(),
57 processed_info: None,
58 asset,
59 }
60 }
61
62 pub fn deserialize(bytes: &[u8]) -> Result<Self, DeserializeMetaError> {
64 Ok(ron::de::from_bytes(bytes)?)
65 }
66}
67
68#[derive(Serialize, Deserialize)]
70pub enum AssetAction<LoaderSettings, ProcessSettings> {
71 Load {
74 loader: String,
75 settings: LoaderSettings,
76 },
77 Process {
82 processor: String,
83 settings: ProcessSettings,
84 },
85 Ignore,
87}
88
89#[derive(Serialize, Deserialize, Default, Debug, Clone)]
94pub struct ProcessedInfo {
95 pub hash: AssetHash,
97 pub full_hash: AssetHash,
99 pub process_dependencies: Vec<ProcessDependencyInfo>,
101}
102
103#[derive(Serialize, Deserialize, Debug, Clone)]
106pub struct ProcessDependencyInfo {
107 pub full_hash: AssetHash,
109 pub path: AssetPath<'static>,
110}
111
112#[derive(Serialize, Deserialize)]
119pub struct AssetMetaMinimal {
120 pub asset: AssetActionMinimal,
121}
122
123#[derive(Serialize, Deserialize)]
126pub enum AssetActionMinimal {
127 Load { loader: String },
130 Process { processor: String },
135 Ignore,
137}
138
139#[derive(Serialize, Deserialize)]
142pub struct ProcessedInfoMinimal {
143 pub processed_info: Option<ProcessedInfo>,
147}
148
149pub trait AssetMetaDyn: Downcast + Send + Sync {
152 fn loader_settings(&self) -> Option<&dyn Settings>;
154 fn loader_settings_mut(&mut self) -> Option<&mut dyn Settings>;
156 fn process_settings(&self) -> Option<&dyn Settings>;
158 fn serialize(&self) -> Vec<u8>;
160 fn processed_info(&self) -> &Option<ProcessedInfo>;
162 fn processed_info_mut(&mut self) -> &mut Option<ProcessedInfo>;
164}
165
166impl<L: AssetLoader, P: Process> AssetMetaDyn for AssetMeta<L, P> {
167 fn loader_settings(&self) -> Option<&dyn Settings> {
168 if let AssetAction::Load { settings, .. } = &self.asset {
169 Some(settings)
170 } else {
171 None
172 }
173 }
174 fn loader_settings_mut(&mut self) -> Option<&mut dyn Settings> {
175 if let AssetAction::Load { settings, .. } = &mut self.asset {
176 Some(settings)
177 } else {
178 None
179 }
180 }
181 fn process_settings(&self) -> Option<&dyn Settings> {
182 if let AssetAction::Process { settings, .. } = &self.asset {
183 Some(settings)
184 } else {
185 None
186 }
187 }
188 fn serialize(&self) -> Vec<u8> {
189 ron::ser::to_string_pretty(
190 &self,
191 PrettyConfig::default().new_line("\n"),
194 )
195 .expect("type is convertible to ron")
196 .into_bytes()
197 }
198 fn processed_info(&self) -> &Option<ProcessedInfo> {
199 &self.processed_info
200 }
201 fn processed_info_mut(&mut self) -> &mut Option<ProcessedInfo> {
202 &mut self.processed_info
203 }
204}
205
206impl_downcast!(AssetMetaDyn);
207
208pub trait Settings: Downcast + Send + Sync + 'static {}
212
213impl<T: 'static> Settings for T where T: Send + Sync {}
214
215impl_downcast!(Settings);
216
217impl Process for () {
219 type Settings = ();
220 type OutputLoader = ();
221
222 async fn process(
223 &self,
224 _context: &mut bevy_asset::processor::ProcessContext<'_>,
225 _settings: &Self::Settings,
226 _writer: &mut bevy_asset::io::Writer,
227 ) -> Result<(), bevy_asset::processor::ProcessError> {
228 unreachable!()
229 }
230}
231
232impl Asset for () {}
233
234impl VisitAssetDependencies for () {
235 fn visit_dependencies(&self, _visit: &mut impl FnMut(bevy_asset::UntypedAssetId)) {
236 unreachable!()
237 }
238}
239
240impl AssetLoader for () {
242 type Asset = ();
243 type Settings = ();
244 type Error = std::io::Error;
245 async fn load(
246 &self,
247 _reader: &mut dyn Reader,
248 _settings: &Self::Settings,
249 _load_context: &mut crate::LoadContext<'_>,
250 ) -> Result<Self::Asset, Self::Error> {
251 unreachable!();
252 }
253
254 fn extensions(&self) -> &[&str] {
255 unreachable!();
256 }
257}
258
259pub(crate) fn meta_transform_settings<S: Settings>(
260 meta: &mut dyn AssetMetaDyn,
261 settings: &(impl Fn(&mut S) + Send + Sync + 'static),
262) {
263 if let Some(loader_settings) = meta.loader_settings_mut() {
264 if let Some(loader_settings) = loader_settings.downcast_mut::<S>() {
265 settings(loader_settings);
266 } else {
267 error!(
268 "Configured settings type {} does not match AssetLoader settings type",
269 core::any::type_name::<S>(),
270 );
271 }
272 }
273}
274
275pub(crate) fn loader_settings_meta_transform<S: Settings>(
276 settings: impl Fn(&mut S) + Send + Sync + 'static,
277) -> MetaTransform {
278 Box::new(move |meta| meta_transform_settings(meta, &settings))
279}
280
281pub type AssetHash = [u8; 32];
283
284pub(crate) async fn get_asset_hash(
286 meta_bytes: &[u8],
287 asset_reader: &mut impl Reader,
288) -> Result<AssetHash, AssetReaderError> {
289 let mut hasher = blake3::Hasher::new();
290 hasher.update(meta_bytes);
291 let mut buffer = [0; blake3::CHUNK_LEN];
292 loop {
293 let bytes_read = asset_reader.read(&mut buffer).await?;
294 hasher.update(&buffer[..bytes_read]);
295 if bytes_read == 0 {
296 break;
298 }
299 }
300 Ok(*hasher.finalize().as_bytes())
301}
302
303pub(crate) fn get_full_asset_hash(
305 asset_hash: AssetHash,
306 dependency_hashes: impl Iterator<Item = AssetHash>,
307) -> AssetHash {
308 let mut hasher = blake3::Hasher::new();
309 hasher.update(&asset_hash);
310 for hash in dependency_hashes {
311 hasher.update(&hash);
312 }
313 *hasher.finalize().as_bytes()
314}