Oxeon / Examples / Reflection

Reflection

Field access by name and runtime trait queries through bevy_reflect in an Oxeon mod.

Planned

Planned. Oxeon already uses bevy_reflect inside the host to generate bindings and to move component data in and out of mods, but mods can’t call the reflection API yet.

Oxeon uses Bevy’s own reflection, bevy_reflect. A mod can read and write a field by name (get_field_mut), walk a struct’s fields generically, and ask at run time whether a value implements a trait marked #[reflect_trait].

Reflection is also how the host works: Oxeon generates bindings from the game’s TypeRegistry and converts component data through reflection, because Rust’s memory layout isn’t stable. Hot reloading is planned to use it as well, carrying a mod’s state across versions by matching fields by name.

12_reflection.ox

examples/syntax/12_reflection.ox
// Reflection through bevy_reflect: field access by name, and runtime
// trait queries on values whose type is not known statically.

use bevy::prelude::*;
use bevy::reflect::{Reflect, ReflectRef, reflect_trait};

#[derive(Reflect, Default)]
struct Stats {
    strength: u32,
    agility: u32,
    title: String,
}

#[reflect_trait]
trait Describe {
    fn describe(&self) -> String;
}

#[derive(Component, Reflect)]
#[reflect(Component, Describe)]
struct Lantern {
    brightness: f32,
}

impl Describe for Lantern {
    fn describe(&self) -> String {
        format!("a lantern at {} lumens", self.brightness)
    }
}

fn reflect_fields(stats: &mut Stats) {
    // Read and write fields by name.
    if let Some(strength) = stats.get_field_mut::<u32>("strength") {
        *strength += 1;
    }

    // Walk every field generically.
    if let ReflectRef::Struct(s) = stats.reflect_ref() {
        for i in 0..s.field_len() {
            let name = s.name_at(i).unwrap();
            info!("field {name}");
        }
    }
}

// Ask, at runtime, whether a reflected value implements `Describe`.
fn describe_any(value: &dyn Reflect, registry: &TypeRegistry) -> Option<String> {
    let reflect_describe = registry.get_type_data::<ReflectDescribe>(value.type_id())?;
    let describe: &dyn Describe = reflect_describe.get(value)?;
    Some(describe.describe())
}