A mod is a Bevy plugin. It exports pub fn plugin(app: &mut App), and in it registers its resources, messages and systems with Bevy’s own API.
Systems are plain functions. Their parameters say what data they use: Res<T> reads a resource, Query<(&mut Health, &Regen)> visits every entity that has both components, and MessageWriter and MessageReader send and receive messages. For now a mod’s systems run one at a time; the plan is for Bevy to derive each system’s data access from these types, so mod systems can run in parallel with the game’s.
Health, Transform and Time belong to the game, and Regen, Orbit, ModSettings and Healed belong to the mod. Components a mod defines are registered as dynamic Bevy components, with names namespaced by the mod.
11_ecs.ox
// ECS through Bevy's own API. `Health`, `Transform` and `Time` come from the
// host game via generated bindings; everything else is defined by the mod.
use bevy::prelude::*;
#[derive(Component, Reflect, Default)]
#[reflect(Component)]
struct Regen {
per_sec: f32,
}
#[derive(Component, Reflect)]
struct Orbit {
radius: f32,
speed: f32,
}
#[derive(Resource, Reflect, Default)]
struct ModSettings {
regen_enabled: bool,
}
#[derive(Message)]
struct Healed {
entity: Entity,
amount: f32,
}
// Mod entry point: a plain `fn(&mut App)`, which Bevy accepts as a plugin.
// The same function works natively through `oxeon-shim`.
pub fn plugin(app: &mut App) {
app.init_resource::<ModSettings>()
.add_message::<Healed>()
.add_systems(Startup, spawn_orbs)
.add_systems(Update, (regen, orbit, log_heals).chain());
}
fn spawn_orbs(mut commands: Commands) {
for i in 0..4 {
commands.spawn((
Transform::default(),
Orbit { radius: 2.0 + i as f32, speed: 1.0 },
Regen { per_sec: 5.0 },
));
}
}
// Each system's data access is derived from its parameter types, so Bevy
// can run mod systems in parallel with the game's.
fn regen(
time: Res<Time>,
settings: Res<ModSettings>,
mut q: Query<(Entity, &mut Health, &Regen)>,
mut healed: MessageWriter<Healed>,
) {
if !settings.regen_enabled {
return;
}
for (entity, mut hp, regen) in &mut q {
let amount = regen.per_sec * time.delta_secs();
hp.0 += amount;
healed.write(Healed { entity, amount });
}
}
fn orbit(time: Res<Time>, mut q: Query<(&mut Transform, &Orbit), Without<Regen>>) {
let t = time.elapsed_secs();
for (mut transform, orbit) in &mut q {
transform.translation.x = (t * orbit.speed).cos() * orbit.radius;
transform.translation.z = (t * orbit.speed).sin() * orbit.radius;
}
}
fn log_heals(mut healed: MessageReader<Healed>) {
for event in healed.read() {
info!("healed {:?} by {}", event.entity, event.amount);
}
}