Hazel

Script Backends

The engine ships the scripting system and no interpreter. A backend is what turns a script file into behaviour: it claims one or more file extensions, and the engine hands it every script with one of those extensions. Which interpreted languages a project can use is therefore decided by which backends are installed, not by how the engine was compiled. Several can be installed at once, and a project can mix languages, one entity even.

Rust needs no backend of its own in this sense: .rs scripts are compiled to native code and called with &mut World (see Rust Scripts). This page is for adding an interpreted language beside it. Backends for other languages can be installed from the Marketplace.

What a backend is

An ordinary native plugin (or an engine crate) that implements ScriptBackend and registers it with App::add_script_backend. Everything it needs is in the contract layer renzora_scripting_api, which a native plugin reaches as renzora. That is the point of the trait living there and not in renzora_scripting: an installed plugin is compiled against the SDK, which offers only bevy and renzora.

A backend owns one job: given a script path and a ScriptContext, run a hook and return ScriptCommands. The engine owns the rest: finding scripted entities, deciding when scripts run, building the context, applying the commands. See The Scripting System for that side.

  engine                                  backend
  ------                                  -------
  find entities with ScriptComponent
  ask defines_hook(path, hook)   ------->  Some(false) skips the rest
  build a ScriptContext
  call_on_update(path, ctx, vars) ------>  load or reuse the script, run the hook
                                 <-------  Vec<ScriptCommand>
  apply the commands to the World

The trait

The required methods:

use std::path::{Path, PathBuf};
use renzora::{FileReader, ScriptBackend, ScriptCommand, ScriptContext};
use renzora::{ScriptVariableDefinition, ScriptVariables};

#[derive(Default)]
struct MyBackend {
    scripts_folder: PathBuf,
    reader: Option<FileReader>,
}

impl ScriptBackend for MyBackend {
    fn name(&self) -> &str { "MyLang" }
    fn extensions(&self) -> &[&str] { &["my"] }

    fn set_scripts_folder(&mut self, path: PathBuf) { self.scripts_folder = path; }
    fn set_file_reader(&mut self, reader: FileReader) { self.reader = Some(reader); }

    fn get_available_scripts(&self) -> Vec<(String, PathBuf)> { Vec::new() }
    fn get_script_props(&self, _path: &Path) -> Vec<ScriptVariableDefinition> { Vec::new() }

    fn call_on_ready(
        &self,
        _path: &Path,
        _ctx: &mut ScriptContext,
        _vars: &mut ScriptVariables,
    ) -> Result<Vec<ScriptCommand>, String> {
        Ok(Vec::new())
    }

    fn call_on_update(
        &self,
        _path: &Path,
        _ctx: &mut ScriptContext,
        _vars: &mut ScriptVariables,
    ) -> Result<Vec<ScriptCommand>, String> {
        Ok(Vec::new())
    }

    fn needs_reload(&self, _path: &Path) -> bool { false }
    fn reload(&self, _path: &Path) -> Result<(), String> { Ok(()) }
    fn eval_expression(&self, _expr: &str) -> Result<String, String> {
        Err("not supported".into())
    }
}

ScriptBackend: Send + Sync, and every call takes &self, so per-script state (compiled chunks, VMs) needs interior mutability.

