Script Extensions
A crate adds script functions by declaring them: a name, the arguments, and one of three things the call does. It writes no interpreter code. Every language backend reads the declarations and builds the functions in its own language, so a function declared once exists in every scripting language a project has installed, and the declaring crate links no interpreter.
The vocabulary is in crates/api/renzora_scripting_api/src/script_extension.rs, re-exported as renzora_scripting::extension for engine crates and as renzora::script_extension for native plugins.
Why declare instead of write
Every hand-written script function in the engine turned out to be the same few lines: read the arguments, pack them into an action, push it. Writing that by hand meant a domain crate such as physics compiled an interpreter just to say "apply_force takes three floats", and a second language would have needed a second copy of every function. Declaring the shape moves the per-language work into the backend, once, and leaves the domain crate with nothing language-specific at all.
It lives in the contract layer, not in renzora_scripting, so that a native plugin (which can only name bevy and renzora) can declare functions too.
The trait
pub trait ScriptExtension: Send + Sync + 'static {
/// For logs.
fn name(&self) -> &str;
/// The functions this crate contributes.
fn bindings(&self) -> Vec<Binding>;
}
A Binding is plain data:
pub struct Binding {
pub name: String, // what scripts call
pub kind: BindingKind, // what the call does
pub params: Vec<Param>, // in call order
pub doc: String, // one line, for autocomplete; may be empty
}
Build one with Bind:
| Constructor | The script function | What a backend does with it |
|---|---|---|
Bind::action(name, action) | returns nothing | packs the arguments and emits ScriptCommand::Action { name: action, .. }, which becomes a triggered ScriptAction |
Bind::read(name, component, field) | returns a value | reads the reflected field through the get path and returns it |
Bind::translate(name) | returns a string | looks its argument up in the localization table |
Three kinds, because that is what the engine's own extensions needed. A fourth is a change to the contract and to every backend, so it should earn its place.
Builder methods:
| Method | Effect |
|---|---|
.arg(name, ParamKind) | One parameter, in call order |
.xyz() | Three Float parameters named x, y, z |
.vec3(name) | One Vec3 parameter |
.doc(text) | The one-line description |
.build() | The Binding |
Parameters
ParamKind | Script arguments consumed | Argument produced |
|---|---|---|
Float, Int, Bool, Str | 1 | one value of that type |
Vec3 | 3 | one ScriptActionValue::Vec3 |
Both vector shapes exist on purpose. An observer that reads x, y and z separately wants .xyz(); one that reads a single target vector wants .vec3("target"). The script call looks the same either way (three numbers); pick whichever your observer expects.
Writing one
An engine crate needs only the contract layer:
[dependencies]
renzora_scripting_api = { path = "../api/renzora_scripting_api" }
use bevy::prelude::*;
use renzora_scripting_api::script_extension::{
Bind, Binding, ParamKind, ScriptExtension, ScriptExtensions,
};
use renzora_scripting_api::{ScriptAction, ScriptActionValue};
#[derive(Component, Reflect, Default)]
#[reflect(Component)]
pub struct Health {
pub current: f32,
}
pub struct CombatScriptExtension;
impl ScriptExtension for CombatScriptExtension {
fn name(&self) -> &str {
"combat"
}
fn bindings(&self) -> Vec<Binding> {
vec![
Bind::action("deal_damage", "deal_damage")
.arg("amount", ParamKind::Float)
.doc("Damage the script's own entity.")
.build(),
Bind::action("knockback", "knockback")
.xyz()
.doc("Push the entity along a world-space vector.")
.build(),
Bind::read("get_health", "Health", "current")
.doc("Current health.")
.build(),
]
}
}
fn on_combat_action(trigger: On<ScriptAction>, mut health: Query<&mut Health>) {
let action = trigger.event();
if action.name != "deal_damage" {
return;
}
let Some(ScriptActionValue::Float(amount)) = action.args.get("amount") else {
return;
};
if let Ok(mut health) = health.get_mut(action.entity) {
health.current -= amount;
}
}
#[derive(Default)]
pub struct CombatPlugin;
impl Plugin for CombatPlugin {
fn build(&self, app: &mut App) {
app.register_type::<Health>()
.add_observer(on_combat_action);
app.world_mut()
.get_resource_or_insert_with(ScriptExtensions::default)
.register(CombatScriptExtension);
}
}
get_resource_or_insert_with rather than resource_mut, because there is no ordering between your plugin and ScriptingPlugin; whichever builds first creates the resource and the other finds it. There is no App extension method for this; it is the same call the engine's own crates make.
A native plugin writes exactly the same code with renzora::script_extension::..., renzora::ScriptAction and renzora::ScriptActionValue.
Engine crates that declare functions this way, for reference: renzora_animation, renzora_audio, renzora_ik, renzora_lang, renzora_navmesh, renzora_particles, renzora_physics, renzora_engine (camera and load groups) and renzora_runtime (game settings).
Handling an action
Bind::action only declares; the work is an observer on ScriptAction, as above. action.entity is the calling script's entity, action.target_entity an optional name or id the script aimed it at, and action.args a HashMap<String, ScriptActionValue> keyed by the parameter names you declared.
The same event arrives from three directions, and one observer serves all of them:
- an interpreted script calling the declared function;
- a built-in
ScriptCommandthat the command queue converts to an action (ApplyForcearrives asapply_force; see The Scripting System); - a Rust script sending it directly:
ScriptAction::new("deal_damage", ctx.entity()).arg("amount", 10.0_f32).send(ctx.world()).
An observer runs inside whatever triggered it, so keep it to the world writes it needs. A function whose work is slow (a request, a query) should start the work and answer later by queuing a GameEvent named by a callback argument the caller passed; scripts receive it through on_event or ScriptHook::Event.
Reads and placeholders
Bind::read(name, component, field) resolves through the same reflection path as a script's get, on the calling script's entity. The usual pattern is a small reflected *ReadState component that your crate keeps up to date on scripted entities, so the script reads a mirror rather than your internal state.
component and field may contain {0}, {1}, ... placeholders, replaced with the call's arguments by script_extension::substitute, which every backend uses so all languages resolve a path identically:
Bind::read("get_animation_length", "AnimatorReadState", "clip_lengths[\"{0}\"]")
.arg("name", ParamKind::Str)
.build()
A map entry is ["key"] in a reflect path; .key is a field access. A placeholder with no matching argument is left as written, so the path visibly fails to resolve rather than silently reading a different field.
Registration rules
- The first declaration of a name wins. A second extension declaring the same function name has that binding refused with a warning, rather than shadowing it, because "which crate won" would otherwise depend on plugin order.
ScriptExtensions::generation()changes on everyregistercall, even one that added nothing. A backend compares it with what it last built and rebuilds its function table only on a change.bindings()returns every declared function;extension_names()the registered extensions, for diagnostics.
What a Rust script sees
Nothing: declarations are for interpreted languages. A Rust script calls an action function by sending the ScriptAction, and needs no read functions because it can read the component directly. Declaring a function is therefore never the only way to expose a feature to Rust; a public, reflected component is.