use alloc::{
boxed::Box,
string::{String, ToString},
vec::Vec,
};
use crate::{
loader::AssetLoader, processor::Process, Asset, AssetPath, DeserializeMetaError,
VisitAssetDependencies,
};
use downcast_rs::{impl_downcast, Downcast};
use ron::ser::PrettyConfig;
use serde::{Deserialize, Serialize};
use tracing::error;
pub const META_FORMAT_VERSION: &str = "1.0";
pub type MetaTransform = Box<dyn Fn(&mut dyn AssetMetaDyn) + Send + Sync>;
#[derive(Serialize, Deserialize)]
pub struct AssetMeta<L: AssetLoader, P: Process> {
pub meta_format_version: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub processed_info: Option<ProcessedInfo>,
pub asset: AssetAction<L::Settings, P::Settings>,
}
impl<L: AssetLoader, P: Process> AssetMeta<L, P> {
pub fn new(asset: AssetAction<L::Settings, P::Settings>) -> Self {
Self {
meta_format_version: META_FORMAT_VERSION.to_string(),
processed_info: None,
asset,
}
}
pub fn deserialize(bytes: &[u8]) -> Result<Self, DeserializeMetaError> {
Ok(ron::de::from_bytes(bytes)?)
}
}
#[derive(Serialize, Deserialize)]
pub enum AssetAction<LoaderSettings, ProcessSettings> {
Load {
loader: String,
settings: LoaderSettings,
},
Process {
processor: String,
settings: ProcessSettings,
},
Ignore,
}
#[derive(Serialize, Deserialize, Default, Debug, Clone)]
pub struct ProcessedInfo {
pub hash: AssetHash,
pub full_hash: AssetHash,
pub process_dependencies: Vec<ProcessDependencyInfo>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ProcessDependencyInfo {
pub full_hash: AssetHash,
pub path: AssetPath<'static>,
}
#[derive(Serialize, Deserialize)]
pub struct AssetMetaMinimal {
pub asset: AssetActionMinimal,
}
#[derive(Serialize, Deserialize)]
pub enum AssetActionMinimal {
Load { loader: String },
Process { processor: String },
Ignore,
}
#[derive(Serialize, Deserialize)]
pub struct ProcessedInfoMinimal {
pub processed_info: Option<ProcessedInfo>,
}
pub trait AssetMetaDyn: Downcast + Send + Sync {
fn loader_settings(&self) -> Option<&dyn Settings>;
fn loader_settings_mut(&mut self) -> Option<&mut dyn Settings>;
fn serialize(&self) -> Vec<u8>;
fn processed_info(&self) -> &Option<ProcessedInfo>;
fn processed_info_mut(&mut self) -> &mut Option<ProcessedInfo>;
}
impl<L: AssetLoader, P: Process> AssetMetaDyn for AssetMeta<L, P> {
fn loader_settings(&self) -> Option<&dyn Settings> {
if let AssetAction::Load { settings, .. } = &self.asset {
Some(settings)
} else {
None
}
}
fn loader_settings_mut(&mut self) -> Option<&mut dyn Settings> {
if let AssetAction::Load { settings, .. } = &mut self.asset {
Some(settings)
} else {
None
}
}
fn serialize(&self) -> Vec<u8> {
ron::ser::to_string_pretty(&self, PrettyConfig::default())
.expect("type is convertible to ron")
.into_bytes()
}
fn processed_info(&self) -> &Option<ProcessedInfo> {
&self.processed_info
}
fn processed_info_mut(&mut self) -> &mut Option<ProcessedInfo> {
&mut self.processed_info
}
}
impl_downcast!(AssetMetaDyn);
pub trait Settings: Downcast + Send + Sync + 'static {}
impl<T: 'static> Settings for T where T: Send + Sync {}
impl_downcast!(Settings);
impl Process for () {
type Settings = ();
type OutputLoader = ();
async fn process(
&self,
_context: &mut bevy_asset::processor::ProcessContext<'_>,
_meta: AssetMeta<(), Self>,
_writer: &mut bevy_asset::io::Writer,
) -> Result<(), bevy_asset::processor::ProcessError> {
unreachable!()
}
}
impl Asset for () {}
impl VisitAssetDependencies for () {
fn visit_dependencies(&self, _visit: &mut impl FnMut(bevy_asset::UntypedAssetId)) {
unreachable!()
}
}
impl AssetLoader for () {
type Asset = ();
type Settings = ();
type Error = std::io::Error;
async fn load(
&self,
_reader: &mut dyn crate::io::Reader,
_settings: &Self::Settings,
_load_context: &mut crate::LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
unreachable!();
}
fn extensions(&self) -> &[&str] {
unreachable!();
}
}
pub(crate) fn meta_transform_settings<S: Settings>(
meta: &mut dyn AssetMetaDyn,
settings: &(impl Fn(&mut S) + Send + Sync + 'static),
) {
if let Some(loader_settings) = meta.loader_settings_mut() {
if let Some(loader_settings) = loader_settings.downcast_mut::<S>() {
settings(loader_settings);
} else {
error!(
"Configured settings type {} does not match AssetLoader settings type",
core::any::type_name::<S>(),
);
}
}
}
pub(crate) fn loader_settings_meta_transform<S: Settings>(
settings: impl Fn(&mut S) + Send + Sync + 'static,
) -> MetaTransform {
Box::new(move |meta| meta_transform_settings(meta, &settings))
}
pub type AssetHash = [u8; 32];
pub(crate) fn get_asset_hash(meta_bytes: &[u8], asset_bytes: &[u8]) -> AssetHash {
let mut hasher = blake3::Hasher::new();
hasher.update(meta_bytes);
hasher.update(asset_bytes);
*hasher.finalize().as_bytes()
}
pub(crate) fn get_full_asset_hash(
asset_hash: AssetHash,
dependency_hashes: impl Iterator<Item = AssetHash>,
) -> AssetHash {
let mut hasher = blake3::Hasher::new();
hasher.update(&asset_hash);
for hash in dependency_hashes {
hasher.update(&hash);
}
*hasher.finalize().as_bytes()
}