MethodCalled
name, extensionsAt registration, for routing, and whenever the editor asks which extensions are scripts (ScriptEngine::script_extensions, used by the Inspector's Scripts section and the asset browser)
set_scripts_folderWhen a project opens (the project root), and on registration if one is already set
set_file_readerWhen the game runs from a .rpak archive (exported and Android builds), and on registration if a reader is already set
get_available_scriptsThrough ScriptEngine::get_available_scripts: (display name, path) pairs, merged and sorted across backends
get_script_propsBefore on_ready, where declared props are merged into the entry's variables (values already set are kept), and by the Inspector's Scripts section to draw them
call_on_ready / call_on_updateOnce, then every frame, for each enabled entry
needs_reload / reloadEvery 0.5 s from check_script_hot_reload; a successful reload re-runs on_ready
eval_expressionThrough ScriptEngine::eval_expression, which asks the first registered backend; nothing in the engine calls it today

Paths handed to hooks are resolved: a relative script_path is joined to the scripts folder.

Optional hooks

Every other hook has a default that returns no commands, so a backend implements only what its language supports, and adding a hook to the trait later breaks no existing backend.

MethodScript hook nameNotes
call_on_fixed_updateon_fixed_updateFrom FixedUpdate, once per tick, only after on_ready; the context's time.delta is the fixed step
call_on_draw(path, width, height, ctx, vars)on_drawReturns Vec<DrawCmd> for the entity's canvas, not commands
call_on_rpc(path, name, args, from, ...)on_rpc
call_on_ui(path, name, args, entity_bits, ...)on_uientity_bits is the firing UI node's Entity::to_bits()
call_on_animation_event(path, name, entity_bits, ...)on_animation_event
call_on_http(path, callback, status, body, ...)on_httpstatus 0 means the request never completed; body is then the error
call_on_player_event(path, id, joined, ...)on_player_joined / on_player_leftServer side
call_on_scene_event(path, scene, error, ...)on_scene_loaded / on_scene_load_failed
call_on_event(path, name, args, ...)on_eventGame events, including the plugin bus
defines_hook(path, hook)See below
evict(path, entity)See below

Use the conventional hook names in your language so a script ported from one language to another keeps its shape. A script that does not define a hook is the common case: return Ok(Vec::new()).

defines_hook

The executor asks defines_hook(path, hook) before building a context, which is the expensive part of a call (an input snapshot, name maps, read handlers). hook is "on_fixed_update" for the fixed pass and renzora::ANY_HOOK ("*") for "anything the frame pass would call". Answer Some(false) when you know the script defines none of it and the whole call is skipped; None (the default) means "cannot tell cheaply" and the hook is called as usual. Answering is an optimisation, never a requirement.

Registering

use bevy::prelude::*;
use renzora::AppScriptBackendExt;

#[derive(Default)]
pub struct MyLangPlugin;

impl Plugin for MyLangPlugin {
    fn build(&self, app: &mut App) {
        app.add_script_backend(MyBackend::default());
    }
}

renzora::plugin!(MyLangPlugin, Runtime);

Runtime scope, because games need the interpreter too; plugin! defaults to Editor.

add_script_backend pushes into PendingScriptBackends, and ScriptingPlugin drains that queue into ScriptEngine in PreStartup. So a backend has no ordering relationship with ScriptingPlugin: it does not matter which plugin builds first. ScriptEngine::add_backend replays the scripts folder and file reader it already holds, so a backend arriving late starts configured.

Routing is first match by extension, in registration order. Two backends claiming the same extension are both registered, and the first one wins every script with it; do not claim an extension another backend already owns.

Rules that are not optional

Read scripts through the file reader. FileReader is Arc<dyn Fn(&Path) -> Option<String> + Send + Sync>. In an exported game scripts live inside the .rpak archive, and only the reader can see them. A backend that reads with std::fs works in the editor and fails in every shipped game. Fall back to the file system only when the reader returns None.

Drop per-entity state in evict. The engine calls evict(Path::new(""), entity_bits) on every backend when a scripted entity is gone. An empty path means every script on that entity; an entity of 0 means every entity running that script. A backend keeping a VM per (entity, script) that ignores this grows without bound as entities churn.

Return errors; do not panic. An Err(String) is logged against the script once and the script keeps being called, so it recovers when the cause goes away. The executor does not catch panics.

Do not write the world. A hook only returns commands. The world is written after the hook returns, by the command queue, so ordering stays the engine's decision and a backend never needs &mut World.

Reading state

From inside a hook, a backend has:

  • the ScriptContext fields (time, transform, input, action map, parent and children, collisions, timers, raycasts, network role);
  • renzora::get_handler::call_get(entity_name, component, field_path) and its siblings, for a script's synchronous get("Component.field"), which read through reflection and return PropertyValue. They are thread-local and installed by the executor around each call;
  • ctx.extensions(), the declared bindings.

Declared bindings

Domain crates and plugins declare script functions instead of writing them (see Script Extensions). Honouring them is what makes a new language useful at once instead of after every crate has learned about it. Read ctx.extensions() (or the ScriptExtensions resource) and build one function per Binding:

  • BindingKind::Action { action }: pack the arguments under the declared parameter names and push ScriptCommand::Action. A ParamKind::Vec3 parameter consumes three numbers from the call and produces one ScriptActionValue::Vec3.
  • BindingKind::Read { component, field }: substitute the call's arguments into both with renzora::script_extension::substitute, then read through call_get.
  • BindingKind::Translate: look the argument up in the localization table.

ScriptExtensions::generation() changes whenever an extension registers; rebuild your function table only when it differs from the one you last built.

Syntax colouring

The code editor knows only its built-in formats, so a language plugin describes its syntax for it:

use renzora::{AppCodeSyntaxExt, CodeSyntax};

app.add_code_syntax(CodeSyntax {
    keywords: &["fn", "let", "if", "else", "return", "true", "false"],
    line_comment: Some("//"),
    block_comment: Some(("/*", "*/")),
    ..CodeSyntax::new("MyLang", &["my"])
});
FieldMeaning
nameWhat the status bar calls the language
extensionsLowercase, without the dot
keywords, typesWords coloured as keywords and as types
caps_are_typesColour every capitalised identifier as a type
line_commentComment to end of line; also what Ctrl+/ inserts
block_commentOpen and close tokens of a multi-line comment
quotesOne-line string delimiters (default "')
multiline_stringsDelimiters of strings that may span lines; checked before quotes
identifier_charsExtra identifier characters, such as $

Everything is &'static, which is safe because a plugin image is never unloaded. The newest registration for an extension wins, including over the editor's built-in syntax. In a game nothing reads it.

Reference

ItemWhere
ScriptBackend, AppScriptBackendExt, FileReader, ANY_HOOK, PendingScriptBackendscrates/api/renzora_scripting_api/src/backend.rs
ScriptCommandcrates/api/renzora_scripting_api/src/command.rs
ScriptContextcrates/api/renzora_scripting_api/src/context.rs
get_handlercrates/api/renzora_scripting_api/src/get_handler.rs
CodeSyntax, AppCodeSyntaxExtcrates/api/renzora_scripting_api/src/syntax.rs
ScriptEngine (routing)crates/renzora_scripting/src/engine.rs
A minimal backend that only claims an extensioncrates/renzora_rust_script/src/backend.rs