oxeon 0.0.3

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(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,
}

/// 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>()
    .expose_to_mods::<Score>()
    .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)),
        }
    }
    // 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);
}

#[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");
    // Low jumps to 5, Mid doubles until High, which leaves it alone below
    // its cap. How many frames ran during loading varies, so check the
    // path rather than exact frames.
    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();
    }
    // `poison` only touches entities without `Regen`; `reap` despawned the
    // ones it brought to zero, including the mod's own `Health(2.0)`.
    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());
    // The test's protected entity, and the two the mod spawned with `Regen`
    // (one through `insert`).
    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");
    // Each frame `touch` changes only the entity with `Regen`; the other is
    // left alone, so it doesn't count as changed again.
    for _ in 0..3 {
        app.update();
    }
    assert_eq!(app.world().resource::<Score>().changed, start + 3);
    // A new entity is added (and changed) once.
    app.world_mut().spawn(Health(5.0));
    app.update();
    let score = app.world().resource::<Score>();
    assert_eq!(
        *score,
        Score {
            changed: start + 5,
            added: 3
        }
    );
    // `Res<Score>` was read: the mod copied `added` into `Regen`.
    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();
    }
    // Infected once (it then has `Poisoned`, so `Without<Poisoned>` skips
    // it), then three frames of poison.
    assert_eq!(health(&app, entity), 7.0);
    // The mod's component is a real component on the entity (its name,
    // `mods/poison.ox::Poisoned`, needs Bevy's `debug` feature to show).
    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}"
    );
    // Only the game's types (editors add Bevy's), and valid Oxeon.
    assert!(!text.contains("struct Commands"), "{text}");
    assert!(oxeon_compiler::compile(&text).is_ok(), "{text}");
    std::fs::remove_dir_all(&dir).ok();
}

#[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);

    // A killing hit: the mod's own `Killed` message reaches its `score`
    // system, which reports back with the game's `Scored`.
    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 }]);
}