oxeon 0.0.2

Rust-like scripting language for modding Bevy games, compiled to sandboxed WebAssembly.
Documentation
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 oxeon::prelude::*;

#[derive(Component, Reflect, Debug)]
#[reflect(Component)]
struct Health(f32);

#[derive(Component, Reflect)]
#[reflect(Component)]
struct Regen {
    per_sec: f32,
}

/// A headless game where each frame lasts 100 ms.
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>()
    .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)),
        }
    }
    // The frame after loading compiles the mod and runs it once.
    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");
    // The failed call never wrote back, and the game keeps running.
    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);
}