oxeon 0.0.2

Rust-like scripting language for modding Bevy games, compiled to sandboxed WebAssembly.
Documentation
//! Oxeon: a Rust-like scripting language for modding Bevy games.
//!
//! Mods are `.ox` files loaded through Bevy's asset system, compiled to
//! WebAssembly and run sandboxed in Wasmtime. Their systems use Bevy's own
//! ECS: the game decides which components mods may see, and mod systems run
//! on the game's schedule.
//!
//! ```no_run
//! use bevy_app::{App, Startup, TaskPoolPlugin};
//! use bevy_asset::{AssetPlugin, AssetServer};
//! use bevy_ecs::prelude::*;
//! use bevy_reflect::Reflect;
//! use bevy_time::TimePlugin;
//! use oxeon::prelude::*;
//!
//! #[derive(Component, Reflect)]
//! #[reflect(Component)]
//! struct Health(f32);
//!
//! fn load_mods(mut commands: Commands, assets: Res<AssetServer>) {
//!     commands.spawn(OxeonMod(assets.load("mods/regen.ox")));
//! }
//!
//! App::new()
//!     .add_plugins((TaskPoolPlugin::default(), TimePlugin, AssetPlugin::default()))
//!     .add_plugins(OxeonPlugin::default())
//!     .expose_to_mods::<Health>()
//!     .add_systems(Startup, load_mods)
//!     .run();
//! ```
//!
//! A mod can then use `Health` like its own type:
//!
//! ```text
//! fn heal(time: Res<Time>, mut q: Query<&mut Health>) {
//!     for mut hp in &mut q {
//!         hp.0 += 1.0 * time.delta_secs();
//!     }
//! }
//!
//! pub fn plugin(app: &mut App) {
//!     app.add_systems(Update, heal);
//! }
//! ```
//!
//! **Status:** early development. Mod systems can use `Res<Time>` and
//! `Query`s over exposed components whose fields are numbers, `bool` or
//! `char`, and run in `Startup` and `Update`. Components defined by mods,
//! other resources, `Commands` and messages come later.

mod asset;
mod bindings;
mod bridge;

pub use asset::{OxeonSource, OxeonSourceLoader};
pub use bindings::OxeonBindings;

use std::collections::HashMap;

use bevy_app::{App, Plugin, Update};
use bevy_asset::prelude::*;
use bevy_ecs::prelude::*;
use bevy_ecs::reflect::AppTypeRegistry;
use bevy_reflect::{GetTypeRegistration, Reflect, TypePath};
use oxeon_diagnostics::RenderOptions;
use oxeon_runtime::{Runtime, RuntimeConfig};

use bindings::ExposedTypes;
use bridge::LoadedMod;

pub mod prelude {
    pub use crate::{OxeonAppExt, OxeonMod, OxeonPlugin, OxeonSource};
}

/// Adds Oxeon mods to a Bevy app. Requires Bevy's `AssetPlugin`, and its
/// `TimePlugin` for mods that use `Res<Time>`.
#[derive(Default)]
pub struct OxeonPlugin {
    pub runtime: RuntimeConfig,
}

impl Plugin for OxeonPlugin {
    fn build(&self, app: &mut App) {
        let runtime =
            Runtime::new(self.runtime.clone()).expect("failed to create the Oxeon runtime");
        app.insert_resource(OxeonRuntime(runtime))
            .init_resource::<ExposedTypes>()
            .init_resource::<OxeonBindings>()
            .init_resource::<LoadedMods>()
            .init_asset::<OxeonSource>()
            .register_asset_loader(OxeonSourceLoader)
            .register_type::<OxeonMod>()
            .add_systems(Update, (compile_mods, run_mods).chain());
    }

    /// Bindings are generated once every plugin has exposed its types.
    fn finish(&self, app: &mut App) {
        let exposed = app.world().resource::<ExposedTypes>().0.clone();
        let registry = app.world().resource::<AppTypeRegistry>().clone();
        let (bindings, problems) = bindings::generate(&registry.read(), &exposed);
        for problem in problems {
            bevy_log::warn!("{problem}");
        }
        app.insert_resource(bindings);
    }
}

/// Lets a game choose which of its types mods can use.
pub trait OxeonAppExt {
    /// Makes a component available to mods, under its type name. Its fields
    /// must be numbers, `bool` or `char`, and it needs
    /// `#[derive(Reflect)]` and `#[reflect(Component)]`.
    fn expose_to_mods<T: Component + Reflect + GetTypeRegistration + TypePath>(
        &mut self,
    ) -> &mut Self;
}

