use bevy_asset::io::Reader;
use bevy_asset::{Asset, AssetLoader, LoadContext};
use bevy_reflect::TypePath;
use oxeon_compiler::Diagnostic;
#[derive(Asset, TypePath, Debug)]
pub struct OxeonSource {
pub source: String,
pub wasm: Vec<u8>,
}
#[derive(Debug, thiserror::Error)]
pub enum OxeonLoadError {
#[error("could not read mod source: {0}")]
Io(#[from] std::io::Error),
#[error("mod source is not valid UTF-8")]
Utf8(#[from] std::string::FromUtf8Error),
#[error("{}", render(.0))]
Compile(Vec<Diagnostic>),
}
fn render(diagnostics: &[Diagnostic]) -> String {
diagnostics
.iter()
.map(|d| d.message.as_str())
.collect::<Vec<_>>()
.join("; ")
}
#[derive(Default, TypePath)]
pub struct OxeonSourceLoader;
impl AssetLoader for OxeonSourceLoader {
type Asset = OxeonSource;
type Settings = ();
type Error = OxeonLoadError;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &(),
_load_context: &mut LoadContext<'_>,
) -> Result<OxeonSource, OxeonLoadError> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let source = String::from_utf8(bytes)?;
let compiled = oxeon_compiler::compile(&source).map_err(OxeonLoadError::Compile)?;
Ok(OxeonSource {
source,
wasm: compiled.wasm,
})
}
fn extensions(&self) -> &[&str] {
&[oxeon_compiler::SOURCE_EXTENSION]
}
}