use std::any::TypeId;
use std::collections::HashMap;
use bevy_ecs::prelude::*;
use bevy_ecs::reflect::ReflectComponent;
use bevy_reflect::{TypeInfo, TypeRegistry};
const TIME: &str = "\
/// The game's clock (Bevy's `Time`).
pub struct Time { delta: f32, elapsed: f32 }
impl Time {
/// Seconds since the previous frame.
pub fn delta_secs(&self) -> f32 { self.delta }
/// Seconds since the game started.
pub fn elapsed_secs(&self) -> f32 { self.elapsed }
}
";
const PRIMITIVES: &[&str] = &[
"f32", "f64", "i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "isize", "usize", "bool",
"char",
];
#[derive(Resource, Default, Clone)]
pub struct OxeonBindings {
pub prelude: String,
pub components: HashMap<String, TypeId>,
}
#[derive(Resource, Default)]
pub(crate) struct ExposedTypes(pub Vec<TypeId>);
pub(crate) fn generate(
registry: &TypeRegistry,
exposed: &[TypeId],
) -> (OxeonBindings, Vec<String>) {
let mut bindings = OxeonBindings {
prelude: TIME.to_owned(),
components: HashMap::new(),
};
let mut problems = Vec::new();
for id in exposed {
let Some(registration) = registry.get(*id) else {
continue;
};
let info = registration.type_info();
let name = info.type_path_table().short_path().to_owned();
if registration.data::<ReflectComponent>().is_none() {
problems.push(format!(
"`{name}` is exposed to mods but isn't reflected as a component; add `#[reflect(Component)]`"
));
continue;
}
let declaration = match info {
TypeInfo::Struct(s) if s.field_len() == 0 => Ok(format!("pub struct {name};\n")),
TypeInfo::Struct(s) => s
.iter()
.map(|f| {
primitive(f.type_path()).map(|ty| format!(" pub {}: {ty},\n", f.name()))
})
.collect::<Result<String, String>>()
.map(|fields| format!("pub struct {name} {{\n{fields}}}\n")),
TypeInfo::TupleStruct(s) => s
.iter()
.map(|f| primitive(f.type_path()).map(|ty| format!("pub {ty}")))
.collect::<Result<Vec<String>, String>>()
.map(|fields| format!("pub struct {name}({});\n", fields.join(", "))),
_ => Err("it isn't a struct".to_owned()),
};
match declaration {
Ok(text) => {
bindings
.prelude
.push_str(&format!("/// The game's `{name}` component.\n{text}"));
bindings.components.insert(name, *id);
}
Err(why) => problems.push(format!("`{name}` can't be exposed to mods yet: {why}")),
}
}
(bindings, problems)
}
fn primitive(type_path: &str) -> Result<&str, String> {
PRIMITIVES
.iter()
.find(|p| **p == type_path)
.copied()
.ok_or_else(|| format!("its field of type `{type_path}` isn't a number, `bool` or `char`"))
}