oxeon 0.0.3

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`/`ResMut` of
//! exposed resources, `Commands` (spawn, insert, despawn),
//! `MessageReader`/`MessageWriter` (the game's messages and their own), and
//! `Query`s over exposed components and components the mod defines, with
//! `Entity` and `With`, `Without`, `Changed` and `Added` filters, and run in
//! `Startup` and `Update`. Fields must be numbers, `bool` or `char`.

mod asset;
mod bindings;
mod bridge;
mod components;
mod messages;

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,
    /// Where to write the game's bindings (the Oxeon declarations of the
    /// types it exposes) at startup, for editors. The language server reads
    /// a file named `oxeon-bindings.ox` next to a mod or in a folder above
    /// it, so `assets/oxeon-bindings.ox` covers every mod under `assets/`
    /// (keep it out of a folder you load mods from as a whole).
    pub bindings_file: Option<std::path::PathBuf>,
}

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 messages = app
            .world()
            .get_resource::<bindings::ExposedMessages>()
            .map(|m| m.0.clone())
            .unwrap_or_default();
        let registry = app.world().resource::<AppTypeRegistry>().clone();
        let (bindings, problems) = bindings::generate(&registry.read(), &exposed, &messages);
        for problem in problems {
            bevy_log::warn!("{problem}");
        }
        if let Some(path) = &self.bindings_file {
            let text = format!(
                "// The types this game exposes to mods, for editors. Generated by\n\
                 // `OxeonPlugin` at startup: don't edit, it's rewritten.\n\n{}",
                bindings.declarations
            );
            // Only rewrite when it changed, so file watchers stay quiet.
            if std::fs::read_to_string(path).ok().as_deref() != Some(text.as_str())
                && let Err(e) = std::fs::write(path, text)
            {
                bevy_log::warn!("couldn't write the bindings file {}: {e}", path.display());
            }
        }
        app.insert_resource(bindings);
    }
}

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

    /// Lets mods read and send a message type with `MessageReader<M>` and
    /// `MessageWriter<M>`. Add it to the app as usual too (`add_message`).
    /// Its fields must be numbers, `bool` or `char`, and it needs
    /// `#[derive(Reflect)]`.
    fn expose_message_to_mods<
        M: bevy_ecs::message::Message
            + Reflect
            + bevy_reflect::FromReflect
            + 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
    }

    fn expose_message_to_mods<
        M: bevy_ecs::message::Message
            + Reflect
            + bevy_reflect::FromReflect
            + GetTypeRegistration
            + TypePath,
    >(
        &mut self,
    ) -> &mut Self {
        self.register_type::<M>();
        let id = std::any::TypeId::of::<M>();
        let world = self.world_mut();
        world
            .get_resource_or_init::<bindings::ExposedMessages>()
            .0
            .push(id);
        world
            .get_resource_or_init::<messages::MessageFnsMap>()
            .0
            .insert(id, messages::MessageFns::of::<M>());
        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,
                        command_components: compiled.command_components,
                        last_run: HashMap::new(),
                        cursors: HashMap::new(),
                        messages_seen: HashMap::new(),
                        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
        .get_resource_or_init::<messages::ModMessages>()
        .new_frame();
    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;
                }
            }
        }
    });
}