impl OxeonAppExt for App {
    fn expose_to_mods<T: Component + Reflect + GetTypeRegistration + TypePath>(
        &mut self,
    ) -> &mut Self {
        self.register_type::<T>();
        self.world_mut()
            .get_resource_or_init::<ExposedTypes>()
            .0
            .push(std::any::TypeId::of::<T>());
        self
    }
}

/// The shared Wasmtime engine used for every mod.
#[derive(Resource, Clone)]
pub struct OxeonRuntime(pub Runtime);

/// Marks an entity as an Oxeon mod, backed by a `.ox` source asset. Keeping
/// the handle keeps the mod loaded.
#[derive(Component, Reflect, Clone)]
pub struct OxeonMod(pub Handle<OxeonSource>);

/// Mods that compiled, by source asset.
#[derive(Resource, Default)]
struct LoadedMods(HashMap<AssetId<OxeonSource>, LoadedMod>);

/// Compiles mods when they load or change. Recompiling replaces the
/// running module; game state lives in the ECS, so nothing is lost. A
/// version that doesn't compile leaves the previous one running.
fn compile_mods(
    mut events: MessageReader<AssetEvent<OxeonSource>>,
    sources: Res<Assets<OxeonSource>>,
    server: Res<AssetServer>,
    bindings: Res<OxeonBindings>,
    runtime: Res<OxeonRuntime>,
    mut mods: ResMut<LoadedMods>,
) {
    // A change can arrive as several events; handle each mod once.
    let mut changed = Vec::new();
    for event in events.read() {
        match event {
            // Sent on the first load and after every reload (as is `Modified`).
            AssetEvent::LoadedWithDependencies { id } => {
                if !changed.contains(id) {
                    changed.push(*id);
                }
            }
            AssetEvent::Removed { id } | AssetEvent::Unused { id } => {
                mods.0.remove(id);
                changed.retain(|c| c != id);
            }
            _ => {}
        }
    }
    for id in changed {
        let Some(source) = sources.get(id) else {
            continue;
        };
        let path = server
            .get_path(id)
            .map_or_else(|| "mod".to_owned(), |p| p.to_string());
        let compiled = match oxeon_compiler::compile_with_prelude(&source.source, &bindings.prelude)
        {
            Ok(compiled) => compiled,
            Err(errors) => {
                for e in &errors {
                    bevy_log::error!(
                        "{}",
                        e.render(&path, &source.source, RenderOptions::default())
                    );
                }
                if mods.0.contains_key(&id) {
                    bevy_log::warn!(
                        "{path}: keeping the previous version until the errors are fixed"
                    );
                }
                continue;
            }
        };
        for w in &compiled.warnings {
            if w.severity == oxeon_diagnostics::Severity::Warning {
                bevy_log::warn!(
                    "{}",
                    w.render(&path, &source.source, RenderOptions::default())
                );
            } else {
                bevy_log::debug!("{}", w.render_plain(&path, &source.source));
            }
        }
        for s in &compiled.systems {
            if let Some(schedule) = &s.schedule
                && !matches!(schedule.as_str(), "Startup" | "Update")
            {
                bevy_log::warn!(
                    "{path}: `{}` uses the schedule `{schedule}`, which mods can't use yet",
                    s.name
                );
            }
        }
        let instance = runtime
            .0
            .load(&compiled.wasm)
            .and_then(|module| runtime.0.instantiate(&module));
        match instance {
            Ok(instance) => {
                bevy_log::info!("loaded {path} ({} system(s))", compiled.systems.len());
                let layouts = compiled
                    .layouts
                    .iter()
                    .map(|l| (l.name.clone(), l.clone()))
                    .collect();
                mods.0.insert(
                    id,
                    LoadedMod {
                        path,
                        instance,
                        systems: compiled.systems,
                        layouts,
                        started: false,
                        failed: false,
                    },
                );
            }
            Err(e) => bevy_log::error!("{path}: {e}"),
        }
    }
}

/// Runs each loaded mod's systems for this frame. A mod whose system fails
/// (a trap, or running out of fuel) is disabled; the game keeps running.
fn run_mods(world: &mut World) {
    world.resource_scope(|world, mut mods: Mut<LoadedMods>| {
        let bindings = world.resource::<OxeonBindings>().clone();
        for m in mods.0.values_mut() {
            if m.failed {
                continue;
            }
            let first_run = !m.started;
            m.started = true;
            for system in m.systems.clone() {
                let runs = match system.schedule.as_deref() {
                    Some("Update") => true,
                    Some("Startup") => first_run,
                    _ => false,
                };
                if !runs {
                    continue;
                }
                if let Err(e) = bridge::run_system(world, &bindings, m, &system) {
                    bevy_log::error!(
                        "{}: `{}` failed, so the mod is disabled: {e}",
                        m.path,
                        system.name
                    );
                    m.failed = true;
                    break;
                }
            }
        }
    });
}