use std::time::{Duration, Instant};
use bevy_app::{App, TaskPoolPlugin};
use bevy_asset::{AssetPlugin, AssetServer, Assets, Handle, LoadState};
use bevy_ecs::prelude::*;
use bevy_reflect::Reflect;
use bevy_time::{TimePlugin, TimeUpdateStrategy};
use bevy_transform::components::Transform;
use oxeon::prelude::*;
#[derive(Component, Reflect, Debug)]
#[reflect(Component)]
struct Health(f32);
#[derive(Resource, Reflect, Default, Debug, PartialEq)]
#[reflect(Resource)]
struct Score {
changed: u32,
added: u32,
}
#[derive(Message, Reflect, Clone)]
struct Hit {
damage: f32,
}
#[derive(Message, Reflect, Clone, Debug, PartialEq)]
struct Scored {
total: u32,
}
#[derive(Component, Reflect)]
#[reflect(Component)]
struct Regen {
per_sec: f32,
}
fn game(assets: &str) -> App {
let mut app = App::new();
app.add_plugins((
TaskPoolPlugin::default(),
TimePlugin,
AssetPlugin {
file_path: assets.into(),
..Default::default()
},
OxeonPlugin::default(),
))
.expose_to_mods::<Health>()
.expose_to_mods::<Regen>()
.expose_to_mods::<Score>()
.expose_to_mods::<Transform>()
.init_resource::<Score>()
.add_message::<Hit>()
.add_message::<Scored>()
.expose_message_to_mods::<Hit>()
.expose_message_to_mods::<Scored>()
.insert_resource(TimeUpdateStrategy::ManualDuration(Duration::from_millis(
100,
)));
app.finish();
app.cleanup();
app
}
fn load(app: &mut App, path: &str) -> Handle<OxeonSource> {
let handle = app
.world()
.resource::<AssetServer>()
.load::<OxeonSource>(path.to_owned());
app.world_mut().spawn(OxeonMod(handle.clone()));
let deadline = Instant::now() + Duration::from_secs(10);
loop {
app.update();
match app.world().resource::<AssetServer>().load_state(&handle) {
LoadState::Loaded => break,
LoadState::Failed(err) => panic!("mod failed to load: {err}"),
_ if Instant::now() > deadline => panic!("timed out loading mod"),
_ => std::thread::sleep(Duration::from_millis(5)),
}
}
app.update();
handle
}
fn health(app: &App, entity: Entity) -> f32 {
app.world()
.get::<Health>(entity)
.expect("entity has health")
.0
}
#[test]
fn loads_example_mod_source() {
let mut app = game("../../examples");
let handle = load(&mut app, "mods/regen.ox");
let sources = app.world().resource::<Assets<OxeonSource>>();
assert!(
sources
.get(&handle)
.expect("asset is loaded")
.source
.contains("fn regen")
);
}
#[test]
fn mod_systems_change_game_components() {
let mut app = game("tests");
let regenerating = app
.world_mut()
.spawn((Health(10.0), Regen { per_sec: 2.0 }))
.id();
let plain = app.world_mut().spawn(Health(5.0)).id();
load(&mut app, "mods/regen.ox");
let before = health(&app, regenerating);
assert!(before > 10.0, "the mod ran: {before}");
for frame in 1..=5 {
app.update();
let now = health(&app, regenerating);
let expected = before + 2.0 * 0.1 * frame as f32;
assert!(
(now - expected).abs() < 1e-4,
"frame {frame}: {now}, expected {expected}"
);
}
assert_eq!(
health(&app, plain),
5.0,
"entities without `Regen` aren't matched"
);
}
#[test]
fn a_mod_that_never_returns_is_disabled() {
let mut app = game("tests");
let entity = app.world_mut().spawn(Health(1.0)).id();
load(&mut app, "mods/spin.ox");
assert_eq!(health(&app, entity), 1.0);
for _ in 0..3 {
app.update();
}
assert_eq!(health(&app, entity), 1.0);
}
#[test]
fn a_mod_with_errors_does_not_run() {
let mut app = game("tests");
let entity = app.world_mut().spawn(Health(1.0)).id();
load(&mut app, "mods/broken.ox");
app.update();
assert_eq!(health(&app, entity), 1.0);
}
#[test]
fn mods_use_enums_and_match() {
let mut app = game("tests");
let weak = app.world_mut().spawn(Health(1.0)).id();
let strong = app.world_mut().spawn(Health(200.0)).id();
load(&mut app, "mods/tiers.ox");
let path = [5.0, 10.0, 20.0, 40.0, 80.0];
let mut seen = vec![health(&app, weak)];
for _ in 0..6 {
app.update();
seen.push(health(&app, weak));
}
assert!(seen.iter().all(|h| path.contains(h)), "{seen:?}");
assert!(
seen.windows(2).all(|w| w[1] == w[0] * 2.0 || w[1] == w[0]),
"{seen:?}"
);
assert_eq!(seen.last(), Some(&80.0));
assert_eq!(health(&app, strong), 100.0, "High caps at 100");
}
#[test]
fn mods_use_option_from_the_prelude() {
let mut app = game("tests");
let low = app.world_mut().spawn(Health(3.0)).id();
let high = app.world_mut().spawn(Health(50.0)).id();
load(&mut app, "mods/option.ox");
app.update();
assert_eq!(health(&app, low), 10.0);
assert_eq!(health(&app, high), 50.0);
}
#[test]
fn mods_spawn_filter_and_despawn() {
let mut app = game("tests");
let doomed = app.world_mut().spawn(Health(4.0)).id();
let protected = app
.world_mut()
.spawn((Health(4.0), Regen { per_sec: 0.0 }))
.id();
load(&mut app, "mods/commands.ox");
for _ in 0..6 {
app.update();
}
assert!(app.world().get_entity(doomed).is_err(), "despawned");
assert_eq!(health(&app, protected), 4.0);
let mut q = app.world_mut().query::<(&Health, Option<&Regen>)>();
let mut seen: Vec<(f32, Option<f32>)> = q
.iter(app.world())
.map(|(h, r)| (h.0, r.map(|r| r.per_sec)))
.collect();
seen.sort_by(|a, b| a.partial_cmp(b).unwrap());
assert_eq!(seen, [(1.0, Some(5.0)), (3.0, Some(0.0)), (4.0, Some(0.0))]);
}
#[test]
fn mods_use_resources_and_change_filters() {
let mut app = game("tests");
let ticking = app
.world_mut()
.spawn((Health(1.0), Regen { per_sec: 0.0 }))
.id();
app.world_mut().spawn(Health(1.0));
load(&mut app, "mods/changes.ox");
let start = app.world().resource::<Score>().changed;
let added = app.world().resource::<Score>().added;
assert_eq!(added, 2, "both entities count as added on the first run");
for _ in 0..3 {
app.update();
}
assert_eq!(app.world().resource::<Score>().changed, start + 3);
app.world_mut().spawn(Health(5.0));
app.update();
let score = app.world().resource::<Score>();
assert_eq!(
*score,
Score {
changed: start + 5,
added: 3
}
);
assert_eq!(app.world().get::<Regen>(ticking).unwrap().per_sec, 3.0);
}
#[test]
fn mods_define_their_own_components() {
let mut app = game("tests");
let entity = app.world_mut().spawn(Health(10.0)).id();
load(&mut app, "mods/poison.ox");
for _ in 0..6 {
app.update();
}
assert_eq!(health(&app, entity), 7.0);
assert_eq!(app.world().inspect_entity(entity).unwrap().count(), 2);
}
#[test]
fn writes_the_bindings_file_for_editors() {
let dir = std::env::temp_dir().join(format!("oxeon-bindings-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("oxeon-bindings.ox");
let mut app = App::new();
app.add_plugins((
TaskPoolPlugin::default(),
TimePlugin,
AssetPlugin::default(),
OxeonPlugin {
bindings_file: Some(path.clone()),
..Default::default()
},
))
.expose_to_mods::<Health>()
.expose_to_mods::<Regen>();
app.finish();
let text = std::fs::read_to_string(&path).expect("written");
assert!(text.contains("pub struct Health(pub f32);"), "{text}");
assert!(
text.contains("pub struct Regen {\n pub per_sec: f32,\n}"),
"{text}"
);
assert!(!text.contains("struct Commands"), "{text}");
assert!(oxeon_compiler::compile(&text).is_ok(), "{text}");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn mods_use_components_whose_fields_are_structs() {
let mut app = game("tests");
let rust_side = app
.world_mut()
.spawn(Transform::from_xyz(5.0, 0.0, 0.0))
.id();
load(&mut app, "mods/moves.ox");
for _ in 0..3 {
app.update();
}
let mut q = app.world_mut().query::<(Entity, &Transform)>();
let all: Vec<(Entity, Transform)> = q.iter(app.world()).map(|(e, t)| (e, *t)).collect();
assert_eq!(all.len(), 2, "the game's entity and the mod's");
let (_, game_t) = all.iter().find(|(e, _)| *e == rust_side).unwrap();
assert!(game_t.translation.x > 5.5, "{game_t:?}");
assert_eq!((game_t.translation.y, game_t.scale.y), (0.0, 2.0));
let (_, mod_t) = all.iter().find(|(e, _)| *e != rust_side).unwrap();
assert_eq!((mod_t.translation.y, mod_t.translation.z), (2.0, 3.0));
assert_eq!(mod_t.scale.y, 2.0);
let angle = 2.0 * game_t.rotation.z.atan2(game_t.rotation.w);
let frames = (angle / 0.5).round() as usize;
assert!(frames >= 2, "{angle}");
let mut expected = Transform::IDENTITY;
for _ in 0..frames {
expected.rotate_z(0.5);
}
assert!(
game_t.rotation.abs_diff_eq(expected.rotation, 1e-6),
"{:?} vs {:?}",
game_t.rotation,
expected.rotation
);
}
#[test]
fn transform_bindings_declare_its_field_types() {
let app = game("tests");
let bindings = app.world().resource::<oxeon::OxeonBindings>();
let text = &bindings.declarations;
assert!(text.contains("#[derive(Clone, Copy, Debug)]\npub struct Transform {\n pub translation: Vec3,\n pub rotation: Quat,\n pub scale: Vec3,\n}"), "{text}");
assert!(
text.contains("pub fn rotate_z(&mut self, angle: f32)"),
"{text}"
);
assert!(!text.contains("pub struct Vec3"), "{text}");
assert!(bindings.prelude.contains("pub struct Vec3"));
}
#[test]
fn mods_read_and_send_messages() {
let mut app = game("tests");
let target = app.world_mut().spawn(Health(5.0)).id();
load(&mut app, "mods/messages.ox");
assert_eq!(health(&app, target), 5.0, "no hits yet");
app.world_mut().write_message(Hit { damage: 2.0 });
app.update();
assert_eq!(health(&app, target), 3.0, "each hit is read once");
app.update();
assert_eq!(health(&app, target), 3.0);
app.world_mut().write_message(Hit { damage: 4.0 });
app.update();
assert_eq!(health(&app, target), -1.0);
assert_eq!(app.world().resource::<Score>().added, 10);
let scored: Vec<Scored> = app
.world_mut()
.resource_mut::<Messages<Scored>>()
.drain()
.collect();
assert_eq!(scored, [Scored { total: 10 }]);
}
#[test]
fn each_call_gets_a_fresh_heap() {
let mut app = game("tests");
app.world_mut().spawn(Health(3.0));
app.world_mut().spawn(Health(42.0));
load(&mut app, "mods/lists.ox");
let before = app.world().resource::<Score>().added;
for _ in 0..100 {
app.update();
}
let score = app.world().resource::<Score>();
assert_eq!(score.changed, 42 + 100000);
assert_eq!(score.added, before + 100, "the mod ran every frame");
}
fn next_reports(app: &mut App) -> Vec<ModReport> {
for _ in 0..5 {
app.update();
let reports: Vec<ModReport> = app
.world_mut()
.resource_mut::<bevy_ecs::message::Messages<ModReport>>()
.drain()
.collect();
if !reports.is_empty() {
return reports;
}
}
panic!("no report after 5 frames");
}
fn load_source(app: &mut App, source: &str) {
app.world_mut().write_message(LoadModSource {
name: "playground/heal.ox".to_owned(),
source: source.to_owned(),
});
}
#[test]
fn mods_load_from_source_text_and_report() {
let mut app = game("tests");
let e = app.world_mut().spawn(Health(0.0)).id();
let healing = |amount: &str| {
format!(
"fn heal(mut q: Query<&mut Health>) {{ for mut h in &mut q {{ h.0 += {amount}; }} }}\n\
pub fn plugin(app: &mut App) {{ app.add_systems(Update, heal); }}"
)
};
load_source(&mut app, &healing("1.0"));
assert_eq!(
next_reports(&mut app),
[ModReport::Loaded {
name: "playground/heal.ox".to_owned(),
systems: vec!["heal".to_owned()],
}]
);
let after_load = health(&app, e);
app.update();
assert_eq!(health(&app, e), after_load + 1.0);
load_source(&mut app, &healing("100.0"));
assert!(matches!(
&next_reports(&mut app)[..],
[ModReport::Loaded { .. }]
));
let replaced = health(&app, e);
app.update();
assert_eq!(health(&app, e), replaced + 100.0);
load_source(
&mut app,
"fn heal(q: Query<&mut Health>) { let x: u32 = 1.5; }",
);
match &next_reports(&mut app)[..] {
[
ModReport::CompileFailed {
name,
errors,
kept_previous,
},
] => {
assert_eq!(name, "playground/heal.ox");
assert!(errors[0].contains("mismatched types"), "{errors:?}");
assert!(kept_previous);
}
other => panic!("{other:?}"),
}
let kept = health(&app, e);
app.update();
assert_eq!(health(&app, e), kept + 100.0);
load_source(
&mut app,
"fn heal(mut q: Query<&mut Health>) { loop {} }\n\
pub fn plugin(app: &mut App) { app.add_systems(Update, heal); }",
);
let mut seen = next_reports(&mut app);
if !seen.iter().any(|r| matches!(r, ModReport::Disabled { .. })) {
seen.extend(next_reports(&mut app));
}
assert!(
seen.iter()
.any(|r| matches!(r, ModReport::Disabled { system, error, .. }
if system == "heal" && error.contains("fuel"))),
"{seen:?}"
);
load_source(&mut app, &healing("1.0"));
next_reports(&mut app);
app.world_mut().write_message(UnloadMod {
name: "playground/heal.ox".to_owned(),
});
for _ in 0..3 {
app.update();
}
let unloaded = health(&app, e);
app.update();
app.update();
assert_eq!(health(&app, e), unloaded);
}
fn drain_logs(app: &mut App) -> Vec<(LogLevel, String)> {
app.world_mut()
.resource_mut::<bevy_ecs::message::Messages<ModLog>>()
.drain()
.map(|l| (l.level, l.text))
.collect()
}
#[test]
fn mods_log_messages() {
let mut app = game("tests");
app.world_mut().spawn(Health(2.5));
app.world_mut()
.spawn((Health(7.0), Transform::from_xyz(1.0, 2.0, 3.0)));
load_source(
&mut app,
r#"
#[derive(Debug, Clone, Copy)]
struct Pair { a: u8, b: (bool, char) }
fn report(q: Query<&Health>, t: Query<&Transform>) {
let n = 3;
for h in &q {
info!("health {:.1}, {h:?}", h.0);
}
for t in &t {
warn!("at {} / {:?}", t.translation, t.translation);
}
let p = Pair { a: 7, b: (true, 'x') };
println!("{p:?} {n:>4} {:#x} {:+.2e}", 255u32, 1500.0f64);
debug!("{:#?}", p);
error!("{{literal}} {0} {0}", n);
if n == 3 {
panic!("stop");
}
}
pub fn plugin(app: &mut App) { app.add_systems(Update, report); }
"#,
);
let reports = next_reports(&mut app);
assert!(
matches!(
&reports[..],
[ModReport::Loaded { .. }, ModReport::Disabled { .. }]
),
"{reports:?}"
);
let mut logs = drain_logs(&mut app);
logs.sort_by_key(|(level, _)| *level as u8);
assert_eq!(
logs,
[
(
LogLevel::Debug,
"Pair {\n a: 7,\n b: (\n true,\n 'x',\n ),\n}".to_owned()
),
(LogLevel::Info, "health 2.5, Health(2.5)".to_owned()),
(LogLevel::Info, "health 7.0, Health(7.0)".to_owned()),
(
LogLevel::Warn,
"at [1, 2, 3] / Vec3(1.0, 2.0, 3.0)".to_owned()
),
(LogLevel::Error, "{literal} 3 3".to_owned()),
(
LogLevel::Print,
"Pair { a: 7, b: (true, 'x') } 3 0xff +1.50e3".to_owned()
),
]
);
}
#[test]
fn mods_log_entities_like_bevy() {
let mut app = game("tests");
app.world_mut().spawn_empty();
let e = app.world_mut().spawn(Regen { per_sec: 1.0 }).id();
load_source(
&mut app,
r#"
fn report(mut commands: Commands, q: Query<(Entity, &Regen)>) {
for (e, _) in &q {
info!("{e:?} {:>6}|", e);
let new = commands.spawn(Health(1.0)).id();
info!("spawned {new}");
}
}
pub fn plugin(app: &mut App) { app.add_systems(Startup, report); }
"#,
);
next_reports(&mut app);
let logs = drain_logs(&mut app);
let spawned = app
.world_mut()
.query_filtered::<Entity, With<Health>>()
.single(app.world())
.unwrap();
assert_eq!(
logs,
[
(LogLevel::Info, format!("{e:?} {e:>6}|")),
(LogLevel::Info, format!("spawned {spawned}")),
]
);
}
#[test]
fn mods_define_their_own_resources() {
let mut app = game("tests");
let mod_source = |extra: &str| {
format!(
r#"
#[derive(Resource, Default)]
struct Counter {{ ticks: u32, total: f32 }}
#[derive(Resource)]
struct Settings {{ step: f32, on: bool }}
fn count(mut c: ResMut<Counter>, s: Res<Settings>) {{
if s.on {{
c.ticks += 1;
c.total += s.step;
}}
info!("{{}} {{}}", c.ticks, c.total);
}}
pub fn plugin(app: &mut App) {{
app.init_resource::<Counter>()
.insert_resource(Settings {{ step: {extra}, on: true }})
.add_systems(Update, count);
}}
"#
)
};
load_source(&mut app, &mod_source("0.5"));
let reports = next_reports(&mut app);
assert!(
matches!(&reports[..], [ModReport::Loaded { .. }]),
"{reports:?}"
);
drain_logs(&mut app);
app.update();
app.update();
let logs = drain_logs(&mut app);
let last = &logs.last().expect("it logged").1;
assert!(last.ends_with(" 1.5") && last.starts_with("3 "), "{logs:?}");
load_source(&mut app, &mod_source("10.0"));
next_reports(&mut app);
let logs = drain_logs(&mut app);
assert_eq!(logs.last().map(|l| l.1.as_str()), Some("5 12"), "{logs:?}");
app.world_mut().write_message(UnloadMod {
name: "playground/heal.ox".to_owned(),
});
for _ in 0..3 {
app.update();
}
let left = app
.world_mut()
.query::<bevy_ecs::world::EntityRef>()
.iter(app.world())
.filter(|e| {
e.archetype().components().iter().any(|c| {
app.world()
.components()
.get_name(*c)
.is_some_and(|n| n.ends_with("(resource)"))
})
})
.count();
assert_eq!(left, 0);
}
#[test]
fn mod_resources_must_be_added_first() {
let mut app = game("tests");
load_source(
&mut app,
r#"
#[derive(Resource)]
struct Lost { n: u32 }
fn use_it(l: Res<Lost>) {}
pub fn plugin(app: &mut App) { app.add_systems(Update, use_it); }
"#,
);
let reports = next_reports(&mut app);
match &reports[..] {
[ModReport::Loaded { .. }, ModReport::Disabled { error, .. }] => {
assert!(error.contains("app.init_resource::<Lost>()"), "{error}")
}
r => panic!("{r:?}"),
}
}
#[test]
fn mod_resources_need_their_derives() {
let mut app = game("tests");
load_source(
&mut app,
r#"
struct Plain { n: u32 }
#[derive(Resource)]
struct NoDefault { n: u32 }
pub fn plugin(app: &mut App) {
app.insert_resource(Plain { n: 1 }).init_resource::<NoDefault>();
}
"#,
);
match &next_reports(&mut app)[..] {
[ModReport::CompileFailed { errors, .. }] => {
let text = errors.join("\n");
assert!(text.contains("`Plain` isn't a resource"), "{text}");
assert!(
text.contains("`NoDefault` doesn't implement `Default`"),
"{text}"
);
}
r => panic!("{r:?}"),
}
}
#[test]
fn mods_get_random_numbers() {
let rolls = |seed: u64| {
let mut app = App::new();
app.add_plugins((
TaskPoolPlugin::default(),
TimePlugin,
AssetPlugin::default(),
OxeonPlugin {
runtime: oxeon_runtime::RuntimeConfig {
random_seed: Some(seed),
..Default::default()
},
..Default::default()
},
));
app.finish();
app.cleanup();
load_source(
&mut app,
r#"
fn roll() {
let d: u8 = rand::random_range(1..=6);
let x = rand::random_range(-2.0..2.0f32);
let unit: f64 = rand::random();
let big: u64 = rand::random();
println!("{d} {x} {unit} {big} {}", rand::random_bool(0.5));
}
pub fn plugin(app: &mut App) { app.add_systems(Update, roll); }
"#,
);
let mut lines = Vec::new();
for _ in 0..100 {
app.update();
lines.extend(drain_logs(&mut app).into_iter().map(|(_, text)| text));
if lines.len() >= 12 {
break;
}
}
lines.truncate(12);
lines
};
let a = rolls(1);
assert_eq!(a.len(), 12, "{a:?}");
for line in &a {
let parts: Vec<&str> = line.split(' ').collect();
let d: u8 = parts[0].parse().unwrap();
let x: f32 = parts[1].parse().unwrap();
let unit: f64 = parts[2].parse().unwrap();
assert!((1..=6).contains(&d) && (-2.0..2.0).contains(&x) && (0.0..1.0).contains(&unit));
}
assert_eq!(a, rolls(1), "the same seed gives the same numbers");
assert_ne!(a, rolls(2));
}