Introduction

Contents

Balaur is a deterministic node-based 2D and 3D game engine. A game is a scene tree of nodes with scripts attached.

The editor: scene tree, viewport, inspector

Hot reload and determinism

A script

// scripts/spinner.bs
pub class Spinner {
    node: Node,
    angle: float,
}

impl Spinner {
    fn update(dt: float) {
        self.angle += dt;
        self.node.transform.rotation_euler = vec3(0.0, self.angle, 0.0);
    }
}

A scene

# scene.toml
[[nodes]]
name = "Ball"
script = { source = "scripts/ball.bs" }
transform = { position = [0.0, 6.0, 0.0] }
body3d = { kind = "dynamic" }
collider3d = { shape = { kind = "sphere", radius = 0.5 } }
shape3d = { shape = { kind = "sphere", radius = 0.5 } }

This scene has a node called Ball with four components: transform, body3d, collider3d and shape3d.

Where to go next

Principles

Contents

  1. Fast to run. Performance is important.
  2. Fast to iterate. Scripts must reload instantly.
  3. Easy to use. Nodes and scripts on top. With a lot of tools.

The practical version (how to build, test and lint) is CONTRIBUTING.md in the engine repository.

Getting started

Contents

Download

A project

balaur new my-game
balaur edit my-game
my-game/
├── project.toml        # [application] name, main_scene
├── scenes/main.toml    # the scene tree, in TOML
└── scripts/hello.bs    # a script attached to a node
examples/hello open in the editor: the World node selected, the viewport, the inspector, and the Output dock showing the boot

Run

Press Play in the editor, or run the project from a terminal:

balaur run my-game

Edit a script

Examples

The examples ship in the repository. Projects plays them in the browser, or starts a project from one to edit there.

balaur edit examples/hello         # 3D: a spinning cube, a bouncing ball, a HUD label
balaur edit examples/angrynerds    # 2D: a slingshot game with 2D physics and widgets
balaur edit examples/rig           # a 2D skeleton: a skinned leg, an arm on two-bone IK
balaur edit examples/rig3d         # a 3D rig imported from a .glb

From source

cargo run -p balaur_cli -- edit my-game

Toolchain and packages: Build from source.

Next

The CLI

Contents

The balaur binary is the editor, the runtime and the CLI.

balaur new my-game
balaur run my-game          # dev mode, hot reload on
balaur edit my-game         # open in the editor
balaur export my-game       # check scripts, bundle my-game.bpak
balaur play my-game.bpak    # run the pack

Commands

Command Effect
(none) Open the project manager: recent projects, a new one from a template, a folder
new <path> Scaffold a project: project.toml, a main scene, one script
add <owner/name | folder> Add a dependency: fetched into deps/<alias>/ and pinned in project.lock, or a folder used as it is
fetch <path> Fill deps/ from project.lock; --update moves each dependency to the newest commit of its branch or tag
run <path> Run in dev mode with hot reload
edit <path> Open the project in the editor
export <path> Check every script and bundle a .bpak; --target <platform> produces a fused executable
play <pack> Run an export pack, with no watcher
import <file> --project <path> Bring a file in: a .glb model, an .aseprite sprite, or a .tmx or .ldtk level
replay <session> Play back a session recorded with run --record; --verify re-checks every tick
check <path> Compile every script a scene attaches without running it, and print each finding with its file and line
test <path> Attach every tests/**/*.bs to a fresh node in a headless copy and tick it for 120 frames; a logged error or a trap fails the run
fmt <path> Format every script in a project, its line breaks and comments kept
lsp Serve the same checks over the Language Server Protocol, for an editor outside Balaur
shrink <path> Write smaller copies of a project's images for one target, which an export folds onto the names the scenes already use
atlas <frames> --name <name> Pack loose frames onto one page: a sprite_sheet under sheets/, with a tag and a clip per run of numbered frames
update Update this install to the newest build on its channel: the binary, the bundled editor and its runtime template
api Dump every script module, function and constant as JSON

Run modes

Mode GPU Window What it is for
headless (--headless) no no tests, CI, servers, determinism runs
offscreen (--offscreen) yes no screenshots, automation, visual CI
windowed yes yes playing and editing

From source

cargo run -p balaur_cli -- run my-game --headless
cargo run -p balaur_cli -- edit my-game

The window feature, on by default, builds the kiss3d/wgpu window. --no-default-features --features headless leaves it out, and everything runs headless. Toolchain and packages: Build from source.

Build from source

Contents

Toolchain

Linux packages

sudo apt-get install -y \
  git build-essential pkg-config \
  libasound2-dev libudev-dev \
  libx11-dev libxcursor-dev libxrandr-dev libxi-dev \
  libxkbcommon-dev libwayland-dev
Package Pulled in by
build-essential a C compiler for zstd and ring; a C++ one for HarfBuzz, the web export's font subsetter
libasound2-dev ALSA, through rodio and cpal: the audio feature
libudev-dev gamepads, through gilrs
libx11-dev, libxcursor-dev, libxrandr-dev, libxi-dev, libxkbcommon-dev, libwayland-dev winit, the window feature

Build

git clone https://github.com/balaurengine/balaur.git
cd balaur
cargo run -p balaur_cli -- run examples/hello --headless --frames 120   # no GPU, no window
cargo run -p balaur_cli -- edit examples/hello                          # the editor

The windowed build compiles 541 crates the first time; after that it is incremental.

On PATH

cargo build --release -p balaur_cli --bin balaur
export PATH="$PWD/target/release:$PATH"
balaur --version      # 0.2.0-alpha.1 (source build)

The binary finds the editor through editor/ beside the sources, at a path baked in at build time. Moved elsewhere, it needs --editor <dir> or BALAUR_EDITOR.

Features

The defaults are window and headless, which turns on everything else a desktop build carries but the window. extensions and apple are off. Build size lists every feature.

If it fails

Error Fix
names edition2024 or a version under 1.98.1 rustup update; drop any rustup override or +toolchain flag
Package alsa was not found in the pkg-config search path libasound2-dev, or alsa-lib-devel. The next missing library fails the same way, so install the whole list
no editor project found; pass --editor <dir> run it from the checkout, or pass --editor

Before a pull request, scripts/precommit.sh runs what CI runs; see CONTRIBUTING.md.

Coming from Godot

Contents

Godot to Balaur, one row per file, node and call; the manual and the reference have the rest.

Files

Godot Balaur
project.godot project.toml: name, main_scene, input actions
scene.tscn scenes/scene.toml: a flat [[nodes]] list, parent by id
script.gd scripts/script.bs: Balaur Script
.tres resources [[assets]] in TOML: mesh, material, animation_library, tileset, … (assets)
.gdshader .wesl in a material asset (shaders)
Export presets, templates balaur export my-game --target linux-x64: one fused binary (shipping)

Nodes

No class hierarchy. A node is whatever its components make it. A collider sits on the same node as its body.

Godot Balaur
Node2D, Node3D A node with a transform: position, rotation, scale. A node without one sits at its parent
RigidBody2D, StaticBody2D, AnimatableBody2D body2d = { kind = "dynamic" } (or static, kinematic); body3d in 3D
CollisionShape2D collider2d = { shape = { kind = "rectangle", size = [1.0, 1.0] } }
CharacterBody2D, CharacterBody3D character2d, character3d
PinJoint2D, HingeJoint3D, … joint2d, joint3d
VehicleBody3D, VehicleWheel3D vehicle3d, wheel3d
Sprite2D sprite
TileMapLayer tilemap over a tileset asset
GPUParticles2D, CPUParticles2D particles2d
GPUParticles3D, CPUParticles3D particles3d
MeshInstance3D, CSGBox3D, … mesh for a model; shape3d for a primitive; boolean3d for CSG
Polygon2D polygon
Camera2D camera2d
Camera3D camera3d
PointLight2D, LightOccluder2D light2d, occluder2d
AudioStreamPlayer, AudioListener3D sound, listener
Skeleton2D / Bone2D, Skeleton3D Nodes with bone2d / bone3d
SkeletonIK, LookAtModifier, SkeletonModification2DFABRIK / CCDIK / Jiggle modifier2d and modifier3d: look_at, two_bone_ik, fabrik, ccdik, jiggle
BoneMap, SkeletonProfile A bone_map asset and node.animation.play(clip, animation::PlayOptions { retarget: path })
PhysicalBone2D, Create Physical Skeleton physics2d::ragdoll(node), and a ragdoll component whose influence mixes the clip with the simulation
AnimationPlayer animation: a clip library and an autoplay
Label, Button, Panel widget with kind = "label" / "button" / "panel"
Control layouts, editor plugins widget nodes (UI)
Instancing a PackedScene instance = "scenes/crate.toml" on a node, with overrides (prefabs)

Scripts

Godot Balaur
extends Node2D pub class Player { node: Node, .. }: the node is a field, its kind is its components
var hp = 3 A field: hp: int
_ready() fn init() in impl Player
_process(delta) fn update(dt: float)
_physics_process(delta) fn fixed_update(dt: float): fixed 60 Hz, before physics
_exit_tree() fn on_free()
@export var speed = 2.0 pub speed: float = 2.0, overridden in [nodes.script.props]
self self; the node is self.node
position, rotation, scale self.node.transform.position, .rotation_euler (radians), .scale; transform.global_position() in world space
$Path/To/Node, get_node("..") self.node.get_node("Path/To/Node"), "../Sibling"
queue_free() node.queue_free(): deferred to end of frame
apply_impulse(v) self.node.body2d.apply_impulse(x, y)
signal hit on a node, enemy.hit.connect(_on_hit) events::listen(self.node, "hit", enemy), then pub fn on_hit(payload: any) (events)
hit.emit(payload) from that node self.node.emit("hit", payload): delivered at the top of the next frame
Connecting to every emitter of a signal events::listen(self.node, "hit"): no emitter argument
Engine signals: pressed, animation_finished, request_completed Methods by name: on_click, on_animation_finished(name), on_response(r)
Calling a method on another node node.call("method", args)
Input.is_action_just_pressed("jump") input::action_just_pressed("jump")
Input.get_axis("left", "right") input::action_value("move_x"): one action, -1 to 1
InputMap in project settings [input.actions] in project.toml (input)
$AnimationPlayer.play("run") self.node.animation.play("run")
$AnimationTree["parameters/playback"].travel("run") self.node.state_machine.travel("run")
create_tween().tween_property(...) animation::tween(self.node, animation::Tween { steps: steps }): Godot's easing names
await get_tree().create_timer(1.0).timeout await task::seconds(1.0); in an async fn; results land at the start of a tick
Variant, Dictionary any, and { "k": v }
null nil, for a T? or an any
HTTPRequest http::request(url) (networking)
FileAccess, ConfigFile fs, settings, the save addon
randf(), randi() random::: seeded, engine-owned, replayable
print() log::info()
preload, load assets::load("path.toml")

The editor

Godot Balaur
2D / 3D / Script / AssetLib tabs Workspaces: Scene, Script, Animation, Physics, UI (editor)
Script reloads on save Hot reload in milliseconds
Debugger tab Breakpoints in the gutter, frames and locals in a dock
Editor plugins in GDScript The editor is a Balaur project; editing its scripts hot reloads the editor
Remote scene tree Play in editor on the same scene and scripts, every run recorded

Differences

Start

balaur new my-game    # project.toml, a main scene, one script
balaur edit my-game

examples/angrynerds is a small 2D game: bodies, colliders, widgets, one script per node. Getting started has the rest.

Compare

Contents

Side by side

Balaur Godot 4 Bevy Fyrox
Engine language Rust C++ Rust Rust
Game code Balaur Script; Rust or C plugins GDScript, C#; Rust or C++ plugins Rust Rust
Model A scene tree A scene tree ECS A scene tree
Scene format .toml, text .tscn, text Rust code, or .ron .rgs
Editor Yes Yes No Yes
Hot reload Scripts, on save Scripts, on save Assets; opt-in code patching Code, marked experimental
Cross-platform determinism Yes: fixed 60 Hz step, replay, rollback No No No
2D and 3D Both Both Both Both
Platforms Desktop, mobile, web Desktop, mobile, web; consoles through partners Desktop, mobile, web Desktop, web
Networking HTTP, WebSockets, WebTransport HTTP, WebSockets, WebRTC, ENet Community crates Community crates
Licence MIT MIT MIT MIT
Age Very new Over a decade Few years Few years

Memory

What an idle project holds, headless: the number that decides how many instances fit on a server.

scene Balaur Godot 4.7
empty project 13 MB 41 MB
10,000 nodes 19 MB 67 MB
50,000 nodes 31 MB 166 MB

Balaur costs about 0.35 KB per node, Godot about 2.5 KB, so the gap widens with the size of the scene.

Physics and scene-tree throughput are on the benchmarks page.

Build size

A 2D hello world, release build.

Balaur Godot 4.7 Bevy 0.19 Fyrox 1.0
desktop binary 44 MB 79 MB 51 MB 29 MB
web module, brotli 5.4 MB 6.6 MB 4.8 MB 3.6 MB

What Balaur does not have yet

Balaur Script

Contents

Balaur Script is the language of game scripts and of the editor itself. A .bs file is statically typed, reads like Rust, and compiles to WebAssembly when it is saved. A running game picks up the new code and keeps its state.

enum Shape { Circle(float), Rect { w: float, h: float }, Empty }

fn area(s: Shape) -> float {
    match s {
        Shape::Circle(r) => r * r * 3.0,
        Shape::Rect { w, h } => w * h,
        Shape::Empty => 0.0,
    }
}

pub fn total() -> float {
    let shapes = [Shape::Circle(2.0), Shape::Rect { w: 2.0, h: 3.5 }, Shape::Empty];
    let sum = 0.0;
    for s in shapes {
        sum += area(s);
    }
    sum
}

// total() == 19.0

How this chapter is laid out

Each page teaches one concept and builds on the pages before it. The pages read in order, and each stands alone when you come back to look something up.

Part What it teaches
Getting started a first script on a node, and how to try code
The basics files, variables, operators, control flow, functions
Types numbers, booleans, strings, lists, maps, optionals, any, vectors, conversions
Structs, classes and enums the types a script declares, and match
Functions in depth function values and &mut parameters
Modules splitting a game across files
Async and await code that waits across frames
Memory what is copied, what is shared, what is freed and when
Errors and traps what the compiler refuses, and what stops a call
Scripts in the engine hooks, exported properties, components, events
Language reference every construct on one page

The script modules reference lists every engine function. The Scripting manual page covers the editor, the debugger and hot reload.

How to read the examples

A comment under an example says what a call answers:

pub fn double(x: int) -> int { x * 2 }

// double(21) == 42

Some calls end in a trap, which stops the call at run time. Others do not compile, and the comment gives the compiler's own message with its line and column:

pub fn half(n: int) -> int { n / 0 }
pub fn broken() -> int { 1 + true }

// error: 2:28: cannot combine int and bool

Trying the examples shows how to run any of them on your own machine.

Your first script

Contents

A script is a .bs file attached to a node in a scene. Start with a new project:

balaur new hello
balaur run hello

The project holds one scene with one node, and one script.

# scenes/main.toml
[[nodes]]
name = "Hello"
script = { source = "scripts/hello.bs" }
// scripts/hello.bs
pub class Hello {
    node: Node,
    elapsed: float,
}

impl Hello {
    fn init() {
        log::info("hello from {self.node.name()}");
    }

    fn update(dt: float) {
        self.elapsed += dt;
    }
}

What each part does

Change it while it runs

Keep the game running, and make the script report once a second:

// scripts/hello.bs
pub class Hello {
    node: Node,
    elapsed: float,
}

impl Hello {
    fn init() {
        log::info("hello from {self.node.name()}");
    }

    fn update(dt: float) {
        self.elapsed += dt;
        if self.elapsed > 1.0 {
            self.elapsed -= 1.0;
            log::info("another second");
        }
    }
}

Save the file. The game keeps running on the new code, and elapsed keeps its value, because a reload carries each field across by name.

A save that does not compile changes nothing. The error goes to the log with its file, line and column, and the old code keeps running.

Next

Trying the examples shows how to run the code on the other pages. Scripts in the engine goes further with hooks and nodes.

Trying the examples

Contents

balaur test runs every script under a project's tests/ folder, so a test file is the quickest place to try a piece of code.

// tests/try.bs
pub class Try {
    node: Node,
}

impl Try {
    fn init() {
        log::info("{double(21)}");
    }
}

fn double(x: int) -> int { x * 2 }
balaur test hello --filter try

To hold a result to a value, log an error when it is wrong:

// tests/doubles.bs
pub class Doubles {
    node: Node,
}

impl Doubles {
    fn init() {
        if double(21) != 42 {
            log::error("double is wrong");
        }
    }
}

fn double(x: int) -> int { x * 2 }

Checking and formatting

balaur check hello       # compile every script of the project, and print each finding
balaur fmt hello         # lay out every script
balaur fmt hello --check # name the files that would change

balaur fmt keeps your line breaks and comments, and it changes no token.

In an editor

The Balaur editor's Script workspace completes names, jumps to definitions and shows errors as you type. balaur lsp <project> serves the same over the Language Server Protocol, for other editors. See Tooling.

Files and items

Contents

A .bs file is a list of items. An item is a declaration at the top level of a file, and code runs only inside functions and methods.

Item Declares
fn a function
const a constant
struct a value with fields
class an object with fields and methods
impl the methods of a class
enum one of several variants
use a link to another file
extern fn a function the host provides

Items may come in any order. A function can call one declared further down.

pub fn greeting() -> str { "hello, {name()}" }

fn name() -> str { NAME }

const NAME = "ball";

// greeting() == "hello, ball"

pub

An item, a field or a method without a mark belongs to its file, and naming it from elsewhere does not compile. pub opens it to every file, and internal to the files of its package. Modules has the rule. A pub field with a default is also an exported property.

Comments

// comments to the end of the line, and /// documents the item below it, which the editor shows on hover. There are no block comments.

// A plain comment.

/// Twice `x`. The editor shows this line on hover.
pub fn double(x: int) -> int { x * 2 }

// double(4) == 8

Statements and expressions

Nearly everything computes a value. A ; ends a statement and throws its value away. A block's last expression, written with no ;, is the value of the block.

pub fn sign(n: int) -> int {
    let s = if n < 0 { -1 } else { 1 };
    s * 10
}

// sign(-3) == -10

Lines do not end statements, so a new line can continue the one before. A block followed by a line opening with [ or - is read as one expression. Write return for a value that follows a block:

pub fn pair(flip: bool) -> [int] {
    if flip {
        log_flip();
    }
    return [1, 2];
}

fn log_flip() {}

// pair(true) == [1, 2]

The same code with a bare [1, 2] on the last line is refused, because the if would be the thing indexed.

Variables and constants

Contents

let declares a variable and always gives it a value. The variable's type comes from that value, or from an annotation when you write one.

pub fn describe() -> str {
    let lives = 3;
    let speed: float = 3;
    let name = "orc";
    "{name} {lives} {speed}"
}

// describe() == "orc 3 3.0"

A variable with no value does not compile: let x: int; stops at the ;.

Assignment

A variable can be assigned again, with a value of its type. +=, -=, *=, /= and %= combine.

pub fn counted() -> int {
    let n = 1;
    n = 5;
    n += 2;
    n *= 3;
    n
}

// counted() == 21

The type stays the one it started with. An int can go into a float variable, as Numbers explains, and nothing else can change a type:

pub fn broken() {
    let n = 1;
    n = "one";
}

// error: 3:9: expected int, got str

Scope and shadowing

A let inside a block ends with the block. A second let of the same name hides the first from that point on, and it may have another type.

pub fn shadowed(x: int) -> str {
    let total = 0;
    for i in 0..3 {
        let step = i * 2;
        total += step;
    }
    let x = "{x + total}";
    x
}

// shadowed(1) == "7"

let mut is accepted and means the same as let. Every variable can be assigned.

Constants

A const sits at the top of a file and holds a literal: a number, a bool or a string. A list or a sum does not compile.

const NAME = "ball";
const SPEED: float = 2.5;
const LIVES = 3;

pub fn label() -> str { "{NAME} {SPEED} {LIVES}" }

// label() == "ball 2.5 3"
const TOTAL = 1 + 2;

// error: 1:17: const `TOTAL` must be a literal

A constant in another file reads as util::NAME. See Modules.

Operators

Contents

Kind Operators Takes
Arithmetic + - * / ints and floats
Remainder % ints
Join + two strings
Comparison < <= > >= ints and floats
Equality == != any two values of a type
Logic && || ! bools
Bits & | ^ ~ ints
Shift << >> ints
Negate - ints and floats
Convert as see Conversions

Each arithmetic, bit and shift operator has an assignment form: +=, -=, *=, /=, %=, &=, |=, ^=, <<= and >>=.

Precedence

From the tightest to the loosest, with parentheses to change the order. The bit operators sit where Rust puts them.

  1. as
  2. -, ! and ~ before a value
  3. *, /, %
  4. +, -
  5. <<, >>
  6. &
  7. ^
  8. |
  9. ==, !=, <, <=, >, >=
  10. &&
  11. ||
pub fn order() -> int { 1 + 2 * 3 }
pub fn grouped() -> int { (1 + 2) * 3 }
pub fn tested(hp: int, armed: bool) -> bool { hp > 0 && armed || hp > 100 }

// order() == 7
// grouped() == 9
// tested(5, true) == true
// tested(5, false) == false

Short-circuit

&& and || stop at the first side that decides. The right side of n != 0 && 10 / n > 1 never divides by zero.

pub fn safe(n: int) -> bool { n != 0 && 10 / n > 1 }

// safe(0) == false
// safe(2) == true

Bits

&, | and ^ work on the 64 bits of two ints, and ~ flips every bit of one. << shifts left. >> shifts right and keeps the sign, so -8 >> 1 is -4; there is no second right shift. A shift takes the low six bits of its count, as WebAssembly does: 1 << 64 is 1, and x >> -1 is x >> 63. Every engine and the iOS build give the same answer.

pub fn flags(held: int, pressed: int) -> int { held & ~pressed | 4 }
pub fn bit(n: int) -> int { 1 << n }
pub fn low_byte(n: int) -> int { n & 255 }
pub fn halved(n: int) -> int { n >> 1 }
pub fn packed(r: int, g: int, b: int) -> int { r << 16 | g << 8 | b }

// flags(7, 2) == 5
// bit(3) == 8
// bit(64) == 1
// low_byte(-1) == 255
// halved(-8) == -4
// packed(1, 2, 3) == 66051

A float is no set of bits: 2.0 & 1 does not compile.

pub fn broken(x: float) -> int { x & 1 }

// error: 1:36: `&` takes two ints, got float and int

What is left out

There is no ++ and no ternary. An if is the ternary:

pub fn bigger(a: int, b: int) -> int { if a > b { a } else { b } }

// bigger(2, 7) == 7

Operators do not cross types, apart from an int meeting a float:

pub fn broken() -> str { "lives: " + 3 }

// error: 1:36: cannot combine str and int

Interpolation is the way to put a number into text: "lives: {n}".

Control flow

Contents

if

The condition is a bool, with no parentheses and always with braces.

pub fn grade(score: int) -> str {
    if score >= 90 {
        "a"
    } else if score >= 50 {
        "b"
    } else {
        "c"
    }
}

// grade(95) == "a"
// grade(60) == "b"
// grade(1) == "c"

An if with an else is a value when both branches give one. Their types must agree, and an int and a float agree as a float. An if with no else is a statement.

pub fn pick(c: bool) -> int { if c { 1 } else { "two" } }

// error: 1:31: the branches of this `if` differ: int and str

A branch may leave instead of giving a value, which reads well at the top of a function:

pub fn first_doubled(xs: [int]) -> int {
    let x = if xs.len() > 0 { xs[0] } else { return -1; };
    x * 2
}

// first_doubled([4]) == 8
// first_doubled([]) == -1

while and loop

while runs as long as its condition holds, and loop runs until a break.

pub fn steps(n: int) -> int {
    let count = 0;
    while n > 1 {
        n = n / 2;
        count += 1;
    }
    count
}

pub fn first_square_over(limit: int) -> int {
    let i = 0;
    loop {
        i += 1;
        if i * i > limit {
            break;
        }
    }
    i
}

// steps(8) == 3
// first_square_over(50) == 8

break takes no value, so a loop gives nothing. Keep the answer in a variable.

for

for i in a..b counts from a up to, and not including, b. A range with a at or past b runs zero times. There is no step and no reverse: use while for those.

for x in xs walks a list in order. A map has no walk of its own, so walk keys() or values().

pub fn sum_to(n: int) -> int {
    let t = 0;
    for i in 0..n {
        t += i;
    }
    t
}

pub fn longest(words: [str]) -> int {
    let best = 0;
    for w in words {
        if w.len() > best {
            best = w.len();
        }
    }
    best
}

pub fn total() -> int {
    let prices: {str: int} = { "ale": 3, "bread": 2 };
    let t = 0;
    for name in prices.keys() {
        t += prices[name].or(0);
    }
    t
}

// sum_to(4) == 6
// longest(["a", "ccc", "bb"]) == 3
// total() == 5

break and continue

break leaves the innermost loop and continue starts its next pass.

pub fn evens_until_nine(xs: [int]) -> int {
    let count = 0;
    for x in xs {
        if x == 9 {
            break;
        }
        if x % 2 != 0 {
            continue;
        }
        count += 1;
    }
    count
}

// evens_until_nine([2, 3, 4, 9, 6]) == 2

return

return value; leaves the function, from anywhere in it. return; leaves one that gives nothing. match is the other way to branch, over the variants of an enum.

Functions

Contents

fn declares a function. Parameters always carry a type, and -> names what the function gives back.

pub fn area(w: float, h: float) -> float {
    w * h
}

// area(2.0, 3.5) == 7.0

The last expression of the body, with no ;, is the value. return leaves earlier.

pub fn clamp(v: int, lo: int, hi: int) -> int {
    if v < lo {
        return lo;
    }
    if v > hi {
        return hi;
    }
    v
}

// clamp(5, 0, 3) == 3
// clamp(-1, 0, 3) == 0

A function with no -> gives nothing back.

pub fn add_to(xs: [int], n: int) {
    xs.push(n);
}

What goes in

A number, a bool or a struct arrives as a copy, so changing it inside the function changes only the copy. A string, a list, a map and a class object arrive as the same thing the caller holds.

struct Wave { hp: int }

fn weaken(w: Wave) { w.hp = 0; }
fn extend(xs: [int]) { xs.push(9); }

pub fn run() -> str {
    let w = Wave { hp: 5 };
    let xs = [1];
    weaken(w);
    extend(xs);
    "{w.hp} {xs.len()}"
}

// run() == "5 2"

&mut parameters write back to the caller's own value.

Leaving arguments out

A trailing parameter that is a T? or an any may be left out, and arrives as nil. Only the end of the list goes: one before the end is still given, as nil when there is nothing to say.

fn label(id: int, name: str?, tag: any) -> str {
    "{id} {name.or("none")} {tag == nil}"
}

pub fn run() -> str {
    "{label(1)}, {label(2, "a")}, {label(3, nil, "t")}"
}

// run() == "1 none true, 2 a true, 3 none false"

The rule is the same for a method, an async fn, a function of another file and the engine's own, as in log::since(). balaur check warns about a last nil that could go, unless it is the only argument: node.set_script(nil) says what it does.

Two arguments are always given. A &mut parameter is a place the call stores back, whatever its type, and so is every parameter before it. A function value takes what its type says, so a call through one names them all, though the function it holds could leave some out.

fn add(a: int, b: int?) -> int { a + b.or(100) }
fn set(out: &mut int?) { out = 1; }

pub fn by_name() -> int { add(1) }
pub fn by_value() -> int {
    let f = add;
    f(1)
}
pub fn by_place() { set(); }

// error: 7:5: `f` takes 2 argument(s), 1 given
// error: 9:21: `set` takes 1 argument(s), 0 given

Recursion and order

A function may call itself, and may call any function in the file, wherever it is declared. Recursion that runs out of stack traps.

pub fn fib(n: int) -> int {
    if n < 2 { n } else { fib(n - 1) + fib(n - 2) }
}

// fib(10) == 55

What is left out

fn f() -> int { 1 }
fn f() -> int { 2 }

// error: 2:1: `f` is defined twice

Function values cover passing a function to another one.

Types overview

Contents

Every value has a type, and the compiler checks every use before the code runs. A script that adds a bool to an int does not start.

Type Holds Page
int a 64-bit signed integer Numbers
float a 64-bit float Numbers
bool true or false Booleans
str UTF-8 text Strings
[T] a list of T Lists
{str: V}, {int: V} a map from keys to V Maps
T? a T, or nil Optionals and nil
any a value whose kind is read at run time The any type
Vec2, Vec3, Color, Transform2d, Transform3d numbers with named fields Vectors and colours
Node a node of the scene Nodes and components
fn(A, B) -> R a function Function values
a struct fields, copied as one value Structs
a class fields and methods, one shared object Classes
an enum one of several variants Enums

Where types are written

A signature always names its types, and a let usually does not have to.

struct Hit { damage: int, tags: [str] }

fn total(hits: [Hit]) -> int {
    let sum = 0;
    for h in hits {
        sum += h.damage;
    }
    sum
}

pub fn run() -> int {
    let first = Hit { damage: 3, tags: [] };
    total([first, Hit { damage: 4, tags: ["fire"] }])
}

// run() == 7

Three values have no type of their own, so they take the one wanted where they go:

pub fn taken() -> int {
    let none: int? = nil;
    let empty: [str] = [];
    let ages: {str: int} = { "ada": 36 };
    empty.len() + ages.len() + none.or(5)
}

// taken() == 6

The same three with a bare let are refused, and each error says what to write:

pub fn a() { let x = nil; }
pub fn b() { let x = []; }
pub fn c() { let x = {}; }

// error: 1:22: `nil` needs the type it stands for: `let x: T? = nil`
// error: 2:22: `[]` needs a type: `let a: [float] = [];`
// error: 3:22: a map literal is typed by where it goes: `let ages: { str: int } = { "ada": 36 };`

Copied or shared

Assigning a value, or passing it to a function, does one of two things.

Copied Shared
int, float, bool str, which never changes, so sharing cannot show
Vec2, Vec3, Color, the transforms lists and maps
structs and enums class objects, and what an any holds when it is a list or a map
struct Wave { hp: int }

pub fn copied() -> int {
    let a = Wave { hp: 1 };
    let b = a;
    b.hp = 2;
    a.hp
}

pub fn shared() -> int {
    let a = [1];
    let b = a;
    b.push(2);
    a.len()
}

// copied() == 1
// shared() == 2

Memory has the details.

Numbers

Contents

int is a 64-bit signed integer. float is a 64-bit IEEE 754 float. A number with a point or an exponent is a float: 3 is an int, and 3.0 and 1e3 are floats.

Ints and floats together

An int meets a float as a float, in arithmetic, in a comparison, in an assignment and on the way out of a function. No cast is needed.

pub fn half(n: int) -> float { n / 2.0 }
pub fn scaled(speed: float) -> float {
    let x: float = 3;
    speed * 2 + x
}
pub fn pick(big: bool) -> float { if big { 10 } else { 0.5 } }
pub fn near(n: int) -> bool { n < 2.5 }

// half(3) == 1.5
// scaled(1.25) == 5.5
// pick(true) == 10.0
// near(2) == true

A float does not become an int by itself, because that loses the fraction. Write as:

pub fn broken() -> int {
    let n = 1;
    n = 2.5;
    n
}

// error: 3:9: expected int, got float
pub fn whole(x: float) -> int { x as int }

// whole(2.9) == 2
// whole(-2.9) == -2

float as int drops the fraction. A float past an int's range gives the nearest end, and NaN gives 0. Conversions has the full table.

Int arithmetic

pub fn wrapped() -> int { 9223372036854775807 + 1 }
pub fn divide(a: int, b: int) -> int { a / b }
pub fn rest(a: int, b: int) -> int { a % b }

// wrapped() == -9223372036854775808
// divide(-7, 2) == -3
// rest(-7, 3) == -1
// rest(7, -3) == 1
// divide(1, 0) traps

Float arithmetic

Floats follow IEEE 754 and give the same bits on every engine and platform. Dividing by zero gives an infinity or a NaN and does not trap. % is for ints only.

pub fn text() -> str {
    let zero = 0.0;
    "{1.0 / zero} {-1.0 / zero} {zero / zero} {0.1 + 0.2} {2.0} {1e21}"
}

// text() == "inf -inf NaN 0.30000000000000004 2.0 1e21"
pub fn broken() -> float { 7.5 % 2.0 }

// error: 1:32: `%` is not defined on float

The math module

math:: works on floats, and each function gives the same bits on every platform.

Group Names
Rounding and limits abs, floor, ceil, round, min, max, clamp
Powers sqrt, pow, exp, log, log10
Trigonometry sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh
Angles to_radians, to_degrees
Constants math::PI, math::TAU, math::INFINITY
pub fn hypot(a: float, b: float) -> float {
    math::sqrt(a * a + b * b)
}

pub fn spin(degrees: float) -> float {
    math::clamp(math::to_radians(degrees), 0.0, math::TAU)
}

An int goes where a float is wanted, so math::sqrt(16) works too.

Booleans

Contents

A bool is true or false. Comparisons give one, and &&, || and ! combine them.

pub fn alive(hp: int, shielded: bool) -> bool {
    hp > 0 || shielded
}

pub fn exposed(hp: int, shielded: bool) -> bool {
    !shielded && hp < 10
}

// alive(0, true) == true
// exposed(5, false) == true

A condition is a bool

if and while take a bool and nothing else. A number, a string or an optional is not a condition, so write the comparison you mean.

pub fn broken(n: int) -> int { if n { 1 } else { 0 } }

// error: 1:35: expected bool, got int
pub fn fixed(n: int) -> int { if n != 0 { 1 } else { 0 } }

// fixed(3) == 1

A bool read out of an any needs .as_bool() first.

Bools and numbers

bool as int gives 1 or 0. The other direction does not exist: write n != 0.

pub fn count(a: bool, b: bool) -> int { (a as int) + (b as int) }

// count(true, true) == 2

&& and || stop at the first side that decides, as Operators shows.

Strings

Contents

A str is UTF-8 text in double quotes. A string never changes: its methods give back new strings. A literal stays on one line, and \n writes a line break.

Interpolation

{...} inside a string writes the value of an expression. A string inside the braces keeps its own quotes. {{ and }} write the braces themselves.

const NAME = "ball";

pub fn label(hp: int, speed: float, alive: bool) -> str {
    "{NAME}: hp {hp}, speed {speed}, alive {alive}, next {hp + 1}, {{braces}}"
}

pub fn nested(words: [str]) -> str {
    "first is {words[0].to_upper()} of {words.len()}, {"say \"hi\""}"
}

// label(7, 2.0, true) == "ball: hp 7, speed 2.0, alive true, next 8, {braces}"
// nested(["ok"]) == "first is OK of 1, say \"hi\""

Every type writes itself, which makes interpolation the way to turn a value into text. A list or a struct comes out in a JSON-like form, and a nil optional as nil.

struct Point { x: int }

pub fn shown() -> str {
    let some: int? = 3;
    let none: int? = nil;
    "{some} {none} {[1, 2]} {Point { x: 1 }.x} {vec2(1.0, 2.0)}"
}

pub fn whole() -> str {
    let p = Point { x: 1 };
    "{p}"
}

// shown() == "3 nil [1, 2] 1 [1.0, 2.0]"
// whole() == "{\"x\": 1}"

Escapes

Escape Writes
\n, \t line break, tab
\", \\ quote, backslash
\u{e9} the code point, in hex
{{, }} a brace
pub fn points() -> str { "caf\u{e9}\ttwo\nlines" }

// points() == "café\ttwo\nlines"

Joining and comparing

+ joins two strings, and == and != compare them. < is not defined on strings. A number has to be interpolated, since + does not cross types.

pub fn joined(a: str, b: str) -> str { a + "-" + b }
pub fn same(a: str, b: str) -> bool { a == b }

// joined("x", "y") == "x-y"
// same("x", "x") == true

Length and offsets

len() counts bytes, and an offset is a byte offset. chars() splits by character. A string has no index: s[0] does not compile, so use slice or chars.

pub fn bytes(s: str) -> int { s.len() }
pub fn letters(s: str) -> int { s.chars().len() }
pub fn cut(s: str, a: int, b: int) -> str { s.slice(a, b) }

// bytes("héllo") == 6
// letters("héllo") == 5
// cut("hello", 1, 3) == "el"
// cut("hello", 3, 99) == "lo"

slice is forgiving: an offset past the end stops at the end, and one inside a character moves back onto it.

Bytes

bytes() gives the UTF-8 of a string as a list of ints, one byte each. encoding::from_utf8 turns such a list back into text, and answers nil when the bytes are not UTF-8.

pub fn code(s: str) -> [int] { s.bytes() }
pub fn text(data: [int]) -> str { encoding::from_utf8(data).or("?") }

// code("hé") == [104, 195, 169]
// text([104, 195, 169]) == "hé"
// text([195]) == "?"

Methods

Method Answers
len() the length in bytes
bytes() the UTF-8 bytes, as a list of ints
contains(s), starts_with(s), ends_with(s) whether the text is there
find(s) the byte offset of the first match, or -1
slice(a, b) the text between two byte offsets
replace(from, to) a copy with every match replaced
split(sep) a list of the parts
split_once(sep) the two sides of the first match, or a list of one
chars() a list of one-character strings
trim() a copy without whitespace at the ends
to_upper(), to_lower() a copy in that case, for all of Unicode
parse_int(), parse_float() the number, or 0 when the text is no number
pub fn words(s: str) -> [str] { s.split(" ") }
pub fn shout(s: str) -> str { s.trim().to_upper() }
pub fn whisper(s: str) -> str { s.to_lower() }
pub fn tagged(s: str) -> bool { s.starts_with("#") && s.contains("go") }
pub fn where_is(s: str, t: str) -> int { s.find(t) }
pub fn swap(s: str) -> str { s.replace("cat", "dog") }
pub fn path(s: str) -> str {
    let parts = s.split_once("#");
    if parts.len() == 2 { "{parts[0]}|{parts[1]}" } else { "none" }
}
pub fn sum(s: str) -> float {
    let total = 0.0;
    for part in s.split(",") {
        total += part.parse_float();
    }
    total
}

// words("a bb c") == ["a", "bb", "c"]
// shout("  hi  ") == "HI"
// whisper("ŞTEFAN") == "ştefan"
// tagged("#let's go!") == true
// where_is("hello", "ll") == 2
// where_is("hello", "x") == -1
// swap("cat and cat") == "dog and dog"
// path("a.png#tile#2") == "a.png|tile#2"
// path("a.png") == "none"
// sum("1.5, 2,x") == 3.5

parse_int and parse_float answer 0 for text that is no number. When zero is a real value as well, check the text first.

Lists

Contents

[T] is a growing list of T. Write one with [a, b, c], or [value; count] for count copies of a value.

pub fn grid() -> int {
    let row = [0; 3];
    let g = [[0; 3]; 2];
    g[1][2] = 5;
    g[1][2] + g.len() + row.len()
}

// grid() == 10

An empty list takes its type from where it goes: let xs: [int] = [];.

Reading and writing

xs[i] reads and xs[i] = v writes. Indexes start at 0, and an index past either end traps.

pub fn third(xs: [int]) -> int { xs[2] }

pub fn bumped() -> [int] {
    let xs = [1, 2, 3];
    xs[0] = 10;
    xs[1] += 5;
    xs
}

// third([7, 8, 9]) == 9
// third([7]) traps
// bumped() == [10, 7, 3]

Methods

Method Does
len() answers how many elements there are
push(v) adds to the end
pop() takes off the end and answers it; traps when empty
insert(i, v) puts v at i, moving the rest up; i may be len()
remove(i) takes out i, moving the rest down, and answers it
extend(other) adds every element of another list
sort() puts numbers or strings in order
pub fn shuffle() -> [int] {
    let xs = [1, 2, 3];
    xs.insert(0, 0);
    xs.insert(4, 4);
    xs.insert(2, 9);
    let gone = xs.remove(2);
    xs.push(gone);
    xs
}

pub fn sorted() -> [int] {
    let xs = [3, 1, 2];
    xs.extend([5, 4]);
    xs.sort();
    xs
}

// shuffle() == [0, 1, 2, 3, 4, 9]
// sorted() == [1, 2, 3, 4, 5]

There is no contains, join or slice. A loop covers them:

fn holds(xs: [int], n: int) -> bool {
    for x in xs {
        if x == n {
            return true;
        }
    }
    false
}

pub fn joined(parts: [str], sep: str) -> str {
    let out = "";
    for i in 0..parts.len() {
        if i > 0 {
            out = out + sep;
        }
        out = out + parts[i];
    }
    out
}

pub fn found() -> bool { holds([1, 2], 2) }

// found() == true
// joined(["a", "b", "c"], ", ") == "a, b, c"

Walking

for x in xs walks in order. Each x is a copy of a value type, so assigning to it leaves the list alone. To change an element, write through its index.

pub fn doubled() -> [int] {
    let xs = [1, 2];
    for x in xs {
        x = 100;
    }
    for i in 0..xs.len() {
        xs[i] *= 2;
    }
    xs
}

// doubled() == [2, 4]

Lists are shared

Assigning a list gives a second name for the same list. A function that takes a list changes the caller's. To copy, build a new one.

fn copy(xs: [int]) -> [int] {
    let out: [int] = [];
    out.extend(xs);
    out
}

pub fn lengths() -> str {
    let a = [1];
    let same = a;
    let other = copy(a);
    same.push(2);
    other.push(3);
    other.push(4);
    "{a.len()} {other.len()}"
}

// lengths() == "2 3"

A struct in a list is a value, so let p = ps[0]; copies it, and ps[0].x = 1 writes in place.

struct P { x: int }

pub fn places() -> str {
    let ps = [P { x: 1 }];
    let p = ps[0];
    p.x = 9;
    let before = ps[0].x;
    ps[0].x = 5;
    "{before} {ps[0].x}"
}

// places() == "1 5"

Mixed lists

A list of ints and floats is a [float]. A list of other mixed kinds is a [any], whose elements are read as any.

pub fn numbers() -> float { [1, 2.5][0] }
pub fn mixed() -> str {
    let row = [1, "two", true];
    "{row.len()} {row[1].as_str()}"
}

// numbers() == 1.0
// mixed() == "3 two"

== compares two lists element by element: [1, 2] == [1, 2] is true.

Maps

Contents

{str: V} and {int: V} map keys to values of one type. A key is a str or an int. A map keeps its keys in the order they were first set.

A literal takes its type from where it goes, so a map needs an annotation, a parameter or a field:

pub fn ages() -> str {
    let ages: {str: int} = { "ada": 36, "alan": 41 };
    ages["grace"] = 85;
    ages["ada"] += 1;
    "{ages}"
}

// ages() == "{\"ada\": 37, \"alan\": 41, \"grace\": 85}"

Reading

m[k] reads a V?, since the key may be missing. Use or for a fallback, or unwrap when the key must be there.

pub fn read(name: str) -> int {
    let ages: {str: int} = { "ada": 36 };
    ages[name].or(-1)
}

pub fn must(name: str) -> int {
    let ages: {str: int} = { "ada": 36 };
    ages[name].unwrap()
}

// read("ada") == 36
// read("nobody") == -1
// must("nobody") traps

m[k] = v sets a key, new or not. m[k] += 1 traps on a missing key, rather than inventing a zero.

pub fn missing() -> int {
    let ages: {str: int} = {};
    ages["nobody"] += 1;
    0
}

// missing() traps

Methods

Method Does
len() answers how many keys there are
has(k) answers whether the key is set
remove(k) takes the key out and answers its value as a V?
keys() answers a list of the keys, in order
values() answers a list of the values, in the same order
pub fn order() -> [str] {
    let scores: {str: int} = { "ada": 1, "alan": 2 };
    scores["grace"] = 3;
    scores["alan"] = 9;
    scores.remove("ada");
    scores["ada"] = 4;
    scores.keys()
}

pub fn total() -> int {
    let scores: {str: int} = { "a": 1, "b": 2 };
    let t = 0;
    for v in scores.values() {
        t += v;
    }
    t
}

pub fn gone() -> str {
    let m: {int: str} = { 1: "a" };
    let hit = m.remove(1);
    let miss = m.remove(1);
    "{hit} {miss} {m.len()}"
}

// order() == ["alan", "grace", "ada"]
// total() == 3
// gone() == "a nil 0"

Setting a key that exists keeps its place. Removing a key and setting it again moves it to the end.

Maps hold maps and objects

A map is shared like a list. A map inside a map comes out as a V?, so unwrap reaches it, and writing through it changes the inner map. A class object in a map is the same object.

pub class Player { name: str, score: int }

pub fn nested() -> int {
    let teams: {str: {str: int}} = {};
    teams["red"] = { "ada": 1 };
    teams["red"].unwrap()["alan"] = 2;
    teams["red"].unwrap().len()
}

pub fn players() -> int {
    let by_name: {str: Player} = {};
    let ada = Player { name: "ada", score: 3 };
    by_name["ada"] = ada;
    let held = by_name["ada"].unwrap();
    held.score += 4;
    ada.score
}

// nested() == 2
// players() == 7

What a map refuses

A key is a str or an int, and a value is never optional, since a missing key is how a map says nil.

pub fn floats() { let m: {float: int} = {}; }

// error: 1:32: a map's key is a `str` or an `int`, found `:`
pub fn optional() { let m: {str: int?} = {}; }

// error: 1:38: a map's value is never nil: a missing key is, found `}`

A {str: V} goes into an any and back. An {int: V} stays typed:

pub fn boxed() -> int {
    let ages: {str: int} = { "ada": 36 };
    let cell: any = ages;
    let back: {str: int} = cell;
    back["ada"].or(0)
}

// boxed() == 36

Optionals and nil

Contents

nil means no value. Most types cannot hold it: an int is always a number and a str is always text. A value that may be missing says so in its type, with ?.

fn find(xs: [str], name: str) -> int? {
    for i in 0..xs.len() {
        if xs[i] == name {
            return i;
        }
    }
    nil
}

pub fn found(name: str) -> int {
    find(["a", "b", "c"], name).or(-1)
}

// found("b") == 1
// found("z") == -1

Where nil goes

nil is a literal, like true, and it has no type of its own. It takes the type of the place it goes to, and that place is a T?, an any or a Node.

struct Bag { best: str?, count: int? }

fn takes(v: any) -> bool { v == nil }

pub fn places() -> str {
    let a: int? = nil;
    let b: any = nil;
    let bag = Bag { best: nil, count: 3 };
    "{a == nil} {b == nil} {bag.best == nil} {takes(nil)}"
}

// places() == "true true true true"

An if with nil in one branch takes the type of the other branch:

pub fn name(k: int) -> str {
    let s = if k > 0 { "pos {k}" } else { nil };
    s.or("none")
}

// name(2) == "pos 2"
// name(0) == "none"

With nothing to say what it stands for, it does not compile. The same goes for a type that can never be nil:

pub fn bare() { let x = nil; }
pub fn never(x: int) -> bool { x == nil }

// error: 1:25: `nil` needs the type it stands for: `let x: T? = nil`
// error: 2:34: a int is never nil; only a `T?` or an `any` is

Using an optional

A T? is not a T. Arithmetic and a T's methods wait until the value is out.

Write Means
x == nil, x != nil whether there is a value
x == 3 whether it holds this value
x.or(fallback) the value, or the fallback
x.unwrap() the value, or a trap
pub fn add(x: int?) -> int { x.or(0) + 1 }
pub fn must(x: int?) -> int { x.unwrap() + 1 }
pub fn is_three(x: int?) -> bool { x == 3 }

// add(4) == 5
// add(nil) == 1
// must(4) == 5
// must(nil) traps
// is_three(3) == true

The compiler says what to do when a value might be missing:

pub fn adds(x: int?) -> int { x + 1 }
pub fn measures(x: str?) -> int { x.len() }

// error: 1:33: cannot combine int? and int
// error: 2:36: this may be nil, so it has no `len`: compare it with `nil`, or a str? has `unwrap`, `or`

A check does not change the type, so inside if x != nil a variable is still a T?. Use unwrap there, or or without the check.

pub fn checked(x: int?) -> int {
    if x != nil {
        x.unwrap() + 1
    } else {
        0
    }
}

// checked(1) == 2
// checked(nil) == 0

or takes a plain value, and to chain two optionals nest the calls: first.or(second.or(0)).

An optional field left out of a literal is nil. A class holds another of itself through an optional, which is how a linked structure is written.

pub class Link { value: int, next: Link? }

pub fn second() -> int {
    let tail = Link { value: 2 };
    let head = Link { value: 1, next: tail };
    head.next.unwrap().value
}

// second() == 2

nil is not an empty map

nil holds nothing. {} in a place that wants an any is a real map with no keys, and it can be written to. They read differently, and they mean different things to the engine: a request with a nil body sends none, and one with {} sends an empty JSON object.

pub fn kinds() -> str {
    let none: any = nil;
    let empty: any = {};
    empty["hp"] = 3;
    "{none == nil} {empty == nil} {none.kind()} {empty.kind()} {empty.len()}"
}

// kinds() == "true false nil map 1"

What is refused

T?? is refused, since one nil is enough. So is any?, because an any can hold nil already. is_some, is_none, is_nil and unwrap_or do not exist, and each error says what to write:

pub fn a(x: int?) -> bool { x.is_some() }
pub fn b(x: int?) -> bool { x.is_none() }
pub fn c(x: int?) -> int { x.unwrap_or(1) }

// error: 1:30: write `x != nil`, not `x.is_some()`
// error: 2:30: write `x == nil`, not `x.is_none()`
// error: 3:29: write `x.or(v)`, not `x.unwrap_or(v)`

Node is the one type that takes nil without a ?: a Node set to nil is no node, and node.is_valid() asks. See Nodes and components.

The any type

Contents

An any holds a value whose kind is known only when the script runs: an HTTP reply, a save file, an event's payload, parsed JSON. Most code never needs one. Use it at the edge where such data comes in, and turn it into typed values as soon as you can.

Making one

Any typed value goes into an any where one is wanted. A list or a map literal in that place becomes an any list or map, whatever it holds.

struct Point { x: int, y: int }

fn spec(name: str) -> any {
    { "name": name, "size": 2.5, "tags": ["a", "b"], "at": Point { x: 1, y: 2 } }
}

pub fn built() -> str {
    let n: any = 3;
    let s: any = "text";
    let empty: any = {};
    empty["late"] = 3;
    "{n} {s} {empty} {spec("one")}"
}

// built() == "3 text {\"late\": 3} {\"name\": \"one\", \"size\": 2.5, \"tags\": [\"a\", \"b\"], \"at\": {\"x\": 1, \"y\": 2}}"

A struct goes in as a map of its fields, leaving out optional fields that are nil.

Reading

a["key"] reads a map and a[i] reads a list, and each gives another any. Reading what is not there gives nil and does not trap, so a chain of reads is safe.

pub fn reads() -> str {
    let hit: any = { "damage": 3, "tags": ["fire", "ice"] };
    let first = hit["tags"][0];
    let far = hit["tags"][5];
    let gone = hit["missing"]["deeper"];
    "{first} {far == nil} {gone == nil} {hit.has("tags")} {hit.len()}"
}

// reads() == "fire true true true 2"

There is one spelling of each. a.get("k"), a.name and a.at(0) are refused, and the error names a["k"] or a[0].

Getting a typed value out

An any is not a number or a string yet. Arithmetic, a condition, or a typed parameter asks for it to be read first.

Method Answers When it holds something else
as_int() an int, truncating a float, 1 for true 0
as_float() a float, from a float or an int 0.0
as_bool() a bool false
as_str() a str ""
as_node() a Node no node
pub fn damage(hit: any) -> int {
    hit["damage"].as_int() + hit["bonus"].as_int()
}

// damage({ "damage": 3, "bonus": 2 }) == 5
// damage({ "damage": 3 }) == 3
pub fn no_read(a: any) -> int {
    let n: int = a["n"];
    n
}
pub fn no_add(a: any) -> int { a["n"] + 1 }
pub fn no_test(a: any) -> int { if a["on"] { 1 } else { 0 } }

// error: 2:19: an `any` is no int: read it with `.as_int()`
// error: 5:39: `+` on an `any`: read it first, as with `.as_int()`
// error: 6:37: an `any` is no bool: read it with `.as_bool()`

or gives a fallback when the value is nil: a["name"].or("anon").

Into a struct, a list or a map

A whole any can go into a typed place. A struct reads its fields by name, which is the shortest way to turn a reply into checked data.

struct Player { name: str, level: int, tags: [str], title: str? }

pub fn welcome(reply: any) -> str {
    let p: Player = reply;
    "{p.name} {p.level} {p.tags.len()} {p.title == nil}"
}

pub fn numbers(reply: any) -> int {
    let scores: [int] = reply["scores"];
    scores[1]
}

// welcome({ "name": "ada", "level": 3, "tags": ["a"] }) == "ada 3 1 true"
// numbers({ "scores": [4, 5] }) == 5

A field the any lacks takes its type's empty value. The kinds of a value are not checked one by one as it goes in, so check the data when it comes from outside the game.

Looking at the kind

kind() answers "nil", "bool", "int", "float", "str", "list", "map" or "node". Compare it against types::KIND_NIL, types::KIND_MAP and their siblings.

pub fn describe(v: any) -> str {
    if v == nil {
        "nothing"
    } else if v.kind() == types::KIND_LIST {
        "{v.len()} items"
    } else {
        "{v.kind()}: {v.text()}"
    }
}

// describe(nil) == "nothing"
// describe([1, 2]) == "2 items"
// describe(3) == "int: 3"

Changing one in place

A list or a map in an any is shared, so a change is seen by everyone holding it.

Write Does
a["k"] = v sets a key of a map
a[i] = v writes an element of a list; i may be len()
push(v), insert(i, v) add to a list, and answer whether they did
remove(k) takes out a key or an index, and answers it or nil
len(), has(k), keys() answer about the size and the keys
sorted() answers an ordered copy of a list
text() answers the text form; "{a}" does the same
pub fn edited() -> str {
    let a: any = { "hp": 10 };
    let b = a;
    b["hp"] = 12;
    b["tags"] = ["x"];
    b["tags"].push("y");
    let gone = a.remove("hp");
    "{a} {gone}"
}

// edited() == "{\"tags\": [\"x\", \"y\"]} 12"

for x in a walks an any list, and a == b compares by value, with ints and floats equal by number and map keys in any order.

Vectors and colours

Contents

The engine declares three structs, available in every file:

Type Fields Made with
Vec2 x, y vec2(x, y)
Vec3 x, y, z vec3(x, y, z)
Color r, g, b, a color(r, g, b, a)
fn sum(v: Vec3) -> float { v.x + v.y + v.z }

pub fn run() -> float {
    let p = vec3(1.0, 2.0, 3.0);
    let moved = p;
    moved.x = 5.0;
    let c = color(0.1, 0.2, 0.3, 1.0);
    sum(p) + moved.x + c.a
}

// run() == 12.0

They are values, so let moved = p; copies. An int goes in as a float: vec2(1, 2) works.

Arithmetic

Operators do not apply to them. Write it out, or keep small helpers in a module.

fn add(a: Vec2, b: Vec2) -> Vec2 { vec2(a.x + b.x, a.y + b.y) }
fn scaled(v: Vec2, k: float) -> Vec2 { vec2(v.x * k, v.y * k) }

pub fn stepped() -> float {
    let p = vec2(1.0, 1.0);
    let velocity = vec2(2.0, 0.5);
    let next = add(p, scaled(velocity, 2.0));
    next.x + next.y
}

// stepped() == 7.0

One way to make one

fn from_list() -> Vec3 {
    let v: Vec3 = [1.0, 2.0, 3.0];
    v
}
fn from_literal() -> Vec2 { Vec2 { x: 1.0, y: 2.0 } }
fn by_index(v: Vec3) -> float { v.at(0) }

// error: 2:19: a Vec3 is written `vec3(..)`, not as a list
// error: 5:29: a Vec2 is written `vec2(..)`, not `Vec2 { .. }`
// error: 6:34: a Vec3 reads a field by its name, as `v.x`

Transforms

Two more hold a placement: the axes, then the origin. They are values too, written with their fields.

Type Fields
Transform2d x, y, origin, each a Vec2
Transform3d x, y, z, origin, each a Vec3
pub fn placed() -> float {
    let at = Transform2d { x: vec2(2.0, 0.0), y: vec2(0.0, 2.0), origin: vec2(4.0, 5.0) };
    at.x.x + at.origin.y
}

// placed() == 7.0

Inside an any

In an any a vector is a list of its numbers, the form a scene file and a component use, and a transform is a map of its axes. A vector reads back at a typed place from a list or from a map of its fields.

struct Ray { origin: Vec3, tint: Color? }

pub fn read() -> str {
    let listed: any = { "origin": [1.0, 2.0, 3.0], "tint": [0.5, 0.5, 0.5, 1.0] };
    let named: any = { "origin": { "x": 4.0, "y": 5.0, "z": 6.0 } };
    let a: Ray = listed;
    let b: Ray = named;
    "{a.origin.y} {a.tint.unwrap().a} {b.origin.z} {b.tint == nil}"
}

// read() == "2.0 1.0 6.0 true"

Conversions

Contents

Nothing changes type by itself, with one exception: an int meets a float as a float. Everything else has one spelling.

From To Write
int float nothing, or x as float
float int x as int, dropping the fraction
bool int x as int, 1 or 0
int bool x != 0
anything str "{x}"
str int, float s.parse_int(), s.parse_float(), 0 when it is no number
T T? nothing
T? T x.or(fallback), x.unwrap()
anything any nothing
any int, float, bool, str, Node .as_int(), .as_float(), .as_bool(), .as_str(), .as_node()
any a struct, a list, a map, a T?, a fn nothing, at a typed place
pub fn from_float(x: float) -> int { x as int }
pub fn from_bool(b: bool) -> int { b as int }
pub fn to_text(n: int) -> str { "{n}" }
pub fn from_text(s: str) -> int { s.parse_int() }

// from_float(2.9) == 2
// from_bool(true) == 1
// to_text(7) == "7"
// from_text("12") == 12
// from_text("twelve") == 0

as covers numbers and bools, and nothing else:

pub fn a() -> int { "1" as int }
pub fn b() -> str { 1 as str }
pub fn c() -> bool { 1 as bool }
pub fn d(n: float) -> int { n.as_int() }
pub fn e(n: int) -> str { n.as_str() }

// error: 1:25: cannot cast str as int
// error: 2:23: cannot cast int as str
// error: 3:24: cannot cast int as bool
// error: 4:30: a float becomes an int as `x as int`, not `x.as_int()`
// error: 5:28: a value becomes text as `"{x}"`, not `x.as_str()`

.as_int() and its siblings belong to any, which is the one type whose kind is not known until the code runs.

Structs

Contents

A struct groups named fields into one value. It has no methods, and it copies when assigned or passed, so it suits small data: a hit, a tile, a row of a table.

struct Hit {
    damage: int,
    source: str,
    tags: [str],
}

fn total(hits: [Hit]) -> int {
    let sum = 0;
    for h in hits {
        sum += h.damage;
    }
    sum
}

pub fn run() -> int {
    let a = Hit { damage: 3, source: "fire", tags: [] };
    let b = Hit { damage: 4, source: "ice", tags: ["cold"] };
    total([a, b])
}

// run() == 7

Defaults and optional fields

A literal names what differs from the declaration. A field left out takes its default, and an optional or any field left out is nil. Any other field has to be named.

pub struct Label {
    kind: str = "label",
    size: int = 3,
    text: str,
    tip: str?,
    data: any,
}

pub fn plain() -> str {
    let label = Label { text: "hi" };
    "{label.kind} {label.size} {label.text} {label.tip == nil} {label.data == nil}"
}

pub fn sized() -> int { Label { text: "x", size: 9 }.size }

// plain() == "label 3 hi true true"
// sized() == 9
struct Label { text: str }

pub fn broken() { let l = Label {}; }

// error: 3:27: missing field `text` of Label: name it, or declare its default in Label

A default is a literal: a number, a bool or a string. For a list or a vector, name it in the literal, or write a function that builds the struct.

struct Enemy { hp: int, path: [Vec2], at: Vec2 }

fn enemy(hp: int) -> Enemy {
    Enemy { hp: hp, path: [], at: vec2(0.0, 0.0) }
}

pub fn fresh() -> int {
    let e = enemy(5);
    e.path.push(vec2(1.0, 1.0));
    e.hp + e.path.len()
}

// fresh() == 6

Each field is named in full: Label { text } and Label { size: 1, ..other } do not compile.

A struct is a value

Assigning a struct copies its fields, and so does passing it. Writing to the copy leaves the original alone. A field written through a variable changes that variable's struct.

struct Inner { n: int }
struct Outer { inner: Inner, tags: [str] }

fn weaken(o: Outer) { o.inner.n = 0; }

pub fn run() -> str {
    let a = Outer { inner: Inner { n: 1 }, tags: [] };
    let b = a;
    b.inner.n = 5;
    a.inner.n += 1;
    weaken(a);
    b.tags.push("t");
    "{a.inner.n} {b.inner.n} {a.tags.len()}"
}

// run() == "2 5 1"

A copy is shallow. a and b hold their own numbers and share the one tags list, since a list is shared by whatever holds it.

To let a function change the caller's struct, use an &mut parameter.

Comparing and printing

== compares two structs field by field, and "{s}" writes one as a map of its fields.

struct P { x: int, name: str }

pub fn same() -> bool { P { x: 1, name: "a" } == P { x: 1, name: "a" } }
pub fn shown() -> str {
    let p = P { x: 1, name: "a" };
    "{p}"
}

// same() == true
// shown() == "{\"x\": 1, \"name\": \"a\"}"

What a struct refuses

A struct cannot contain itself by value, since it would never end. Through a list it can. impl does not apply, so a function takes the struct instead, or the struct becomes a class.

struct Tree { kids: [Tree] }

pub fn run() -> int {
    let t = Tree { kids: [Tree { kids: [] }] };
    t.kids.len()
}

// run() == 1
struct A { a: A }

// error: 1:1: struct A contains itself through `a`; put it in an array, or make it a class
pub struct S { x: int }
impl S { fn m() -> int { 1 } }

// error: 2:10: `impl S`: a struct has no methods; make it a `class`, or write a function that takes it

Classes

Contents

A class is written like a struct, and works differently: there is one object, and everyone holding it holds the same one. A class is also the type that has methods.

pub class Counter {
    count: int,
    step: int = 1,
}

impl Counter {
    pub fn bump() {
        self.count += self.step;
    }

    pub fn bump_twice() -> int {
        self.bump();
        self.bump();
        self.count
    }
}

pub fn run() -> int {
    let c = Counter { count: 0 };
    c.bump_twice()
}

// run() == 2

One object

Assigning an object, passing it or storing it adds a holder and copies nothing. A change through one holder is seen by all of them.

pub class Player { name: str, score: int }

fn award(p: Player) { p.score += 10; }

pub fn run() -> int {
    let ada = Player { name: "ada", score: 0 };
    let same = ada;
    let team = [ada];
    award(same);
    team[0].score += 1;
    for member in team {
        member.score += 1;
    }
    ada.score
}

// run() == 12

== still compares by fields, so two objects with equal fields are equal.

Making objects

A class has no static functions and no constructors. A plain function is the constructor, and the usual name is new, called from another file as enemy::new(5).

pub class Enemy { hp: int, path: [Vec2] }

pub fn new(hp: int) -> Enemy {
    Enemy { hp: hp, path: [] }
}

pub fn run() -> int { new(3).hp }

// run() == 3
class C { n: int }
impl C { fn make() -> int { 1 } }

pub fn broken() -> int { C::make() }

// error: 4:26: the engine has no `C::make`

A class holds another of itself through an optional or a list. That is how trees, chains and graphs are written.

pub class Tree { value: int, kids: [Tree], parent: Tree? }

fn leaf(value: int) -> Tree {
    Tree { value: value, kids: [] }
}

fn total(t: Tree) -> int {
    let sum = t.value;
    for kid in t.kids {
        sum += total(kid);
    }
    sum
}

pub fn run() -> int {
    let root = leaf(1);
    root.kids.push(leaf(2));
    root.kids.push(leaf(3));
    total(root)
}

// run() == 6

Directly, it would never end:

pub class N { next: N }

// error: 1:1: struct N contains itself through `next`; make it `N?`

Two objects that hold each other are never freed, as Memory explains.

Struct or class

Pick a struct when Pick a class when
it is a small piece of data it has an identity that things refer to
a copy is what you want several holders must see the same changes
no methods are needed methods belong on it
it is passed around often and small it is big, since an object passes as one pointer

A script on a node is always a class. See Scripts on nodes.

What is left out

There is no inheritance, no interface and no generic. A field of function type, or an enum with a variant per kind, covers what those usually do.

Enums

Contents

An enum is a value that is exactly one of its variants. A variant carries nothing, values by position, or named fields.

enum Shape {
    Circle(float),
    Rect { w: float, h: float },
    Empty,
}

fn area(s: Shape) -> float {
    match s {
        Shape::Circle(r) => r * r * 3.0,
        Shape::Rect { w, h } => w * h,
        Shape::Empty => 0.0,
    }
}

pub fn run() -> float {
    let shapes = [Shape::Circle(2.0), Shape::Rect { w: 2.0, h: 3.5 }, Shape::Empty];
    let total = 0.0;
    for s in shapes {
        total += area(s);
    }
    total
}

// run() == 19.0

Making one

A variant is written by its path, in the form it was declared.

enum Light { Red, Green }
enum Pair { Two(int, int) }
enum Size { Box { w: int, h: int } }

pub fn run() -> int {
    let l = Light::Red;
    let p = Pair::Two(1, 2);
    let s = Size::Box { w: 3, h: 4 };
    let same = l == Light::Red;
    if same { 1 } else { 0 }
}

// run() == 1

The compiler holds each form to its declaration:

Written Refused with
Light::Red(1) `Light::Red` carries nothing: write `Light::Red`
Pair::Two(1) `Pair::Two` takes 2 values, given 1
Pair::Two `Pair::Two` carries values: `Pair::Two(..)`
Size::Box(1) `Size::Box` has named fields: write `Size::Box { .. }`
Size::Box { w: 1 } missing field `h` of `Size::Box`
Light {} `Light` is an enum: make one with `Light::Variant`

What goes inside

A variant can carry any type: a struct, a list, an optional, an any, a class object or another enum. match is the only way to read what it carries.

struct Point { x: int, y: int }
enum Hit { Miss, At(Point), Maybe(int?), Raw(any) }
enum Turn { Move(Hit), Pass }
struct Board { last: Turn, hits: [Hit] }

fn score(h: Hit) -> int {
    match h {
        Hit::At(p) => p.x * 10 + p.y,
        Hit::Maybe(n) => n.or(-1),
        Hit::Raw(a) => a.len(),
        Hit::Miss => 0,
    }
}

pub fn board() -> int {
    let b = Board {
        last: Turn::Move(Hit::At(Point { x: 2, y: 5 })),
        hits: [Hit::Miss, Hit::Maybe(nil), Hit::Maybe(4), Hit::Raw([1, 2, 3])],
    };
    let total = 0;
    for h in b.hits {
        total += score(h);
    }
    total
}

// board() == 6

An enum is a value

An enum copies as a struct does, and == compares two of them. Since it is a value, it cannot hold itself directly. A recursive shape goes through a list or a class.

enum Tree { Leaf, Branch([Tree]) }

fn count(t: Tree) -> int {
    match t {
        Tree::Leaf => 1,
        Tree::Branch(kids) => {
            let sum = 0;
            for k in kids {
                sum += count(k);
            }
            sum
        }
    }
}

pub fn run() -> int {
    count(Tree::Branch([Tree::Leaf, Tree::Branch([Tree::Leaf])]))
}

// run() == 2

An enum in another file reads by its path: shapes::Shape::Circle(1.0).

Pattern matching

Contents

match takes an enum apart, or compares a value with each arm. On an enum, each arm names a variant and binds what it carries.

enum Shape { Circle(float), Rect { w: float, h: float }, Empty }

fn name(s: Shape) -> str {
    match s {
        Shape::Circle(r) => "circle {r}",
        Shape::Rect { w, h: tall } => "rect {w}x{tall}",
        _ => "nothing",
    }
}

pub fn run() -> str {
    "{name(Shape::Circle(1.5))} {name(Shape::Rect { w: 1.0, h: 2.0 })} {name(Shape::Empty)}"
}

// run() == "circle 1.5 rect 1.0x2.0 nothing"

Patterns

Pattern Takes
Shape::Empty that variant
Shape::Circle(r) that variant, binding its value to r
Shape::Circle(_) that variant, binding nothing
Shape::Rect { w, h } that variant, binding fields by name
Shape::Rect { w, h: tall } the same, with h bound as tall
Shape::Rect { w, h: _ } the same, ignoring h
Shape::Circle(_) | Shape::Empty either variant, binding nothing
"go", 3, -1, true, nil that value
STOP, verbs::STOP the value of that constant
"left" | "right" either value
_ any value
other any value, binding it to other, unless a constant is named other

A pattern stops at one level, so bind the inner enum and match it again. An arm has no if guard.

enum Inner { A(int), B }
enum Outer { X(Inner), Y }

pub fn read(o: Outer) -> int {
    match o {
        Outer::X(inner) => match inner {
            Inner::A(n) => n,
            Inner::B => -1,
        },
        Outer::Y => 0,
    }
}

pub fn run() -> int { read(Outer::X(Inner::A(7))) + read(Outer::Y) }

// run() == 7

Matching a value

A match on a string, an int, a bool or an optional compares the subject with each arm in order. The last arm takes whatever no arm named. A float is no pattern, since two floats seldom compare equal.

const STOP: str = "stop";

fn verb(name: str) -> str {
    match name {
        "go" => "walk",
        STOP => "halt",
        "left" | "right" => "turn",
        other => "no verb {other}",
    }
}

pub fn run() -> str { "{verb("go")}, {verb("stop")}, {verb("left")}, {verb("fly")}" }

// run() == "walk, halt, turn, no verb fly"

A bare name compares with the constant of that name, and binds when no constant has it. A | joins values or variants, and none of its alternatives binds a name.

pub fn f(s: str) -> int { match s { "a" => 1, "b" => 2 } }

// error: 1:27: a `match` on a value ends with an arm that takes any value: `_ => ..`
pub fn f(s: str) -> int { match s { "a" => 1, "b" | "a" => 2, _ => 3 } }

// error: 1:47: `"a"` is matched twice

Every variant is covered

A match names every variant once, or ends with an arm that takes any value. Adding a variant makes the compiler point at each match that misses it.

enum Shape { Circle(float), Rect { w: float, h: float }, Empty }
pub fn f(s: Shape) -> int { match s { Shape::Circle(r) => 1, Shape::Empty => 2 } }

// error: 2:29: this `match` misses `Shape::Rect`
enum Light { Red, Green }
pub fn twice(l: Light) -> int { match l { Light::Red => 1, Light::Red => 2, Light::Green => 3 } }

// error: 2:60: `Light::Red` is matched twice
enum Light { Red, Green }
pub fn late(l: Light) -> int { match l { _ => 1, Light::Red => 2 } }

// error: 2:42: an arm after one that takes any value is never reached

A match is a value

Each arm gives a value, and they must agree. An arm that needs several lines takes a block, whose last expression is its value.

enum Light { Red, Green }

pub fn wait(red: bool) -> int {
    let light = if red { Light::Red } else { Light::Green };
    let seconds = match light {
        Light::Red => {
            let base = 2;
            base * 15
        }
        Light::Green => 0,
    };
    seconds + 1
}

// wait(true) == 31
// wait(false) == 1

Leaving from an arm

An arm may return, break or continue. The subject is worked out once, before the arms.

enum Event { Key(str), Click { x: int, y: int }, Tick }

fn first_click(events: [Event]) -> int {
    for e in events {
        match e {
            Event::Click { x, y: _ } => { return x; }
            _ => { continue; }
        }
    }
    -1
}

pub fn clicks() -> str {
    let a = first_click([Event::Tick, Event::Key("k"), Event::Click { x: 7, y: 1 }]);
    let b = first_click([Event::Tick]);
    "{a} {b}"
}

// clicks() == "7 -1"

In an async fn, an arm of a match statement may also await.

Function values

Contents

A function is a value. Its name without a call gives the value, and fn(A, B) -> R is its type.

fn double(x: int) -> int { x * 2 }
fn square(x: int) -> int { x * x }
fn apply(f: fn(int) -> int, x: int) -> int { f(x) }

pub fn twice(k: int) -> int {
    let f = double;
    let g: fn(int) -> int = square;
    apply(f, k) + apply(g, k)
}

pub fn table(k: int) -> int {
    let fs = [double, square, double];
    let t = 0;
    for f in fs {
        t += f(k);
    }
    t
}

// twice(5) == 35
// table(3) == 21

Storing one

A function value goes in a local, a list, a map, a field or an any. A call goes through a local, so take the value out first.

fn square(x: int) -> int { x * x }

pub class Picker { pick: fn(int) -> int }

impl Picker {
    pub fn run(x: int) -> int {
        let f = self.pick;
        f(x)
    }
}

pub fn picked(k: int) -> int {
    let p = Picker { pick: square };
    p.run(k)
}

pub fn from_map() -> int {
    let named: {str: fn(int) -> int} = { "sq": square };
    let f = named["sq"].unwrap();
    f(3)
}

pub fn from_any() -> int {
    let v: any = { "f": square };
    let f: fn(int) -> int = v["f"];
    f(4)
}

// picked(6) == 36
// from_map() == 9
// from_any() == 16

No closures

A function value names a function, and nothing more. It captures no variables, since there are no closures. Where a callback needs state, pass the state in, as the second function here does:

struct Tally { sum: int }

fn add(t: &mut Tally, n: int) { t.sum += n; }

fn each(xs: [int], t: &mut Tally, f: fn(&mut Tally, int)) {
    for x in xs {
        f(t, x);
    }
}

pub fn run() -> int {
    let t = Tally { sum: 0 };
    each([1, 2, 3], t, add);
    t.sum
}

// run() == 6

The engine calls back by name instead: a listener names a method.

What is a value

Only a plain function of the script is. A method, an engine function and an async fn are not, and the types must match exactly.

pub class S { x: int }
impl S { fn m() -> int { 1 } }
fn one() -> int { 1 }
async fn wait_a_bit() -> int { 1 }

pub fn method() -> int { let g = S.m; 1 }
pub fn not_a_function(x: int) -> int { x(1) }
pub fn wrong_type() -> int { let g: fn(int) -> int = one; 1 }
pub fn async_one() -> int { let g = wait_a_bit; 1 }

// error: 6:34: unknown name `S`
// error: 7:40: `x` is a int, not a function
// error: 8:54: expected fn(int) -> int, got fn() -> int
// error: 9:37: only a script's own plain function can be a `fn` value; `wait_a_bit` is not one

References with &mut

Contents

A struct or a number arrives as a copy. &mut before a parameter's type makes it the caller's own value: changes are written back to the caller's variable or field when the function returns.

struct Wave { hp: int }

fn grow(w: &mut Wave) { w.hp += 1; }
fn weaken(w: Wave) { w.hp = 0; }
fn inc(n: &mut int) { n += 1; }

pub fn run() -> str {
    let w = Wave { hp: 1 };
    grow(w);
    grow(&mut w);
    weaken(w);
    let n = 1;
    inc(n);
    "{w.hp} {n}"
}

// run() == "3 2"

At the call grow(w) and grow(&mut w) mean the same, and the second is there for readers who want to see it.

What can be passed

The argument is a place that can be written to: a variable, or a field of one, self's fields included.

struct Tally { hits: int }
class Editor { tally: Tally, count: int }

fn bump(t: &mut Tally) { t.hits += 1; }
fn inc(n: &mut int) { n += 1; }

impl Editor {
    pub fn click() -> int {
        bump(self.tally);
        inc(self.count);
        self.tally.hits + self.count
    }
}

pub fn run() -> int {
    let e = Editor { tally: Tally { hits: 0 }, count: 0 };
    e.click()
}

// run() == 2

A literal, a call's result or a list element has no place to write back to:

pub struct I { n: int }
fn bump(i: &mut I) { i.n += 1; }
fn inc(n: &mut int) { n += 1; }

pub fn a() { bump(I { n: 1 }); }
pub fn b() { let xs = [1]; inc(xs[0]); }

// error: 5:19: `bump` changes this argument: pass a variable or a field
// error: 6:34: `inc` changes this argument: pass a variable or a field

For an element of a list, read it, pass the local, and write it back. Or write through the index.

One place, once

One place is never handed to two &mut parameters of one call, since the second write would undo the first.

pub struct I { n: int }
fn two(a: &mut I, b: &mut I) {}
pub struct E { a: I }
pub fn f(e: E) { two(e.a, e.a); }

// error: 4:28: `two` would change this twice: it is part of another `&mut` argument

When you do not need it

A class object and a list are shared already, so a plain parameter changes them. &mut on one of those lets the function replace the whole thing.

class C { n: int }

fn change(c: C) { c.n = 5; }
fn replace(c: &mut C) { c = C { n: 9 }; }

pub fn run() -> str {
    let a = C { n: 1 };
    change(a);
    let first = a.n;
    replace(a);
    "{first} {a.n}"
}

// run() == "5 9"

Limits

pub struct I { n: int }
async fn w(i: &mut I) {}

// error: 2:12: an `async fn` takes no `&mut` parameter: its caller runs on while it waits

Modules

Contents

A file is a module. use name; links name.bs, and its pub items read as name::item.

// util.bs
pub class Rect { pub w: float, pub h: float }

impl Rect {
    pub fn area() -> float { self.w * self.h }
}

pub const SCALE: float = 2.0;

pub fn grow(r: Rect) -> Rect {
    Rect { w: r.w * SCALE, h: twice(r.h) }
}

fn twice(x: float) -> float { x * 2.0 }
use util;

pub fn area() -> float {
    let r = util::grow(util::Rect { w: 1.0, h: 2.0 });
    r.area() + util::SCALE
}

// area() == 10.0

Who may name what

Every function, constant, struct, class, enum, field and method has one of three reaches.

Written Who may name it
nothing its own file
internal every file of its package
pub every file

A file's package is the addons/<name> or deps/<alias> folder it sits in, or else the project.

// secrets.bs
fn hidden() -> int { 1 }

pub class Vault {
    pub id: int = 1,
    code: int = 42,
}

impl Vault {
    pub fn label() -> str { self.mask() }
    fn mask() -> str { "#{self.id}" }
}
use secrets;

pub fn broken() -> int { secrets::hidden() }

// error: 3:26: `hidden` is private to `secrets`: mark it `pub` there

A field and a method follow the same rule, and a literal may not set a field its file keeps.

use secrets;

pub fn peek(v: secrets::Vault) -> int { v.code }
pub fn open(v: secrets::Vault) -> str { v.mask() }
pub fn make() -> secrets::Vault { secrets::Vault { code: 7 } }

// error: 3:42: `Vault.code` is private to `secrets`: mark it `pub` there
// error: 4:42: `Vault.mask` is private to `secrets`: mark it `pub` there
// error: 5:35: `Vault.code` is private to `secrets`: mark it `pub` there

internal opens an item to the other files of its addon, and no further.

// addons/kit/core.bs
internal fn seed() -> int { 7 }
pub fn roll() -> int { seed() + 1 }
use addons::kit::core;

pub fn open() -> int { core::roll() }
pub fn broken() -> int { core::seed() }

// error: 4:26: `seed` is internal to `addons/kit`: mark it `pub` there

pub says more than the others on two things. A pub free function is one the engine may call, and a pub field with a default is a property a scene tunes. A field other files read and no scene should set is internal.

The engine and node.call reach a method by its name as the script runs, so its hooks need no mark.

How a file is found

use util; looks for util.bs beside the file, then in each folder above it, up to the project root. use a::b; is a/b.bs, and its items read as b::name.

Written File Items read as
use util; util.bs util::clamp
use combat::damage; combat/damage.bs damage::roll
use addons::gamend::core; addons/gamend/core.bs core::query

Files may use each other in a circle, and a file may use the file that uses it.

Scripts and modules

A file with a class named after it can be attached to a node, and it is a script. A file without one is a plain module that others use. A script's other items are a module too, so use spinner; works from another script.

Types across files

A type reads by its path in every position: in a literal, in a signature and in a pattern.

// shapes.bs
pub enum Shape { Circle(float), Empty }
use shapes;

fn area(s: shapes::Shape) -> float {
    match s {
        shapes::Shape::Circle(r) => r * r,
        shapes::Shape::Empty => 0.0,
    }
}

pub fn run() -> float { area(shapes::Shape::Circle(2.0)) }

// run() == 4.0

Engine modules

log::, math::, input:: and the rest need no use. They come with the engine, every call is typed against it, and the script modules reference lists them. A call the engine does not have stops at compile time.

pub fn broken() { nope::call(); }

// error: 1:19: the engine has no `nope::call`

Some functions are the editor's: all of debugger, script, project and export, and the verbs of dependency that write a project. The reference marks each one. Only a file of the editor, or one under a game's or an addon's editor/ folder, may call them. A game's runtime does not have them, so a call from any other file stops at compile time. For the same reason a game's file may not use one of the editor's files.

Saving

Saving a module reloads every script that uses it, and each object keeps its fields across the reload.

Async and await

Contents

An async fn can stop in the middle, wait for something, and pick up on a later frame. The game keeps running meanwhile. This is what a cutscene, a cooldown or a network call wants.

// scripts/door.bs
pub class Door {
    node: Node,
    open: bool,
}

impl Door {
    pub async fn init() {
        log::info("opening in two seconds");
        await task::seconds(2.0);
        self.open = true;
        await task::frames(1);
        log::info("open");
    }
}

What can wait

Await Resumes
task::seconds(t) after t seconds of simulation time, on the fixed step ceil(t * tick_hz)
task::frames(n) after n frames
task::wait(token) when an engine call finishes, with its result as an any
another script async fn when it returns, with its value

An engine call that takes time answers with a token, and task::wait waits for it.

// scripts/fetch.bs
pub class Fetch {
    node: Node,
}

impl Fetch {
    pub async fn init() {
        let reply = await task::wait(http::request("https://example.com/status"));
        log::info("{reply["status"]}");
        let next = await self.count_down(3);
        log::info("{next}");
    }

    async fn count_down(from: int) -> str {
        let n = from;
        while n > 0 {
            await task::seconds(1.0);
            n -= 1;
        }
        "done"
    }
}

Where it may go

await goes in an async fn, as a statement, a let or an assignment, and in the arm of a match statement. To use a result inside a larger expression, bind it first.

async fn ready() -> bool { true }

pub async fn broken() -> int {
    if await ready() { 1 } else { 2 }
}

// error: 4:5: write `let v = await ..;` and then `return v;`
async fn ready() -> bool { true }

pub async fn fixed() -> int {
    let r = await ready();
    if r { 1 } else { 2 }
}

An async function can be called only with await, and only from another async fn:

async fn f() -> int { 1 }

pub fn missing_await() -> int { f() }

// error: 3:33: `f` is async: `await f(..)` inside an `async fn`

Which hooks may wait

init and an event handler may be async. update and fixed_update run every frame and may not. Start the waiting from init or a handler, and let update read what it left behind.

Rules

Memory

Contents

There is no garbage collector and nothing to free by hand. Values are copied or counted, and a counted one is freed the moment its last holder goes. Nothing a game sees depends on when a collector runs, and no frame pauses for one.

Copied values

int, float, bool, vectors, colours, structs and enums are values. They live where they are declared, and assigning one copies it. A Vec3 or a small struct costs no allocation.

Counted values

str, lists, maps, class objects and what an any holds live on the heap with a count of their holders. A second holder adds to the count and copies nothing. When the count reaches zero the value is freed, and whatever it held loses a holder too.

struct Item { name: str, tags: [str] }

pub fn kept(n: int) -> int {
    let items: [Item] = [];
    for i in 0..n {
        let tags = ["a", "b"];
        tags.push("tag {i}");
        items.push(Item { name: "item {i}", tags: tags });
    }
    let last = items[n - 1];
    items = [];
    last.tags.len()
}

// kept(50) == 3

Here items = []; frees the old list and everything only it held. last is a copy of the struct, and it keeps its share of that item's strings and its tags list.

Copies are shallow

A struct's copy holds its own numbers, and it shares the lists and objects inside it.

struct P { x: int, tags: [str] }

pub fn run() -> str {
    let p = P { x: 1, tags: [] };
    let q = p;
    q.x = 2;
    q.tags.push("t");
    "{p.x} {p.tags.len()}"
}

// run() == "1 1"

Cycles

Counting cannot free a ring: two class objects that hold each other keep each other's count above zero. A list or an any that holds itself does the same. That memory is never freed, so break the link yourself when you are done, or let one side refer to the other by id.

pub class Peer { name: str, other: Peer? }

pub fn linked() -> str {
    let a = Peer { name: "a" };
    let b = Peer { name: "b", other: a };
    a.other = b;
    let read = a.other.unwrap().name;
    a.other = nil;
    read
}

// linked() == "b"

Limits

A script's module grows to 256 MiB at most, and an allocation past that traps. The instance runs its next call as before. Errors and traps has the full list.

Large state

A struct passes as a copy of every field, and a class object as one pointer. Keep a large piece of state in a class, and pass it freely. The editor's own state is written this way.

Errors and traps

Contents

There is no exception and no try. A problem shows up in one of three ways.

Kind When What happens
Compile error on save or at balaur check the old code keeps running
Trap at run time, on a bug the call ends, and the next call runs
An answer of nil or false at run time, on an expected failure the caller checks it

Compile errors

An error names its line and column, and often what to write instead. A file reports one error for each function that does not compile.

pub fn f() -> int {
    let x = 1;
    x + true
}
fn g() { let s: str = 3; }
fn h() { nope(); }

// error: 3:7: cannot combine int and bool
// error: 5:23: expected str, got int
// error: 6:10: unknown function `nope`

Every engine call is typed too, so a misspelled one stops at compile time rather than on the frame it runs.

Traps

A trap stops the running call at once. The line goes to the log, and the rest of the game goes on. The object keeps its fields as they were when the call stopped, and its next call runs as usual.

What traps Example
An index past either end of a list xs[9]
pop on an empty list, remove out of range xs.pop()
unwrap on nil x.unwrap()
An int divided by zero, / or % n / 0
The smallest int divided by -1
+= on a missing map key ages["nobody"] += 1
Too much memory, too deep a recursion
pub fn first(xs: [int]) -> int { xs[0] }
pub fn must(x: int?) -> int { x.unwrap() }
pub fn split(n: int) -> int { 100 / n }

// first([]) traps
// must(nil) traps
// split(0) traps
// first([3]) == 3

A trap is a bug to fix, and nothing in a script catches one. In the editor, break on error stops at the line with every variable as it was. See Debugging.

Expected failures

Where failure is a normal outcome, the call answers it and the caller decides. An optional is the usual form: m[k] reads nil for a missing key, and find answers -1.

fn parse_level(text: str) -> int? {
    let n = text.parse_int();
    if n > 0 { n } else { nil }
}

pub fn level(text: str) -> int {
    parse_level(text).or(1)
}

// level("7") == 7
// level("oops") == 1

Your own functions should do the same, with T? or an enum for more detail.

enum Loaded { Ok(str), Missing, Bad { line: int } }

fn describe(l: Loaded) -> str {
    match l {
        Loaded::Ok(text) => text,
        Loaded::Missing => "no file",
        Loaded::Bad { line } => "bad line {line}",
    }
}

pub fn run() -> str { describe(Loaded::Bad { line: 4 }) }

// run() == "bad line 4"

Engine calls

An engine call that fails ends the script's call and logs the error, like a trap. Where failure is expected, the engine answers instead: node.patch_component answers false, toml::parse answers nil. Check those, and write log::error when something is worth reporting.

Scripts on nodes

Contents

A script is a pub class named after its file, with door_bell.bs holding DoorBell. Each node the file is attached to gets one object of the class, and the object lives as long as the node does.

// scripts/spinner.bs
pub class Spinner {
    pub speed: float = 2.0,
    pub clockwise: bool = true,
    node: Node,
    angle: float,
    direction: float,
}

impl Spinner {
    fn init() {
        self.angle = 0.0;
        self.direction = if self.clockwise { 1.0 } else { -1.0 };
    }

    fn update(dt: float) {
        if input::action_just_pressed("reverse") {
            self.direction = -self.direction;
        }
        self.angle += dt * self.speed * self.direction;
        self.node.transform.rotation_euler = vec3(0.0, self.angle, 0.0);
    }
}
[[nodes]]
name = "Spinner"
script = { source = "scripts/spinner.bs" }

Hooks

The engine calls these methods when the class declares them.

Hook When
init() once, after the properties are written
update(dt: float) once a frame, with the measured frame time
fixed_update(dt: float) on the fixed 60 Hz step, before physics
on_free() before the node or the script goes

Simulation belongs in fixed_update, which is what keeps a replay identical. Drawing and input feel belong in update. See Determinism.

A scene inits children before parents.

Methods the engine calls by name

Any other method is yours. The engine also calls one by name when something names it: a binding row in a scene, or on_hit for an event. A button with this row calls pressed on the nearest node from its own up whose script has it:

bindings = { rows = [{ event = "pointer_click", action = "call", value = "pressed" }] }

The method is handed the event's value and then the node the row sits on, and may name neither.

// scripts/menu.bs
pub class Menu {
    node: Node,
    presses: int,
}

impl Menu {
    pub fn pressed() {
        self.presses += 1;
        log::info("pressed {self.presses} times");
    }
}

Reloading

Saving a script recompiles it, and each object carries over every field that kept its name and type. A field the new code adds starts at its default, and a field it dropped goes. A field holding a fn still names the same function, found by its name in the new code, and holds none once the new code drops it. A running task does not carry over.

Exported properties

Contents

A pub field with a literal default is a property. The inspector shows it, and a scene sets it per node.

// scripts/turret.bs
pub class Turret {
    pub range: float = 12.0,
    pub burst: int = 3,
    pub armed: bool = true,
    pub label: str = "turret",
    pub target: Node,
    node: Node,
}

impl Turret {
    fn init() {
        log::info("{self.label} covers {self.range}");
    }
}
[[nodes]]
name = "Turret"

[nodes.script]
source = "scripts/turret.bs"

[nodes.script.props]
range = 20.0
target = "../Enemy"

Nodes as properties

A pub field of type Node takes a path, resolved from the scripted node once the whole scene exists. A path naming nothing gives no node, which is_valid() tells apart, and a warning naming the field and the path. A [Node] field takes a list of paths.

At run time

node.attach_script(path, props) does the same on a running node.

pub fn arm(node: Node) {
    node.attach_script("scripts/turret.bs", { "range": 5.0 });
}

Nodes and components

Contents

Node is a handle to a node of the scene. Its operations are methods, and each of its components is a field.

Finding nodes

pub fn look(node: Node) {
    let world = scene::root().get_node("World");
    let enemy = node.get_node("../Enemy");
    let parent = node.parent();
    for child in node.children() {
        log::info(child.name());
    }
    if enemy.is_valid() {
        log::info(enemy.path());
    }
}

A lookup that finds nothing answers no node rather than failing, and is_valid() tells them apart. So does a node that has been freed, which makes the check worth keeping in a field you hold across frames.

Properties

A component's properties read and write as fields, checked against its schema at compile time. A misspelled property does not compile.

pub fn lift(node: Node) {
    let p = node.transform.position;
    node.transform.position = vec3(p.x, p.y + 1.0, p.z);
    node.transform.rotation_euler = vec3(0.0, math::to_radians(90.0), 0.0);
}

Rotations are in radians, and the inspector shows degrees.

Operations

A component's operations are methods on its field. The component reference lists them.

pub fn kick(node: Node) {
    node.body2d.apply_impulse(vec2(0.0, 12.0));
    if node.body2d.linear_velocity().x > 5.0 {
        node.body2d.set_linear_velocity(vec2(5.0, 0.0));
    }
}

Whole components

Where a component's name is computed, or several keys change at once, pass an any map.

pub fn make_solid(node: Node) {
    node.set_component("body3d", { "kind": physics3d::BODY_DYNAMIC });
    node.patch_component("body3d", { "mass": 2.0, "gravity_scale": 0.5 });
}

set_component replaces a component, and patch_component changes the keys it names. patch_component answers false, and logs why, where the component refuses the value.

Other scripts

There are three ways to reach another script.

Way Written For
Typed let tree: scene_tree::SceneTree? = node.script; a script whose class you know
By name node.call("method", arg) any node, checked at run time
By event self.node.emit("hit", payload) whoever is listening

The typed form answers nil when the node runs another class. On a match, a call on it is a direct call, with its types checked.

// scripts/scene_tree.bs
pub class SceneTree {
    node: Node,
    pub size: int,
}
// scripts/inspector.bs
use scene_tree;

pub class Inspector {
    node: Node,
}

impl Inspector {
    fn init() {
        let tree: scene_tree::SceneTree? = self.node.get_node("../Tree").script;
        if tree != nil {
            log::info("{tree.unwrap().size}");
        }
    }
}

Events

Contents

An event is a name and a payload, sent to whoever listens. A script declares the events it sends, and a listener names a node, which hears the event as its on_<name> method.

// scripts/enemy.bs
/// The enemy was struck; the payload holds the `damage`.
event hit;

/// An enemy reached the gate, said from no node with the enemy's name.
event alarm;

pub class Enemy {
    node: Node,
}

impl Enemy {
    pub fn strike(damage: int) {
        self.node.emit("hit", { "damage": damage });
    }

    pub fn reach_gate() {
        events::emit("alarm", self.node.name());
    }
}
// scripts/tower.bs
/// The tower found its enemy and began to listen.
event ready;

pub class Tower {
    node: Node,
    enemy: Node,
    damage: int,
}

impl Tower {
    fn init() {
        self.enemy = scene::root().get_node("World/Enemy");
        events::listen(self.node, "hit", self.enemy);
        events::listen(self.node, "alarm");
        self.node.emit("ready", { "from": self.node.name() });
    }

    pub fn on_hit(payload: any, source: Node) {
        self.damage += payload["damage"].as_int();
        log::info("{source.name()} has taken {self.damage}");
    }

    pub fn on_alarm(payload: any) {
        log::warn("alarm: {payload}");
    }
}

Declaring an event

event hit; at the top of a file names an event the script sends. The /// lines above it are its description. The compiler reads the item without running the script, so a tool knows what a node sends:

event is a word only where an item starts. Anywhere else it is a name like any other.

/// The round ended; the payload is the winner's name.
event round_over;

pub fn total(queued: [int]) -> int {
    let sum = 0;
    for event in queued {
        sum += event;
    }
    sum
}

// total([1, 2, 3]) == 6

Delivery

An event arrives at the top of the next frame's update, in emission then subscription order. The frame of delay keeps a handler from freeing the node being ticked. A replay re-runs the script, which emits again, so events are reproducible.

Waiting for one

events::next answers a token that task::wait can wait on. It resumes with the payload.

// scripts/gate.bs
pub class Gate {
    node: Node,
}

impl Gate {
    pub async fn init() {
        let payload = await task::wait(events::next("alarm"));
        log::info("alarm from {payload}");
    }
}

Events from the engine

The engine calls methods by name too: on_animation_finished(name, source) from an animation, and on_websocket_event from an HTTP request. A node hears its own engine events with no listen: a button's script hears its click as on_pointer_click(button, source). Most have a polling twin, such as input::key_just_pressed, for code that prefers to ask each frame.

Language reference

Contents

Every construct on one page, for looking things up. The rest of this chapter teaches them with examples.

A file

A .bs file holds items in any order: fn, struct, class, enum, impl, const, extern fn, event and use. An item with no mark belongs to its file, internal opens it to its package, and pub to every file. // starts a comment and /// documents an item.

event name; names an event the file's node sends. It takes no mark, and event is a word only where an item starts.

Types

Type Holds Assigning it
int a 64-bit signed integer copies
float a 64-bit float copies
bool true or false copies
str UTF-8 text that never changes shares
Node a node of the scene, or none copies the handle
[T] a list shares
{str: V}, {int: V} a map, kept in the order keys were first set shares
T? a T, or nil as T
any a value of any kind, read at run time shares a list or a map
fn(A, B) -> R a function, named elsewhere copies
Vec2, Vec3, Color, Transform2d, Transform3d numbers with named fields copies
a struct fields copies, shallowly
a class fields and methods shares the object
an enum one of its variants copies

Variables and constants

let declares a variable and gives it a value: let n = 3;, let x: float = 3;. A variable can be assigned again, and +=, -=, *=, /=, %=, &=, |=, ^=, <<= and >>= combine. A let ends with its block and may hide an earlier one. A const holds a literal, for the file, and another file reads it as util::NAME.

Operators

Tightest first: as, then unary -, ! and ~, then * / %, then + -, then << >>. Then &, then ^, then |, then == != < <= > >=, then &&, then ||. && and || stop at the first side that decides.

Numbers

Strings

Lists

Maps

Optionals

any

Structs and classes

pub struct Label { kind: str = "label", size: int = 3, text: str, tip: str? }

pub class Counter { count: int }

impl Counter {
    pub fn bump() { self.count += 1; }
}

Enums and match

enum Shape { Circle(float), Rect { w: float, h: float }, Empty }

fn area(s: Shape) -> float {
    match s {
        Shape::Circle(r) => r * r * 3.0,
        Shape::Rect { w, h } => w * h,
        Shape::Empty => 0.0,
    }
}

Functions

Control flow

Modules

use util; links util.bs from beside the file or a folder above it, and its pub items read as util::name. use a::b; is a/b.bs. Files may use each other, and the file that uses them.

Fields and methods take the same marks as items. A package is the addons/<name> or deps/<alias> folder a file sits in, or else the project. A name a file may not reach stops at compile time.

Async

async fn may await a host call or another script async fn, and resumes on a later frame. await goes in a statement, a let or an assignment. An async fn takes no &mut parameter. update and fixed_update may not be async.

Errors

A compile error names its line and column: 6:7: cannot combine int and bool. A file gives one error for each function that does not compile. A trap ends the call, and the next call runs.

Not in the language

Generics, traits, inheritance, closures, tuples, exceptions, T?? and any?.

Scenes and nodes

Contents

Nodes are entities

A node is an ECS entity with Name, Parent, Children and GlobalTransform.

The node tree of examples/hello, with the Platform node's components in the inspector

Scene files

A flat list of [[nodes]] entries with name, an optional parent by id, script, and one key per component.

[[nodes]]
id = "n_ball"
name = "Ball"
parent = "n_world"
script = { source = "scripts/ball.bs" }
body3d = { kind = "dynamic" }
collider3d = { shape = { kind = "sphere", radius = 0.5 } }
shape3d = { shape = { kind = "sphere", radius = 0.5 } }

[nodes.transform]
position = [0, 6, 0]
rotation_euler = [0, 1.5708, 0]   # radians
scale = [1, 1, 1]

Prefabs

A prefab is a scene file. instance on a node places one: the file's root merges into that node, and the root's children become the node's.

[[nodes]]
id = "n_crate_b"
name = "CrateB"
instance = "scenes/crate.toml"
transform = { position = [-0.5, 5, 1.5] }

[nodes.overrides.Lid.shape3d]
color = [0.9, 0.3, 0.25, 1]

In the editor:

Components

Plugins declare named, schema-described components. A property's type is one of float, int, bool, string, enum, flags, vec2, vec3, vec4, color, asset, node, list, map, record or variant, with a default, enum options and a readonly marker. A malformed schema fails at boot naming the component and property.

One registration gives:

The scene-file key collider3d = { shape = { kind = "sphere", radius = 0.5 } }
The runtime API Every property as a field on the node's handle (node.collider3d.density = 15.0), plus node.set_component, patch_component, get_component, has_component, remove_component, component_names, scene::component_types() and scene::component_schema(name)
Editor support The Add component palette and the property inspectors, generated from the registry
Component Plugin Purpose
transform core Position, rotation and scale in the parent's space
body3d, collider3d physics 3D rigid body and collider (rapier3d)
body2d, collider2d physics 2D rigid body and collider (rapier2d)
shape3d, shape2d render 3D / 2D primitive with a color
sprite, tilemap, tile_collision, particles2d render, physics Textured 2D quad; a tile grid over a tileset, autotiled and collided as one shape; a particle emitter
particles3d render A particle emitter in 3D, one instanced quad per particle
mesh render An OBJ or glTF mesh, optionally skinned to a skeleton
boolean3d, boolean2d render The node's children joined, cut out of one another, or overlapped
multimesh3d, multimesh2d render A multimesh asset's mesh drawn once per instance, in one draw call
polygon render A textured 2D polygon, GPU-skinned to a rig
camera2d, camera3d render The 2D or 3D camera
bone2d, bone3d core A rest pose; a node with one is a bone
modifier2d, modifier3d anim look_at, two_bone_ik, fabrik, ccdik or jiggle, run after the clip
animation anim A clip library (by reference or inline) and an autoplay clip
sound audio A sound file with volume and looping
widget ui HUD element (label / button / panel) anchored to the screen

Objects

Every shape the engine draws is a mesh, built without a GPU. A collider fits it, a ray picks it, and a headless test measures it.

Every object, one row per category

[[assets]]
id = "blade"
type = "mesh"
source = "models/blade.glb"   # a model file

[[assets]]
id = "ring"
type = "mesh"
kind = "torus"                # a primitive, with its own knobs
radius = 1.0
tube_radius = 0.3

[[assets]]
id = "word"
type = "mesh"
kind = "text"                 # a word, shaped from the project's fonts
text = "BALAUR"

[[assets]]
id = "triangle"
type = "mesh"
positions = [[0, 0, 0], [1, 0, 0], [0, 1, 0]]   # the vertices themselves

The primitives row

Paths

[[assets]]
id = "arch"
type = "mesh"
kind = "extrude"
path = "#outline"
depth = 0.5
bevel = 0.08
Kind What it makes
path2d, path3d A run of cubic control points with a closed flag
extrude A closed outline given thickness, with an optional bevel
lathe A profile revolved around y
sweep A cross-section carried along a rail

A line2d whose mesh names a path2d strokes it. Its join, cap, miter_limit and taper set how the stroke turns a corner, how it ends and how it narrows along its length.

An arch extruded, a goblet revolved, a rail swept

Booleans and multimeshes

Union, difference and intersection of a cube and a ball

Ellipse, star, ngon and capsule; a rect and a circle joined, cut and intersected

A row, a ring and a scattered grid

[[assets]]
id = "posts"
type = "multimesh"
mesh = { type = "mesh", kind = "box", size = [0.32, 0.8, 0.32] }
instances = [
  { position = [0.0, 0.0, 0.0] },
  { position = [0.9, 0.0, 0.0], rotation_euler = [0.0, 0.5, 0.0], scale = [1.0, 2.0, 1.0] },
  { position = [1.8, 0.0, 0.0], color = [0.7, 0.6, 0.4, 1.0], custom = [1.0, 0.0, 0.0, 0.0] },
]

[[nodes]]
id = "n_row"
name = "Row"

[nodes.multimesh3d]
source = "#posts"

Vertex colours and morph targets

type = "material"
shader = "shaders/painted.wesl"
features = { vertex_color = true }

A word as a mesh, and a triangle coloured per vertex

examples/objects has all of it, one row per category.

Reacting without a script

Three scene keys: [variables], states on a node, and bindings on a node.

[variables]
score = { type = "int", value = 0 }

[[nodes]]
name = "Room"

[[nodes]]
name = "Door"
parent = "Room"

[nodes.states]
current = "shut"

[nodes.states.shut]
shape3d = { color = "#734f2b" }

[nodes.states.open]
shape3d = { color = "#4cbf66" }

[[nodes]]
name = "Ball"
parent = "Room"

[[nodes.bindings.rows]]
event = "pointer_click"
action = "add_variable"
target = "score"
value = 1

[[nodes.bindings.rows]]
event = "pointer_click"
when = "score >= 3"
action = "set_state"
target = "../Door"
value = "open"

The Bindings view: two binding rows on the ball, one counting the click and one opening the door when the score reaches three

examples/hello carries exactly this.

Events Pointer enter, exit, down, up, click, drag, drop; key down and up; a declared action; scroll; resize; a variable or a state changing; a collision starting or stopping. Each also reaches the node's script as on_<event>, bindings first
Actions set_state, set_variable, add_variable, play, play_sound, instantiate, free, switch, open_url, emit, call, visible, toast
when A comparison over the scene's variables, joined with && and ||
States A table of component properties patched over the node's own. node.states.set_state("hover") does the same from a script, and on_state_changed(from, to) follows

Import settings

art/hero.png.import.toml holds the import settings for art/hero.png.

# art/hero.png.import.toml
filter = "nearest"   # pixel art, drawn crisp
srgb = true          # false for a normal map or a mask

The same 32-pixel sprite at ten times its size, filtered linearly and with nearest

# project.toml: the default for every file of a kind
[import.texture]
filter = "nearest"

The Import tab showing filter and srgb for a selected picture

Scripting

Contents

Scripts are Balaur Script: .bs files attached to nodes in a scene. The language is statically typed, reads like Rust, and compiles to WebAssembly.

The model

// scripts/spinner.bs
pub class Spinner {
    pub speed: float = 2.0,
    node: Node,
    angle: float,
}

impl Spinner {
    fn init() {
        self.angle = 0.0;
    }

    fn update(dt: float) {
        self.angle += dt * self.speed;
        self.node.transform.rotation_euler = vec3(0.0, self.angle, 0.0);
    }

    fn fixed_update(dt: float) {}   // the fixed 60 Hz step, before physics
}
Hook When
init once, after the properties are written
update(dt) once a frame, with the measured frame time
fixed_update(dt) on the fixed 60 Hz step, before physics. Simulation belongs here
on_free before the node or the script goes

The Script workspace: the file, the hooks it declares, and the events its node receives

The language

Has Example
int (64-bit), float (64-bit), bool, str let n = 3; let x: float = 0.5;
Vec2, Vec3, Color vec3(0.0, 1.0, 0.0), p.x
Lists [1, 2, 3], [0.0; 16], xs.push(4), xs.len()
Optional values let hit: Node? = nil; hit != nil, hit.unwrap()
Structs, copied as values struct Wave { hp: int, name: str }
Classes, one object every holder shares class Board { cells: [int] }
Free-form data any: an HTTP reply, a save, a map written { "k": v }
Enums enum Shape { Circle(float), Empty }, match s { Shape::Circle(r) => r, Shape::Empty => 0.0 }
Function values let f: fn(int) -> int = double;
A caller's value, written back fn grow(w: &mut Wave) { w.hp += 1; }
if as a value let sign = if self.clockwise { 1.0 } else { -1.0 };
Loops while, loop, for i in 0..n, for x in xs
Interpolation "hp {self.hp} of {MAX}"
Async async fn, await task::seconds(0.5);

Properties

Every pub field is a property the inspector shows and a scene sets, whatever its type. An internal or unmarked field stays the script's own.

pub class Spinner {
    /// Turns a second.
    pub speed: float = 2.0,
    pub clockwise: bool = true,
    pub target: Node,
    pub stops: [float],
    node: Node,
}
[nodes.script]
source = "scripts/spinner.bs"

[nodes.script.props]
speed = 3.5
target = "../Wheel"
stops = [0.25, 0.75]

Modules

Engine modules are reached with ::. Every call is typed against the engine the script compiles for.

let t = engine::time();
let ball = scene::root().get_node("World/Ball");
self.node.set_component("body3d", { "kind": physics3d::BODY_DYNAMIC });

engine, scene, log, input, random, math, physics, physics2d, physics3d, render, audio, ui, animation, skeleton, assets, http, websocket, events, task, fs, toml, json, and more. Every function and constant is in the script modules reference, generated from a booted engine.

Shape Example
Named values, never spelled input::KEY_SPACE, physics3d::BODY_DYNAMIC, ui::ANCHOR_TOP_LEFT
Node operations are methods self.node.get_node("../Target"), node.queue_free()
Two or three numbers are a vector input::mouse_position().x
A record is a struct log::since(cursor).entries, ui::widget_rect(n).unwrap().width
Free-form data is an any r["status"], r["body"], { "kind": "sphere" }
Trailing optional arguments may be left out log::since()

A component's operations are methods on its field of the node: self.node.body2d.apply_impulse(x, y). A module keeps what belongs to no node, such as physics2d::raycast. The component reference lists the operations per component.

self.node.body2d.apply_impulse(0.0, 12.0);
if self.node.body2d.linear_velocity().x > 5.0 {
    self.node.body2d.set_linear_velocity(5.0, 0.0);
}

A component's properties are fields. A script moves a node by writing its transform:

let p = self.node.transform.position;
self.node.transform.position = vec3(p.x, p.y + 1.0, p.z);
self.node.transform.rotation_euler = vec3(0.0, math::to_radians(90.0), 0.0);

Script files as modules

// scripts/util.bs
pub fn clamp(v: float, lo: float, hi: float) -> float {
    if v < lo { lo } else if v > hi { hi } else { v }
}
// scripts/runner.bs
use util;

pub class Runner {
    node: Node,
    speed: float,
}

impl Runner {
    fn update(dt: float) {
        self.speed = util::clamp(self.speed + dt, 0.0, 10.0);
    }
}

Errors

A compile error names the file, line and column:

scripts/spinner.bs:14:27: error: cannot combine bool and int

Logs

log::info, log::warn and log::error write a line. The engine keeps the last 500 in memory, and the Output dock shows them. log::print writes to standard output as it stands.

Each run also writes its log to logs/run.log in the game's user data folder, and keeps the last five runs as run.1.log and on. [log] to_file turns it off and [log] keep sets how many runs stay. A panic is written there before the process dies. A browser keeps the file in the page's storage, so the next visit can read the run that crashed.

On Android the user data folder is in the app's internal storage, and every line also goes to logcat under the tag balaur: adb logcat -s balaur.

log::since(cursor) answers each line once, for a script that sends the log somewhere:

let read = log::since(self.cursor);
for entry in read.entries {
    send(entry.level, entry.message);
}
self.cursor = read.cursor;

read.missed counts the lines dropped before they were read.

Tooling

script::check, complete, hover, signature, definition, symbols, references, rename and format answer from the running engine. Two clients read them: the editor's Script workspace, and balaur lsp, a Language Server Protocol server on stdin and stdout.

The completion popup: a module path, and the functions and constants under it

After the caret What completes
physics2d:: that module's functions and constants, each with the line the reference prints
self.node.body2d. that component's properties and operations
self. the script's fields and methods
a string, a list or an any, then . that type's methods
anything else this file's functions, structs and locals, the modules, keywords
Key What it does
⌘B Go to definition: locals, fields, methods, functions and structs
⌥⇧F Format the buffer
⌘⇧R Rename an identifier in the file
⌘⇧F Replace text

Ctrl works in place of ⌘ in every chord here.

A rename matches the name as a token, inside {..} interpolations too, and skips string text and comments. Both rename and replace list every match before writing.

balaur fmt .           # lay every script out
balaur fmt . --check   # name the files that would change; exits 1 if any do

The formatter keeps the author's line breaks and comments, indents each line by the brackets above it, and keeps one blank line of a run. It changes no token.

balaur lsp <project> serves diagnostics, completion, hover, signature help, go-to-definition, document symbols, references, rename and formatting. The engine repository ships a VS Code extension in editors/code; its README has the Neovim and Zed recipes.

Events

The engine calls methods a script declares by name.

init and an event handler may be async. One suspends on task::wait and resumes at the start of the tick the result enters the simulation. update and fixed_update never await. See Networking for the delivery model.

pub class Fetch {
    node: Node,
}

impl Fetch {
    pub async fn init() {
        let r = await task::wait(http::request("https://example.com"));
        log::info("{r["status"]} {r["body"]}");
    }
}

Two ways for scripts to reach each other:

Shape Call
One target, by node handle node.call("method", args...), up to four arguments
A named event from an emitter to its subscribers events
pub class Tower {
    node: Node,
    enemy: Node,
}

impl Tower {
    fn init() {
        self.enemy = scene::root().get_node("World/Enemy");
        events::listen(self.node, "hit", self.enemy);   // only that enemy's
        events::listen(self.node, "hit");               // every emitter's
        self.node.emit("hit", { "damage": 3 });         // from this node
    }

    pub fn on_hit(payload: any) {}   // on_<name>, whichever it was
}

Hot reload

A save that did not compile, reported in the Output dock

Debugging

Click a line number in the Script workspace to set a breakpoint and run the scene. The Debugger dock shows the call stack and each frame's variables.

Control Key
Continue F5
Step over, into, out F10, F11, Shift+F11

The same controls are the debugger module:

debugger::set_breakpoints("scripts/ball.bs", [12, 30]);
let pause = debugger::stop_location();   // nil, or the pause: reason, line, frames
debugger::resume(debugger::STEP_OVER);   // CONTINUE, STEP_OVER, STEP_INTO, STEP_OUT
debugger::set_break_on_error(true);

Where it runs

Time against the same code in Rust, on macOS:

Target Engine Particles fib(25)
iOS native code, compiled at export 1.1x 1.3x
Desktop, Android wasmtime 2.3x 1.6x
A file under the debugger wasmi 16x 11x

In a browser the page's own engine runs them at 1.1x and 1.0x Rust compiled to WebAssembly.

Determinism in scripts

Shaders and materials

Contents

Shaders are WESL: WGSL plus imports, @if variants and dead-code elimination, linked to WGSL at run time. A material asset names a shader and its values. sprite, shape2d, shape3d, mesh and tilemap take one. A node can pass one to its subtree. A node with neither draws with the built-in material.

A material and its shader

# materials/glow.toml
type = "material"
shader = "shaders/glow.wesl"

[params]
speed = 2.0
rings = 5.0
tint = "#ffb347"
// shaders/glow.wesl

struct Params { speed: f32, rings: f32, tint: vec4<f32> }
@group(3) @binding(0) var<uniform> params: Params;

@vertex fn vs_main(in: VertexInput) -> VertexOutput {
    return vertex(in);
}

@fragment fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    let uv: vec2<f32> = in.uv;
    let dist: f32 = length(uv - vec2<f32>(0.5, 0.5)) * 2.0;
    let wave: f32 = 0.5 + 0.5 * sin(dist * params.rings * 6.2832 - time() * params.speed);
    let ramp: vec4<f32> = params.tint * wave * wave;
    let albedo: vec4<f32> = sample_albedo(uv) * tint(in);
    return albedo + ramp * albedo.a;
}
Import What it binds
package::sprite The 2D contract: frame and object uniforms, vertex inputs, vertex and place, sample_albedo, tint, time
package::mesh The 3D contract, with shade(in) for the scene's lights and fog
package::post A pass over the whole frame: fullscreen, frame(uv) and texel()
constants The engine's limits, MAX_LIGHTS, MAX_PROBES and MAX_JOINTS: the numbers its own buffers are sized by

A shader file holds its two entry points; the rest is imported.

A material for a whole subtree

The material component goes on any node, including one that draws nothing. The node and its subtree draw with it.

[[nodes]]
id = "rig"
name = "Rig"

[nodes.material]
source = "materials/metal.toml"

A pass over the whole frame

A material named in a camera's post draws over the frame. It imports package::post, has no mesh or texture of its own, and keeps its Params at @group(1).


struct Params { amount: f32 }
@group(1) @binding(0) var<uniform> params: Params;

@vertex fn vs_main(@builtin(vertex_index) index: u32) -> PostInput {
    return fullscreen(index);
}

@fragment fn fs_main(in: PostInput) -> @location(0) vec4<f32> {
    let c: vec4<f32> = frame(in.uv);
    return vec4<f32>(mix(c.rgb, vec3<f32>(1.0) - c.rgb, params.amount), 1.0);
}

In the editor

Way How
A line's value Click a line number in the gutter; the viewport draws that line's value for every pixel that reaches it: a vec2 as red and green, an f32 as grey, a vec4 as colour. The line must declare a typed value (let dist: f32 = ...) or a constructor. Click again to restore the picture
Channels render::set_debug_view("normals") draws the scene's normals. "uv", "depth" and "albedo" are the others; "" is the picture. The command palette has one command per channel

Determinism

examples/shaders is the material above on a sprite, beside a plain one.

Rendering

Contents

A 2D scene draws unlit until it has a light2d. One light2d starts a light map at the camera's resolution. Everything drawn is multiplied by that map plus the camera's ambient_color. Sprites, polygons and tile maps are lit with no material.

A warm point light and a cool fill light over a backdrop, a rect and a circle occluder each casting a shadow away from the warm light, and the rest of the frame fallen to a dark ambient

A light

[[nodes]]
id = "n_lamp"
name = "Lamp"

[nodes.transform]
position = [0, 2.5, 0]

[nodes.light2d]
kind = "point"          # point | directional
color = "#ffd28a"
range = 8.0             # world units; a point light fades to nothing here
intensity = 1.6
shadow_enabled = true

Ambient

[nodes.environment]
ambient_color = "#181c22"   # what an unlit surface is multiplied by

Occluders and shadows

[nodes.occluder2d]
# mesh = "meshes/wall.toml"   # points in order; empty derives the outline
# closed = true               # the last point joins the first

Three occluders under one directional light, each casting a parallel shadow strip at the light's angle: a rect, a circle and a capsule, their outlines traced faithfully

The editor with an occluder node selected: only the Points mode chip, an Occluder section in the inspector, and the light gizmos over the lit scene

Post-processing

[nodes.camera2d.effects]
post = ["bloom"]
bloom_threshold = 0.9   # brightness a pixel has to pass
bloom_intensity = 0.7   # how much is added back

Custom passes

post runs in list order. An unknown name is a material drawn over the whole frame.

[nodes.camera3d.effects]
post = ["materials/heat.toml", "tonemap", "bloom", "materials/grade.toml"]

See Shaders for what a post material imports.

Light map coverage

Lights in 3D

[[nodes]]
name = "Key"

[nodes.transform]
position = [4, 7, 4]
rotation_euler = [-0.87266, 0.69813, 0]   # radians: -50° and 40°

[nodes.light3d]
kind = "spot"
color = "#fff2e0"
intensity = 6
range = 30
inner_angle_degrees = 25
outer_angle_degrees = 45

A spot light selected in the editor, its cone drawn in the viewport and its light3d rows in the inspector

The scene's atmosphere

[nodes.environment]
sky = "skies/studio.hdr"
ambient_color = "#20242a"
tonemap = "neutral"
exposure = 1.1
fog_mode = "exponential"
fog_color = "#9fb4c8"
fog_density = 0.012

A physically based material

A 3D material imports package::pbr for metallic, roughness, emissive and reflectance. The default is Lambert.


struct Params { metallic: f32, roughness: f32, reflectance: f32 }
@group(3) @binding(0) var<uniform> params: Params;

@fragment fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    var s = default_surface(in);
    s.metallic = params.metallic;
    s.roughness = max(params.roughness, 0.045);
    s.reflectance = params.reflectance;
    return shade_pbr(in, s);
}

Drawing only when asked

[window] low_processor = true makes a window draw a frame only when something asks for one. Input asks, and so do ui::request_repaint() and a repaint scheduled with ui::request_repaint(ui::RepaintOptions { after: seconds }).

Work that finishes on another thread wakes it when it reports, and so do a log line and a changed script. Between frames no script runs and nothing is drawn, and a browser tab checks every 16 ms. It suits a tool or a turn-based game. The editor runs this way; a game that moves every frame leaves it off.

[window]
low_processor = true

Limits

Animation

Contents

One plugin, balaur_animation: one asset type (animation_library), one component (animation), one script module, one system. Tracks address properties through the component registry. The plugin depends only on the core and animates the renderer and the UI.

For animators

Balaur for animators: bones, skinning, IK and the timeline, on the rig that ships in the game.

Clips

A clip is a length, a loop_mode (none | linear | pingpong) and a list of tracks. It lives in its own file, inline in the scene node, or in a library file under [clips.<name>], addressed file.toml#name.

# animations/platform.toml
type = "animation_library"

[clips.patrol]
length = 4.0
loop_mode = "pingpong"

[[clips.patrol.tracks]]
property = "position"      # position | rotation_euler | rotation | scale | <component>/<property>
interpolation = "linear"   # step | linear | cubic
keys = [
  { time = 0.0, value = [-2.5, 0.25, -2.0] },
  { time = 4.0, value = [-2.5, 0.25, 2.0], ease = "in_out_sine" },
]

[[clips.patrol.tracks]]
keys = [{ time = 4.0, call = "on_reached_end" }]   # a method track
# in the scene
[nodes.animation]
library = "animations/platform.toml"
autoplay = "patrol"

The script module

self.node.animation.play("hop", animation::PlayOptions { speed_scale: 1.0 });
self.node.animation.pause();   // resume continues
self.node.animation.queue("wave");
self.node.animation.stop();    // animation::stop_tween(handle) ends a tween

A method track calls a method on the node's script by name, such as on_reached_end().

Also seek, time, current_clip, is_playing and add_clip, which builds a clip from a map at run time. is_tween_running(handle) answers for a tween.

Every word a clip or a machine spells has a constant, such as animation::LOOP_PINGPONG, animation::INTERPOLATION_CUBIC and animation::EASE_OUT_BACK, so a script never spells one as a string.

Crossfades and state machines

blend_time on play blends out of the current clip over that many seconds. A track only the old clip keys follows it out, and a fade started mid-fade blends from where the last one had got to.

self.node.animation.play("run", animation::PlayOptions { blend_time: 0.2, ease: animation::EASE_IN_OUT_SINE });

A state_machine asset names states, each a clip of the player's library, and the transitions between them. The state_machine component runs one.

# animations/hero_machine.toml
type = "state_machine"
start = "idle"

[states]
idle = ""                # "" plays the clip named like the state
run = "run_cycle"

[[transitions]]
from = "idle"
to = "run"
advance_mode = "auto"    # disabled | enabled (travel only) | auto
condition = "moving"
blend_time = 0.2
# in the scene
[nodes.state_machine]
machine = "animations/hero_machine.toml"
self.node.state_machine.set_condition("moving", true);
self.node.state_machine.travel("jump");   // the cheapest chain of transitions
let now = self.node.state_machine.current_state();

Tweens

A clip generated from the node's current values, run through the same sampler and fixed step.

let steps: [any] = [
    { "property": "position", "to": [0.0, 3.0, 0.0], "duration": 0.5, "ease": animation::EASE_OUT_BACK },
    { "property": "shape3d/color", "to": [1.0, 0.0, 0.0, 1.0], "duration": 0.5, "parallel": true },
    { "call": "on_landed" },
];
animation::tween(self.node, animation::Tween { steps: steps });
Key What it does
to, by, from absolute, relative, explicit start
target tween another node
parallel join this step to the one before it
interval, call sequence among the property steps

The Animation workspace

Skeletons and skins

A bone is a node with a rest pose: bone2d in 2D, bone3d in 3D. A skin is a polygon: a textured 2D polygon whose mesh carries bone weights. A clip on the character keys its bones by path.

[[nodes]]
name = "Thigh"
parent = "n_hip"
transform = { position = [0, 0.85, 0] }
bone2d = { rest_position = [0, 0.85], rest_rotation = 0.0 }

[nodes.polygon]                       # on a sibling node
texture = "art/limb.png"
skeleton = ".."                       # the rig root; bones are its descendants

[nodes.polygon.mesh]                  # a `mesh` asset, inline
positions = [[-0.4, 0], [0.4, 0], [0.4, 0.85], [-0.4, 0.85]]
[[nodes.polygon.mesh.skin.bones]]
path = "Hip/Thigh"
weights = [0, 0, 1, 1]

A polygon's inspector: vertices, drawn polygons, bones and brush

Tools

Tool What it does
Rig bone Bones as diamonds in 2D and octahedra in 3D: click to select, drag to pose, + bone grows a child from the selection
Polygon · Points Outline and internal vertices
Polygon · Polygons The triangulation by hand
Polygon · UV The points placed over the texture
Polygon · Weights Bone influence painted with a brush

The polygon stays skinned during editing. The inspector's Skeleton section has the two rest-pose verbs.

Weights mode, painting the thigh bone

Modifiers

A modifier2d runs after the clip every frame. modifier3d is the same five kinds over bone3d.

kind What it does
look_at Turns one bone so it points at a target node.
two_bone_ik Bends a root, middle and tip chain so the tip reaches the target; flip_bend_direction picks the bend side.
fabrik Reaches with a chain of any length. Converges from any pose. iterations, tolerance.
ccdik The same reach, one bone at a time. The only kind with an angle_limit per bone.
jiggle No target: a spring per bone toward the clip's pose. stiffness, damping, mass, gravity, use_gravity.

chain_count says how many bones a chain solver walks, counting the driven one. Zero walks to the deepest tip.

[nodes.modifier2d]
kind = "two_bone_ik"
bone = "Shoulder"
target = "Target"

A camera that trails a node is the library's scripts/follow.bs, which the camera rigs use. It moves its node to the target plus offset, lag seconds behind, with node.transform.set_global_position.

# A camera that trails the player a fifth of a second behind.
[nodes.script]
source = "scripts/follow.bs"

[nodes.script.props]
target = "../Player"
lag = 0.2
offset = [0, 3, 8]
# The plume in examples/rig: nothing keys it, and it moves anyway.
[nodes.modifier2d]
kind = "jiggle"
bone = "Hip/Thigh/Shin/Plume"
stiffness = 26.0
damping = 0.32
use_gravity = true

The Rig tool drawing a modifier's chain, the dashed line to its target and the handle that drags it

The viewport draws the chain a modifier solves, a dashed line to the target and a handle that drags the target node. A chain_count of two draws two bones.

Free-form deformation

A polygon/deform track keys an [dx, dy] offset per vertex, added to the authored positions before skinning: a mouth, a cape edge or a breathing outline. Spine calls it free-form deformation.

type = "animation_library"

[clips.breathe]
length = 1.0

[[clips.breathe.tracks]]
target = "Limb"
property = "polygon/deform"
keys = [
  { time = 0.0, value = [0, 0, 0, 0] },
  { time = 1.0, value = [-0.09, 0, 0.09, 0], ease = "in_out_sine" },
]

Retargeting

A bone_map asset pairs canonical bone names with one rig's node paths. A clip authored for a different skeleton plays through it.

type = "bone_map"

[bones]
Hips = "Armature/Hips"
Spine = "Armature/Hips/Spine"
let hero = scene::get_node("World/Hero");
hero.animation.play("walk", animation::PlayOptions { retarget: "animations/hero.bonemap.toml" });

The Bone map dock: canonical names on the left, the rig's own bones on the right

The Bone map dock fills rows by name and writes the asset. Matching ignores case, separators and an exporter's prefix: LeftUpperArm finds mixamorig:LeftUpperArm.

Weights, mirroring and tracing

The Weights dock over a skinned polygon

Verb What it does
Weights dock Picked vertices, one editable weight per bone, a per-vertex sum that goes red when it is not one
Bind, Unbind, Normalize On the picked vertices
Auto Weights by distance to each bone's segment
Smooth Average with the vertices sharing an edge
Mirror (Rig) Reflects every bone's rest over x or y, and hands each rest to the bone whose name differs by a side: Arm_L to Arm_R, left_hand to right_hand
Mirror (Polygon) Reflects the picked vertices and swaps the weights the same way
Trace Walks a texture's alpha at a threshold and writes the outline as points, simplified to a tolerance in pixels

Ragdolls

physics2d::ragdoll(node, opts) walks a rig into a body and a capsule per bone, hinged to its parent's, and leaves a ragdoll component.

let axis: any = { "axis": physics2d::AXIS_ROTATION, "limits": [-0.7, 0.7] };
physics2d::ragdoll(self.node, physics2d::RagdollOptions { influence: 0.0, thickness: 0.22, axes: [axis] });
// … and later, to fall over:
self.node.ragdoll.set_ragdoll_influence(1.0);

3D rigs

balaur import model.glb --project my-game

The column of examples/rig3d bent by its sway clip, its three bones deforming the imported mesh

examples/rig is one figure with four kinds of rigging: a clip keying bone rotations, two-bone IK reaching a moving target, a jiggle plume, and a polygon/deform breathing outline. It falls into a ragdoll every few seconds. examples/rig3d is an imported column.

Determinism and scheduling

Physics

Contents

A plugin wrapping Rapier: rapier3d for body3d and collider3d, rapier2d for body2d and collider2d. Both worlds run over the same scene tree, built with Rapier's enhanced-determinism feature, stepped on a fixed 60 Hz tick.

Declaring bodies

[[nodes]]
name = "Crate"
transform = { position = [0, 3, 0] }
body3d = { kind = "dynamic" }      # dynamic | kinematic | static
collider3d = { shape = { kind = "box", size = [1.0, 1.0, 1.0] } }
self.node.set_component("body3d", { "kind": physics3d::BODY_DYNAMIC });
self.node.set_component("collider3d", { "shape": { "kind": physics3d::SHAPE_SPHERE, "radius": 0.5 } });

self.node.set_component("body2d", { "kind": physics2d::BODY_DYNAMIC });
self.node.set_component("collider2d", { "shape": { "kind": physics2d::SHAPE_RECTANGLE, "size": [1.0, 1.0] } });

Component handles

self.node.body2d.apply_impulse(1.0, 0.0);

Driving the simulation

Module What is in it
physics3d, physics2d Bodies, colliders, joints, velocities and queries, one module per world
node.body2d, node.collider3d max_contact_impulse(), the strongest impact in the last step
physics Both worlds: set_paused, is_paused, clear, set_sleeping_allowed, sleeping_allowed, the debug draw, the solver's tuning and counters

The editor pauses physics until play. Its Physics workspace draws every body's collider and centre of mass over the scene, playing or not.

The Physics workspace's collider and centre-of-mass overlays over examples/angrynerds, the Bird selected

The full function lists are in the script modules reference.

Determinism

UI

Contents

A UI is widget components on scene nodes: saved with the scene, edited in the inspector, previewed in the viewport. A script fills them and answers their events. It never draws.

The editor's shell, docks, inspector and tab rows are widget nodes in editor/scenes/main.toml.

Widgets: game HUDs as scene nodes

[[nodes]]
name = "Score"

[nodes.widget]
kind = "label"
text = "Score 0"
anchor = "top_left"
x = 20
y = 16
font_size = 22
text_color = "#2b2b2b"

The UI workspace: examples/angrynerds' Score, Birds, Hint and Restart widgets in the tree, the HUD over the safe area, and the Restart button in the inspector

A button's click calls a method through a bindings row:

[[nodes]]
name = "Start"
script = { source = "scripts/start.bs" }
bindings = { rows = [{ event = "pointer_click", action = "call", value = "start_pressed" }] }

[nodes.widget]
kind = "button"
text = "Start"
pub class Start {
    node: Node,
}

impl Start {
    pub fn start_pressed() {
        log::info("start");
    }
}
// scripts/restart_button.bs, on the Restart node
pub class RestartButton {
    node: Node,
}

impl RestartButton {
    pub fn on_restart() {
        self.node.get_node("../Game").call("restart");
    }
}
self.node.widget.text = "Score 10";

The kinds

Group Kinds
Text label, text_field, text_area, code
Controls button, checkbox, switch, dropdown, slider, number_field, color_picker, progress_bar, menu
Data list, tree, table
Boxes panel, row, column, grid, scroll, tabs, fold, dialog, window, stack, viewport
Other image, separator

A row with wrap_children = "wrap" starts a new line when the row is full.

Only the rows on screen are built, in all three. A long list costs its viewport rather than its length. A secondary click picks the row it lands on, so a context menu acts on what it opened over; a row already picked keeps the set it is in.

A list with two rows picked, the same entries as a folding tree, and again as a table with named columns

A screen of nodes: a card grid, a control row and a wrapping chip flow

Layout

A container hands its children rects.

Layout is taffy, the layout engine Dioxus and Blitz use. It runs over the whole tree before drawing. ui::widget_rect reads a rect back in the same frame.

Themes and roles

A widget_theme asset says how each kind looks. A widget takes the theme of the nearest ancestor that names one.

type = "widget_theme"

[colors]
background = "#0e1116"
primary = "#6fa4d8"

[button]
fill = "bg_control"
corner_radius = "radius"
padding_x = 10

[button.hover]
fill = "primary_bg"

[roles.primary]
fill = "primary_fill"
text_color = "text_on_primary"
font_weight = 700
Token What it paints
bg_app, bg_panel the ground behind everything, and a sheet on it
bg_control, bg_control_hover a control at rest, and under the pointer
border_default every outline
text_default, text_muted, text_subtle three levels of text
primary_fill, primary_fill_hover a solid fill, and the same under the pointer
primary_text, primary_bg ink in the colour, and a tint of it behind a control that is on
text_on_primary ink on primary_fill
font_size_small, font_size_large, font_size_title from font_size
radius_small, radius_large from radius
control_height_small, control_height_large, control_height_touch from control_height

secondary, success, warning and danger take the same five colour tokens as primary.

A list, tree or table paints more than one plate, so the parts it draws are [colors] of their own. Each takes the built-in look where the theme names none, and a colour with no alpha draws nothing.

Token What it paints
row_selected, row_selected_text a picked row, and the ink on it
row_hover, row_active what a row takes under the pointer, and while it is held
row_stripe a table's every other row
table_header its header's plate
table_rule the lines down its columns, and the one under its header
tree_guide the lines down a tree's indent

These are the rows, not the box: [list.hover] still dresses the whole view under the pointer, the way it does any other kind. So table_rule = "#00000000" is a table with no lines, and row_stripe the same is one with no striping. padding_x on the kind is the air either side of a cell, and gap is the space between a list's cards.

Also on every widget: tooltip, icon (a glyph from the theme's icon family, drawn before the caption), enabled and interactive. Both are on unless turned off: enabled = false greys the widget out and swallows its clicks, and interactive = false lets the pointer through to the scene.

image is the picture an image widget or a button draws, sheet the picture a list cuts its card faces from, and language what a code widget highlights.

Three more say what a widget answers to. context names a menu a right click or a long press opens at the pointer. shortcut is a chord that clicks the widget from anywhere, as cmd+shift+s or f5. selectable lets a drag over a label select its text for the platform's copy key.

The ui module

What a script asks of the UI and tells it.

pub class Hud {
    node: Node,
}

impl Hud {
    // on_click = "pressed" on any widget under this node
    pub fn pressed(value: any, widget: Node) {
        if widget.name() == "Copy" {
            ui::set_clipboard("score 120");
        }
    }
}

Example

examples/interface is a whole screen built from widgets: a card grid, an outline, a table, a row of every control, and a theme with roles and hover states. One script fills the three views; the layout is in the scene.

Three more scenes sit beside it. scenes/rows.toml is the three row views over one set of entries. scenes/menus.toml is a menu bar and a context menu; scenes/text.toml is a label with links and hints, a selectable line, and numbers with arrows and units. Open any of them with --scene.

Input

Contents

Actions

Declared in project.toml:

[input.actions]
jump = ["Space", "gamepad:south"]
move_x = ["keys:KeyA,KeyD", "axis:left_x"]
fire = ["mouse:left"]
if input::action_just_pressed("jump") {
    // ...
}
let x = input::action_value("move_x");   // -1 to 1

Keyboard and mouse

let jumped = input::key_just_pressed(input::KEY_SPACE);
let firing = input::mouse_down(input::MOUSE_BUTTON_LEFT);
let at = input::mouse_position();   // at.x, at.y

key_down, key_just_pressed and key_just_released cover keys by named constant, and a key's value is its W3C KeyboardEvent.code. KEY_SHIFT, KEY_CONTROL, KEY_ALT and KEY_META answer for either side. The mouse adds position, per-frame delta, five MOUSE_BUTTON_* buttons and scroll delta.

Gamepads

for pad in input::gamepads() {
    let jumped = input::gamepad_just_pressed(pad.as_int(), input::GAMEPAD_BUTTON_SOUTH);
    let x = input::gamepad_axis(pad.as_int(), input::GAMEPAD_AXIS_LEFT_X);
}

Rumble, motion and the touchpad

let pad = input::gamepads()[0].as_int();
let turn = input::gamepad_gyro(pad);          // radians per second
let tilt = input::gamepad_acceleration(pad);  // g, with gravity in it
for touch in input::gamepad_touches(pad) {
    // touch["x"] and touch["y"] run 0 to 1 across the surface
}
Call What it does
gamepad_rumble(pad, opts), opts holding strong, weak and duration Runs the two motors at 0 to 1 for that many seconds; answers whether it started
gamepad_stop_rumble(pad) Stops it
gamepad_can_rumble(pad) Whether the pad has motors
gamepad_gyro, gamepad_acceleration, gamepad_touches A PlayStation pad's motion and touchpad, decoded from its HID reports over USB or Bluetooth

A pad with no gyroscope or touchpad reads zero and an empty list, as an absent pad does. All of it is in the recorded snapshot and replays.

Touch

[input]
emulate_mouse_from_touch = true   # the default
emulate_touch_from_mouse = false  # the default

Touch controls

A touch_button presses an action while a finger is on it. A touch_stick pushes one action per axis. The game reads the action.

[nodes.touch_stick]
action_x = "move_x"
action_y = "move_y"        # 1 pushed away from the player, as a gamepad reads
anchor = "bottom_left"
x = 40.0                   # design pixels in from the anchored side
y = 40.0
radius = 90.0

[nodes.touch_button]
action = "jump"
anchor = "bottom_right"
kind = "circle"

Gestures

let pinch = input::pinch();
if pinch.scale != nil {
    self.zoom *= pinch.scale.unwrap();
}
let pan = input::pan();             // pan.x, pan.y: two fingers or more
let swipe = input::swipe();         // swipe["x"], swipe["y"]: a unit direction
let held = input::long_press().has("x");   // once per hold
Call Answers
pinch() { scale, x, y } while two fingers move apart or together; scale is against last frame
pan() { x, y }, the average movement of every finger down
swipe() { x, y, speed } on the frame a finger that travelled far enough lifts
long_press() { x, y } once, when a still finger has held long enough

Each derives from the recorded fingers and the fixed step, and replays. Each answers empty when nothing is happening. swipe_pixels, long_press_seconds and long_press_slop_pixels in [input] set the thresholds.

The on-screen keyboard

Dropped files

input::dropped_files() returns the paths of files dropped onto the window this frame.

Feeding input from a script

feed_key, feed_mouse, feed_mouse_button, feed_touch(id, x, y, phase) and feed_action(name, value) put input into the frame as if a device reported it. A test, a showcase or an automation client drives a game with them. A fed frame records and replays like a real one.

Seeing input

The full surface

Every function and all named constants, keys, mouse buttons, pad buttons and axes, are in the script modules reference.

Networking

Contents

Crate Protocol Calls
balaur_http requests http::request
balaur_websocket connections websocket::connect, send, close
balaur_webtransport QUIC the same Transport seam

All three are on by default, each behind its own feature. Building without http drops the HTTP and TLS stack; without webtransport drops QUIC and its runtime.

For multiplayer games

Balaur for multiplayer puts this delivery model beside the fixed tick, rollback and replay.

The delivery model

sequenceDiagram
  participant S as script
  participant W as worker threads
  participant T as start of the next tick
  S->>W: http::request / websocket::send_text
  W-->>T: completion, over the channel
  T->>T: recorded in the tick's snapshot
  T->>S: handler method, or the awaited id resolves, in arrival order

Scripts never poll. There are two shapes.

The first is a handler method: a connection names the node that handles its events, dispatched as method calls.

pub class Status {
    node: Node,
    socket: int,
}

impl Status {
    fn init() {
        self.socket = websocket::connect(self.node, "wss://game.example/play");
    }

    pub fn on_websocket_event(e: any) {
        log::info("{e["socket"]} {e["kind"]}");
    }
}

The second is a sequential await: a request returns a token the script suspends on, from an async entry point.

pub async fn init() {
    let r = await task::wait(http::request("https://example.com"));
    log::info("{r["status"]} {r["body"]}");
}

The script resumes at the start of a later tick, in arrival order. Given the same recorded arrivals the result is deterministic.

Options and configuration

let headers = [websocket::Header { name: "Authorization", value: "Bearer {self.token}" }];
self.socket = websocket::connect(self.node, "wss://game.example/play", websocket::ConnectOptions {
    on_event: "on_socket",
    compression: true,
    headers: headers,
});
[websocket]
compression = true   # offer permessage-deflate on every connection

[http]
timeout_seconds = 10.0   # for a request that names none

Events instead of signals

For a hosted game backend (auth, storage, lobbies) see Gamend, built on the same delivery contract.

Rollback, and what is missing

Rollback is built. Two engines exchange only inputs, predict each other, roll back when a prediction was wrong, and compare a per-tick digest to catch a desync. It runs over WebSockets or QUIC. On QUIC a datagram is a true datagram: a lost input costs a misprediction, not a stall.

Replication, RPC and WebRTC are missing. The plan is PLAN-networking.md, with the short form on the roadmap. Raw UDP is not planned: QUIC datagrams cover it, with encryption and a browser story.

Gamend

Contents

The balaur_gamend plugin connects scripts to a Gamend backend through the gamend module: login, REST endpoints, lobbies and server hooks. It is on by default; building without the gamend feature drops it.

sequenceDiagram
  participant S as script
  participant G as gamend module
  participant B as Gamend backend
  participant T as next tick
  S->>G: gamend::login(…) → id
  G->>B: request, on a worker thread
  B-->>G: reply
  G-->>T: queued for the start of the tick
  T->>S: on_gamend_event, or the awaited id resolves

The sequential shape

pub class Online {
    node: Node,
    socket: int,
}

impl Online {
    pub async fn init() {
        gamend::configure();   // [gamend] url: gamend.org unless the project names its own
        let device = gamend::Credentials { device_id: engine::device_id() };
        let login = await task::wait(gamend::login(device));
        self.socket = gamend::connect(self.node);
        let hook = await task::wait(gamend::call_hook(self.socket, "arena", "start"));
    }

    pub fn on_gamend_event(e: any) {
        if e["kind"].as_str() == gamend::EVENT_REOPENED {
            log::info("back online");
        }
    }
}

Staying connected

A socket dropped without gamend::close comes back by itself.

The full function list is in the script modules reference.

Accounts

login and register cover the ways a player gets an account.

let device = gamend::Credentials { device_id: engine::device_id() };
await task::wait(gamend::login(device));

let account = gamend::Credentials { email: "ana@example.com", password: "a long password" };
await task::wait(gamend::register(account));
await task::wait(gamend::login(account));

The server

gamend::configure() with no URL reads the project's [gamend] settings.

[gamend]
url = "https://gamend.org"
local_url = "http://localhost:4000"
plugin = "skyrace"

Stores

Contents

The platform module is one script API over every store.

flowchart LR
  S["script"] --> P["platform: sign-in, achievements, leaderboards, cloud saves, purchases"]
  P --> A["Game Center · iCloud · StoreKit: the apple module, today"]
  P --> G["Play Games (planned)"]
  P --> ST["Steam (planned)"]
  P --> N["no store loaded: every call answers kind = unsupported"]
pub class Player {
    node: Node,
}

impl Player {
    pub async fn init() {
        events::listen(self.node, "platform_event");
        let me = await task::wait(platform::sign_in());
        log::info("playing as {me["alias"]}");
        platform::unlock("first_blood");
    }

    pub fn on_platform_event(e: any) {
        if e["kind"].as_str() == platform::EVENT_SIGNED_OUT {
            // The player signed out in the OS. A node that listens hears it.
        }
    }
}

The portable module

Call What it does
sign_in, player, signed_in Who is playing. A node listening for platform_event hears a later sign-out
unlock, progress Award an achievement, or report progress on it
submit_score, scores Post to a leaderboard, and read it: scope, period, count and start in the options
cloud_read, cloud_write A value the store syncs between the player's devices
set_presence What the player is doing, where the store shows it

A store without one of these answers unsupported: Game Center has no presence.

Achievements and rollback

Apple

The apple feature puts Game Center behind the portable calls and adds the apple module.

Portable call On an Apple platform
platform::sign_in Game Center, including its sign-in sheet
platform::unlock, progress GKAchievement
platform::submit_score, scores GKLeaderboard
platform::cloud_read, cloud_write The iCloud key-value store

Apple only:

pub async fn init() {
    events::listen(self.node, "apple_event");                  // arrivals nobody asked for
    let proof = await task::wait(apple::identity());  // for the server to check
    apple::show_dashboard(apple::ShowDashboardOptions { state: "leaderboards" });
    apple::access_point(true, apple::AccessPointOptions { location: "top_trailing" });
}

The engine never decides who a player is or whether a purchase counts. It carries the proof (an identity signature, an identity token, a transaction's signed jws) for a server such as Gamend to check.

Buying

pub class Shop {
    node: Node,
}

impl Shop {
    pub async fn init() {
        let found = await task::wait(apple::products(["com.studio.game.coins"]));
        let bought = await task::wait(apple::purchase("com.studio.game.coins"));
        if bought["kind"].as_str() == apple::EVENT_PURCHASED {
            // Send bought["jws"] to your server. Once it has granted the thing:
            apple::finish_purchase(bought["id"].as_str());
        }
    }
}

Export declarations

Apple resolves each of these services against the bundle. A game declares them in project.toml; balaur export writes the Info.plist and the entitlements file from it. See Shipping.

The full function list is in the script modules reference.

Plugins

Contents

Everything above the core is a plugin: physics, rendering, audio, networking. One Plugin trait covers them all, and one source builds either way.

Static Dynamic
Ships as Part of the engine binary, behind a cargo feature A shared library in the project's extensions/ directory
Runs on Every platform, the web included macOS, Linux and Windows
Written in Rust Rust, or C, Zig, Odin, C++
Needs An engine built from source A desktop release, which has the extensions feature
Starter crates/balaur_physics examples/extension_greeter (Rust), examples/extension_c_counter (C)

A dynamic plugin in Rust

balaur_plugin is the one dependency.

[package]
name = "greeter"
version = "0.1.0"
edition = "2024"

[lib]
crate-type = ["cdylib"]

[dependencies]
balaur_plugin = { git = "https://github.com/balaurengine/balaur", tag = "v0.2.0" }
use balaur_plugin::prelude::*;

pub struct Greeter {
    manifest: Manifest,
}

impl Default for Greeter {
    fn default() -> Self {
        Self {
            manifest: Manifest::new("greeter", env!("CARGO_PKG_VERSION")),
        }
    }
}

impl Plugin for Greeter {
    fn manifest(&self) -> &Manifest {
        &self.manifest
    }

    fn declare(&mut self, reg: &mut Registry<'_>) -> Result<()> {
        let mut m = reg.script_module("greeter")?;
        m.function("greet", |_: &Engine, name: String| Ok(format!("hello, {name}")));
        m.constant("VERSION", Value::Str(env!("CARGO_PKG_VERSION").into()));
        Ok(())
    }
}

balaur_plugin::export_plugin!(Greeter);
cargo build --release
cp target/release/libgreeter.dylib my-game/extensions/   # .so on Linux, greeter.dll on Windows

Scripts call greeter::greet("world") like any built-in module.

A dynamic plugin in C

Any compiler with a C ABI works. No toolchain match is needed.

int32_t balaur_extension_declare(const BalaurApi *api, BalaurRegistry *registry) {
    BalaurModule *m = api->module_open(registry, balaur_str("counter"));
    api->module_function(m, balaur_str("add"), add, NULL);
    api->module_close(m);
    return 0;
}
cc -shared -fPIC -I path/to/include -o libcounter.so counter.c   # .dylib on macOS

A C plugin covers script functions and constants. Components, systems and calls back into scripts are on the roadmap.

A static plugin

A static plugin is part of the engine build and runs on the web and mobile.

Turning plugins on and off

[plugins] in project.toml decides what a project loads.

The design is in ARCHITECTURE.md.

The editor

Contents

A Balaur project. Its scripts draw the interface through the ui module, and editing one hot reloads the editor. Every binding it uses (filesystem access, TOML parsing, scene instantiation, script reload, camera control, debug drawing) is available to any project.

balaur edit my-game

The editor on examples/angrynerds: the node tree, the viewport with its 2D grid and gizmo, the inspector, and the dock tabs

The project manager

Started with no project, the editor opens on the manager. It has four tabs: the projects this machine has opened, the examples that ship with the editor, the projects on Forge, and the engine build itself. It is a screen of the editor rather than a window of its own, so it hot reloads like the rest of the shell and works on a phone.

The Projects tab: a filter, the ways to start, and the projects this machine has opened with their paths, times and engine versions

A row says when it was last opened and which engine opened it. A project whose folder has gone stays in the list and says so, because a missing one is usually an unplugged disk. New project opens a dialog; Open folder uses the platform's own folder picker.

Opening a project starts the editor on it and closes this one. One process is one project, because the export and import modules and the file root are built for the project the editor booted with.

Open project…, New project… and Recent projects… are in the command palette, so the manager is reachable without closing what is open. Opened that way, it has a Back button, and Escape returns to the project.

Examples

The Examples tab: a card per example project, each with its name and a line saying what it is

The example projects ship beside the editor. Opening one copies it into your projects folder and opens the copy, so the shipped example stays as it was and a second copy is a second project.

Engine versions

The manager's Engine tab is the build itself: which version this is, which channel it follows, and every release that channel has published. Opening the tab reads the release feed once; installing replaces the whole install, which is what balaur update does from a terminal.

The Engine tab: this build and whether it is current, the channel to follow, and the releases on it

Follow picks the line: alpha, beta, rc, stable or nightly. The releases under it are that line's, newest first, with the installed one marked. Each button says which way it goes, Install or Downgrade, and a release can also be named exactly. An install downloads in the background with a progress bar; restart to use it.

A build from a checkout belongs to no channel and says so. An install that cannot replace itself says why before offering anything: a macOS bundle offers the release's disk image to download, and a cargo target directory offers nothing.

About Balaur

The About dialog: the version, build, channel, platform and license, and where this build's channel stands

About Balaur, in the menu under the logo, shows the version, build, channel, platform and license. It checks the build's own channel once and offers the newest release on it, through the same code as the Engine tab.

The document and the mirror

Workspaces

The top bar switches between five workspaces. Each arranges the same panels (node tree, viewport or code, docks, inspector) around one job.

Selecting

The selection is a set. Its first node is the active node.

The Library dock open under the viewport, with a torus selected and pointed at the library's metal material

Tools

The strip beside the viewport: Select, Move, Rotate, Scale, Pen, and two rig tools. Rig bone grows and poses a skeleton. Polygon edits a skinned polygon's points, triangulation, UVs and weights. Both are under Skeletons and skins.

Pen edits a path2d asset in place: click adds an anchor, drag pulls its handles, alt breaks the pair, right-click removes one, and clicking the first anchor closes the path.

Asset imports

A file dropped on the window becomes a node.

Docks, palette, themes

Eleven docks sit under the viewport.

The Cost dock: a row per node with its triangles, texture bytes and a bar, and a multimesh drawing sixteen copies

The code pane with the window to itself, the hooks list beside it, and the Focus chip lit in the top bar

Start-up states

The editor starts in any state named on the command line.

balaur edit examples/rig --offscreen --frames 100 \
  --state "anim,select:Thigh,tool:bone,shot=thigh.png"

Extending the editor

A plugin is a Balaur Script file adding docks, windows, palette commands, inspector sections, property editors, viewport overlays and start-up states.

// mygame/editor/counter.bs
pub class Counter {
    node: Node,
    shown: int = -1,
}

impl Counter {
    pub fn register() -> any {
        {
            "panels": [{ "id": "counter", "title": "Counter", "draw": "draw" }],
            "commands": [{ "title": "Count scripted nodes", "icon": "Σ", "run": "count" }],
        }
    }

    pub fn count(payload: any) {
        let editor = scene::get_node("Editor");
        let n = 0;
        for found in editor.call("nodes") {
            if found.as_node().script_path() != "" {
                n += 1;
            }
        }
        self.shown = n;
        editor.call("kit_changed");
    }

    pub fn draw(payload: any) {
        let editor = scene::get_node("Editor");
        editor.call("kit_rows", payload["host"], "body", [editor.call("kit_empty", "{self.shown} scripted nodes")]);
    }
}

Each list is optional.

List Entry The method gets, and answers
panels { id, title, icon, tall, draw } { host, theme }; fills the dock at host
dialogs { id, title, rows } { theme }; answers the window's rows
commands { title, icon, shortcut, run } {}
inspector_sections a method name { theme, node }; answers rows drawn under the built-in inspector
overlays a method name {}; draws viewport lines
property_editors a schema datatype: a method name { spec, value, at }; answers the row's controls
startup_states a state name: a method name {}; a plugin's own --state

A panel with tall: true makes the bottom dock grow while it is open.

A dock is a node. The editor makes each registered dock a subtree and hands the panel method its path: a head for verbs, a side for pages, a body of rows and a foot. A plugin reaches the editor through the Editor node's methods.

Method What it does
nodes() The scene's nodes, in tree order
select(i) Selects row i
open_scene(rel) Opens one of the project's scenes
plugins() The plugins loaded, by file name
kit_bar(host, part, controls) Puts a row of controls on head, side or foot
kit_rows(host, part, specs) Puts rows on the body; a spec is { label, controls }
kit_pages(host, id, groups) A sidebar of pages, and answers the open one
kit_tree(id, value, opts) A map or list as rows; edit makes leaves fields
kit_field(label, value, opts) A labelled value; mask hides it, copy adds a copy button
kit_heading(title), kit_empty(text) A heading, and what an empty panel says
kit_files(id, opts) A folder's files; TOML and JSON open as editable trees
kit_save_prefs() A write of the editor's settings
kit_save_project() A write of the game's project.toml, after a plugin set a project setting
kit_short_path(path) A path with the home folder written as ~
kit_changed(), kit_open_dialog(id) Redraws the plugin's docks and windows; opens a window
pub fn draw(payload: any) {
    let editor = scene::get_node("Editor");
    editor.call("kit_rows", payload["host"], "body", [
        editor.call("kit_field", "token", "abcd1234efgh5678", { "mask": true, "copy": true }),
    ]);
}

A control is the widget table the editor's own rows are built from. The controls are nodes: they take theme roles, and the same layout places them.

The editor's User data dock is kit_files over the open game's user data folder. Saves and prefs open there as structures you can edit. A game played in the editor writes to that same folder.

A plugin runs unsandboxed in the editor's host, with the editor's capabilities.

Determinism

Contents

Identical inputs produce a bit-for-bit identical simulation on every platform. Replays, lockstep networking and content-change checks depend on it.

For multiplayer games

Balaur for multiplayer: lockstep, rollback, and a replay to attach to a bug report.

Engine measures

Scripting and determinism

Hazard Status
sin, cos, exp, pow, ... call the platform libm, which differs across OSes The math module (math::sin, math::pow, math::PI, ...) is pure-Rust libm, bit-identical everywhere. The language's own sqrt, abs, floor, ceil, min and max are IEEE-exact
A random source seeded from entropy The language has none. The random module (random::seed/float/range/int) is an engine-owned seeded PCG32 stream with a fixed default seed
Iteration order over a map An any map keeps its keys in the order they were written, on every machine
Wall-clock time leaking into simulation Simulation goes in fixed_update(dt), on the 60 Hz step with a constant dt; update(dt) is for presentation. engine::tick() is the clock
Hot reload mid-run Off for a run to be verified

Checking, recording, replaying

--fixed-tick pins the step. --trace-digest writes a hash of the world each tick.

balaur run my-game --fixed-tick --trace-digest run-a.txt
balaur run my-game --fixed-tick --record run.blr
balaur replay run.blr --verify          # stops at the first tick that disagrees
balaur replay run.blr --entries-at 25   # that tick, one digest per node and component

In the editor

Tests

Shipping a game

Contents

flowchart LR
  A["scripts · scenes · assets · manifest"] -->|"balaur export"| B[".bpak: scripts, scenes, assets; sorted keys, so the same sources give the same bytes"]
  B -->|"balaur play"| C["a runtime"]
  B -->|"fuse onto a runtime"| D["one self-contained executable per platform"]

Export packs

balaur export my-game        # writes my-game.bpak
balaur play my-game.bpak     # run the pack

Splash Screen

A game's first frames have nothing to draw yet. [application] splash is the picture that goes over them, on every target, a browser tab included. It is project-relative, fits the screen and keeps its aspect.

[application]
splash = "art/logo.png"
splash_seconds = 1.5

A script that reports a load holds the splash past its seconds, and draws a bar under the picture. One that reports nothing leaves at its seconds.

ui::set_load_progress(0.4, "textures");
ui::finish_loading();

The seconds are engine time, so a recorded session replays the splash for as long as the run showed it.

Fused executables

balaur export my-game --target linux-x64     # or macos-universal, windows-x64
Getting another platform's runtime How
Download balaur export offers to fetch it from the engine's release tag, verified against SHA256SUMS, into a per-user cache (<data dir>/balaur/runtimes/<version>)
Without a prompt --download, or --no-download to forbid fetching (CI)
By hand drop a balaur-runtime-* binary into runtimes/, point BALAUR_RUNTIMES at a directory, or pass --runtime <file>

A runtime is pinned to the compiler version that wrote the export pack.

Smaller runtimes

[export] runtime puts a game on a runtime with one physics world, or with neither, smaller than the full one. Every target has all three.

[export]
runtime = "2d"          # "full", "2d", "3d" or "bare"

[override.web.export]
runtime = "3d"          # for one target alone
balaur export my-game --target linux-x64-server -o my-game-server

Mobile

balaur export my-game --target ios       # -> my-game.app
balaur export my-game --target android   # -> my-game-android/ (an APK layout)

Web

balaur export my-game --target web       # -> my-game-web/

A pack in pieces

[export]
later = ["scenes/level*.toml"]

Apple

An .app is written from the [apple] table.

[apple]
bundle_id = "com.studio.game"    # the identifier registered in App Store Connect
team_id = "AB12CD34EF"           # the ten-character team identifier
version = "1.2"                  # CFBundleShortVersionString
build_number = "7"               # CFBundleVersion
min_ios = "15.0"                 # iOS; min_macos for the Mac
capabilities = ["game-center", "icloud-kv", "in-app-purchase"]

[apple.plist]                    # anything else the bundle needs, as written
ITSAppUsesNonExemptEncryption = false
codesign --entitlements my-game.entitlements --sign "Apple Distribution: …" my-game.app

Updates

balaur update replaces the whole install as a set: the binary, the bundled editor and its runtime.

Save games

The library's save addon keeps one table per slot in the player's user data directory. Add it from the Library dock, which adds it with the Gamend addon too.

use addons::save::save;

save::write("slot1", { "level": 4, "coins": 120 });
let data = save::read("slot1");
Call What it does
save::write(slot, data) stores a table as saves/<slot>.toml in the user data directory
save::read(slot) brings it back, or nil when there is none
save::slots() lists them
save::remove(slot) deletes one

Embedding

fn main() -> anyhow::Result<()> {
    balaur::boot_pack(include_bytes!("game.bpak"))
}

Embedding needs a Rust toolchain. Fused export does not.

Build size

Contents

The engine module is most of a web game's download. Two modules are built from one crate: the game template balaur export --target web ships, and the editor's module behind the examples and a project's editor.

balaur_bg.wasm, 2026-11-02 Raw Brotli
Game template 19.7 MB 5.0 MB
Game template, physics2d only 17.3 MB 4.6 MB
Game template, physics3d only 17.6 MB 4.7 MB
The editor's module 25.1 MB 6.6 MB

What a game template leaves out

The template is balaur_cli built without four features the editor's module has.

The web game template also leaves out two features every other build has, and builds its own std:

Every build decodes images as PNG, JPEG, WebP, BMP, TGA, HDR and EXR, the formats a material and a sky read. The marked-up text shaper and egui's share one harfrust and one read-fonts.

Module contents

One module carries the whole engine; nothing loads lazily.

section Editor's module Game template
code 19.1 MB 15.7 MB
data 5.8 MB 3.8 MB

scripts/wasm_crates.py in the engine repository charges a module's code to its crates, and every build of a template writes that table to crates-<template>.txt beside it. scripts/native_crates.py does the same for a desktop, Android or iOS template.

Baked in by a dependency Raw Brotli
kiss3d's Tony McMapface table, the editor's module only 0.8 MB 0.2 MB
egui's default fonts, the editor's module only 1.4 MB 0.7 MB

A game that sets tonemap = "tony_mcmapface" carries the Tony McMapface table in its export pack instead, deflated: 350 KB more pack.

The rest of the data is tables: Unicode data for the text shapers, codec tables, and kiss3d's built-in shaders, linked when it compiles.

Export pack size

The export pack is the second download. Every export prints a report.

pack 2.0 MB
section                                 entries      bytes
manifest                                      1       78 B
scenes                                        1     3.4 KB
scripts                                      37   488.2 KB
assets                                        6     1.6 MB

extension                               entries      bytes
ttf                                           4     1.5 MB
png                                           2    22.7 KB

largest                                              bytes
fonts/Phosphor-Fill.ttf                           477.2 KB
fonts/SourceSans3-Regular.ttf                     421.1 KB
fonts/SourceSans3-Semibold.ttf                    415.9 KB
assets/balaur-logo.png                             20.2 KB

0 files nothing references, 0 B

Where an export pack's bytes are, and what lossless re-encoding takes off

[export]
strip = true                             # drop an asset no scene, script or include glob names
include = ["sfx/**"]                     # ...except paths a script builds at run time
image_recode = "webp"                    # write lossless WebP
font_recode = "subset"                   # cut a face to the characters the project shows
font_original = ["fonts/SourceSans3-*"]  # ...but ship these whole
audio_recode = "flac"                    # write uncompressed WAV as lossless FLAC

Anything under fonts/ survives a strip: the UI finds faces by listing that directory, and no scene names one.

Two more keys are lossy, and named separately from the lossless ones.

[export]
image_recode = "quantized"  # a 256-colour palette with alpha, then the PNG pass
image_quality = 80          # the palette's quality target, 0 to 100
audio_recode = "vorbis"     # an Ogg Vorbis stream instead of the original PCM
audio_quality = 0.5     # libvorbis quality, -0.1 to 1.0

One picture overrides the mode in its own import settings.

# art/logo.png.import.toml
recode = "original" # this one ships exactly as drawn

Building a smaller runtime

Every release carries a template per physics world for every target, and one with neither, which the project picks (see Shipping).

[export]
runtime = "2d"   # web-2d: no rapier3d; "3d" leaves out rapier2d, "bare" both

A template built with fewer features still is passed to the exporter.

WEB_FEATURES=audio,vorbis,browser,window,physics2d,bs-web scripts/package_runtime.sh web
balaur export my-game --target web --runtime dist/balaur-runtime-web

Features

The cargo features of balaur_cli, the binary every runtime is built from, and what each adds to a wasm32-unknown-unknown build. A feature's native dependencies are gated off that target, so http or websocket costs a browser build only the plugin's own code; the two that matter there are audio and window.

The web runtime (scripts/package_runtime.sh web) is built with --no-default-features --features audio,flac,mp3,mp4,vorbis,wav,http,websocket,webtransport,multiplayer,browser,physics2d,physics3d,bs-web,bs-jit,window and links 288 crates. Override the set with WEB_FEATURES=... scripts/package_runtime.sh web.

WEB_THREADS=1 builds the second runtime, which adds parallel to that set: rapier's solver threads on rayon, which needs the shared memory and atomics only that build has.

Feature Default Web runtime What it is Adds to a web build
apple off off apple.* for scripts, and Game Center and iCloud under platform.*. Off, a build drops GameKit and the objc2 bindings to it. platform.* is always there; with no store behind it every call answers unsupported. balaur_apple
audio off on Sound. Off, a build drops rodio, cpal and the platform audio stack. nothing
browser off on browser.* for scripts: the page a browser build runs in. Always compiles; off the web every call answers nil. nothing
bs off off Balaur Script (.bs), the language scripts are written in: bs on wasmi or an iOS export's native build, bs-jit on wasmtime (5 to 7 times wasmi, about 11 MB; not on the web or iOS), bs-web on the page's own engine. nothing
bs-jit off on nothing
bs-wasmi off off The interpreter alone: what the web editor's module adds beside bs-web so a debugger can park a call. nothing
bs-web off on nothing
compile off off The WESL shader linker, the .bs compiler and its C translator: a dev run, the editor and an export. A template leaves it off and draws with the shaders an export linked, and runs the script units it compiled, into the export pack. nothing
editor off off The editor: edit and export, the export.*, project.*, debugger.* and script.* modules its scripts call, a browser tab's editor entry points, and egui's bundled faces. A game template leaves it off. nothing
env-filter off off RUST_LOG with tracing's full filter syntax, regex included. Off, plain target=level rows, and 0.23 MB less of a web module. nothing
extensions off off Load extensions from a project's extensions/ directory at run time. libloading
flac off on One feature per container audio decodes; a build without one plays none of that format. nothing
headless on off Every default but the window: a tool that opens none, on a machine that may have no display. Its runs are headless. nothing
http off on http.* for scripts. Off, a build drops ureq and its TLS stack. nothing
import off off balaur import, import.* for the editor and SVGs read in place. The web game runtime leaves it off: a game reads what an import and export wrote. nothing
mp3 off on nothing
mp4 off on nothing
multiplayer off on multiplayer.* for scripts: host, join and play a rollback match over whichever of websocket and webtransport the build has. nothing
parallel off off rapier's solver on rayon. Native builds want it; a browser can only take it with shared memory and atomics, which is the threaded web runtime alone. nothing
physics2d off on The 2D physics world: physics2d.* and its components. nothing
physics3d off on The 3D physics world: physics3d.* and its components. nothing
vorbis off on nothing
wav off on nothing
webgl on off WebGL2 beside WebGPU in a browser, for a page without WebGPU. 1.0 MB of a web module, and nothing on any other target. glow, wgpu-core, wgpu-core-deps-wasm, wgpu-hal, wgpu-naga-bridge
websocket off on websocket.* for scripts, and the websocket Transport. Off, a build drops tungstenite, rustls and the frame codec; the Gamend addon's realtime socket runs on them. nothing
webtransport off on The WebTransport Transport, over QUIC: the transport rollback and replication are meant to run on. Off, a build drops quinn, its runtime and the certificate machinery, which is most of what a networked build costs. nothing
window on on Windowed rendering (kiss3d/wgpu). egui-wgpu, glow, kiss3d, naga, wgpu, winit, … (27 crates)

What the web runtime resolves

The features on in the dependencies that weigh most. A feature named here is enabled; whether it links code on the web is up to that crate's own target gates (winit's X11 is on and compiles nothing in a browser).

Crate Version Features on
egui 0.37.0 none
wgpu 30.0.1 dx12, fragile-send-sync-non-atomic-wasm, gles, metal, parking_lot, std, vulkan, web, web-sys, webgpu, wgsl
image 0.25.10 bmp, exr, hdr, jpeg, png, tga, webp
rodio 0.23.0 cpal, dither, experimental, flac, mp3, mp4, noise, playback, rand, rand_distr, symphonia, symphonia-aac, symphonia-flac, symphonia-isomp4, symphonia-mp3, symphonia-ogg, symphonia-pcm, symphonia-vorbis, symphonia-wav, vorbis, wasm-bindgen, wav
rapier3d 0.36.1 alloc, debug-render, dim3, enhanced-determinism, f32, fem, serde-serialize, std
parry3d 0.31.1 alloc, dim3, downcast-rs, ena, enhanced-determinism, f32, hashbrown, indexmap, required-features, rstar, serde, serde-serialize, serde_arrays, slab, smallvec, spade, std
cosmic-text 0.19.0 monospace_fallback, shape-run-cache, std, swash, sys-locale
wesl — not in the runtime

The web profile

The web profile in the engine's Cargo.toml sets opt-level = "z", fat LTO, one codegen unit, panic = "abort" and stripped symbols, and the script runs wasm-opt -Oz after bindgen. panic_immediate_abort would cut more, and a panic in a browser would then log nothing.

Continuous integration

Contents

Three actions, each named for what it produces. A game pins one version, the engine's, and gets the engine, its runtimes and the actions from that tag.

uses: Produces
balaurengine/balaur/.github/actions/setup@v0.2.0 a published balaur on PATH, verified against the release's SHA256SUMS, with the named runtimes
balaurengine/balaur/.github/actions/export-game@v0.2.0 a signed build per target, uploaded as an artifact
balaurengine/balaur/.github/actions/build-engine@v0.2.0 the editor and runtimes built from source, for features the published build lacks

setup installs the release its own ref names: @v0.2.0 installs v0.2.0. @main follows the rolling nightly.

A build on every tag

name: Build
on:
  push:
    tags: ["v*"]

jobs:
  export:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: balaurengine/balaur/.github/actions/setup@v0.2.0
        with:
          targets: "linux-x64 windows-x64 web"
      - uses: balaurengine/balaur/.github/actions/export-game@v0.2.0
        with:
          targets: "linux-x64 windows-x64 web"

The whole file for an unsigned build. setup downloads the engine and export-game runs it. No secret, account or Rust toolchain is needed.

Signing

      - uses: balaurengine/balaur/.github/actions/export-game@v0.2.0
        with:
          targets: "macos-universal ios"
          macos-identity: "Developer ID Application: Studio (AB12CD34EF)"
          macos-certificate: ${{ secrets.MACOS_CERTIFICATE_P12 }}
          macos-certificate-password: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
          notarize: true
          notary-key: ${{ secrets.ASC_KEY_P8 }}
          notary-key-id: ${{ secrets.ASC_KEY_ID }}
          notary-issuer: ${{ secrets.ASC_ISSUER_ID }}

A GitHub secret holds text. Every file-shaped secret is stored base64-encoded: a .p12, a .p8, a .mobileprovision, a .jks, a .pfx.

base64 -i certificate.p12 | pbcopy      # macOS
base64 -w0 release.jks                  # Linux

Per target:

Target Needs Runner
linux-x64, linux-arm64 nothing any
windows-x64 windows-certificate and its password, or an Azure Trusted Signing metadata JSON for a key in a cloud HSM any; a non-Windows runner signs through osslsigncode
macos-universal macos-certificate, macos-identity, and the three notary-* inputs to notarize macOS
ios ios-certificate, ios-identity and ios-provisioning-profile; ipa: true for TestFlight macOS
android android-keystore, android-key and the passwords; without them the build takes Android's debug identity, which installs but ships nowhere any with the SDK
web nothing; a browser trusts the origin any

Identities, team ids and keystore aliases are not secrets and may live in the project's [apple], [android] and [windows] tables. Passwords may not.

A custom engine

The published runtimes carry window and extensions, plus apple on macOS. A different set (a smaller web build, one without the networking stack) means building the engine.

      - uses: actions/checkout@v7
        with:
          repository: balaurengine/balaur
          ref: v0.2.0
      - uses: ./.github/actions/build-engine
        with:
          target: linux-x64
          features: "window,extensions,audio"

Runner cost

Without runners of your own

Forge runs the same exports as a service. With its GitHub App installed, every push builds each target you pick on Linux, macOS and iOS included, so there are no Mac minutes. Forge signs each build with keys that never enter it and puts a Forge / <target> check on the commit. The first build guide walks through it.

Text

Contents

text2d and text3d draw text in the scene. The widget layer draws text on the screen.

One shaper and one glyph atlas serve both: bidirectional text, Arabic joining, CJK and Thai line breaking and the project's font chain work the same in a panel and in the world.

Text, one row per thing it does

Two components

text2d draws in the 2D pass, sized like a sprite. text3d draws in the 3D pass on a quad facing the camera. They take the same keys, and text3d adds a few.

[[nodes]]
id = "sign"
name = "Sign"

[nodes.transform]
position = [0.0, 1.6, 0.0]

[nodes.text3d]
text = "A score on a sign"
font_size = 64
color = [1.0, 0.85, 0.3, 1.0]
pixels_per_unit = 110
text_style = { outline_size = 3.0, outline_color = [0.1, 0.05, 0.0, 1.0] }
Key What it does
text The string drawn
text_key A key in the project's strings, re-read every frame; it wins over text
font The face: a file such as fonts/Inter.ttf, or a font asset. Empty takes the theme's default font
font_size, font_weight, font_style Height in font pixels, 100–900, and normal, italic or oblique
text_style Line height, spacing, outline and shadow: a text_style asset, or one written inline
color, text_align Tint, and where the block sits across the node's origin
max_width, max_height, max_lines Font pixels the lines wrap and stop at, and the most lines kept
line_break, tab_width Where a wrapped line may break, and the spaces between tab stops
truncate, truncate_at End a cut block with an ellipsis, and which part it stands in for
markup Read the text as markup
material What every layer draws with, reading the glyph atlas as its texture
pixels_per_unit Font pixels to one world unit

Outline and shadow

text_style holds what dresses a text past its font. Write it inline, as above, or keep it in a file under text_styles/ and name its path.

# text_styles/sign.toml
type = "text_style"
line_height = 1.2         # baselines apart, as a multiple of the size
letter_spacing = 1.0      # extra pixels between glyphs
outline_size = 3.0
outline_color = [0.1, 0.05, 0.0, 1.0]
shadow_offset_x = 2.0
shadow_offset_y = 2.0
shadow_color = [0.0, 0.0, 0.0, 0.5]

Markup

With markup = true the text takes the same tags as a widget's label: [b], [i], [color=#7fd4ff], [wave amp= freq=], [center], [right] and an inline [img=…]. A coloured run keeps its own colour over the block's.

Two more tags answer the pointer, which only a widget label can do: [url=target] calls that label's on_link with the target, and [hint=text] shows the text while the pointer rests on the span.

From a script

let node = scene::get_node("Hud/Score");
node.text2d.text = "{self.score}";
let p = self.node.transform.global_position();
render::draw_text_3d(p.x, p.y + 2.0, p.z, "over a character", render::TextOptions { font_size: 32.0, text_align: "center" });
render::draw_text_2d(0.0, 3.0, "in the 2D pass", render::TextOptions { font_size: 24.0 });

Measuring

let size = render::text_size("measure me", render::TextOptions { font_size: 32.0 });   // size.x, size.y

Bitmap fonts

[nodes.text2d]
text = "SCORE 1200"
font = "fonts/pixel.fnt"
font_size = 32

Editing in the viewport

Double-click a text2d or text3d in the Scene workspace to open a field over it. Enter keeps the text, Escape drops it.

Cost

examples/text has all of it.

Tile maps

Contents

A tilemap node draws a grid of cells over a tileset.

Collision

[tiles.0]
collision = "full"

[tiles.7]
collision = [[[0, 16], [16, 16], [16, 8]]]   # a slope, in tile pixels
one_way = true

set_cell marks the map. The collider is rebuilt once on the next fixed step, however many cells changed.

Autotiling

A painted terrain resolves through one table of [[rules]], read in order. The first match wins.

[[rules]]
terrain = "grass"
pattern = ["?#?",     # ? any   # this terrain   . anything else
           "?#.",
           "?##"]
tile = 12
transforms = ["rotate", "mirror"]
outside = "same"

Animated and occluding tiles

[tiles.14]
animation = { frames = [14, 15, 16], fps = 8 }

[tiles.3]
occluder = true

Cells and layouts

The Tiles dock

Importing from Tiled and LDtk

balaur import level.tmx --project game
balaur import world.ldtk --project game

Writes the atlas, a tileset per sheet (grid, spacing, margin, per-tile collision, animations) and a scene for the level: one root named after the map, one tilemap node per tile layer under it.

An .ldtk project writes a scene per level. Its entities become nodes under that root, each carrying its fields.

A level too big for a scene keeps its rows in a .cells file that cells names. tilemap, tileset and tile_collision are in the reference.

Dependencies

Contents

A dependency is another Balaur project, imported whole into deps/<alias>/. Its scenes, scripts, textures, fonts and sounds are the game's to use and not to change.

# project.toml
[dependencies]
ui_kit = { project = "dragos/ui-kit", branch = "main" }
fonts = { project = "ana/fonts", tag = "v2" }
stash = { path = "../stash" }

Adding one

balaur add dragos/ui-kit            # alias ui_kit, default branch
balaur add ana/fonts --tag v2
balaur add ../stash --as stash      # a folder
balaur fetch                        # fill deps/ from project.lock
balaur fetch --update               # newest commit of each branch or tag

Paths

A dependency's files name each other from its own root.

Read-only

Export

Script API

Function Does
dependency::list() Every installed dependency: alias, folder, kind, project, branch, tag, path, rev, license
dependency::of(path) The alias a path lies in, or nil
dependency::make_local(from, to) Make local
dependency::move_into(paths, alias) Move to project
dependency::add_path(game, alias, path) Declare a path dependency and install it
dependency::install(game) Read [dependencies] again and install each

Not yet

Balaur Script reference

Contents

What each construct does, and what it refuses. The examples are programs from the compiler's test corpus (crates/balaur_bs/tests/programs/), which runs every one on wasmi, wasmtime, native code and the browser's engine and holds them to the same answer. Scripting covers how a script meets a node.

A file

A .bs file holds items in any order: fn, struct, class, enum, impl, const, extern fn and use. pub makes an item reachable from outside the file. // starts a comment.

const NAME = "ball";
pub fn label(hp: int) -> str { "{NAME}: hp {hp}" }

Types

Type Holds
int a 64-bit signed integer
float a 64-bit float
bool true or false
str UTF-8 text, counted by reference
Node a node of the scene, or none
[T] a list, counted by reference
{str: V}, {int: V} a map, kept in the order keys were first set
T? a T, or nil
any a value of any kind, looked at when the script runs
fn(A, B) -> R a function, named elsewhere
a struct a value, copied field by field
a class one object every holder shares
an enum one of its variants, a value

Vec2, Vec3 and Color are structs the engine declares, and a list of numbers stands where one goes: let p: Vec3 = [1.0, 2.0, 3.0];.

Variables and constants

let declares a variable, typed by its value or by what it names: let n = 3;, let x: float = 3;. A variable can be assigned again, and +=, -=, *=, /= and %= combine. A let inside a block ends with the block. A const is fixed for the file, and a module's reads as util::NAME.

Numbers

Strings

const NAME = "ball";
pub fn label(hp: int, speed: float, alive: bool) -> str {
    "{NAME}: hp {hp}, speed {speed}, alive {alive}, {{braces}}"
}
// label(7, 2.0, true) is "ball: hp 7, speed 2.0, alive true, {braces}"

Lists

pub fn shuffle() -> [int] {
    let xs = [1, 2, 3];
    xs.insert(0, 0);
    xs.insert(4, 4);
    xs.insert(2, 9);
    let gone = xs.remove(2);
    xs.push(gone);
    xs
}
// shuffle() is [0, 1, 2, 3, 4, 9]

Maps

pub fn ages() -> {str: int} {
    let ages: {str: int} = {"ada": 36, "alan": 41};
    ages["grace"] = 85;
    ages["ada"] += 1;
    ages
}

Optionals

A T? is a T or nil. It is used through its methods: is_some, is_none, unwrap, which traps on nil, and or(fallback). x == nil compares. A value that is always there has none of them, and an optional cannot itself be optional.

pub fn names(k: int) -> str {
    let s: str? = if k > 0 { "pos {k}" } else { nil };
    s.or("none")
}

Structs and classes

A struct is a value: assigning or passing one copies its fields. A class is one object on the heap, shared by everyone holding it. A class holds itself through C? or a list; a struct only through a list.

pub struct Label { kind: str = "label", size: int = 3, text: str, tip: str? }
pub fn plain() -> str {
    let label = Label { text: "hi" };
    "{label.kind} {label.size} {label.text} {label.tip.is_none()}"
}
// plain() is "label 3 hi true"

A literal names what differs from the declared defaults. A field left out takes its default, or nil when it is optional; any other field must be named. impl Type { .. } gives a type its methods, with self writable.

Enums and match

An enum's variants carry nothing, values by position, or named fields. match takes the value apart.

enum Shape { Circle(float), Rect { w: float, h: float }, Empty }

fn area(s: Shape) -> float {
    match s {
        Shape::Circle(r) => r * r * 3.0,
        Shape::Rect { w, h } => w * h,
        Shape::Empty => 0.0,
    }
}

Functions

fn double(x: int) -> int { x * 2 }
fn apply(f: fn(int) -> int, x: int) -> int { f(x) }
pub fn twice(k: int) -> int { apply(double, k) }

Control flow

any

An any holds what has no one type: an HTTP reply, a save, a host's payload. Ints, floats, bools, strings, nodes, lists, structs and optionals box into one where one is wanted, and an any becomes the typed value a place asks for: let n: int = a["n"];.

kind, as_int, as_float, as_bool, as_str, as_node, len, has, keys, text, push, insert, remove and sorted. a["k"] reads a map and a[0] a list, and { "k": v } builds a map. A map or a list in an any changes in place for every holder.

Modules

use util; links util.bs from beside the file or a folder above it, and its pub items read as util::name. use a::b; is a/b.bs. Files may use each other, and the file that uses them.

Async

async fn may await a host call or another script async fn, and the host resumes it on a later frame. An async fn takes no &mut parameter: its caller runs on while it waits.

Errors

A compile error names its line and column: 6:7: cannot combine int and bool. A file that reads gives one error for each function that does not compile. A trap at run time (an index out of range, unwrap on nil, a division by zero, a missing map key under +=) ends the call, and the next call runs.

Not in the language

Generics, traits, closures, T?? and any?.

Architecture

Contents

The long version is ARCHITECTURE.md in the engine repository.

Layers

flowchart TB
  S["scripts: game code, and the editor itself, in .bs files"]
  B["balaur_bs: the compiler to WebAssembly, run on wasmtime, wasmi, a browser or as native code"]
  R["balaur_script_bs: host, hot reload, use files, debugger"]
  M["balaur_script, the seam: Bindings, ScriptHost, Value. Traits only. No language, no dependencies."]
  D["modules declared once against the seam: engine, scene, node, assets, animation, input, physics, …"]
  subgraph P["plugins"]
    direction LR
    P1["physics (rapier)"] ~~~ P2["render (kiss3d)"] ~~~ P3["audio (rodio)"] ~~~ P4["input (winit)"] ~~~ P5["anim (clip)"] ~~~ P6["your plugin"]
  end
  C["balaur_core: hecs ECS + scene tree + assets + scheduler. Names no scripting language."]
  S --> B --> R --> M --> D --> P --> C

Backends depend on core. Core never depends on a backend; the compiler enforces the direction.

ECS

Math

The Engine handle

Scene tree

The frame

flowchart LR
  A["First"] --> B["PreUpdate<br/>reload pump"] --> C["Update<br/>scripts, animation"]
  C --> D["FixedUpdate<br/>fixed_update, physics"] --> E["PostUpdate<br/>audio"]
  E --> F["SceneSync<br/>transforms"] --> G["Render"] --> H["Last<br/>deferred destruction"]
Rule
Fixed step FixedUpdate drains one accumulator into whole 60 Hz steps, zero to four a frame
Never the frame time The simulation never sees the measured frame time
Deferred structure A script's spawn or free waits for Last

The script seam

Plugins

The workspace

Crate Role
balaur_script The scripting seam: traits and a neutral value type; no language, no dependencies
balaur_core ECS world (hecs), scene tree, scheduler, plugin API, digests, replay, snapshots, export packs
balaur_geometry Meshes, primitives, paths, CSG, tiles, voxels, heightfields and bones
balaur_asset glTF models, images and textures
balaur_import Importers: models, Aseprite sprites, and Tiled and LDtk levels
balaur_project A pack built from a project, its report and strip, and the desktop's shell
balaur_bs Balaur Script: the compiler to WebAssembly, the runtime on wasmtime, wasmi and a browser's engine, the C translation for iOS, the formatter and the editor tooling
balaur_script_bs The Balaur Script backend: host, hot reload, use files, the debugger, export
balaur_physics Rapier plugin; the reference for wrapping a Rust crate for scripting
balaur_render Renderable components (shapes, sprites, skinned polygons, meshes) + render module; kiss3d/wgpu backend behind a feature flag
balaur_animation Animation clips, the pure sampler, tweens, easing, rig modifiers; the animation module
balaur_audio rodio-backed audio module
balaur_input Backend-agnostic input snapshot + input module
balaur_http http for scripts, delivered into the simulation per tick
balaur_websocket websocket for scripts, and a Transport for sessions
balaur_webtransport QUIC behind the same Transport, with native datagrams
balaur_net Rollback sessions between peers over any transport
balaur_multiplayer The multiplayer module: host, join and play a rollback match from a script
balaur_gamend The Gamend backend (gamend module): login, REST, realtime, server hooks
balaur_platform The platform module and the seam a store plugs into: sign-in, achievements, leaderboards, cloud saves
balaur_apple Game Center, iCloud and Sign in with Apple behind that seam, plus apple for purchases, notifications and opened URLs
balaur_plugin The Plugin trait a module or run-time extension implements, plus the loader
balaur_ui Game and editor UI as scene nodes, laid out with taffy and painted with egui; the ui module
balaur_text Shaping, font discovery and glyph outlines for UI and world text
balaur_browser The browser module: the page a browser build runs in
balaur_debug The DAP server, and the debugger and profiler script modules
balaur_android The Android entry point: a NativeActivity library that boots a packed game
balaur_derive Derives: a component's struct is its schema
balaur_cfg Build-script helper: the target facts every crate gates on
balaur_testkit Test harness: one booted app, ticked until its script says so
balaur Batteries-included facade: standard_app, boot_project, boot_pack
balaur_export Export as a library: export packs, fused executables, and the Apple and Android bundles; the editor and the CLI both use it
balaur_cli The balaur binary: new, run, export, play, edit, import, replay, api
balaur_bench Headless benchmarks: where a frame's time goes, and what scripting costs

Quality

Contents

Every rule here is a script. All but the example passes run on every push and pull request. docs/QUALITY.md has the same list with file paths.

Workflows

One workflow owns the triggers and calls four.

Workflow Covers
lint everything that reads the code without running it
docs both kinds of documentation
test everything that runs the engine
build everything that produces a download

A pull request runs all four. Only the release-publishing job is skipped.

The compiler

House lints

Three scripts, two severities. Error fails CI and is mechanical. Report prints only.

Rule Fails on
platform float math .sin(), .powf() and the rest that differ between operating systems; sqrt, abs and floor are exact and allowed
nondeterministic iteration iterating a hash map or set
channels outside the recorded seam anything that could reach the outside world during a replay
unjustified unwrap unwrap or expect outside tests without a justification
allow without a reason an #[allow(..)] that does not say why
TODO without an issue a TODO with no issue
function and file length 120 lines, 1200 lines
naming the mechanical half of the naming rules, a dozen checks
Also held How
The ratchet A per-file baseline records the violations predating each rule. Above that count fails. The baseline is never raised by hand
Comments One or two lines stating a constraint, in Rust, Balaur Script, Python, shell, YAML and TOML. A block over three lines fails, as does one that restates the line under it
Names Decided once and checked mechanically. The API half boots the engine and reads what it offers

Determinism

Two determinism breaks are compile errors:

Line endings are pinned in the index. CI checks two things:

  1. Every platform steps the same simulation. One digest per tick, 600 frames, five projects. The first differing line is the tick.
  2. The same sources build the same binary. Built twice on one runner and compared.

scripts/e2e.sh exports every example twice in separate processes; the files must be byte-identical.

A change that alters a recorded digest has to say why.

Tests

About 3,100 tests across 28 crates, on three desktop platforms. Beyond the plain run:

A test's name is a sentence about behaviour: freeing_a_node_frees_its_children. A test asserting from inside a script carries one control proving the script ran.

Example passes

scripts/e2e.sh runs the fifteen example projects these ways. scripts/precommit.sh --e2e runs it; CI does not.

Pass What it proves
check every script a scene attaches compiles, with a warning as a failure
run dev mode, from the sources
export, twice the two export packs match
play the export pack runs without the sources or a compiler
edit the editor, itself a Balaur project, booted headless against every example
render, twice the game and the editor drawn surface-less on a real GPU

The editor's self-tests run on angrynerds, hello, objects and rig, which between them hold what every test needs.

Every pass needs a clean exit and a clean log. A logged error or warning fails the run, as does an editor scene node the editor cannot resolve.

Headless covers loading, mirroring and asset rebinding, and the render passes what drawing reports. What a screen looks like is one screenshot per editor screen, rendered offscreen and diffed against a committed catalogue before any change to the editor's shell.

Generated documentation

Performance

Supply chain

Releases

Review

Review covers what a script cannot check:

One concern per pull request. Code, tests and docs land together, and the roadmap moves with the change.

Benchmarks

Contents

Balaur is the quickest engine on all 12 physics cases: about 3× faster than Godot Jolt and 11–18× faster than Godot Physics.

3D

3D chart

Balaur Godot Rapier 3D Godot Jolt Godot Box3D Godot Physics 3D
pyramid
3795 bodies
pyramid
10.33 ms 14.62 ms 26.92 ms 13.52 ms 48.03 ms
mixed_pile
5000 bodies
mixed_pile
4.94 ms 11.28 ms 13.70 ms 9.72 ms 84.90 ms
joint_grid
5000 bodies, 9950 joints
joint_grid
3.13 ms 8.92 ms — 10.27 ms 26.08 ms
smash
5001 bodies
smash
8.17 ms 19.14 ms 12.12 ms 9.62 ms 99.98 ms
query_storm
2000 bodies
query_storm
4.68 ms 5.93 ms 26.45 ms 6.67 ms 73.26 ms
drop
8000 bodies
drop
3.21 ms 12.26 ms 22.14 ms 11.34 ms —

2D

2D chart

Balaur Godot Rapier 2D Godot Box2D v3 Godot Physics 2D
pyramid
10000 bodies
pyramid
7.02 ms 20.03 ms 21.33 ms 147.26 ms
mixed_pile
5000 bodies
mixed_pile
2.88 ms 9.25 ms 6.71 ms 71.12 ms
joint_grid
5000 bodies, 9950 joints
joint_grid
2.20 ms 10.16 ms 4.93 ms —
smash
5001 bodies
smash
3.49 ms 11.86 ms 11.57 ms 55.09 ms
query_storm
2000 bodies
query_storm
4.23 ms 6.25 ms 4.56 ms 57.24 ms
drop
8000 bodies
drop
6.35 ms 16.54 ms 22.66 ms 103.34 ms

Nodes

Milliseconds for the whole loop, lower is better. Godot's numbers are its own published run, on a 12th-gen i5.

operation Balaur Godot
add_children 24.33 ms 28.19 ms
delete_children_in_order 13.35 ms 9.82 ms
delete_children_reverse 14.47 ms 6.10 ms
delete_children_random 17.04 ms 19.63 ms
get_node 51.69 ms 29.60 ms

How it was measured

Balaur c862aad11 against Godot 4.7-stable (official) on Apple M1, 8 cores, Darwin 25.6.0, 2026-09-06. The scenes are the godot-rapier benchmark suite's (post, docs), body for body; each runs 300 timed steps at 60 Hz after a settle, and the tables show the median physics tick.

Running it

cargo build --release -p balaur_cli --bin balaur
python3 scripts/bench_compare.py --shots --godot-results <benchmarks-repo>/results

One case on its own, or in the editor:

target/release/balaur run examples/benchmark --headless --fixed-tick -- --case=3d/pyramid
target/release/balaur edit examples/benchmark

Built on

Contents

The Rust libraries under Balaur, and what each does:

Library What it does in Balaur
hecs The ECS
Rapier 2D and 3D physics, built with enhanced-determinism
wgpu via kiss3d Rendering, windowed and offscreen; winit for the window
egui Paints the widget nodes
rodio Audio playback
gilrs Gamepads
wasmtime Runs scripts compiled to WebAssembly on desktop and Android
wasmi A WebAssembly interpreter, for scripts under the debugger
glamx Math: glam re-exported whole, plus pose and rotation types
libm Bit-identical transcendentals on every platform
gltf, image Model and texture loading
ureq, tungstenite, rustls HTTP, WebSockets, TLS
serde, toml Scenes, assets, project files, export packs
notify The file watcher behind hot reload
tracing Logging
clap The balaur command line
libloading Run-time extensions from shared libraries

Reference

Contents

Every component, asset type and script module in the engine.

Components

2D

component properties what it gives a node
articulation2d 8 Solves the node's joint2d in reduced coordinates.
body2d 23 A 2D rigid body simulated by rapier in the xy plane.
bone2d 4 Makes the node a 2D bone.
boolean2d 8 Draws the node as its 2D children combined by operation, holes and all.
breakable_joint2d 2 What snaps the node's joint2d: past either, it breaks and calls on_joint_break.
camera2d 4 The orthographic camera a flat scene is drawn from.
character2d 17 A 2D character controller.
collider2d 23 The node's 2D collision shape, chosen by kind.
convex_decomposition2d 1 How the node's collider2d cuts its mesh into convex pieces, for a convex_decomposition.
follow2d 12 Pulls the node's body2d towards the pose of target every fixed step.
generic_joint2d 3 Which axes a joint2d of kind generic locks, and which free ones it ties into one.
joint2d 13 Joins this node's body to connected_body.
light2d 9 A 2D light at the node's position.
line2d 13 A stroked line at the node through the points of a mesh or path2d asset.
mesh_collider2d 10 How the node's collider2d turns its mesh into a shape.
modifier2d 14 Poses 2D bones toward target after the clip runs.
multimesh2d 5 Godot's MultiMeshInstance2D.
occluder2d 2 The outline the node blocks 2D light with.
particles2d 18 A visual-only 2D emitter at the node.
polygon 6 A filled, textured 2D polygon from the mesh asset's points and triangles.
rope_joint2d 1 How long a joint2d of kind rope may stretch.
screen_notifier2d 2 A box that announces screen_entered as it comes on screen and screen_exited as it leaves.
shape2d 4 A 2D primitive at the node, tinted by color and drawn with texture.
soft_circle2d 2 The size of a softbody2d laid out as a circle: a disk of particles inside a rim.
soft_collision2d 3 A mesh the node's softbody2d meets the world through beside its own surface, deformed with the body.
soft_custom2d 5 The particles and elements of a custom softbody2d, as the author lists them.
soft_grid2d 2 The size and the cells of a softbody2d laid out as a grid: a sheet of particles.
soft_outline2d 1 The corners of a softbody2d laid out as an outline: a ring of particles around an inside.
soft_polyline2d 1 Which segments of its mesh a softbody2d laid out as a polyline joins.
soft_rope2d 3 Where a softbody2d laid out as a rope runs, and how many particles it is made of.
soft_skin2d 2 The mesh a softbody2d with cells carries as its skin.
soft_volumetric2d 2 How a volumetric softbody2d fills its mesh's outline with triangles.
softbody2d 35 A deformable 2D body.
spring_joint2d 1 The length a joint2d of kind spring pulls back to.
sprite 14 A textured 2D quad at the node, sized by pixels_per_unit.
text2d 19 A block of text drawn in the 2D pass, pixels_per_unit font pixels per world unit.
tile_collision 20 Collision for the node's tilemap cells.
tile_shapes 2 How the node's tile_collision builds the tiles whose collision is polygons, the ones a tileset gives collision = [[[x, y], ...]].
tilemap 9 A grid of tiles from one tileset asset, centred on the node.
touch_button 10 An on-screen button that presses an action while a finger is on it.
touch_stick 12 An on-screen stick that drives action_x and action_y from -1..1 while a thumb drags it.
transform 4 The node's position, rotation_euler, scale and skew in its parent's space.

3D

component properties what it gives a node
articulation3d 8 Solves the node's joint3d in reduced coordinates.
body3d 25 A 3D rigid body simulated by rapier.
bone3d 4 Makes the node a 3D bone.
boolean3d 9 Draws the node as its children combined by operation.
breakable_joint3d 2 What snaps the node's joint3d: past either, it breaks and calls on_joint_break.
camera3d 10 The camera the scene is drawn from.
character3d 17 A 3D character controller.
collider3d 24 The node's 3D collision shape, chosen by kind.
convex_decomposition3d 9 How the node's collider3d cuts its mesh into convex pieces.
follow3d 12 Pulls the node's body3d towards the pose of target every fixed step.
generic_joint3d 4 Which axes a joint3d of kind generic locks, and which free ones it ties into one.
joint3d 13 Joins this node's body to connected_body.
light3d 9 A 3D light placed and aimed by the node.
mesh 10 3D geometry from the mesh asset in source, drawn at the node.
mesh_collider3d 9 How the node's collider3d turns its mesh into a shape.
modifier3d 14 Poses bone3d nodes toward target after the clip runs.
multimesh3d 9 Godot's MultiMeshInstance3D.
particles3d 23 A visual-only 3D emitter at the node, drawn as instances of one quad.
reflection_probe 9 A box the room around it was captured inside.
rope_joint3d 1 How long a joint3d of kind rope may stretch.
shape3d 9 A 3D primitive at the node, tinted by color and drawn with texture.
soft_cloth_tube3d 4 The shape of a softbody3d laid out as a cloth_tube.
soft_collision3d 3 A mesh the node's softbody3d meets the world through beside its own surface, deformed with the body.
soft_custom3d 7 The particles and elements of a custom softbody3d, as the author lists them.
soft_grid3d 2 The size and the cells of a softbody3d laid out as a box or a cloth.
soft_rope3d 3 Where a softbody3d laid out as a rope runs, and how many particles it is made of.
soft_skin3d 2 The mesh a softbody3d with cells carries as its skin.
soft_sphere3d 2 The size of a softbody3d laid out as a sphere: a refined icosahedron of particles.
soft_volumetric3d 5 How a volumetric softbody3d fills its mesh with tetrahedra.
softbody3d 35 A deformable 3D body.
spring_joint3d 1 The length a joint3d of kind spring pulls back to.
text3d 25 A block of text drawn in the 3D pass on a quad, pixels_per_unit font pixels per world unit.
vehicle3d 6 Makes the node's body3d a raycast vehicle chassis.
wheel3d 11 One wheel of the vehicle3d above it.

Physics

component properties what it gives a node
ragdoll 2 Drives a rig's bones from bodies, one body per bone and named after it, which the editor's Create Physical Skeleton builds.

Rendering

component properties what it gives a node
debug_draw 7 A wireframe over every triangle edge of the node's drawing.
environment 36 The scene's atmosphere.
material 1 source is the material asset this node and everything under it draw with.

Animation

component properties what it gives a node
animation 4 Plays animation clips on the node.
state_machine 4 Runs the state_machine asset in machine over the player node's clips.

Audio

component properties what it gives a node
listener 4 The point positional sounds are heard from.
sound 23 A sound on the node.

UI

component properties what it gives a node
widget 57 A HUD element drawn every frame.
widget_box 5 The rarer words about a box, which any kind may carry.
widget_button 7 The rows a button or menu reads.
widget_check 4 The rows a checkbox, switch or button reads.
widget_child 4 What a child says to the parent it sits in, whatever its own kind.
widget_code 6 The rows a code widget reads: what it highlights and its gutter.
widget_color_picker 3 The rows a color_picker reads: the colour it holds and what it offers.
widget_dropdown 3 The rows a dropdown reads: what it offers, how tall its list grows and what shuts it.
widget_field 14 The rows a text_field, text_area or code reads.
widget_fold 1 The row a fold reads: whether it shows what is under its header.
widget_grid 6 The rows a grid reads: its tracks and its named areas.
widget_image 8 The rows an image reads: its picture, the part of it drawn and how it sits in its box.
widget_layout 9 The rows a container reads: how it lays out what is in it.
widget_list 4 The rows a list or tree reads: its card faces, and what a drag or a mark on a row does.
widget_menu 7 The rows a menu reads: where its popup opens and what shuts it.
widget_range 24 The rows a slider, number_field or progress_bar reads.
widget_rows 4 The rows a list, tree or table reads: what it holds and what is picked.
widget_scroll 12 The rows a scroll, list, tree or table reads.
widget_separator 3 The rows a separator reads: the room it takes and how far its line runs.
widget_shortcut 3 The rows of a chord that clicks a widget, which any kind may carry.
widget_table 8 The rows a table reads: its columns and how they sort.
widget_tabs 1 The row a tabs reads: which child it shows.
widget_text 11 The rows a kind drawing a caption reads.
widget_window 9 The rows a window or a dialog reads: whether it is up, its chrome, and what shuts it.

Other

component properties what it gives a node
bindings 1 Reactions the node runs from a table.
meta 0 Named values filed on the node, like Godot's set_meta.
states 1 Named looks for the node.
timer 5 Counts wait_time seconds down and emits timeout from the node.

Asset types

type files used by
animation_library animations/ animation.library
bone_map animations/ —
camera_effects camera_effects/ camera2d.effects, camera3d.effects
font fonts/ text2d.font, text3d.font, widget.font
heightfield heightfields/ —
material materials/ boolean2d.material, boolean3d.material, line2d.material, material.source, mesh.material, multimesh2d.material, multimesh3d.material, particles2d.material, particles3d.material, polygon.material, shape2d.material, shape3d.material, sprite.material, text2d.material, text3d.material, tilemap.material
mesh models/ line2d.mesh, mesh.source, occluder2d.mesh, polygon.mesh, soft_collision2d.collision_mesh, soft_collision3d.collision_mesh, softbody2d.mesh, softbody3d.mesh
multimesh multimeshes/ multimesh2d.source, multimesh3d.source
path2d paths/ —
path3d paths/ —
physics_material physics_materials/ collider2d.physics_material, collider3d.physics_material, softbody2d.physics_material, softbody3d.physics_material, tile_collision.physics_material
skeleton_profile animations/ —
soft_material soft_materials/ softbody2d.soft_material, softbody3d.soft_material
sprite_sheet sheets/ particles2d.sheet, sprite.sheet
state_machine animations/ state_machine.machine
text_style text_styles/ text2d.text_style, text3d.text_style, widget.text_style
texture textures/ boolean2d.texture, boolean3d.texture, line2d.texture, mesh.texture, multimesh2d.texture, multimesh3d.texture, particles2d.texture, particles3d.texture, polygon.texture, shape2d.texture, shape3d.texture, sprite.texture
tileset tilesets/ tilemap.tileset
voxels voxels/ —
widget_theme themes/ widget.theme

Script modules

module functions what it is for
animation 19 Clip playback on a node's animation component: play, pause, seek and query.
apple 18 Apple services beyond platform.*: Game Center identity, purchases, notifications.
assets 9 Asset definitions by reference.
audio 19 Sound playback.
browser 5 The page a browser build runs in; off the web every query answers nil.
debugger 9 Breakpoints, pausing a script and resuming it.
dependency 6 The projects a game imports whole under deps/<alias>/, declared in [dependencies].
encoding 3 Bytes to base64 text and back, and UTF-8 bytes back to text.
engine 31 The running app.
events 4 Named events between scripts.
export 5 Exports the project being edited.
forge 5 Projects kept on Forge, for the editor's pickers, and adding one to a game as a dependency.
fs 9 Files on disk, project-relative unless the path is absolute.
geometry2d 11 Polygons on the plane as lists of Vec2 points in outline order.
geometry3d 7 Mesh operations.
hash 2 SHA-256 content hashes of files and strings.
http 2 HTTP requests off the frame.
import 6 Imports a .glb or .gltf model, an .aseprite sprite, or a .tmx or .ldtk level into the project being edited, with the importers balaur import runs.
input 52 One frame of input.
json 2 JSON text to and from script values.
log 7 The info, warn and error levels a script writes at, and the buffer behind them.
math 24 Deterministic float maths backed by pure-Rust libm.
multimesh2d 13 Thousands of copies of one sprite in one draw.
multimesh3d 12 Thousands of copies of one mesh in one draw.
multiplayer 14 Host, join and play a rollback match.
node 57 What every node has: name, path, transform, children, components and script.
physics 12 What spans both physics worlds: pausing, sleeping, tuning and clearing.
physics2d 118 The 2D rigid-body world.
physics3d 127 The 3D rigid-body world.
picture 1 A picture of a project.
platform 10 Store services every platform shares: sign-in, achievements, leaderboards, cloud saves.
project 15 The projects this machine has opened, the templates a new one starts from, and the folder picker the OS provides.
quat 8 Rotations as quaternions { x, y, z, w }.
random 6 The engine's one deterministic PCG32 stream.
regex 6 Regular expressions, the regex-lite dialect: no look-around or back-references.
release 4 Which build of the engine this is, what the channels are publishing, and replacing this install with another.
render 45 What a frame is made of.
replay 16 Records what a running game is fed and plays it back.
rollback 2 Rollback netcode from a script's side.
scene 23 The node tree.
script 13 What a tool asks about a script file.
settings 10 Every setting the engine, its plugins and the game declare, by path.
skeleton 1 Bones under a rig node, in the order a skin numbers joints in.
strings 5 Localization: one strings/<locale>.toml per language, keys to strings.
task 3 Waiting inside an async method.
toml 3 TOML text to and from script tables, the format of scene files, asset definitions and component properties.
types 0 The names of a value's type: what kind() answers on an any.
ui 37 What a script asks of the UI and tells it.
websocket 5 A long-lived socket for text or binary frames.
window 7 The OS window and the display under it.

animation

Contents

animation · 4 properties · Animation

Plays animation clips on the node. library is the clip asset, autoplay the clip started on load, speed_scale the rate; the animation module drives playback.

In a scene, animation is the node key that applies it. A script reaches each property below as a field on node.animation: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.animation.get() and node.animation.set(table).

Properties

property type default description
autoplay string — Clip to start when the scene loads; empty starts nothing
library asset · animation_library — The clip library this node plays from
root_node node — The node the clip's tracks resolve against; empty means this node
speed_scale float 1 Playback rate for every clip on this node

Asset types this component references: animation_library.

Script functions

Methods of node.animation, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From animation:

method what it does
add_clip(string, animation::Clip) Give this node a clip of its own under that name, shaped like a scene file's.
current_clip() -> str? The clip playing or paused on this node, and nil once it has ended, been stopped, or never started.
is_playing() -> bool Whether a clip is advancing on this node; a paused, stopped, finished or absent one answers false.
pause() Hold the playhead where it is, keeping the clip current so resume has something to go back to.
play(string, animation::PlayOptions?) Start the clip of that name on this node; the trailing options table takes speed_scale (a multiplier), from_start, blend_time (seconds to blend out of the clip before), ease (the blend's curve, an EASE_* constant), and retarget (a bone_map reference, so this rig can play another rig's clips).
queue(string) Play the clip of that name once the current one ends; a looping clip never ends, so a queue behind one never drains.
resume() Carry on from where pause left off; a stopped, finished or never-started node is left alone.
seek(float) Move the playhead to a number of seconds and pose the node there, even on a paused or ended clip.
stop() End the clip on this node, leaving the pose where it is; resume cannot revive it.
time() -> float Seconds of playback since the current clip started, before wrapping; a stopped clip keeps where it stopped.

articulation2d

Contents

2d · physics · 8 properties · 2D

Solves the node's joint2d in reduced coordinates: the chain never drifts and can be solved for inverse kinematics, but cannot close a loop or break.

In a scene, articulation2d is the node key that applies it. A script reaches each property below as a field on node.articulation2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.articulation2d.get() and node.articulation2d.set(table).

Properties

property type default description
gear_offset float 0 Where this joint stands when the gear_with joint is at 0
gear_ratio float 1 How far this joint turns or slides per unit of the gear_with joint's
gear_with node — On an articulation: another joint node of the same chain this joint follows, its first free axis tied to that joint's first free axis
kinematic_link bool false On an articulation: the solver never changes this joint's velocity, so the link holds its pose against its parent and moves only by solve_ik
link_axes list [] One record per free axis whose link moves differently from rapier's own: its damping, the inertia a rotor adds, and dry friction
passive_rest float 0 On an articulation: where that spring rests, in radians about a rotation axis and units along a linear one
passive_stiffness float 0 On an articulation: a spring on each free axis pulling it towards passive_rest; 0 is none At least 0.
self_collision bool true On an articulation: let the chain's links collide with each other. One setting for the whole chain, off when any of its joints says off

articulation3d

Contents

3d · physics · 8 properties · 3D

Solves the node's joint3d in reduced coordinates: the chain never drifts and can be solved for inverse kinematics, but cannot close a loop or break.

In a scene, articulation3d is the node key that applies it. A script reaches each property below as a field on node.articulation3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.articulation3d.get() and node.articulation3d.set(table).

Properties

property type default description
gear_offset float 0 Where this joint stands when the gear_with joint is at 0
gear_ratio float 1 How far this joint turns or slides per unit of the gear_with joint's
gear_with node — On an articulation: another joint node of the same chain this joint follows, its first free axis tied to that joint's first free axis
kinematic_link bool false On an articulation: the solver never changes this joint's velocity, so the link holds its pose against its parent and moves only by solve_ik
link_axes list [] One record per free axis whose link moves differently from rapier's own: its damping, the inertia a rotor adds, and dry friction
passive_rest float 0 On an articulation: where that spring rests, in radians about a rotation axis and units along a linear one
passive_stiffness float 0 On an articulation: a spring on each free axis pulling it towards passive_rest; 0 is none At least 0.
self_collision bool true On an articulation: let the chain's links collide with each other. One setting for the whole chain, off when any of its joints says off

bindings

Contents

interaction · 1 property · Other

Reactions the node runs from a table: each row is an event, a when over the scene's [variables], an action, a target node and a value.

In a scene, bindings is the node key that applies it. A script reaches each property below as a field on node.bindings: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.bindings.get() and node.bindings.set(table).

Properties

property type default description
rows list [] The binding rows, each { event, when, action, target, value }

body2d

Contents

2d · physics · 23 properties · 2D

A 2D rigid body simulated by rapier in the xy plane. kind is dynamic, static, kinematic or kinematic_velocity; add a collider2d for its shape.

In a scene, body2d is the node key that applies it. A script reaches each property below as a field on node.body2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.body2d.get() and node.body2d.set(table).

Properties

property type default description
allow_fast_rotation bool false Allow a spin fast enough that rapier would otherwise clamp it
angular_damping float 0 Drag on spin, in the same terms as linear_damping At least 0.
can_sleep bool true Let the body stop being simulated once it has held still
center_of_mass vec2 [0,0] Where the extra mass sits, in the node's own space; only read when mass is set
continuous_collision bool false Also sweep moving bodies: a fast dynamic body sweeps static colliders without this, and this adds kinematic and dynamic ones
dominance int 0 A body in a higher group is unpushable by a lower one; a kinematic body keeps its own group, and only a static body outranks every group Range -128–127.
enabled bool true Simulate this body at all; a disabled body keeps its state and costs nothing
gravity_scale float 1 Multiplier on world gravity for this body: 0 hangs in the air, negative floats up
inertia float 0 Resistance to spin, read when mass is set; 0 derives it from the colliders' shapes scaled to the mass, about center_of_mass when that is set At least 0.
initial_angular_velocity float 0 How fast the body spins when it is made; radians per second in the file, and a later patch does not reapply it
initial_linear_velocity vec2 [0,0] How fast the body travels when it is made, in units per second; a later patch does not reapply it
internal_iterations int 0 Extra Gauss-Seidel iterations inside each substep for the island this body is in; the island runs the largest any of its bodies asks At least 0.
kind enum dynamic How 2D physics drives the node: simulated, immovable, moved by script, or moved by a velocity you set One of dynamic, static, kinematic, kinematic_velocity.
linear_damping float 0 Drag on travel: how fast the body loses speed with nothing touching it At least 0.
lock_rotation bool false Stop the body turning; how a 2D character stays upright
lock_translation flags [] Axes the body may not move along One of x, y.
mass float 0 The body's total mass; 0 sums what its colliders weigh At least 0.
sleep_angular_threshold float 0.5 The spin below which a body with no collider counts as still; radians per second in the file At least 0.
sleep_threshold float 0.05 The speed of the body's farthest point below which it counts as still, in length units per second scaled by [physics] length_unit At least 0.
solver_iterations int 0 Extra solver substeps for the whole island this body is in, joints and contacts together: everything it touches pays for them At least 0.
speculative_distance float 0 Distance ahead the body predicts contacts, in units; cheaper than ccd for merely fast bodies At least 0.
start_asleep bool false Make the body asleep, with no velocity, until something wakes it; read once, when the body is made
time_to_sleep float 0.5 Seconds of stillness before the body sleeps At least 0.

Script functions

Methods of node.body2d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From physics2d:

method what it does
add_constant_force(Vec2) Push the body every step until the constant force is set back to zero; unlike an impulse this is spread over time.
add_constant_force_at_point(Vec2, Vec2) Push at a world point every step, which also turns the body.
add_constant_torque(float) Turn the body every step until the constant torque is set back to zero.
angular_velocity() -> float How fast the body is spinning, in radians per second.
apply_force(Vec2) Push the body for the next step only; add_constant_force keeps pushing.
apply_force_at_point(Vec2, Vec2) Push at a world point for the next step only, which also turns the body.
apply_impulse(Vec2) Add an instant change in momentum, as if the body were struck.
apply_impulse_at_point(Vec2, Vec2) Strike the body at a world point, which spins it as well as moves it.
apply_torque(float) Turn the body for the next step only; add_constant_torque keeps turning it.
apply_torque_impulse(float) Add an instant change in angular momentum, as if the body were spun.
constant_force() -> Vec2 The force every step integrates until it is set back to zero.
constant_torque() -> float The torque every step integrates until it is set back to zero.
effective_angular_inertia() -> float The inertia the solver turns: zero with rotation locked, and on any body that is not dynamic.
effective_dominance() -> float The dominance rapier will use for this body: its own group, or the rank every non-dynamic body outranks with.
effective_mass() -> Vec2 The mass the solver pushes against along each world axis: zero along a locked axis, and on any body that is not dynamic.
is_ccd_active() -> bool Whether the body moved fast enough last step for rapier to sweep it, with or without continuous_collision.
is_moving() -> bool Whether the body is awake and actually going somewhere.
is_sleeping() -> bool Whether the body is asleep and being skipped.
kinetic_energy() -> float The body's kinetic energy, for a rest test the solver agrees with.
linear_velocity() -> Vec2 How fast the body is travelling, in units per second.
local_center_of_mass() -> Vec2 Where the body's whole mass sits, in the body's own space.
max_contact_impulse() -> float The hardest contact this body took in the last step, every collider on it included; zero when nothing touched it.
next_position() -> physics2d::Pose The pose a kinematic body has been told to move to.
potential_energy() -> float The body's gravitational potential energy over one step.
predict_position(float) -> physics2d::Pose Where the body will be after dt seconds at its current velocity.
predict_position_with_forces(float) -> physics2d::Pose The same, with the forces already applied taken into account: where a thrust or a spring will have put it.
set_angular_velocity(float) Set how fast the body spins, in radians per second.
set_constant_force(Vec2) Replace the constant force with this one; zero stops the push.
set_constant_torque(float) Replace the constant torque with this one; zero stops the turn.
set_linear_velocity(Vec2) Set how fast the body travels, in units per second.
sleep() Put the body to sleep now.
teleport(Vec2, physics2d::TeleportOptions?) Move the body to a world position at once, clearing its velocity: what assigning the node's position cannot do, because the step writes that back every tick. A rotation turns it too, in radians.
time_since_can_sleep() -> float Seconds the body has spent under its sleep thresholds; it sleeps once this reaches time_to_sleep.
total_inertia() -> float The body's resistance to spin, colliders included.
total_mass() -> float The body's total mass: its mass when it states one, or what its colliders weigh.
velocity_at_point(Vec2) -> Vec2 How fast a world point on the body is moving, spin included.
wake_up() Wake the body, so the next step moves it.
world_center_of_mass() -> Vec2 Where the body's whole mass sits, in world space.

body3d

Contents

3d · physics · 25 properties · 3D

A 3D rigid body simulated by rapier. kind is dynamic, static, kinematic or kinematic_velocity; add a collider3d for its shape.

In a scene, body3d is the node key that applies it. A script reaches each property below as a field on node.body3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.body3d.get() and node.body3d.set(table).

Properties

property type default description
allow_fast_rotation bool false Allow a spin fast enough that rapier would otherwise clamp it
angular_damping float 0 Drag on spin, in the same terms as linear_damping At least 0.
can_sleep bool true Let the body stop being simulated once it has held still
center_of_mass vec3 [0,0,0] Where the extra mass sits, in the node's own space; only read when mass is set
continuous_collision bool false Also sweep moving bodies: a fast dynamic body sweeps static colliders without this, and this adds kinematic and dynamic ones
dominance int 0 A body in a higher group is unpushable by a lower one; a kinematic body keeps its own group, and only a static body outranks every group Range -128–127.
enabled bool true Simulate this body at all; a disabled body keeps its state and costs nothing
gravity_scale float 1 Multiplier on world gravity for this body: 0 hangs in the air, negative floats up
gyroscopic_forces bool false Model the wobble a spinning body's own inertia gives it, as a thrown American football has
inertia vec3 [0,0,0] Resistance to spin about each axis, read when mass is set; 0 derives it from the colliders' shapes scaled to the mass, about center_of_mass when that is set
inertia_rotation vec3 [0,0,0] Turns the axes inertia is measured about, as rotation_euler does; read with a non-zero inertia. Euler radians in the file
initial_angular_velocity vec3 [0,0,0] How fast the body spins when it is made, about each axis; radians per second in the file, and a later patch does not reapply it
initial_linear_velocity vec3 [0,0,0] How fast the body travels when it is made, in units per second; a later patch does not reapply it
internal_iterations int 0 Extra Gauss-Seidel iterations inside each substep for the island this body is in; the island runs the largest any of its bodies asks At least 0.
kind enum dynamic How physics drives the node: simulated, immovable, moved by script, or moved by a velocity you set One of dynamic, static, kinematic, kinematic_velocity.
linear_damping float 0 Drag on travel: how fast the body loses speed with nothing touching it At least 0.
lock_rotation flags [] World axes the body may not turn about; locking all three keeps a character upright One of x, y, z.
lock_translation flags [] World axes the body may not move along One of x, y, z.
mass float 0 The body's total mass; 0 sums what its colliders weigh At least 0.
sleep_angular_threshold float 0.5 The spin below which a body with no collider counts as still; radians per second in the file At least 0.
sleep_threshold float 0.05 The speed of the body's farthest point below which it counts as still, in length units per second scaled by [physics] length_unit At least 0.
solver_iterations int 0 Extra solver substeps for the whole island this body is in, joints and contacts together: everything it touches pays for them At least 0.
speculative_distance float 0 Distance ahead the body predicts contacts, in units; cheaper than ccd for merely fast bodies At least 0.
start_asleep bool false Make the body asleep, with no velocity, until something wakes it; read once, when the body is made
time_to_sleep float 0.5 Seconds of stillness before the body sleeps At least 0.

Script functions

Methods of node.body3d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From physics3d:

method what it does
add_constant_force(Vec3) Push the body every step until the constant force is set back to zero; unlike an impulse this is spread over time.
add_constant_force_at_point(Vec3, Vec3) Push at a world point every step, which also turns the body.
add_constant_torque(Vec3) Turn the body every step until the constant torque is set back to zero.
angular_velocity() -> Vec3 How fast the body is spinning, in radians per second about each axis.
apply_force(Vec3) Push the body for the next step only; add_constant_force keeps pushing.
apply_force_at_point(Vec3, Vec3) Push at a world point for the next step only, which also turns the body.
apply_impulse(Vec3) Add an instant change in momentum, as if the body were struck.
apply_impulse_at_point(Vec3, Vec3) Strike the body at a world point, which spins it as well as moves it.
apply_torque(Vec3) Turn the body for the next step only; add_constant_torque keeps turning it.
apply_torque_impulse(Vec3) Add an instant change in angular momentum, as if the body were spun.
constant_force() -> Vec3 The force every step integrates until it is set back to zero.
constant_torque() -> Vec3 The torque every step integrates until it is set back to zero.
effective_angular_inertia() -> [Vec3] The world-space inertia the solver turns, rotation locks applied, as its three rows.
effective_dominance() -> float The dominance rapier will use for this body: its own group, or the rank every non-dynamic body outranks with.
effective_mass() -> Vec3 The mass the solver pushes against along each world axis: zero along a locked axis, and on any body that is not dynamic.
is_ccd_active() -> bool Whether the body moved fast enough last step for rapier to sweep it, with or without continuous_collision.
is_moving() -> bool Whether the body is awake and actually going somewhere.
is_sleeping() -> bool Whether the body is asleep and being skipped.
kinetic_energy() -> float The body's kinetic energy, for a rest test the solver agrees with.
linear_velocity() -> Vec3 How fast the body is travelling, in units per second.
local_center_of_mass() -> Vec3 Where the body's whole mass sits, in the body's own space.
max_contact_impulse() -> float The hardest contact this body took in the last step, every collider on it included; zero when nothing touched it.
next_position() -> physics3d::Pose The pose a kinematic body has been told to move to.
potential_energy() -> float The body's gravitational potential energy over one step.
predict_position(float) -> physics3d::Pose Where the body will be after dt seconds at its current velocity.
predict_position_with_forces(float) -> physics3d::Pose The same, with the forces already applied taken into account: where a thrust or a spring will have put it.
set_angular_velocity(Vec3) Set how fast the body spins, in radians per second about each axis.
set_constant_force(Vec3) Replace the constant force with this one; zero stops the push.
set_constant_torque(Vec3) Replace the constant torque with this one; zero stops the turn.
set_linear_velocity(Vec3) Set how fast the body travels, in units per second.
sleep() Put the body to sleep now.
teleport(Vec3, physics3d::TeleportOptions?) Move the body to a world position at once, clearing its velocity: what assigning the node's position cannot do, because the step writes that back every tick. A rotation turns it too, in Euler radians.
time_since_can_sleep() -> float Seconds the body has spent under its sleep thresholds; it sleeps once this reaches time_to_sleep.
total_inertia() -> Vec3 The body's resistance to spin about each of its principal axes, colliders included.
total_inertia_rotation() -> Vec3 How those principal axes are turned in the body's own space, as Euler radians as rotation_euler reads them.
total_mass() -> float The body's total mass: its mass when it states one, or what its colliders weigh.
velocity_at_point(Vec3) -> Vec3 How fast a world point on the body is moving, spin included.
wake_up() Wake the body, so the next step moves it.
world_center_of_mass() -> Vec3 Where the body's whole mass sits, in world space.

bone2d

Contents

2d · animation · 4 properties · 2D

Makes the node a 2D bone. rest_position and rest_rotation are the pose a rig returns to; length and angle draw its gizmo.

In a scene, bone2d is the node key that applies it. A script reaches each property below as a field on node.bone2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.bone2d.get() and node.bone2d.set(table).

Properties

property type default description
angle float 0 Gizmo direction of a tip bone, in radians; ignored while a child bone exists
length float 0 Gizmo length of a tip bone; 0 draws to the first child bone At least 0.
rest_position vec2 [0,0] Local rest translation
rest_rotation float 0 Local rest rotation about z, in radians

bone3d

Contents

3d · animation · 4 properties · 3D

Makes the node a 3D bone. rest_position, rest_rotation and rest_scale are the pose a rig returns to; length draws its gizmo.

In a scene, bone3d is the node key that applies it. A script reaches each property below as a field on node.bone3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.bone3d.get() and node.bone3d.set(table).

Properties

property type default description
length float 0 Gizmo length of a tip bone; 0 draws to the first child bone At least 0.
rest_position vec3 [0,0,0] Local rest translation
rest_rotation vec3 [0,0,0] Local rest rotation, euler radians in the order rotation_euler uses
rest_scale vec3 [1,1,1] Local rest scale

boolean2d

Contents

2d · render · 8 properties · 2D

Draws the node as its 2D children combined by operation, holes and all. The children stay in the tree, hidden and editable; fill_rule and the cleanup keys tune the combination, and color, texture and material dress the result.

In a scene, boolean2d is the node key that applies it. A script reaches each property below as a field on node.boolean2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.boolean2d.get() and node.boolean2d.set(table).

Properties

property type default description
clean_result bool true Clear the result of the near-duplicate points rounding leaves
color color [1,1,1,1] Tint of the result, as channel floats or #rrggbb / #rrggbbaa
fill_rule enum even_odd Which parts of crossing or nested outlines count as inside: an odd number of them, any winding, or only counter-clockwise or clockwise winding One of even_odd, non_zero, positive, negative.
keep_collinear bool false Keep a point that sits on the straight line between its neighbours, in the children and in the result
material asset · material — The material the result draws with; empty takes an inherited material component, else the built-in one
min_area float 0 A result outline or hole enclosing less than this area, in square units of the node's own space, is dropped At least 0.
operation enum union How the children are combined, in the order they are declared One of union, difference, intersection, symmetric_difference, reverse_difference.
texture asset · texture — Image file, project-relative, or a texture asset the result is drawn with, centred on the node at 100 texture pixels per unit, as a polygon's default UVs are; empty draws the colour alone

Asset types this component references: material, texture.

boolean3d

Contents

3d · render · 9 properties · 3D

Draws the node as its children combined by operation: union, difference or intersection. The children stay in the tree, hidden and editable; color, texture and material dress the result.

In a scene, boolean3d is the node key that applies it. A script reaches each property below as a field on node.boolean3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.boolean3d.get() and node.boolean3d.set(table).

Properties

property type default description
cast_shadow bool true Whether the result casts a shadow from the lights that cast
color color [0.8,0.8,0.8,1] Tint of the result, as channel floats or #rrggbb / #rrggbbaa
light_layers flags [] The light layers the result is lit on: a light3d lights it when their light_layers share one; empty is every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
material asset · material — The material the result draws with; empty takes an inherited material component, else the built-in one
operation enum union How the children are combined, in the order they are declared One of union, difference, intersection.
receive_shadows bool true Whether shadows land on it; off lights it as if nothing stood between it and every light
render_layers flags [] The layers the result is drawn on: a camera3d draws it when their render_layers share one; empty is every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
segmentation_id int 0 The id render.snap_aov("segmentation") colours this node by; nodes sharing one share a colour. Zero takes one of its own, from 1 up At least 0.
texture asset · texture — Image file, project-relative, or a texture asset the result is drawn with, over the UVs the children carry through the cut; empty draws the colour alone

Asset types this component references: material, texture.

Script functions

Methods of node.boolean3d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From render:

method what it does
built_mesh() -> render::BuiltMesh? The triangles the node's boolean settled on, ready to be written out as a mesh asset; nil when the node draws no built geometry.

breakable_joint2d

Contents

2d · physics · 2 properties · 2D

What snaps the node's joint2d: past either, it breaks and calls on_joint_break. An articulation never breaks, so this sits beside a joint that is not one.

In a scene, breakable_joint2d is the node key that applies it. A script reaches each property below as a field on node.breakable_joint2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.breakable_joint2d.get() and node.breakable_joint2d.set(table).

Properties

property type default description
break_force float 0 The force, in newtons, that snaps the joint; 0 never breaks it by force At least 0.
break_torque float 0 The torque about the anchor, in newton metres, that snaps the joint; 0 never breaks it by torque At least 0.

breakable_joint3d

Contents

3d · physics · 2 properties · 3D

What snaps the node's joint3d: past either, it breaks and calls on_joint_break. An articulation never breaks, so this sits beside a joint that is not one.

In a scene, breakable_joint3d is the node key that applies it. A script reaches each property below as a field on node.breakable_joint3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.breakable_joint3d.get() and node.breakable_joint3d.set(table).

Properties

property type default description
break_force float 0 The force, in newtons, that snaps the joint; 0 never breaks it by force At least 0.
break_torque float 0 The torque about the anchor, in newton metres, that snaps the joint; 0 never breaks it by torque At least 0.

camera2d

Contents

2d · render · 4 properties · 2D

The orthographic camera a flat scene is drawn from. pixels_per_unit scales it, and the last current camera wins; the scene's environment lights it. Only its node moves it.

In a scene, camera2d is the node key that applies it. A script reaches each property below as a field on node.camera2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.camera2d.get() and node.camera2d.set(table).

Properties

property type default description
current bool true Whether this camera drives the view; the last current one wins
effects asset · camera_effects — The passes the frame resolves through and how each is tuned; empty draws the frame as it is
hidpi bool true Count pixels_per_unit in logical pixels, multiplied by the display's scale; off counts physical pixels, for pixel art that should land on the screen's own grid
pixels_per_unit float 60 Zoom in logical pixels per world unit At least 0.01.

Asset types this component references: camera_effects.

camera3d

Contents

3d · render · 10 properties · 3D

The camera the scene is drawn from. Its node places and aims it, looking along the node's -z as a light3d shines; the lens rows say how it projects and what it draws, effects how the frame resolves, and the last current camera wins.

In a scene, camera3d is the node key that applies it. A script reaches each property below as a field on node.camera3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.camera3d.get() and node.camera3d.set(table).

Properties

property type default description
current bool true Whether this camera drives the view; the last current one wins
effects asset · camera_effects — The passes the frame resolves through and how each is tuned; empty draws the frame as it is
far float 1000 The farthest distance drawn, in world units At least 0.000001.
focus_distance float 10 How far ahead the camera's focus sits, in world units: an orthographic frame with no orthographic_height is sized from it, and a stereo pair converges there At least 0.001.
fov_degrees float 45 The vertical field of view; in orthographic, how much of focus_distance the frame covers Range 1–179.
near float 0.1 The nearest distance drawn, in world units At least 0.000001.
orthographic_height float 0 The orthographic frame's full height in world units; zero sizes it from focus_distance and fov_degrees At least 0.
projection enum perspective Perspective, or parallel lines that stay parallel One of perspective, orthographic.
render_layers flags [] The layers this camera draws: a node whose render_layers share one; empty is every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
stereo_separation float 0 Above zero, a stereo pair this far apart in world units: one eye in each half of the frame, both converging focus_distance ahead. A stereo camera ignores projection and keeps +y up At least 0.

Asset types this component references: camera_effects.

character2d

Contents

2d · physics · 17 properties · 2D

A 2D character controller: node.character2d.move_by slides the node along walls and steps it up ledges. Needs a collider2d; a kinematic body2d lets it push bodies.

In a scene, character2d is the node key that applies it. A script reaches each property below as a field on node.character2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.character2d.get() and node.character2d.set(table).

Properties

property type default description
exclude list [] Nodes a move passes through: their colliders, and every collider on their body
exclude_kinds flags [] The body kinds a move passes through: static takes colliders with no body too. The character's own collision_layer and collision_mask filter the rest One of static, kinematic, dynamic.
floor_max_angle float 0.7853982 The steepest slope the character may walk up; radians in the file, degrees in the inspector Range 0–90.
floor_snap_length float 0.2 How far below its feet the character looks for ground to stay stuck to over a crest; 0 turns snapping off At least 0.
hit_sensors bool false Stop at sensors; off, a move passes through them
hit_solids bool true Stop at colliders that are not sensors; off, a move passes through them
lengths enum absolute Whether floor_snap_length, step_height, step_min_width and safe_margin are world units or fractions of the character's shape: relative measures the width across up_direction for step_min_width, and the height along it for the rest One of absolute, relative.
min_slide_angle float 0.5235988 The shallowest slope the character slides back down; radians in the file, degrees in the inspector Range 0–90.
normal_nudge float 0.0001 A tiny push along the contact normal that stops the character catching on seams At least 0.
push_bodies bool true Push dynamic bodies the character walks into, rather than passing through them
push_mass float 0 The mass a push is worked out with; 0 takes the body's mass, or the colliders' when there is no body At least 0.
safe_margin float 0.01 A gap kept between the character and everything else, so the solver never has to push it out of a wall At least 0.
slide bool true Slide along what is in the way instead of stopping dead against it
step_height float 0.3 The tallest step the character climbs without jumping; 0 turns stepping off At least 0.
step_min_width float 0.2 How much clear ground a step needs on top before it may be climbed At least 0.
step_on_dynamic bool false Climb onto dynamic bodies too, not only static and kinematic ones
up_direction vec2 [0,1] Which way is up for this character: the axis it stands along and measures slopes against

Script functions

Methods of node.character2d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From physics2d:

method what it does
move_character_by(Vec2) -> physics2d::CharacterMove Move the character by an offset, sliding along walls, climbing steps and staying on the ground. Every solid collider of the character is swept. Call it from fixed_update.

character3d

Contents

3d · physics · 17 properties · 3D

A 3D character controller: node.character3d.move_by slides the node along walls and steps it up ledges. Needs a collider3d; a kinematic body3d lets it push bodies.

In a scene, character3d is the node key that applies it. A script reaches each property below as a field on node.character3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.character3d.get() and node.character3d.set(table).

Properties

property type default description
exclude list [] Nodes a move passes through: their colliders, and every collider on their body
exclude_kinds flags [] The body kinds a move passes through: static takes colliders with no body too. The character's own collision_layer and collision_mask filter the rest One of static, kinematic, dynamic.
floor_max_angle float 0.7853982 The steepest slope the character may walk up; radians in the file, degrees in the inspector Range 0–90.
floor_snap_length float 0.2 How far below its feet the character looks for ground to stay stuck to over a crest; 0 turns snapping off At least 0.
hit_sensors bool false Stop at sensors; off, a move passes through them
hit_solids bool true Stop at colliders that are not sensors; off, a move passes through them
lengths enum absolute Whether floor_snap_length, step_height, step_min_width and safe_margin are world units or fractions of the character's shape: relative measures the width across up_direction for step_min_width, and the height along it for the rest One of absolute, relative.
min_slide_angle float 0.5235988 The shallowest slope the character slides back down; radians in the file, degrees in the inspector Range 0–90.
normal_nudge float 0.0001 A tiny push along the contact normal that stops the character catching on seams At least 0.
push_bodies bool true Push dynamic bodies the character walks into, rather than passing through them
push_mass float 0 The mass a push is worked out with; 0 takes the body's mass, or the colliders' when there is no body At least 0.
safe_margin float 0.01 A gap kept between the character and everything else, so the solver never has to push it out of a wall At least 0.
slide bool true Slide along what is in the way instead of stopping dead against it
step_height float 0.3 The tallest step the character climbs without jumping; 0 turns stepping off At least 0.
step_min_width float 0.2 How much clear ground a step needs on top before it may be climbed At least 0.
step_on_dynamic bool false Climb onto dynamic bodies too, not only static and kinematic ones
up_direction vec3 [0,1,0] Which way is up for this character: the axis it stands along and measures slopes against

Script functions

Methods of node.character3d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From physics3d:

method what it does
move_character_by(Vec3) -> physics3d::CharacterMove Move the character by an offset, sliding along walls, climbing steps and staying on the ground. Every solid collider of the character is swept. Call it from fixed_update. It reads the world the step just wrote.

collider2d

Contents

2d · physics · 23 properties · 2D

The node's 2D collision shape, chosen by kind. It belongs to the node's body2d or the nearest body above it; without one it is static geometry.

In a scene, collider2d is the node key that applies it. A script reaches each property below as a field on node.collider2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.collider2d.get() and node.collider2d.set(table).

Properties

property type default description
center_of_mass vec2 [0,0] Where this collider's mass sits, in its own space; read with inertia, and both 0 keep the shape's own
collision_layer flags ["1"] The layers this collider is on One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
collision_margin float 0 A margin the solver treats as already touching; stops thin shapes tunnelling and jittering At least 0.
collision_mask flags [] The layers it collides with; empty means every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
collision_test enum both Whether a pair is tested when both colliders' layers accept the other, or when either does; two colliders that differ use both One of both, either.
contact_force_threshold float 0 How hard a contact must be before on_contact_force is called At least 0.
contact_pairs flags ["dynamic_dynamic","dynamic_kinematic","dynamic_static"] Which pairs of body kinds this collider is tested against; a sensor is tested against every kind whatever this says One of dynamic_dynamic, dynamic_kinematic, dynamic_static, kinematic_kinematic, kinematic_static, static_static.
density float 1 Mass per volume, so the shape's size sets its mass; 0 makes a collider that adds no mass to its body At least 0.
enabled bool true Collide at all; a disabled collider keeps its shape and costs nothing
inertia float 0 This collider's resistance to spin; 0 with a center_of_mass takes the shape's own about that centre At least 0.
mass float 0 Mass in kilograms, overriding what density works out to; 0 keeps the density At least 0.
offset vec2 [0,0] Where the shape sits relative to the node
offset_rotation float 0 How the shape is turned relative to the node; radians in the file
one_way bool false A platform bodies land on from the side one_way_axis names and pass through from the other
one_way_angle float 0.1 How far a contact's normal may lean from one_way_axis and still hold the body; radians in the file Range 0–180.
one_way_axis vec2 [0,1] The side a one-way platform holds bodies on, in the collider's own axes: [0, 1] lands them from above and lets them up through from below
physics_material asset · physics_material — What the surface is made of: friction, bounce and how each combines; empty takes a physics_material at its defaults
sensor bool false Detects overlaps without colliding: bodies pass through and are reported
shape variant {"edge_radius":0,"kind":"rectangle","size":[1,1]} The collision shape, and the dimensions or the source that kind reads
solver_layer flags ["1"] Layers for the solver alone: a pair can be detected but not resolved One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
solver_mask flags [] Which solver layers this one pushes against; empty means all of them One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
solver_test enum both The same choice for the solver layers One of both, either.
surface_velocity vec2 [0,0] How fast the surface slides along itself, in the collider's own axes: a conveyor belt carries what rests on it

Asset types this component references: physics_material.

Script functions

Methods of node.collider2d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From physics2d:

method what it does
aabb() -> physics2d::Aabb The world-space box the collider currently occupies, from its lowest corner to its highest.
broad_phase_aabb() -> physics2d::Aabb The box the broad phase files the collider under, which also reaches ahead by its body's speculative_distance.
collider_mass_properties() -> physics2d::MassProperties What this collider adds to its body, in its own space.
collider_mesh() -> physics2d::ColliderMesh A voxel collider's outline as points and the segments between them, for drawing it or for spawning the pieces it broke into.
collider_volume() -> float How much area the shape encloses.
collision_aabb() -> physics2d::Aabb The box the narrow phase tests the collider in: its shape's box grown by its collision_margin and the world's prediction distance.
combine_voxels(Node) Tell two voxel colliders on one lattice about each other's cells, so a body sliding from one onto the other does not catch on the seam. Both must share a cell size and a rotation.
contacts() -> [physics2d::Contact] Every contact point on this node's collider this step. Empty for a sensor, which has no contacts by definition.
crop_voxels(int, int, int, int) Empty every cell outside the cells from (min_x, min_y) to (max_x, max_y), both included. A range holding no filled cell leaves the grid as it was.
handles() -> physics2d::Handles The rapier handles behind this node, its body and its colliders. For matching a log line against rapier's own output.
heightfield_hole(int) -> bool Whether a heightfield segment has no ground.
overlaps() -> [Node] The nodes this one currently intersects; rapier reports a pair only when one of the two colliders is a sensor.
pose_in_body() -> physics2d::Pose? Where the collider sits in its body's frame; nothing for a collider with no body.
set_heightfield_hole(int, bool) Remove or restore one segment of a heightfield's ground, numbered from the first height.
set_voxel(int, int, bool) Fill or empty one cell of a voxel collider: digging a hole, or building a wall, while the game runs.
set_voxel_size(Vec2) Resize every cell of a voxel collider, keeping which cells are filled.
swept_aabb() -> physics2d::Aabb The box the collider covers over the next fixed step, from where it is to where its body's velocity and forces carry it.
voxel(int, int) -> bool Whether one cell of a voxel collider is filled.
voxel_at(Vec2) -> [int] The cell a world position falls in, as two whole numbers.
voxel_size() -> Vec2 How big one cell of a voxel collider is, along each axis.

collider3d

Contents

3d · physics · 24 properties · 3D

The node's 3D collision shape, chosen by kind. It belongs to the node's body3d or the nearest body above it; without one it is static geometry.

In a scene, collider3d is the node key that applies it. A script reaches each property below as a field on node.collider3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.collider3d.get() and node.collider3d.set(table).

Properties

property type default description
center_of_mass vec3 [0,0,0] Where this collider's mass sits, in its own space; read with inertia, and both 0 keep the shape's own
collision_layer flags ["1"] The layers this collider is on One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
collision_margin float 0 A margin the solver treats as already touching; stops thin shapes tunnelling and jittering At least 0.
collision_mask flags [] The layers it collides with; empty means every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
collision_test enum both Whether a pair is tested when both colliders' layers accept the other, or when either does; two colliders that differ use both One of both, either.
contact_force_threshold float 0 How hard a contact must be before on_contact_force is called At least 0.
contact_pairs flags ["dynamic_dynamic","dynamic_kinematic","dynamic_static"] Which pairs of body kinds this collider is tested against; a sensor is tested against every kind whatever this says One of dynamic_dynamic, dynamic_kinematic, dynamic_static, kinematic_kinematic, kinematic_static, static_static.
density float 1 Mass per volume, so the shape's size sets its mass; 0 makes a collider that adds no mass to its body At least 0.
enabled bool true Collide at all; a disabled collider keeps its shape and costs nothing
inertia vec3 [0,0,0] This collider's resistance to spin about each axis; 0 with a center_of_mass takes the shape's own about that centre
inertia_rotation vec3 [0,0,0] Turns the axes inertia is measured about, as rotation_euler does; read with a non-zero inertia. Euler radians in the file
mass float 0 Mass in kilograms, overriding what density works out to; 0 keeps the density At least 0.
offset vec3 [0,0,0] Where the shape sits relative to the node
offset_rotation vec3 [0,0,0] How the shape is turned relative to the node, as rotation_euler turns one; Euler radians in the file
one_way bool false A platform bodies land on from the side one_way_axis names and pass through from the other
one_way_angle float 0.1 How far a contact's normal may lean from one_way_axis and still hold the body; radians in the file Range 0–180.
one_way_axis vec3 [0,1,0] The side a one-way platform holds bodies on, in the collider's own axes: [0, 1, 0] lands them from above and lets them up through from below
physics_material asset · physics_material — What the surface is made of: friction, bounce and how each combines; empty takes a physics_material at its defaults
sensor bool false Detects overlaps without colliding: bodies pass through and are reported
shape variant {"edge_radius":0,"kind":"box","size":[1,1,1]} The collision shape, and the dimensions or the source that kind reads
solver_layer flags ["1"] Layers for the solver alone: a pair can be detected but not resolved One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
solver_mask flags [] Which solver layers this one pushes against; empty means all of them One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
solver_test enum both The same choice for the solver layers One of both, either.
surface_velocity vec3 [0,0,0] How fast the surface slides along itself, in the collider's own axes: a conveyor belt carries what rests on it

Asset types this component references: physics_material.

Script functions

Methods of node.collider3d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From physics3d:

method what it does
aabb() -> physics3d::Aabb The world-space box the collider currently occupies, from its lowest corner to its highest.
broad_phase_aabb() -> physics3d::Aabb The box the broad phase files the collider under, which also reaches ahead by its body's speculative_distance.
collider_mass_properties() -> physics3d::MassProperties What this collider adds to its body, in its own space.
collider_mesh() -> physics3d::ColliderMesh The collider's shape as points and triangles, including a voxel grid's, for drawing it or for spawning the pieces it broke into.
collider_volume() -> float How much space the shape encloses.
collision_aabb() -> physics3d::Aabb The box the narrow phase tests the collider in: its shape's box grown by its collision_margin and the world's prediction distance.
combine_voxels(Node) Tell two voxel colliders on one lattice about each other's cells, so a body sliding from one onto the other does not catch on the seam. Both must share a cell size and a rotation.
contacts() -> [physics3d::Contact] Every contact point on this node's collider this step. Empty for a sensor, which has no contacts by definition.
crop_voxels(int, int, int, int, int, int) Empty every cell outside the cells from (min_x, min_y, min_z) to (max_x, max_y, max_z), both included. A range holding no filled cell leaves the grid as it was.
handles() -> physics3d::Handles The rapier handles behind this node, its body and its colliders. For matching a log line against rapier's own output.
heightfield_hole(int, int) -> bool Whether a heightfield cell has no ground.
overlaps() -> [Node] The nodes this one currently intersects; rapier reports a pair only when one of the two colliders is a sensor.
pose_in_body() -> physics3d::Pose? Where the collider sits in its body's frame; nothing for a collider with no body.
set_heightfield_hole(int, int, bool) Remove or restore the ground of one heightfield cell, named by the row and column of its first corner.
set_voxel(int, int, int, bool) Fill or empty one cell of a voxel collider: digging a hole, or building a wall, while the game runs.
set_voxel_size(Vec3) Resize every cell of a voxel collider, keeping which cells are filled.
swept_aabb() -> physics3d::Aabb The box the collider covers over the next fixed step, from where it is to where its body's velocity and forces carry it.
voxel(int, int, int) -> bool Whether one cell of a voxel collider is filled.
voxel_at(Vec3) -> [int] The cell a world position falls in, as three whole numbers.
voxel_size() -> Vec3 How big one cell of a voxel collider is, along each axis.

convex_decomposition2d

Contents

2d · physics · 1 property · 2D

How the node's collider2d cuts its mesh into convex pieces, for a convex_decomposition.

In a scene, convex_decomposition2d is the node key that applies it. A script reaches each property below as a field on node.convex_decomposition2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.convex_decomposition2d.get() and node.convex_decomposition2d.set(table).

Properties

property type default description
method variant {"kind":"exact","overlap":0.9} How a convex_decomposition is cut, and the rows that way reads

convex_decomposition3d

Contents

3d · physics · 9 properties · 3D

How the node's collider3d cuts its mesh into convex pieces, for a convex_decomposition or a fit to one.

In a scene, convex_decomposition3d is the node key that applies it. A script reaches each property below as a field on node.convex_decomposition3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.convex_decomposition3d.get() and node.convex_decomposition3d.set(table).

Properties

property type default description
approximate_hulls bool true Estimate each piece's hull while cutting rather than building it exactly
hull_downsampling int 4 How coarsely a piece's hull is sampled while choosing a cut; 1 uses every point At least 1.
max_concavity float 0.01 How deep a dent a piece may keep before it is cut again At least 0.
max_convex_hulls int 1024 The most pieces a decomposition is asked to leave; parry 0.31 passes it on unread, so it limits nothing yet At least 1.
method enum vhacd How a convex_decomposition is cut: into convex hulls, or into voxel parts One of vhacd, voxels.
plane_downsampling int 4 How coarsely the cutting planes are searched first; 1 tries every one At least 1.
resolution int 64 How fine the voxel grid a decomposition cuts is At least 1.
revolution_bias float 0.05 How much a cut prefers an axis of revolution Range 0–1.
symmetry_bias float 0.05 How much a cut prefers a plane of symmetry Range 0–1.

debug_draw

Contents

render · 7 properties · Rendering

A wireframe over every triangle edge of the node's drawing, a point on every vertex, and whether its surface draws at all, for any drawable in either dimension.

In a scene, debug_draw is the node key that applies it. A script reaches each property below as a field on node.debug_draw: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.debug_draw.get() and node.debug_draw.set(table).

Properties

property type default description
draw_surface bool true Whether the surface draws; off leaves the wireframe and the points alone
point_color color [0,0,0,0] The points' colour; an alpha of zero takes the node's own
point_size float 0 Size of a point drawn on every vertex; zero draws none. Not on WebGL2 At least 0.
point_sizing enum world What point_size counts: world scales with the view, screen is pixels One of world, screen.
wireframe_color color [0,0,0,0] The wireframe's colour; an alpha of zero takes the node's own
wireframe_sizing enum world What wireframe_width counts: world scales with the view, screen is pixels One of world, screen.
wireframe_width float 0 Width of a line drawn along every triangle edge; zero draws none. Not on WebGL2 At least 0.

environment

Contents

render · 36 properties · Rendering

The scene's atmosphere: sky, ambient_color, fog_mode, exposure, tonemap, colour grading and how shadows fall. The last current one wins; per-view effects stay on camera.post, and what the device can afford is [render].

In a scene, environment is the node key that applies it. A script reaches each property below as a field on node.environment: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.environment.get() and node.environment.set(table).

Properties

property type default description
ambient_color color [0.389,0.409,0.431,1] Light every surface gets whatever the lights do, a 2D one's before any light2d as a 3D one's
auto_exposure_enabled bool false Measure the frame's average brightness and adapt the exposure to it, replacing exposure. It adapts on the wall clock, so two captures of one fixed-step frame can differ
auto_exposure_key float 0.18 The mid grey auto-exposure maps the frame's average brightness to At least 0.
auto_exposure_max float 8 The highest exposure auto-exposure settles at, for the darkest scenes At least 0.
auto_exposure_min float 0.05 The lowest exposure auto-exposure settles at, for the brightest scenes At least 0.
auto_exposure_speed float 3 How fast auto-exposure follows the scene, per second At least 0.
contrast float 1 Contrast around mid grey At least 0.
current bool true Whether this is the environment the scene draws under; the last current one in tree order wins
exposure float 1 Linear multiplier before the tonemap At least 0.
fog_color color [0.624,0.706,0.784,1] What distance fades toward
fog_density float 0.02 Thickness, for exponential fog At least 0.
fog_end float 80 Where linear fog is total, in world units At least 0.
fog_height_falloff float 0 How fast fog thins with height; zero fills the scene evenly At least 0.
fog_mode enum none How fog thickens with distance One of none, linear, exponential, exponential_squared.
fog_start float 10 Where linear fog begins, in world units At least 0.
gamma float 1 Gamma applied in linear space At least 0.01.
hue_degrees float 0 Turns every hue about the grey axis before the tonemap, in degrees
saturation float 1 Colour multiplier around luminance; zero is grey At least 0.
shadow_bias float 0.0012 Depth the lighting pass allows before it calls a point shadowed. Raise it to cure acne; lower it to keep contact shadows attached. Not yet honoured on a node with a shader material At least 0.
shadow_cascades int 4 How many cascades a directional light splits its shadow range into; each takes one of shadow_views Range 1–4.
shadow_constant_bias int 1 Depth-buffer units the shadow pass pushes every caster back by
shadow_distance float 60 How far along the view a directional light's cascades reach, in world units; the camera's far caps it At least 0.
shadow_enabled bool true Whether any light casts shadows at all
shadow_first_cascade_distance float 12 How far along the view the first, sharpest cascade reaches, in world units At least 0.01.
shadow_slope_bias float 1.75 How far the shadow pass pushes a caster back per unit of its depth slope, so a surface seen edge-on by the light does not shadow itself
shadow_softness float 1 How far a shadow's edge is blurred At least 0.
sky string — Equirectangular image, project-relative: .hdr, .exr or .png. It draws behind the scene and lights it. Empty is no sky
sky_enabled bool true False takes the sky away: it stops drawing and stops lighting, and ambient_color lights the scene as it does with no sky
sky_intensity float 1 Brightness of the sky, and of the light it casts At least 0.
sky_light string — Equirectangular image, project-relative, that lights the scene in place of sky, which still draws. Empty lights with sky; it lights even with no sky drawn, and sky_enabled = false takes it away too
sky_light_intensity float -1 Brightness of the light the sky casts, apart from how bright it draws; below zero follows sky_intensity At least -1.
sky_rotation_degrees float 0 Turn of the sky about y, in degrees
tonemap enum neutral The curve the HDR film is mapped through. A scene with no environment node draws untonemapped One of none, aces, reinhard, agx, neutral, tony_mcmapface.
transmission_blur_quality enum high How smoothly rough glass blurs what it refracts; low is cheapest and can look blocky One of low, medium, high.
transmission_enabled bool true Whether glass refracts what is behind it. Off draws a material with transmission as plain opaque PBR and skips the passes
white_balance vec3 [1,1,1] Per-channel linear gain before the tonemap; [1, 1, 1] leaves colour alone

follow2d

Contents

2d · physics · 12 properties · 2D

Pulls the node's body2d towards the pose of target every fixed step, with rapier's PD or PID controller. node.follow2d.reset() forgets what a PID summed.

In a scene, follow2d is the node key that applies it. A script reaches each property below as a field on node.follow2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.follow2d.get() and node.follow2d.set(table).

Properties

property type default description
integral_gain vec2 [1,1] How hard the gap in position summed over time pulls, per axis, with pid
kind enum pd Rapier's proportional-derivative controller, or the same with an integral that keeps pulling against a steady push One of pd, pid.
position_gain vec2 [60,60] How hard a gap in position pulls, per axis: about one over the fixed step closes it in one step
rotation_axes flags ["rotation"] Whether the body is turned to the target's rotation too: the one turn a 2D body has, as a 2D joint names it One of rotation.
rotation_gain float 60 How hard a gap in rotation pulls
rotation_integral_gain float 1 How hard the gap in rotation summed over time pulls, with pid
spin_gain float 0.8 How much of a gap in spin a step corrects
target node — The node whose pose the body is pulled to; empty pulls nothing
target_angular_velocity float 0 The spin the body is pulled to match, radians a second in the file
target_linear_velocity vec2 [0,0] The velocity the body is pulled to match, in world units per second
translation_axes flags ["x","y"] The axes the body is pulled along One of x, y.
velocity_gain vec2 [0.8,0.8] How much of a gap in velocity a step corrects, per axis: 0 none, 1 all of it

Script functions

Methods of node.follow2d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From physics2d:

method what it does
reset_follow() Forget what a pid follow summed, so it pulls from now as if it had just started.

follow3d

Contents

3d · physics · 12 properties · 3D

Pulls the node's body3d towards the pose of target every fixed step, with rapier's PD or PID controller. node.follow3d.reset() forgets what a PID summed.

In a scene, follow3d is the node key that applies it. A script reaches each property below as a field on node.follow3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.follow3d.get() and node.follow3d.set(table).

Properties

property type default description
integral_gain vec3 [1,1,1] How hard the gap in position summed over time pulls, per axis, with pid
kind enum pd Rapier's proportional-derivative controller, or the same with an integral that keeps pulling against a steady push One of pd, pid.
position_gain vec3 [60,60,60] How hard a gap in position pulls, per axis: about one over the fixed step closes it in one step
rotation_axes flags ["x","y","z"] The axes the body is turned about One of x, y, z.
rotation_gain vec3 [60,60,60] How hard a gap in rotation pulls, per axis
rotation_integral_gain vec3 [1,1,1] How hard the gap in rotation summed over time pulls, per axis, with pid
spin_gain vec3 [0.8,0.8,0.8] How much of a gap in spin a step corrects, per axis
target node — The node whose pose the body is pulled to; empty pulls nothing
target_angular_velocity vec3 [0,0,0] The spin the body is pulled to match about each axis, radians a second in the file
target_linear_velocity vec3 [0,0,0] The velocity the body is pulled to match, in world units per second
translation_axes flags ["x","y","z"] The axes the body is pulled along One of x, y, z.
velocity_gain vec3 [0.8,0.8,0.8] How much of a gap in velocity a step corrects, per axis: 0 none, 1 all of it

Script functions

Methods of node.follow3d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From physics3d:

method what it does
reset_follow() Forget what a pid follow summed, so it pulls from now as if it had just started.

generic_joint2d

Contents

2d · physics · 3 properties · 2D

Which axes a joint2d of kind generic locks, and which free ones it ties into one.

In a scene, generic_joint2d is the node key that applies it. A script reaches each property below as a field on node.generic_joint2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.generic_joint2d.get() and node.generic_joint2d.set(table).

Properties

property type default description
coupled_translation flags [] Free linear axes tied into one distance, whose limit and motor come from the first of them; a rope and a spring couple both already One of x, y.
lock_rotation bool false Stop a generic joint turning
lock_translation flags [] The axes a generic joint may not slide along One of x, y.

generic_joint3d

Contents

3d · physics · 4 properties · 3D

Which axes a joint3d of kind generic locks, and which free ones it ties into one.

In a scene, generic_joint3d is the node key that applies it. A script reaches each property below as a field on node.generic_joint3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.generic_joint3d.get() and node.generic_joint3d.set(table).

Properties

property type default description
coupled_rotation flags [] Free turning axes tied into one angle, whose limit and motor come from the first of them One of x, y, z.
coupled_translation flags [] Free linear axes tied into one distance, whose limit and motor come from the first of them; a rope and a spring couple all three already One of x, y, z.
lock_rotation flags [] The axes a generic joint may not turn about One of x, y, z.
lock_translation flags [] The axes a generic joint may not slide along One of x, y, z.

joint2d

Contents

2d · physics · 13 properties · 2D

Joins this node's body to connected_body. kind is fixed, hinge, slider, rope, spring, groove or generic; both ends need a body2d on or above the node. axes limits and drives each free axis.

In a scene, joint2d is the node key that applies it. A script reaches each property below as a field on node.joint2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.joint2d.get() and node.joint2d.set(table).

Properties

property type default description
anchor vec2 [0,0] Where the joint attaches on this node, in its own space
anchor_rotation float 0 Turns this end's joint frame: what a hinge's angle and its limits measure from, and the relative turn a fixed joint holds. Radians in the file
axes list [] One record per free axis to limit or drive. A rope's x takes no limits (max_length is its limit); a spring's x is its spring, whose motor stays off
axis vec2 [1,0] The joint frame's x axis: what a slider or a groove slides along, and a generic joint's x names
collide_connected bool false Let the two joined bodies collide with each other
connected_anchor vec2 [0,0] Where it attaches on the other node, in that node's space
connected_anchor_rotation float 0 The same for the other end's frame
connected_axis vec2 [0,0] The same axis in the other node's space, for a slider, a groove or a generic joint; zero takes axis
connected_body node — The node at the joint's other end; this node is the first end
enabled bool true Hold the two bodies together at all. Off keeps the joint and stops solving it; an articulation leaves its chain instead, as rapier's chains ignore the switch
kind enum fixed How the two bodies may move relative to each other One of fixed, hinge, slider, rope, spring, groove, generic.
softness_damping_ratio float 1 The damping ratio of that spring; 1 settles without overshooting At least 0.
softness_hz float 1000000 How stiffly the joint's locked axes and limits are held, as a spring frequency in hertz; lower lets them stretch and spring back At least 0.

Script functions

Methods of node.joint2d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From physics2d:

method what it does
joint_force() -> physics2d::JointForce The force and the torque the joint held through the last step. An articulation has none to read, and says so.
joint_state() -> physics2d::JointState What the joint is doing.
solve_ik(Vec2, physics2d::IkOptions?) Move a reduced-coordinates chain so its last link reaches a world position, leaving every joint inside its limits. Options: rotation (radians to turn the link to), constrain (the world axes to match: x, y, rotation; the translation by default, every axis when rotation is given), damping (1.0), iterations (10), tolerance (0.001).

joint3d

Contents

3d · physics · 13 properties · 3D

Joins this node's body to connected_body. kind is fixed, hinge, slider, ball_socket, rope, spring or generic; both ends need a body3d on or above the node. axes limits and drives each free axis.

In a scene, joint3d is the node key that applies it. A script reaches each property below as a field on node.joint3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.joint3d.get() and node.joint3d.set(table).

Properties

property type default description
anchor vec3 [0,0,0] Where the joint attaches on this node, in its own space
anchor_rotation vec3 [0,0,0] Turns this end's joint frame about its own axes, as rotation_euler turns a node: what a hinge's angle and its limits measure from, and the relative turn a fixed joint holds. Euler radians in the file
axes list [] One record per free axis to limit or drive. A rope's x takes no limits (max_length is its limit); a spring's x is its spring, whose motor stays off
axis vec3 [0,0,1] The joint frame's x axis: what a hinge turns about, a slider slides along, and a generic joint's x and rotation_x name
collide_connected bool false Let the two joined bodies collide with each other
connected_anchor vec3 [0,0,0] Where it attaches on the other node, in that node's space
connected_anchor_rotation vec3 [0,0,0] The same for the other end's frame
connected_axis vec3 [0,0,0] The same axis in the other node's space, for a hinge, a slider or a generic joint; zero takes axis
connected_body node — The node at the joint's other end; this node is the first end
enabled bool true Hold the two bodies together at all. Off keeps the joint and stops solving it; an articulation leaves its chain instead, as rapier's chains ignore the switch
kind enum fixed How the two bodies may move relative to each other One of fixed, hinge, slider, ball_socket, rope, spring, generic.
softness_damping_ratio float 1 The damping ratio of that spring; 1 settles without overshooting At least 0.
softness_hz float 1000000 How stiffly the joint's locked axes and limits are held, as a spring frequency in hertz; lower lets them stretch and spring back At least 0.

Script functions

Methods of node.joint3d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From physics3d:

method what it does
joint_force() -> physics3d::JointForce The force and the torque the joint held through the last step: what break_force and break_torque are measured against. An articulation has none to read, and says so.
joint_state() -> physics3d::JointState What the joint is doing.
solve_ik(Vec3, physics3d::IkOptions?) Move a reduced-coordinates chain so its last link reaches a world position, leaving every joint inside its limits. Options: rotation (euler radians to turn the link to), constrain (the world axes to match: x, y, z, rotation_x, rotation_y, rotation_z; the translation by default, every axis when rotation is given), damping (1.0), iterations (10), tolerance (0.001).

light2d

Contents

2d · render · 9 properties · 2D

A 2D light at the node's position. kind is point, directional or spot; the first light2d in a scene drops everything else to the environment's ambient_color.

In a scene, light2d is the node key that applies it. A script reaches each property below as a field on node.light2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.light2d.get() and node.light2d.set(table).

Properties

property type default description
color color [1,1,1,1] Light colour, as channel floats or #rrggbb / #rrggbbaa
height float 1 How far above the plane a normal-mapped node sees a point or spot light, in world units; lower grazes the bumps. For a directional light, its rise over run: 1 comes in at 45 degrees. Only a node whose material names a normal map reads it At least 0.
inner_angle_degrees float 20 Half-angle of a spot light's full-brightness cone, in degrees Range 0–179.
intensity float 1 Brightness multiplier; over 1 blows past white At least 0.
kind enum point A point light fades to nothing at range; a directional one lights the whole view; a spot throws a cone the node's rotation aims, down at rest One of point, directional, spot.
outer_angle_degrees float 35 Half-angle a spot light fades to nothing at, in degrees Range 0–179.
range float 6 How far a point light reaches, in world units At least 0.
shadow_enabled bool true Whether occluder2d outlines cast shadows from this light
source_radius float 0.25 The disc a camera's gi pass emits a point or spot light from, in world units; gi gives a spot no cone and a directional light no form At least 0.

light3d

Contents

3d · render · 9 properties · 3D

A 3D light placed and aimed by the node. kind is directional, point or spot; the first light3d in a scene retires the engine's default key light.

In a scene, light3d is the node key that applies it. A script reaches each property below as a field on node.light3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.light3d.get() and node.light3d.set(table).

Properties

property type default description
color color [1,1,1,1] Light colour, as channel floats or #rrggbb / #rrggbbaa
inner_angle_degrees float 20 Half-angle of a spot light's full-brightness cone, in degrees Range 0–179.
intensity float 3 Brightness multiplier; over 1 blows past white At least 0.
kind enum directional A point light fades to nothing at range, a directional one lights the whole scene, a spot one throws a cone the node aims One of directional, point, spot.
light_layers flags [] The light layers this light reaches: a node whose light_layers share one; empty is every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
outer_angle_degrees float 35 Half-angle a spot light fades to nothing at, in degrees Range 0–179.
range float 30 How far a point or spot light reaches, in world units At least 0.
shadow_enabled bool true Whether this light casts shadows from the nodes that say they cast
source_radius float 0 Radius of the sphere the light shines from, in world units, which softens its shadows. Read by the path tracer only; the rasterizer's edge is environment.shadow_softness At least 0.

line2d

Contents

2d · render · 13 properties · 2D

A stroked line at the node through the points of a mesh or path2d asset, tinted by color and drawn with texture.

In a scene, line2d is the node key that applies it. A script reaches each property below as a field on node.line2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.line2d.get() and node.line2d.set(table).

Properties

property type default description
cap enum round How an open line ends One of round, butt, square.
closed bool false Join the last point back to the first, making a polygon outline
color color [0.8,0.8,0.8,1] Tint, as channel floats or #rrggbb / #rrggbbaa
gradient color [0,0,0,0] The colour the line fades to at its far end, from color at its start; a zero alpha means no gradient
gradient_steps int 32 How many colours the gradient steps through along the line At least 1.
join enum round How the line's segments meet One of round, miter, bevel.
material asset · material — The material this draws with; empty draws with the built-in one
mesh asset · mesh — Where the line's points come from: a mesh asset's vertices, or a path2d asset, which is sampled into points and so draws as a stroked curve
miter_limit float 4 How far a miter join may reach, in half-widths, before its corner is cut to a bevel At least 1.
segments int 32 Cuts around a round join or cap At least 3.
taper vec2 [1,1] Multipliers on width at the line's start and end, blended along it; anything but [1, 1] draws round joins and caps
texture asset · texture — An image, or a texture asset, the line draws with, repeating once per world unit of its length
width float 0.02 Line thickness in world units At least 0.001.

Asset types this component references: material, mesh, texture.

listener

Contents

audio · 4 properties · Audio

The point positional sounds are heard from: distance sets volume, offset across its right sets pan, and the closing speed against speed_of_sound bends pitch. The last current listener wins; without one, sounds play flat.

In a scene, listener is the node key that applies it. A script reaches each property below as a field on node.listener: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.listener.get() and node.listener.set(table).

Properties

property type default description
current bool true Whether the mix is heard from this node; the last current one wins
ear_distance float 0 Distance between the ears along the node's right. Above 0 the pan is how much nearer one ear is; 0 pans by direction alone, opening up inside min_distance At least 0.
max_doppler float 2 The most doppler multiplies a pitch by; its inverse is the least At least 1.
speed_of_sound float 343 Units a second sound travels at, which doppler measures closing speeds against At least 0.001.

material

Contents

render · 1 property · Rendering

source is the material asset this node and everything under it draw with. A renderable's own material property overrides it for that node alone.

In a scene, material is the node key that applies it. A script reaches each property below as a field on node.material: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.material.get() and node.material.set(table).

Properties

property type default description
source asset · material — The material asset; empty takes the parent's

Asset types this component references: material.

mesh

Contents

3d · render · 10 properties · 3D

3D geometry from the mesh asset in source, drawn at the node. With a skin, the rig skeleton names deforms it.

In a scene, mesh is the node key that applies it. A script reaches each property below as a field on node.mesh: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.mesh.get() and node.mesh.set(table).

Properties

property type default description
cast_shadow bool true Whether this casts a shadow from the lights that cast
color color [1,1,1,1] Tint the texture and the material are multiplied by, as channel floats or #rrggbb / #rrggbbaa; an alpha below one draws it see-through
light_layers flags [] The light layers this is lit on: a light3d lights it when their light_layers share one; empty is every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
material asset · material — The material this draws with; empty draws with the built-in one
receive_shadows bool true Whether shadows land on it; off lights it as if nothing stood between it and every light
render_layers flags [] The layers this is drawn on: a camera3d draws it when their render_layers share one; empty is every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
segmentation_id int 0 The id render.snap_aov("segmentation") colours this node by; nodes sharing one share a colour. Zero takes one of its own, from 1 up At least 0.
skeleton node — The rig a skinned mesh deforms with; empty means this node
source asset · mesh — The mesh asset this node draws
texture asset · texture — Image file, project-relative, or a texture asset; empty draws the colour alone

Asset types this component references: material, mesh, texture.

mesh_collider2d

Contents

2d · physics · 10 properties · 2D

How the node's collider2d turns its mesh into a shape: the shape a fit takes, the edges a polyline keeps, how a convex_polygon and a voxelized outline are read, and what a triangle_mesh tidies first.

In a scene, mesh_collider2d is the node key that applies it. A script reaches each property below as a field on node.mesh_collider2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.mesh_collider2d.get() and node.mesh_collider2d.set(table).

Properties

property type default description
connected_components bool false Work out which triangles form each separate piece of the mesh
drop_bad_topology bool false Drop the triangles that stop the mesh's edge topology from being built
drop_degenerate_triangles bool true Drop triangles that name one vertex twice; merges vertices too
drop_duplicate_triangles bool true Drop a triangle whose three vertices another one already names; merges vertices too
fill enum solid Whether voxelizing an outline fills its inside or only its edge, for voxelized_mesh and a vhacd or voxels decomposition One of solid, surface.
fill_cavities bool false When a solid fill floods an outline, leave the holes it walls off empty
fix_self_intersections bool false When a solid fill floods an outline, handle the places it crosses itself
merge_vertices bool true Merge vertices at exactly the same place when building a triangle_mesh
oriented bool false Treat a triangle_mesh or polyline as one-sided: the winding decides which side is solid, counter-clockwise enclosing the solid
topology bool false Build the mesh's half-edge topology

mesh_collider3d

Contents

3d · physics · 9 properties · 3D

How the node's collider3d turns its mesh into a shape: how a voxelized mesh or a decomposition's grid is filled, and what a triangle_mesh tidies first.

In a scene, mesh_collider3d is the node key that applies it. A script reaches each property below as a field on node.mesh_collider3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.mesh_collider3d.get() and node.mesh_collider3d.set(table).

Properties

property type default description
connected_components bool false Work out which triangles form each separate piece of the mesh
drop_bad_topology bool false Drop the triangles that stop the mesh's edge topology from being built
drop_degenerate_triangles bool true Drop triangles that name one vertex twice; merges vertices too
drop_duplicate_triangles bool true Drop a triangle whose three vertices another one already names; merges vertices too
fill enum solid Whether voxelizing a mesh fills its inside or only its shell, for voxelized_mesh and a convex_decomposition's voxel grid One of solid, surface.
fill_cavities bool false When a solid fill floods a mesh, leave the cavities a closed surface walls off empty
merge_vertices bool true Merge vertices at exactly the same place when building a triangle_mesh
oriented bool false Treat the triangle_mesh as a closed, outward-facing surface, which makes inside and outside meaningful
topology bool false Build the mesh's half-edge topology

meta

Contents

interaction · 0 properties · Other

Named values filed on the node, like Godot's set_meta. It has no fixed properties; every key is the author's.

In a scene, meta is the node key that applies it. A script reaches each property below as a field on node.meta: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.meta.get() and node.meta.set(table).

Properties

property type default description

modifier2d

Contents

2d · animation · 14 properties · 2D

Poses 2D bones toward target after the clip runs. kind is look_at, two_bone_ik, fabrik, ccdik or jiggle.

In a scene, modifier2d is the node key that applies it. A script reaches each property below as a field on node.modifier2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.modifier2d.get() and node.modifier2d.set(table).

Properties

property type default description
angle_limit float 0 How far a ccdik bone may turn from its rest, in radians; 0 leaves it free
bone node — The driven bone; empty means this node. For a chain solver, its root
chain_count int 0 How many bones the chain holds, counting the driven one; 0 walks to the deepest tip
damping float 0.75 How much of a jiggle bone's speed survives a tick, 0 to 1
enabled bool true Whether the modifier runs; off leaves the clip's pose alone
flip_bend_direction bool false Bend a two-bone chain the other way
gravity vec2 [0,-6] Pull on a jiggle bone while use_gravity is on
iterations int 10 Solver passes for fabrik and ccdik
kind enum look_at Aim one bone at the target, bend a two-bone chain to it, reach with a chain of any length (fabrik or ccdik), or let a chain lag behind the pose (jiggle) One of look_at, two_bone_ik, fabrik, ccdik, jiggle.
mass float 0.75 What gravity weighs against stiffness on a jiggle bone
stiffness float 3 How hard a jiggle bone is pulled back to the pose
target node — The point to aim at. Unused by jiggle
tolerance float 0.01 How close to the target ends a fabrik or ccdik solve early
use_gravity bool false Whether a jiggle chain is pulled by gravity

modifier3d

Contents

3d · animation · 14 properties · 3D

Poses bone3d nodes toward target after the clip runs. kind is look_at, two_bone_ik, fabrik, ccdik or jiggle.

In a scene, modifier3d is the node key that applies it. A script reaches each property below as a field on node.modifier3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.modifier3d.get() and node.modifier3d.set(table).

Properties

property type default description
angle_limit float 0 How far a ccdik bone may turn from its rest, in radians; 0 leaves it free
bone node — The driven bone; empty means this node. For a chain solver, its root
chain_count int 0 How many bones the chain holds, counting the driven one; 0 walks to the deepest tip
damping float 0.75 How much of a jiggle bone's speed survives a tick, 0 to 1
enabled bool true Whether the modifier runs; off leaves the clip's pose alone
flip_bend_direction bool false Bend a two-bone chain the other way
gravity vec3 [0,-6,0] Pull on a jiggle bone while use_gravity is on
iterations int 10 Solver passes for fabrik and ccdik
kind enum look_at Aim one bone at the target, bend a two-bone chain to it, reach with a chain of any length (fabrik or ccdik), or let a chain lag behind the pose (jiggle) One of look_at, two_bone_ik, fabrik, ccdik, jiggle.
mass float 0.75 What gravity weighs against stiffness on a jiggle bone
stiffness float 3 How hard a jiggle bone is pulled back to the pose
target node — The point to aim at. Unused by jiggle
tolerance float 0.01 How close to the target ends a fabrik or ccdik solve early
use_gravity bool false Whether a jiggle chain is pulled by gravity

multimesh2d

Contents

2d · render · 5 properties · 2D

Godot's MultiMeshInstance2D: the multimesh asset in source, its mesh drawn flat once per instance in one call, each instance tinted over color. The node keeps its own copy of the instances, so a script's edits stay on it; children draw once.

In a scene, multimesh2d is the node key that applies it. A script reaches each property below as a field on node.multimesh2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.multimesh2d.get() and node.multimesh2d.set(table).

Properties

property type default description
color color [1,1,1,1] Tint under every instance's own colour, as channel floats or #rrggbb / #rrggbbaa
material asset · material — The material this draws with; empty takes an inherited material component, else the built-in one
pixels_per_unit float 100 Texture pixels per world unit, for a mesh that carries no UVs of its own At least 0.01.
source asset · multimesh — The multimesh asset: the mesh and the instances it is drawn at
texture asset · texture — Image file, project-relative, or a texture asset; empty draws the colour alone

Asset types this component references: material, multimesh, texture.

Script functions

Methods of node.multimesh2d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From multimesh2d:

method what it does
instance_color(int) -> Color The colour one instance draws in.
instance_count() -> int How many instances the node holds.
instance_custom_data(int) -> Color One instance's four floats of custom data, as a colour.
instance_region(int) -> render::InstanceRegion? The texture rectangle one instance's row names with region_origin and region_size, in pixels, or nil when it names none.
instance_transform(int) -> Transform2d One instance's transform.
instances() -> [render::MultimeshInstance] Every instance as the multimesh asset spells it, so assets.save writes a scripted layout into a file.
set_instance_color(int, Color) The colour one instance draws in.
set_instance_count(int) How many instances the node holds. Those below the count keep where they were; new ones are plain, at the node.
set_instance_custom_data(int, Color) Four floats a material's shader reads for one instance, as a colour.
set_instance_transform(int, Transform2d) Place one instance. A shear is kept, as the instance's basis.
set_instances([render::MultimeshInstance]) Replace every instance with a list in the multimesh asset's shape.
set_visible_instance_count(int) How many instances draw, from the first; -1 draws them all.
visible_instance_count() -> int How many instances draw; -1 is all of them.

multimesh3d

Contents

3d · render · 9 properties · 3D

Godot's MultiMeshInstance3D: the multimesh asset in source, its mesh drawn once per instance in one call, each instance's color tinted over the node's. The node keeps its own copy of the instances, so a script's edits stay on it; children draw once.

In a scene, multimesh3d is the node key that applies it. A script reaches each property below as a field on node.multimesh3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.multimesh3d.get() and node.multimesh3d.set(table).

Properties

property type default description
cast_shadow bool true Whether the instances cast a shadow from the lights that cast
color color [1,1,1,1] Tint under every instance's own colour, as channel floats or #rrggbb / #rrggbbaa
light_layers flags [] The light layers this is lit on: a light3d lights it when their light_layers share one; empty is every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
material asset · material — The material every instance draws with; empty draws with the built-in one
receive_shadows bool true Whether shadows land on it; off lights it as if nothing stood between it and every light
render_layers flags [] The layers this is drawn on: a camera3d draws it when their render_layers share one; empty is every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
segmentation_id int 0 The id render.snap_aov("segmentation") colours this node by; nodes sharing one share a colour. Zero takes one of its own, from 1 up At least 0.
source asset · multimesh — The multimesh asset: the mesh and the instances it is drawn at
texture asset · texture — Image file, project-relative, or a texture asset; empty draws the colour alone

Asset types this component references: material, multimesh, texture.

Script functions

Methods of node.multimesh3d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From multimesh3d:

method what it does
instance_color(int) -> Color The colour one instance draws in.
instance_count() -> int How many instances the node holds.
instance_custom_data(int) -> Color One instance's four floats of custom data, as a colour.
instance_transform(int) -> Transform3d One instance's transform.
instances() -> [render::MultimeshInstance] Every instance as the multimesh asset spells it, so assets.save writes a scripted layout into a file.
set_instance_color(int, Color) The colour one instance draws in.
set_instance_count(int) How many instances the node holds. Those below the count keep where they were; new ones are plain, at the node.
set_instance_custom_data(int, Color) Four floats a material's shader reads for one instance, as a colour.
set_instance_transform(int, Transform3d) Place one instance. A shear is kept, as the instance's basis.
set_instances([render::MultimeshInstance]) Replace every instance with a list in the multimesh asset's shape.
set_visible_instance_count(int) How many instances draw, from the first; -1 draws them all.
visible_instance_count() -> int How many instances draw; -1 is all of them.

occluder2d

Contents

2d · render · 2 properties · 2D

The outline the node blocks 2D light with. With no mesh it follows the node's collider2d, or else its circle, capsule, rect or sprite shape.

In a scene, occluder2d is the node key that applies it. A script reaches each property below as a field on node.occluder2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.occluder2d.get() and node.occluder2d.set(table).

Properties

property type default description
closed bool true Whether the last point joins the first, making the outline a loop
mesh asset · mesh — Outline points in order, [x, y] in the node's space; empty derives the outline from the node's collider2d, then from its 2D shape

Asset types this component references: mesh.

Script functions

Methods of node.occluder2d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From render:

method what it does
outline() -> [Vec2] The outline this node blocks 2D light with, as its points in world space, with the first repeated at the end when the outline is closed. Empty on a node with no occluder2d.

particles2d

Contents

2d · render · 18 properties · 2D

A visual-only 2D emitter at the node: rate, lifetime, speed, direction, spread_degrees and gravity. The live particles are renderer state the simulation never sees.

In a scene, particles2d is the node key that applies it. A script reaches each property below as a field on node.particles2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.particles2d.get() and node.particles2d.set(table).

Properties

property type default description
angular_speed_degrees float 0 The fastest a particle spins, in degrees a second, counter-clockwise when positive; each takes a speed at random between zero and this
color color [1,1,1,1] Tint, as channel floats or #rrggbb / #rrggbbaa
color_end color [1,1,1,0] The tint a particle fades to by the end of its life
direction vec2 [0,1] Which way the particles leave; [0, 1] is straight up
emitting bool true Whether new particles are born; live ones finish either way
explosiveness float 0 How much of a one-shot burst is born at once; the rest is spread over the lifetime Range 0–1.
gravity vec2 [0,-3] Acceleration applied over a particle's life
lifetime float 1 Seconds a particle lives At least 0.05.
material asset · material — The material this draws with; empty takes an inherited material component, else the built-in one
one_shot bool false Emit one burst of rate times lifetime particles and stop; setting emitting false and true again fires another
rate float 20 Particles born per second At least 0.
rotation_degrees float 0 The most a particle is turned at birth, either way, in degrees; each takes a turn at random up to this At least 0.
sheet asset · sprite_sheet — A sprite_sheet whose frames each particle steps through over its life, first to last; its image is drawn when texture is empty
size float 0.1 A particle's edge length in world units At least 0.
size_end float -1 The edge length a particle grows or shrinks to by the end of its life, in world units; below zero keeps size
speed float 2 Initial speed in world units per second At least 0.
spread_degrees float 30 Half-angle of the emission cone in degrees At least 0.
texture asset · texture — An image, or a texture asset, each particle draws with; empty draws a flat square

Asset types this component references: material, sprite_sheet, texture.

particles3d

Contents

3d · render · 23 properties · 3D

A visual-only 3D emitter at the node, drawn as instances of one quad: rate, lifetime, speed, direction, spread_degrees and gravity in world space. The live particles are renderer state the simulation never sees; a sprite sheet does not reach them, because a 3D instance carries no texture rectangle.

In a scene, particles3d is the node key that applies it. A script reaches each property below as a field on node.particles3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.particles3d.get() and node.particles3d.set(table).

Properties

property type default description
angular_speed_degrees float 0 The fastest a particle spins in its own plane, in degrees a second; each takes a speed at random between zero and this
billboard bool true Turn each particle to face the camera; off lays every one in the node's own XY plane
cast_shadow bool false Whether the particles cast a shadow from the lights that cast
color color [1,1,1,1] Tint, as channel floats or #rrggbb / #rrggbbaa
color_end color [1,1,1,0] The tint a particle fades to by the end of its life
direction vec3 [0,1,0] Which way the particles leave, in world space; [0, 1, 0] is straight up
emitting bool true Whether new particles are born; live ones finish either way
explosiveness float 0 How much of a one-shot burst is born at once; the rest is spread over the lifetime Range 0–1.
gravity vec3 [0,-3,0] Acceleration applied over a particle's life, in world space
lifetime float 1 Seconds a particle lives At least 0.05.
light_layers flags [] The light layers this is lit on: a light3d lights it when their light_layers share one; empty is every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
material asset · material — The material every particle draws with; empty draws with the built-in one, which blends
one_shot bool false Emit one burst of rate times lifetime particles and stop; setting emitting false and true again fires another
rate float 20 Particles born per second At least 0.
receive_shadows bool true Whether shadows land on it; off lights it as if nothing stood between it and every light
render_layers flags [] The layers this is drawn on: a camera3d draws it when their render_layers share one; empty is every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
rotation_degrees float 0 The most a particle is turned in its own plane at birth, either way, in degrees At least 0.
segmentation_id int 0 The id render.snap_aov("segmentation") colours this node by; nodes sharing one share a colour. Zero takes one of its own, from 1 up At least 0.
size float 0.1 A particle's edge length in world units At least 0.
size_end float -1 The edge length a particle grows or shrinks to by the end of its life, in world units; below zero keeps size
speed float 2 Initial speed in world units per second At least 0.
spread_degrees float 30 Half-angle of the emission cone; 180 scatters every way Range 0–180.
texture asset · texture — An image, or a texture asset, each particle draws with; empty draws a flat square

Asset types this component references: material, texture.

polygon

Contents

2d · render · animation · 6 properties · 2D

A filled, textured 2D polygon from the mesh asset's points and triangles. With skin weights, the rig skeleton names deforms it.

In a scene, polygon is the node key that applies it. A script reaches each property below as a field on node.polygon: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.polygon.get() and node.polygon.set(table).

Properties

property type default description
color color [1,1,1,1] Tint, as channel floats or #rrggbb / #rrggbbaa
material asset · material — The material this draws with; empty takes an inherited material component, else the built-in one
mesh asset · mesh — Vertices, triangulation, UVs and skin weights; positions are [x, y] in the node's space
pixels_per_unit float 100 Texture pixels per world unit, for the default UV mapping At least 0.01.
skeleton node — The rig root; empty means this node
texture asset · texture — Image file, project-relative, or a texture asset; empty draws the tint alone

Asset types this component references: material, mesh, texture.

ragdoll

Contents

physics · 2 properties · Physics

Drives a rig's bones from bodies, one body per bone and named after it, which the editor's Create Physical Skeleton builds. influence is how much of the simulated pose the bones take, 0 to 1.

In a scene, ragdoll is the node key that applies it. A script reaches each property below as a field on node.ragdoll: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.ragdoll.get() and node.ragdoll.set(table).

Properties

property type default description
bodies node — The node holding the bodies, one per bone, named after it
influence float 1 How much of the simulated pose the bones take Range 0–1.

reflection_probe

Contents

3d · render · 9 properties · 3D

A box the room around it was captured inside. A reflective surface within it mirrors that capture, aimed at the box, instead of the distant sky.

In a scene, reflection_probe is the node key that applies it. A script reaches each property below as a field on node.reflection_probe: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.reflection_probe.get() and node.reflection_probe.set(table).

Properties

property type default description
capture_far float 0 The farthest distance a capture draws, in world units; zero takes the camera's At least 0.
capture_layers flags [] The layers a capture draws: the nodes whose render_layers share one. Leave moving nodes off it and let ssr reflect them; empty is every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
capture_near float 0 The nearest distance a capture draws, in world units; with capture_far both above zero, else the camera's own planes At least 0.
falloff float 0.5 How wide the soft edge at the box's face is; a surface crossing it fades back to the sky At least 0.
image string — Baked equirectangular image, project-relative. Empty captures the scene from the node's own position
image_rotation_degrees float 0 Turn of the captured map about y, in degrees
intensity float 1 Brightness of what the probe reflects At least 0.
size vec3 [10,10,10] The box this probe speaks for, in world units, centred on the node and turned with it. A node with a shader material still reads the box unturned At least 0.
update_mode enum once When a probe with no image captures the scene: once when placed or moved, or every frame. One capture draws the scene six times, at environment.probe_capture_size_pixels square One of once, always.

rope_joint2d

Contents

2d · physics · 1 property · 2D

How long a joint2d of kind rope may stretch.

In a scene, rope_joint2d is the node key that applies it. A script reaches each property below as a field on node.rope_joint2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.rope_joint2d.get() and node.rope_joint2d.set(table).

Properties

property type default description
max_length float 0 The rope's greatest length At least 0.

rope_joint3d

Contents

3d · physics · 1 property · 3D

How long a joint3d of kind rope may stretch.

In a scene, rope_joint3d is the node key that applies it. A script reaches each property below as a field on node.rope_joint3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.rope_joint3d.get() and node.rope_joint3d.set(table).

Properties

property type default description
max_length float 0 The rope's greatest length At least 0.

screen_notifier2d

Contents

2d · render · 2 properties · 2D

A box that announces screen_entered as it comes on screen and screen_exited as it leaves; offset and size place it around the node. A hidden node is off screen.

In a scene, screen_notifier2d is the node key that applies it. A script reaches each property below as a field on node.screen_notifier2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.screen_notifier2d.get() and node.screen_notifier2d.set(table).

Properties

property type default description
offset vec2 [-0.5,-0.5] The box's lower corner from the node, in the node's own units: scaled and turned with it
size vec2 [1,1] The box's width and height, in the node's own units: scaled and turned with it

Script functions

Methods of node.screen_notifier2d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From render:

method what it does
is_on_screen() -> bool Whether any of the notifier's box was on screen at the end of the last frame.

shape2d

Contents

2d · render · 4 properties · 2D

A 2D primitive at the node, tinted by color and drawn with texture: shape is a circle, rectangle, capsule, ellipse, star or ngon, and the dimensions that kind reads. A stroked line is line2d.

In a scene, shape2d is the node key that applies it. A script reaches each property below as a field on node.shape2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.shape2d.get() and node.shape2d.set(table).

Properties

property type default description
color color [0.8,0.8,0.8,1] Tint, as channel floats or #rrggbb / #rrggbbaa
material asset · material — The material this draws with; empty draws with the built-in one
shape variant {"corner_radius":0,"kind":"rectangle","segments":32,"size":[1,1]} The shape drawn, and its dimensions
texture asset · texture — An image, or a texture asset, the shape draws with over its own UVs

Asset types this component references: material, texture.

shape3d

Contents

3d · render · 9 properties · 3D

A 3D primitive at the node, tinted by color and drawn with texture: shape is a sphere, box, capsule, cylinder, cone, plane, torus, pyramid, prism or tube, and the dimensions that kind reads.

In a scene, shape3d is the node key that applies it. A script reaches each property below as a field on node.shape3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.shape3d.get() and node.shape3d.set(table).

Properties

property type default description
cast_shadow bool true Whether this casts a shadow from the lights that cast
color color [0.8,0.8,0.8,1] Tint, as channel floats or #rrggbb / #rrggbbaa
light_layers flags [] The light layers this is lit on: a light3d lights it when their light_layers share one; empty is every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
material asset · material — The material this draws with; empty draws with the built-in one
receive_shadows bool true Whether shadows land on it; off lights it as if nothing stood between it and every light
render_layers flags [] The layers this is drawn on: a camera3d draws it when their render_layers share one; empty is every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
segmentation_id int 0 The id render.snap_aov("segmentation") colours this node by; nodes sharing one share a colour. Zero takes one of its own, from 1 up At least 0.
shape variant {"corner_radius":0,"kind":"box","segments":32,"size":[1,1,1]} The primitive drawn, and its dimensions
texture asset · texture — Image file, project-relative, or a texture asset, drawn over the shape's own UVs; empty draws the colour alone

Asset types this component references: material, texture.

soft_circle2d

Contents

2d · physics · 2 properties · 2D

The size of a softbody2d laid out as a circle: a disk of particles inside a rim.

In a scene, soft_circle2d is the node key that applies it. A script reaches each property below as a field on node.soft_circle2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_circle2d.get() and node.soft_circle2d.set(table).

Properties

property type default description
particle_count int 16 How many particles the rim of a circle is made of At least 2.
radius float 0.5 Radius At least 0.001.

soft_cloth_tube3d

Contents

3d · physics · 4 properties · 3D

The shape of a softbody3d laid out as a cloth_tube: a sleeve of cloth wrapped around a segment.

In a scene, soft_cloth_tube3d is the node key that applies it. A script reaches each property below as a field on node.soft_cloth_tube3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_cloth_tube3d.get() and node.soft_cloth_tube3d.set(table).

Properties

property type default description
axis vec3 [0,1,0] The segment a cloth_tube is wrapped around, relative to the node
cells vec3 [4,4,4] Particles around the tube, then cells along it; the third is not read
end_radius float 0 A cloth_tube's radius at its end; 0 takes radius At least 0.
radius float 0.5 Radius at the tube's start At least 0.001.

soft_collision2d

Contents

2d · physics · 3 properties · 2D

A mesh the node's softbody2d meets the world through beside its own surface, deformed with the body: its triangles in 3D, the outline of its triangles in 2D.

In a scene, soft_collision2d is the node key that applies it. A script reaches each property below as a field on node.soft_collision2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_collision2d.get() and node.soft_collision2d.set(table).

Properties

property type default description
collision_binding variant {"distance":0.01,"kind":"nearest"} How the mesh follows the body: each vertex on the nearest particle, vertex i on particle i, or riding the cell that holds it, so a coarse cage of cells can carry a fine mesh
collision_mesh asset · mesh — The mesh, in the node's space
collision_self_contacts bool false Let the mesh collide with itself

Asset types this component references: mesh.

soft_collision3d

Contents

3d · physics · 3 properties · 3D

A mesh the node's softbody3d meets the world through beside its own surface, deformed with the body: its triangles in 3D, the outline of its triangles in 2D.

In a scene, soft_collision3d is the node key that applies it. A script reaches each property below as a field on node.soft_collision3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_collision3d.get() and node.soft_collision3d.set(table).

Properties

property type default description
collision_binding variant {"distance":0.01,"kind":"nearest"} How the mesh follows the body: each vertex on the nearest particle, vertex i on particle i, or riding the cell that holds it, so a coarse cage of cells can carry a fine mesh
collision_mesh asset · mesh — The mesh, in the node's space
collision_self_contacts bool false Let the mesh collide with itself

Asset types this component references: mesh.

soft_custom2d

Contents

2d · physics · 5 properties · 2D

The particles and elements of a custom softbody2d, as the author lists them.

In a scene, soft_custom2d is the node key that applies it. A script reaches each property below as a field on node.soft_custom2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_custom2d.get() and node.soft_custom2d.set(table).

Properties

property type default description
bend_edge_indices list [] A custom body's bending edges, each a pair of particle indices
cell_indices list [] A custom body's triangles, three particle indices each, counter-clockwise
edge_indices list [] A custom body's structural edges, each a pair of particle indices; empty takes the cells' edges
points list [] The particles of a custom body, relative to the node
surface_indices list [] A custom body's outward boundary segments, each a pair of particle indices: what holds its area and what it collides through; empty takes the cells' boundary

soft_custom3d

Contents

3d · physics · 7 properties · 3D

The particles and elements of a custom softbody3d, as the author lists them.

In a scene, soft_custom3d is the node key that applies it. A script reaches each property below as a field on node.soft_custom3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_custom3d.get() and node.soft_custom3d.set(table).

Properties

property type default description
bend_edge_indices list [] A custom body's bending edges, each a pair of particle indices
cell_indices list [] A custom body's tetrahedra, four particle indices each, positively oriented
dihedral_indices list [] A custom body's bending hinges between two triangles: the shared edge's two particles, then the two opposite ones
edge_indices list [] A custom body's structural edges, each a pair of particle indices; empty takes the cells' edges
points list [] A custom body's particles, relative to the node
surface_indices list [] A custom body's outward triangles, three particle indices each: what holds its volume and what it collides through; empty takes the cells' boundary
wire_indices list [] A custom body's segments it collides through when it has no surface, as a rope does, each a pair of particle indices

soft_grid2d

Contents

2d · physics · 2 properties · 2D

The size and the cells of a softbody2d laid out as a grid: a sheet of particles.

In a scene, soft_grid2d is the node key that applies it. A script reaches each property below as a field on node.soft_grid2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_grid2d.get() and node.soft_grid2d.set(table).

Properties

property type default description
cells vec2 [4,4] How many cells along each axis of a grid
size vec2 [1,1] Whole size of the sheet

soft_grid3d

Contents

3d · physics · 2 properties · 3D

The size and the cells of a softbody3d laid out as a box or a cloth: a block of particles, or a sheet of them.

In a scene, soft_grid3d is the node key that applies it. A script reaches each property below as a field on node.soft_grid3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_grid3d.get() and node.soft_grid3d.set(table).

Properties

property type default description
cells vec3 [4,4,4] How many cells along each axis, for box; a cloth reads the first two
size vec3 [1,1,1] Whole size along each axis: a box's block, or a cloth's sheet along x and z

soft_outline2d

Contents

2d · physics · 1 property · 2D

The corners of a softbody2d laid out as an outline: a ring of particles around an inside.

In a scene, soft_outline2d is the node key that applies it. A script reaches each property below as a field on node.soft_outline2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_outline2d.get() and node.soft_outline2d.set(table).

Properties

property type default description
points list [] The outline's corners counter-clockwise, relative to the node

soft_polyline2d

Contents

2d · physics · 1 property · 2D

Which segments of its mesh a softbody2d laid out as a polyline joins.

In a scene, soft_polyline2d is the node key that applies it. A script reaches each property below as a field on node.soft_polyline2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_polyline2d.get() and node.soft_polyline2d.set(table).

Properties

property type default description
edges enum chain Which segments a polyline body joins: its mesh's points in order, or the edges of its mesh's triangles One of chain, mesh.

soft_rope2d

Contents

2d · physics · 3 properties · 2D

Where a softbody2d laid out as a rope runs, and how many particles it is made of.

In a scene, soft_rope2d is the node key that applies it. A script reaches each property below as a field on node.soft_rope2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_rope2d.get() and node.soft_rope2d.set(table).

Properties

property type default description
a vec2 [0,0] Where a rope starts, relative to the node
b vec2 [0,-1] Where a rope ends, relative to the node
particle_count int 16 How many particles a rope is made of At least 2.

soft_rope3d

Contents

3d · physics · 3 properties · 3D

Where a softbody3d laid out as a rope runs, and how many particles it is made of.

In a scene, soft_rope3d is the node key that applies it. A script reaches each property below as a field on node.soft_rope3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_rope3d.get() and node.soft_rope3d.set(table).

Properties

property type default description
a vec3 [0,0,0] Where a rope starts, relative to the node
b vec3 [0,-1,0] Where a rope ends, relative to the node
particle_count int 16 How many particles a rope is made of At least 2.

soft_skin2d

Contents

2d · physics · 2 properties · 2D

The mesh a softbody2d with cells carries as its skin: a grid, a volumetric body or a custom one with cells, whose particles are not the mesh's own.

In a scene, soft_skin2d is the node key that applies it. A script reaches each property below as a field on node.soft_skin2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_skin2d.get() and node.soft_skin2d.set(table).

Properties

property type default description
skin bool true Keep the mesh asset's outline as what the cells carry and the node draws
skin_collision bool false Meet the world through the skin rather than the cells' boundary

soft_skin3d

Contents

3d · physics · 2 properties · 3D

The mesh a softbody3d with cells carries as its skin: a box, a volumetric body or a custom one with cells, whose particles are not the mesh's own.

In a scene, soft_skin3d is the node key that applies it. A script reaches each property below as a field on node.soft_skin3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_skin3d.get() and node.soft_skin3d.set(table).

Properties

property type default description
skin bool false Keep the mesh asset as the drawn surface and let the cells carry it, so a detail the cells cannot resolve survives
skin_collision bool false Meet the world through the skin rather than the cells' boundary

soft_sphere3d

Contents

3d · physics · 2 properties · 3D

The size of a softbody3d laid out as a sphere: a refined icosahedron of particles.

In a scene, soft_sphere3d is the node key that applies it. A script reaches each property below as a field on node.soft_sphere3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_sphere3d.get() and node.soft_sphere3d.set(table).

Properties

property type default description
radius float 0.5 Radius At least 0.001.
subdivisions int 2 How many times a sphere's icosahedron is refined; each level quadruples the triangles Range 0–6.

soft_volumetric2d

Contents

2d · physics · 2 properties · 2D

How a volumetric softbody2d fills its mesh's outline with triangles.

In a scene, soft_volumetric2d is the node key that applies it. A script reaches each property below as a field on node.soft_volumetric2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_volumetric2d.get() and node.soft_volumetric2d.set(table).

Properties

property type default description
cell_size float 0.25 How big one triangle is when a volumetric body fills an outline; smaller is finer, slower and stiffer to tear At least 0.001.
min_angle float 0.5235988 The smallest corner a volumetric body's triangles aim for; past 30 degrees the fill may not finish. Radians in the file Range 0–30.

soft_volumetric3d

Contents

3d · physics · 5 properties · 3D

How a volumetric softbody3d fills its mesh with tetrahedra.

In a scene, soft_volumetric3d is the node key that applies it. A script reaches each property below as a field on node.soft_volumetric3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.soft_volumetric3d.get() and node.soft_volumetric3d.set(table).

Properties

property type default description
boundary_subdivisions int 0 How many times a solid fill's cells along the mesh's surface are halved, finer than cell_size Range 0–4.
cell_size float 0.25 How big one tetrahedron is when a volumetric body fills a mesh; smaller is finer, slower and stiffer to tear At least 0.001.
fill enum solid What a volumetric body's cells cover: the mesh's whole inside, which needs a closed mesh, or a crust along its surface alone, which does not One of solid, surface.
smoothing int 0 How many passes pull a solid fill's blocky boundary towards the mesh; 0 leaves it on the cell lattice At least 0.
smoothing_guard float 0.15 How close to the mesh smoothing may pull the boundary, as a fraction of the cell size At least 0.

softbody2d

Contents

2d · physics · render · 35 properties · 2D

A deformable 2D body: particles linked by elastic constraints, laid out by kind and made of what the material rows say. A polygon on the same node is drawn from the solver's positions when the two agree on the vertex count, which the polygon, triangle_mesh and volumetric kinds give and a generator does not.

In a scene, softbody2d is the node key that applies it. A script reaches each property below as a field on node.softbody2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.softbody2d.get() and node.softbody2d.set(table).

Properties

property type default description
can_sleep bool true Let the body stop being simulated once it settles
collides bool true Meet the world at all; off, the body passes through everything and only its pins and ties hold it
collision_layer flags ["1"] The layers this collider is on One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
collision_mask flags [] The layers it collides with; empty means every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
color color [0.8,0.8,0.8,1] What the body is drawn in when its node has nothing of its own to deform, as a cloth or a rope has not
contact_force_threshold float 0 How hard a contact must be before on_contact_force is called At least 0.
contact_pairs flags ["dynamic_dynamic","dynamic_kinematic","dynamic_static"] Which pairs of body kinds this collider is tested against; a sensor watching kinematic platforms needs more than the default One of dynamic_dynamic, dynamic_kinematic, dynamic_static, kinematic_kinematic, kinematic_static, static_static.
dominance int 0 Which body wins a contact: a higher one is never pushed by a lower one Range -127–127.
edge_springs list [] Edges with a spring of their own, its frequency in hertz and its damping ratio, instead of the edge or bend rows', each named by the two particles it joins
enabled bool true Take part in the simulation; off leaves the body where it is with no contacts or constraints until it is on again, without a rebuild
gravity_scale float 1 How much gravity pulls on the particles
kind enum grid How the body's particles and elements are laid out One of grid, circle, polygon, outline, rope, volumetric, triangle_mesh, polyline, custom.
linear_damping float 0 Air friction on the particles At least 0.
mass float 1 What the whole body weighs, spread over its particles At least 0.
masses list [] Each particle's own mass, by index; empty spreads mass over them evenly
max_tears_per_step int 0 The most edges that may tear in one step, which paces a crack; 0 is no limit At least 0.
mesh asset · mesh — Points and triangles for a polygon, triangle_mesh, polyline or volumetric body, and the skin a body with cells carries unless its soft_skin2d says otherwise: the same asset a polygon draws
min_piece int 0 The smallest piece, in elements, a tear may split off; 0 lets rapier choose At least 0.
orientation enum auto How the surface meets what is inside it: solid encloses matter and pushes bodies out, shell holds bodies in, auto is solid when the surface is closed One of auto, solid, shell.
particle_radius float 0 How thick the particles are; 0 takes what the layout works out At least 0.
physics_material asset · physics_material — What the surface is made of: friction, bounce and how each combines; empty takes a physics_material at its defaults
pinned_particles list [] The particles held where they are, by index: a cloth hangs from these, and particle_count() says how many there are to choose from
regions list [] Parts of the body with a material of their own, each the particles it covers: soft_material for its edge spring and shape matching, empty keeping the body's; stiffness_scale on the cells wholly inside, tear_resistance on its edges and cells, and pinned to hold it still. Each is a soft_frame body joints may attach to
seams list [] Structural edges added between particles the layout left apart, each as long as its two particles stand at the start
self_collision bool false Let the body's own surface collide with itself, which stops a cloth passing through its own fold
sensor bool false Report contacts and push nothing: the body passes through what it touches
soft_material asset · soft_material — What the body is made of: its cells, springs, volume, yield and tearing; empty takes a soft_material at its defaults
solver enum constraints Which solver runs the elasticity: sequential constraints, or an implicit Euler step over the whole body One of constraints, fem.
solver_iterations int 3 Extra iterations inside each substep, for the same Range 0–64.
solver_layer flags ["1"] Layers for the solver alone: a pair can be detected but not resolved One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
solver_mask flags [] Which solver layers this one pushes against; empty means all of them One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
solver_substeps int 0 Extra solver substeps for this body and everything it touches Range 0–64.
tear_resistance list [] Edges that tear sooner or later than the rest, each named by the two particles it joins: below 1 is a perforation, above 1 a seam
tension_only enum none Which edges resist stretching only, so the body folds freely and never pushes itself open: none, all, or the tension_only_edges listed One of none, all, listed.
tension_only_edges list [] The edges that resist stretching only when tension_only is listed, each named by the two particles it joins

Asset types this component references: mesh, physics_material, soft_material.

Script functions

Methods of node.softbody2d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From physics2d:

method what it does
add_particle_force(int, Vec2) Push one particle with force each step until reset_forces.
add_softbody_force(Vec2) Push every free particle with force each step until reset_forces.
apply_particle_impulse(int, Vec2) Strike one particle.
apply_softbody_impulse(Vec2) Change every free particle's velocity by impulse at once, as a kick to the whole body.
apply_softbody_impulse_at_point(Vec2, Vec2, float) Strike the particles within radius of point, less the further they are; a radius of 0 strikes them all.
apply_softbody_radial_impulse(Vec2, float, float) Push the particles within radius away from center, as a blast does.
attach_particle(int, Node) Tie one particle to a node's rigid body where it is now: the body and the particle pull on each other.
cut_softbody([Vec2]) -> [physics2d::SoftTear] Cut the body along a blade at once, as crossing reads it; answers a record for each piece it changed, the one on_torn hears.
detach_particle(int) -> bool Untie one particle from every body it was attached to; answers whether it was attached.
has_pending_tears() -> bool Whether some edge or cell is marked to tear at the end of the next step.
is_softbody_sleeping() -> bool Whether the body has come to rest and stopped being simulated.
pin_particle(int) Hold one particle where it is, which is how a cloth hangs from a hook.
reset_plasticity() Undo every permanent set the body took: rest lengths, rest angles and rest shapes go back to how it was built, and it springs back from where it is.
reset_softbody_forces() Take back every force add_force and add_particle_force gave the body.
set_cell_tear_resistance(int, float) The same for one cell's tear strain.
set_edge_tear_resistance(int, float) How many times the material's threshold one edge takes to tear; 1 is the material's.
set_particle_damaged(int, bool) Mark one particle as damaged or mend it: a damaged particle tears as an outside one does, which seeds where a crack starts.
set_particle_position(int, Vec2) Put one particle at at with no change of velocity.
set_particle_target(int, Vec2) Move a held particle to at over the next step, with the velocity that takes, which is how a cloth is dragged.
set_particle_velocity(int, Vec2) Set one particle's velocity; a held one keeps moving at it.
softbody_area() -> float How much area the body and every piece torn off it enclose right now, against rest_area for how far it is squeezed.
softbody_attachments() -> [physics2d::SoftAttachment] Every particle tied to a rigid body.
softbody_boundary() -> [[int]] The body's surface as particle indices: segments in 2D, triangles in 3D.
softbody_cell(int) -> physics2d::SoftCell Everything one cell holds.
softbody_cells() -> [[int]] Every cell as its particle indices: triangles in 2D, tetrahedra in 3D.
softbody_contacts() -> physics2d::SoftContacts What the body's surface touched in the last step.
softbody_crossing([Vec2]) -> physics2d::SoftCrossing The edges and cells a blade meets, without cutting: the blade is a segment's two points in 2D, a triangle's three in 3D.
softbody_edge(int) -> physics2d::SoftEdge Everything one edge holds.
softbody_edges() -> [[int]] Every edge as the two particle indices it joins, in the order stress reports them.
softbody_effective_particle_radius() -> float How thick the particles are: what was asked for, or what the layout worked out.
softbody_particle(int) -> physics2d::SoftParticle Everything one particle holds.
softbody_particle_count() -> int How many particles the body has, every piece torn off it included: a generator decides, not the author.
softbody_rest_area() -> float How much they enclose at rest.
softbody_stress() -> [float] Each edge's load as a fraction of its tear threshold, smoothed over tear_smoothing: 0 slack, 1 tearing; the larger of its stretch over tear_strain and its force over tear_force, and 0 while neither is set.
softbody_total_mass() -> float What the whole body weighs, every piece included.
softbody_volume_pieces() -> [physics2d::SoftVolumePiece] Each closed piece of the surface whose volume is held; an open sheet has none.
softbody_world_center_of_mass() -> Vec2 The centre of mass of the body and its pieces, which is where it is when a deformable body has no one position.
tear_cell(int) Tear one cell at the end of the next step: a particle near its middle splits across its main stretch.
tear_edge(int) Tear one edge at the end of the next step.
tear_softbody([int], [int]) -> [physics2d::SoftTear] Tear the given edges and cells at once; answers a record for each piece it changed, the one on_torn hears.
unpin_particle(int) Let a held particle go; it keeps the velocity it had.
wake_up_softbody() Start simulating a resting body again.

softbody3d

Contents

3d · physics · render · 35 properties · 3D

A deformable 3D body: particles linked by elastic constraints, laid out by kind and made of what the material rows say. The node is drawn from the solver's positions.

In a scene, softbody3d is the node key that applies it. A script reaches each property below as a field on node.softbody3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.softbody3d.get() and node.softbody3d.set(table).

Properties

property type default description
can_sleep bool true Let the body stop being simulated once it settles
collides bool true Meet the world at all; off, the body passes through everything and only its pins and ties hold it
collision_layer flags ["1"] The layers this collider is on One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
collision_mask flags [] The layers it collides with; empty means every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
color color [0.8,0.8,0.8,1] What the body is drawn in when its node has nothing of its own to deform, as a cloth or a rope has not
contact_force_threshold float 0 How hard a contact must be before on_contact_force is called At least 0.
contact_pairs flags ["dynamic_dynamic","dynamic_kinematic","dynamic_static"] Which pairs of body kinds this collider is tested against; a sensor watching kinematic platforms needs more than the default One of dynamic_dynamic, dynamic_kinematic, dynamic_static, kinematic_kinematic, kinematic_static, static_static.
dominance int 0 Which body wins a contact: a higher one is never pushed by a lower one Range -127–127.
edge_springs list [] Edges with a spring of their own, its frequency in hertz and its damping ratio, instead of the edge or bend rows', each named by the two particles it joins
enabled bool true Take part in the simulation; off leaves the body where it is with no contacts or constraints until it is on again, without a rebuild
gravity_scale float 1 How much gravity pulls on the particles
kind enum box How the body's particles and elements are laid out One of box, sphere, cloth, cloth_tube, rope, volumetric, triangle_mesh, custom.
linear_damping float 0 Air friction on the particles At least 0.
mass float 1 What the whole body weighs, spread over its particles At least 0.
masses list [] Each particle's own mass, by index; empty spreads mass over them evenly
max_tears_per_step int 0 The most edges that may tear in one step, which paces a crack; 0 is no limit At least 0.
mesh asset · mesh — Geometry for a triangle_mesh or volumetric body, and the skin a body with cells carries when its soft_skin3d asks for one
min_piece int 0 The smallest piece, in elements, a tear may split off; 0 lets rapier choose At least 0.
orientation enum auto How the surface meets what is inside it: solid encloses matter and pushes bodies out, shell holds bodies in, auto is solid when the surface is closed One of auto, solid, shell.
particle_radius float 0 How thick the particles are; 0 takes what the layout works out At least 0.
physics_material asset · physics_material — What the surface is made of: friction, bounce and how each combines; empty takes a physics_material at its defaults
pinned_particles list [] The particles held where they are, by index: a cloth hangs from these, and particle_count() says how many there are to choose from
regions list [] Parts of the body with a material of their own, each the particles it covers: soft_material for its edge spring and shape matching, empty keeping the body's; stiffness_scale on the cells wholly inside, tear_resistance on its edges and cells, and pinned to hold it still. Each is a soft_frame body joints may attach to
seams list [] Structural edges added between particles the layout left apart, each as long as its two particles stand at the start
self_collision bool false Let the body's own surface collide with itself, which stops a cloth passing through its own fold
sensor bool false Report contacts and push nothing: the body passes through what it touches
soft_material asset · soft_material — What the body is made of: its cells, springs, volume, yield and tearing; empty takes a soft_material at its defaults
solver enum constraints Which solver runs the elasticity: sequential constraints, or an implicit Euler step over the whole body One of constraints, fem.
solver_iterations int 3 Extra iterations inside each substep, for the same Range 0–64.
solver_layer flags ["1"] Layers for the solver alone: a pair can be detected but not resolved One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
solver_mask flags [] Which solver layers this one pushes against; empty means all of them One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
solver_substeps int 0 Extra solver substeps for this body and everything it touches Range 0–64.
tear_resistance list [] Edges that tear sooner or later than the rest, each named by the two particles it joins: below 1 is a perforation, above 1 a seam
tension_only enum none Which edges resist stretching only, so the body folds freely and never pushes itself open: none, all, or the tension_only_edges listed One of none, all, listed.
tension_only_edges list [] The edges that resist stretching only when tension_only is listed, each named by the two particles it joins

Asset types this component references: mesh, physics_material, soft_material.

Script functions

Methods of node.softbody3d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From physics3d:

method what it does
add_particle_force(int, Vec3) Push one particle with force each step until reset_forces.
add_softbody_force(Vec3) Push every free particle with force each step until reset_forces.
apply_particle_impulse(int, Vec3) Strike one particle.
apply_softbody_impulse(Vec3) Change every free particle's velocity by impulse at once, as a kick to the whole body.
apply_softbody_impulse_at_point(Vec3, Vec3, float) Strike the particles within radius of point, less the further they are; a radius of 0 strikes them all.
apply_softbody_radial_impulse(Vec3, float, float) Push the particles within radius away from center, as a blast does.
attach_particle(int, Node) Tie one particle to a node's rigid body where it is now: the body and the particle pull on each other.
cut_softbody([Vec3]) -> [physics3d::SoftTear] Cut the body along a blade at once, as crossing reads it; answers a record for each piece it changed, the one on_torn hears.
detach_particle(int) -> bool Untie one particle from every body it was attached to; answers whether it was attached.
has_pending_tears() -> bool Whether some edge or cell is marked to tear at the end of the next step.
is_softbody_sleeping() -> bool Whether the body has come to rest and stopped being simulated.
pin_particle(int) Hold one particle where it is, which is how a cloth hangs from a hook.
reset_plasticity() Undo every permanent set the body took: rest lengths, rest angles and rest shapes go back to how it was built, and it springs back from where it is.
reset_softbody_forces() Take back every force add_force and add_particle_force gave the body.
set_cell_tear_resistance(int, float) The same for one cell's tear strain.
set_edge_tear_resistance(int, float) How many times the material's threshold one edge takes to tear; 1 is the material's.
set_particle_damaged(int, bool) Mark one particle as damaged or mend it: a damaged particle tears as an outside one does, which seeds where a crack starts.
set_particle_position(int, Vec3) Put one particle at at with no change of velocity.
set_particle_target(int, Vec3) Move a held particle to at over the next step, with the velocity that takes, which is how a cloth is dragged.
set_particle_velocity(int, Vec3) Set one particle's velocity; a held one keeps moving at it.
softbody_attachments() -> [physics3d::SoftAttachment] Every particle tied to a rigid body.
softbody_boundary() -> [[int]] The body's surface as particle indices: segments in 2D, triangles in 3D.
softbody_cell(int) -> physics3d::SoftCell Everything one cell holds.
softbody_cells() -> [[int]] Every cell as its particle indices: triangles in 2D, tetrahedra in 3D.
softbody_contacts() -> physics3d::SoftContacts What the body's surface touched in the last step.
softbody_crossing([Vec3]) -> physics3d::SoftCrossing The edges and cells a blade meets, without cutting: the blade is a segment's two points in 2D, a triangle's three in 3D.
softbody_dihedral(int) -> physics3d::SoftDihedral Everything one hinge holds.
softbody_dihedrals() -> [[int]] Every bending hinge between two surface triangles, as four particle indices: the shared edge, then the two opposite particles.
softbody_edge(int) -> physics3d::SoftEdge Everything one edge holds.
softbody_edges() -> [[int]] Every edge as the two particle indices it joins, in the order stress reports them.
softbody_effective_particle_radius() -> float How thick the particles are: what was asked for, or what the layout worked out.
softbody_particle(int) -> physics3d::SoftParticle Everything one particle holds.
softbody_particle_count() -> int How many particles the body has, every piece torn off it included: a generator decides, not the author.
softbody_rest_volume() -> float How much they enclose at rest.
softbody_stress() -> [float] Each edge's load as a fraction of its tear threshold, smoothed over tear_smoothing: 0 slack, 1 tearing; the larger of its stretch over tear_strain and its force over tear_force, and 0 while neither is set.
softbody_total_mass() -> float What the whole body weighs, every piece included.
softbody_volume() -> float How much space the body and every piece torn off it enclose right now, against rest_volume for how far it is squeezed.
softbody_volume_pieces() -> [physics3d::SoftVolumePiece] Each closed piece of the surface whose volume is held; an open sheet has none.
softbody_world_center_of_mass() -> Vec3 The centre of mass of the body and its pieces, which is where it is when a deformable body has no one position.
tear_cell(int) Tear one cell at the end of the next step: a particle near its middle splits across its main stretch.
tear_edge(int) Tear one edge at the end of the next step.
tear_softbody([int], [int]) -> [physics3d::SoftTear] Tear the given edges and cells at once; answers a record for each piece it changed, the one on_torn hears.
unpin_particle(int) Let a held particle go; it keeps the velocity it had.
wake_up_softbody() Start simulating a resting body again.

sound

Contents

audio · 23 properties · Audio

A sound on the node: file, volume_linear, pitch_scale and loop, with its stems mixed in and its queue played after it. autoplay starts it on load, node.sound.play() triggers it, seek and skip move it, positional plays it from the node for the listener, and the node announces sound_finished when it plays out. What it passes through on the way out is its bus's, declared in [audio.buses].

In a scene, sound is the node key that applies it. A script reaches each property below as a field on node.sound: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.sound.get() and node.sound.set(table).

Properties

property type default description
attenuation enum inverse How a positional sound falls off past min_distance: inverse halves its gain at every doubling of distance, inverse_square quarters it One of inverse, inverse_square.
autoplay bool false Start playing when the node enters the scene
bus string — Audio bus this plays through; empty is master
crossfade_time float 0 Seconds a playing sound fades out over when file changes, while the new file, if autoplay starts it, fades in; 0 cuts At least 0.
delay float 0 Seconds of silence before the sound starts. Read when it starts At least 0.
doppler_level float 0 How much the closing speed bends the pitch; 0 is off, 1 physical At least 0.
end_time float 0 Seconds into file each play stops at, and a loop turns back at; 0 plays to the end. Read when it starts At least 0.
fade_in_time float 0 Seconds the sound rises from silence over when it starts At least 0.
fade_out_time float 0 Seconds the sound falls to silence over: the last ones before it plays out, and the first after sound.stop At least 0.
file string — Audio file, project-relative; required to play
loop bool false Restart the sound when it ends; with a queue, each file repeats until node.sound.skip() moves on
loop_offset float -1 Seconds into file every repeat after the first starts from; below 0 takes the file's own loop_offset import setting. Read when it starts At least -1.
max_distance float 50 Silent beyond this distance from the listener At least 0.001.
min_distance float 1 Full volume within this distance of the listener At least 0.001.
pan float 0 Balance of a sound that is not positional: -1 left, 0 both channels at full, 1 right. A positional sound is panned by where it is Range -1–1.
paused bool false Hold the sound where it is; playback_time and the count to sound_finished hold with it
pitch_scale float 1 Playback speed multiplier At least 0.01.
playback_time float 0 Seconds into the file playing now, counted on the fixed step so a run with no output device reads the same; 0 when nothing plays Read-only: engine output the inspector shows but never writes.
positional bool false Place the sound where the node is, heard from the listener
queue list [] Files played after file, in order and without a gap; node.sound.skip() moves to the next. Read when it starts
start_time float 0 Seconds into file each play starts from. Read when it starts At least 0.
stems list [] Files mixed with file for its whole length, each at its own import level. Read when it starts
volume_linear float 1 Linear gain; 1 is the file's own level At least 0.

Script functions

Methods of node.sound, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From audio:

method what it does
play() -> int Start the node's own sound from the top, replacing what it had going, and return the new handle.
seek(float) Jump the node's sound to seconds into the file it is playing; playback_time reads it back. A node with nothing playing is left alone.
skip() Move the node's sound on to the next file in its queue. Past the last one it has played out, and the node announces sound_finished.
stop() Silence what the node's sound started, over its fade_out_time; a node carrying none is left alone.

spring_joint2d

Contents

2d · physics · 1 property · 2D

The length a joint2d of kind spring pulls back to.

In a scene, spring_joint2d is the node key that applies it. A script reaches each property below as a field on node.spring_joint2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.spring_joint2d.get() and node.spring_joint2d.set(table).

Properties

property type default description
rest_length float 0 The length a spring pulls back to At least 0.

spring_joint3d

Contents

3d · physics · 1 property · 3D

The length a joint3d of kind spring pulls back to.

In a scene, spring_joint3d is the node key that applies it. A script reaches each property below as a field on node.spring_joint3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.spring_joint3d.get() and node.spring_joint3d.set(table).

Properties

property type default description
rest_length float 0 The length a spring pulls back to At least 0.

sprite

Contents

2d · render · 14 properties · 2D

A textured 2D quad at the node, sized by pixels_per_unit. A sprite_sheet in sheet cuts it into frames frame picks.

In a scene, sprite is the node key that applies it. A script reaches each property below as a field on node.sprite: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.sprite.get() and node.sprite.set(table).

Properties

property type default description
centered bool true Centre the image on the node; off puts its top-left corner there
color color [1,1,1,1] Tint, as channel floats or #rrggbb / #rrggbbaa
flip_x bool false Mirror horizontally
flip_y bool false Mirror vertically
frame int 0 Current sheet cell, counted left-to-right then top-to-bottom At least 0.
material asset · material — The material this draws with; empty draws with the built-in one
nine_slice_margins_pixels vec4 [0,0,0,0] Left, right, top and bottom margins in texture pixels: the corners keep their size at pixels_per_unit while the edges and the middle stretch to size. All zero takes the margins from the sheet's first slice with a center, drawing that slice's part of the frame, and draws one plain quad without one
offset vec2 [0,0] Where the image sits against the node, in texture pixels with y down; turns and scales with the node
pixels_per_unit float 0 Texture pixels per world unit; 0 takes the texture's own pixels_per_unit import setting, which is 100 unless it says At least 0.
region_origin vec2 [0,0] Top-left corner of the atlas cell to draw, in texture pixels; used with region_size
region_size vec2 [0,0] Size of the atlas cell to draw, in texture pixels; [0, 0] draws the whole image and sizes the quad from the cell
sheet asset · sprite_sheet — A sprite_sheet whose frames frame indexes; its texture is drawn unless texture names another, and it wins over the region
size vec2 [0,0] Whole size in world units; [0, 0] sizes from the texture
texture asset · texture — Image file, project-relative, or a texture asset that reads it with settings of its own. Empty draws nothing

Asset types this component references: material, sprite_sheet, texture.

state_machine

Contents

animation · 4 properties · Animation

Runs the state_machine asset in machine over the player node's clips. auto transitions fire when their conditions come on; state_machine.travel moves to a state.

In a scene, state_machine is the node key that applies it. A script reaches each property below as a field on node.state_machine: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.state_machine.get() and node.state_machine.set(table).

Properties

property type default description
check_node node — The node whose script answers the transitions' check methods; empty means this node
enabled bool true Whether the machine is running
machine asset · state_machine — The state machine to run
player node — The animation player it drives; empty means this node

Asset types this component references: state_machine.

Script functions

Methods of node.state_machine, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From animation:

method what it does
current_state() -> str? The state the machine is in, or nil before it has entered one.
jump(string) Cut the state machine to the named state on the next step, with no fade.
set_condition(string, bool) Turn on or off a condition that auto transitions wait on.
travel(string) Head for the named state through the cheapest chain of transitions, each costing its priority and fading as it says; a state no transition reaches is cut to directly.

states

Contents

interaction · 1 property · Other

Named looks for the node. Every key beside current is a state holding per-component property tables; node.states.set_state("hover") patches one over the node at once.

In a scene, states is the node key that applies it. A script reaches each property below as a field on node.states: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.states.get() and node.states.set(table).

Properties

property type default description
current string — The state this node is in; empty is the pose the scene gave it

Script functions

Methods of node.states, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From node:

method what it does
set_state(string) Put the node in one of its states: the state's table is patched over the components it names, and on_state_changed(from, to) follows. A node already in that state is left alone.

text2d

Contents

2d · render · 19 properties · 2D

A block of text drawn in the 2D pass, pixels_per_unit font pixels per world unit.

In a scene, text2d is the node key that applies it. A script reaches each property below as a field on node.text2d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.text2d.get() and node.text2d.set(table).

Properties

property type default description
color color [1,1,1,1] Tint, as channel floats or #rrggbb / #rrggbbaa
font asset · font — The face it draws in, and how: a face file such as fonts/Inter.ttf, or a font asset. Empty takes the theme's default font
font_size float 32 Height in font pixels, before pixels_per_unit sizes it in the world At least 1.
font_style enum normal Upright, the family's italic face, or the upright face slanted; a family with no italic is slanted either way One of normal, italic, oblique.
font_weight int 400 Stroke weight, 400 regular and 700 bold Range 100–900.
line_break enum word_smart Where a wrapped line may break: between words with a too-long word cut anywhere, between words only, or anywhere One of word_smart, word, arbitrary.
markup bool false Read the text as markup: bold, italic, colour, alignment, wave and inline images
material asset · material — The material every layer draws with, reading the glyph atlas as its texture; empty takes an inherited material component, else the built-in one. Its [surface] says whether the glyphs are cut out (alpha = "mask"), which sides of a text3d draw and whether the scene hides it
max_height float 0 Font pixels the lines stop at; zero has no limit At least 0.
max_lines int 0 The most lines a block keeps; zero keeps every line At least 0.
max_width float 0 Font pixels the lines wrap at; zero runs the text on one line At least 0.
pixels_per_unit float 100 Font pixels to one world unit, sizing the block the way a sprite is sized At least 0.01.
tab_size int 8 Spaces between tab stops Range 1–64.
text string — The text drawn; text_key wins over it
text_align enum center Where the block sits across the node's origin, and its lines within it: start and end follow the text's direction, left and right do not, justify stretches every full line One of start, center, end, left, right, justify.
text_key string — A key in the project's strings, re-read every frame so a language change shows at once
text_style asset · text_style — How it is dressed past its font: line height and spacing, the lines drawn with the glyphs, an outline and a shadow. Empty draws it plain
truncate bool false End a block cut short with an ellipsis; needs max_width, and cuts at max_lines or max_height when either is set, else at one line
truncate_at enum end Which part of a cut line the ellipsis stands in for One of end, start, middle.

Asset types this component references: font, material, text_style.

text3d

Contents

3d · render · 25 properties · 3D

A block of text drawn in the 3D pass on a quad, pixels_per_unit font pixels per world unit; billboard turns it to the camera.

In a scene, text3d is the node key that applies it. A script reaches each property below as a field on node.text3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.text3d.get() and node.text3d.set(table).

Properties

property type default description
billboard bool true Turn to face the camera every frame; off leaves it in the node's own plane
cast_shadow bool true Whether it casts a shadow from the lights that cast. Through a material whose surface cuts the glyphs out, the shadow keeps their shapes; otherwise each glyph shadows as its whole quad
color color [1,1,1,1] Tint, as channel floats or #rrggbb / #rrggbbaa
font asset · font — The face it draws in, and how: a face file such as fonts/Inter.ttf, or a font asset. Empty takes the theme's default font
font_size float 32 Height in font pixels, before pixels_per_unit sizes it in the world At least 1.
font_style enum normal Upright, the family's italic face, or the upright face slanted; a family with no italic is slanted either way One of normal, italic, oblique.
font_weight int 400 Stroke weight, 400 regular and 700 bold Range 100–900.
light_layers flags [] The light layers this is lit on: a light3d lights it when their light_layers share one; empty is every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
line_break enum word_smart Where a wrapped line may break: between words with a too-long word cut anywhere, between words only, or anywhere One of word_smart, word, arbitrary.
markup bool false Read the text as markup: bold, italic, colour, alignment, wave and inline images
material asset · material — The material every layer draws with, reading the glyph atlas as its texture; empty takes an inherited material component, else the built-in one. Its [surface] says whether the glyphs are cut out (alpha = "mask"), which sides of a text3d draw and whether the scene hides it
max_height float 0 Font pixels the lines stop at; zero has no limit At least 0.
max_lines int 0 The most lines a block keeps; zero keeps every line At least 0.
max_width float 0 Font pixels the lines wrap at; zero runs the text on one line At least 0.
pixels_per_unit float 100 Font pixels to one world unit, sizing the block the way a sprite is sized At least 0.01.
receive_shadows bool true Whether shadows land on it; off lights it as if nothing stood between it and every light
render_layers flags [] The layers this is drawn on: a camera3d draws it when their render_layers share one; empty is every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
segmentation_id int 0 The id render.snap_aov("segmentation") colours this node by; nodes sharing one share a colour. Zero takes one of its own, from 1 up At least 0.
tab_size int 8 Spaces between tab stops Range 1–64.
text string — The text drawn; text_key wins over it
text_align enum center Where the block sits across the node's origin, and its lines within it: start and end follow the text's direction, left and right do not, justify stretches every full line One of start, center, end, left, right, justify.
text_key string — A key in the project's strings, re-read every frame so a language change shows at once
text_style asset · text_style — How it is dressed past its font: line height and spacing, the lines drawn with the glyphs, an outline and a shadow. Empty draws it plain
truncate bool false End a block cut short with an ellipsis; needs max_width, and cuts at max_lines or max_height when either is set, else at one line
truncate_at enum end Which part of a cut line the ellipsis stands in for One of end, start, middle.

Asset types this component references: font, material, text_style.

tile_collision

Contents

2d · physics · 20 properties · 2D

Collision for the node's tilemap cells: every tile the tileset marks solid, one shape per behaviour, with the material keys a collider2d takes. mass weighs the whole map, shared across its colliders by area; one_way makes every cell a platform, holding bodies on one_way_axis.

In a scene, tile_collision is the node key that applies it. A script reaches each property below as a field on node.tile_collision: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.tile_collision.get() and node.tile_collision.set(table).

Properties

property type default description
center_of_mass vec2 [0,0] Where the whole map's mass sits, in the node's own space; read with inertia, and both 0 keep the shapes' own
collision_layer flags ["1"] The layers this collider is on One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
collision_margin float 0 A margin the solver treats as already touching; stops thin shapes tunnelling and jittering At least 0.
collision_mask flags [] The layers it collides with; empty means every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
collision_test enum both Whether a pair is tested when both colliders' layers accept the other, or when either does; two colliders that differ use both One of both, either.
contact_force_threshold float 0 How hard a contact must be before on_contact_force is called At least 0.
contact_pairs flags ["dynamic_dynamic","dynamic_kinematic","dynamic_static"] Which pairs of body kinds this collider is tested against; a sensor watching kinematic platforms needs more than the default One of dynamic_dynamic, dynamic_kinematic, dynamic_static, kinematic_kinematic, kinematic_static, static_static.
density float 1 Mass per volume, so the shape's size sets its mass; 0 makes a collider that adds no mass to its body At least 0.
enabled bool true Collide at all; a disabled collider keeps its shape and costs nothing
inertia float 0 The whole map's resistance to spin about center_of_mass, shared over its colliders by area; 0 takes the shapes' own about that centre At least 0.
mass float 0 Mass in kilograms, overriding what density works out to; 0 keeps the density At least 0.
one_way bool false A platform bodies land on from the side one_way_axis names and pass through from the other
one_way_angle float 0.1 How far a contact's normal may lean from one_way_axis and still hold the body; radians in the file Range 0–180.
one_way_axis vec2 [0,1] The side a one-way cell holds bodies on, in the map's axes: [0, 1] lands them from above and lets them up through from below. A flipped or turned shaped tile turns it with its polygon
physics_material asset · physics_material — What the surface is made of: friction, bounce and how each combines; empty takes a physics_material at its defaults
sensor bool false Detects overlaps without colliding: bodies pass through and are reported
solver_layer flags ["1"] Layers for the solver alone: a pair can be detected but not resolved One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
solver_mask flags [] Which solver layers this one pushes against; empty means all of them One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
solver_test enum both The same choice for the solver layers One of both, either.
surface_velocity vec2 [0,0] How fast every cell's surface slides along itself, in the map's axes: a conveyor belt carries what rests on it

Asset types this component references: physics_material.

tile_shapes

Contents

2d · physics · 2 properties · 2D

How the node's tile_collision builds the tiles whose collision is polygons, the ones a tileset gives collision = [[[x, y], ...]]: what each polygon becomes and how far it is rounded. Whole cells read none of it.

In a scene, tile_shapes is the node key that applies it. A script reaches each property below as a field on node.tile_shapes: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.tile_shapes.get() and node.tile_shapes.set(table).

Properties

property type default description
edge_radius float 0 Rounds each shaped tile's polygon by this radius At least 0.
fit enum convex_hull What a shaped tile's polygon becomes: its hull, its box, its oriented box, or convex pieces that keep a concave outline One of convex_hull, aabb, obb, convex_decomposition.

tilemap

Contents

2d · render · 9 properties · 2D

A grid of tiles from one tileset asset, centred on the node. cells holds rows of tile ids, or names the .cells file holding them; pixels_per_unit is tile pixels per world unit.

In a scene, tilemap is the node key that applies it. A script reaches each property below as a field on node.tilemap: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.tilemap.get() and node.tilemap.set(table).

Properties

property type default description
cells variant {"kind":"inline","rows":[]} The tile ids: rows of them in the scene, or a .cells file holding them, for a level too big to read in a scene
color color [1,1,1,1] Tint over every tile, as channel floats or #rrggbb / #rrggbbaa
flags list [] How each cell is turned, as rows of numbers beside the cells: 1 mirrors it left to right, 2 top to bottom, 4 across its diagonal
material asset · material — The material the whole map draws with; empty draws with the built-in one
origin vec2 [0,0] The column and row of the first cell: a map grows in any direction by moving this, and cell 0,0 always has its top-left corner on the node
pixels_per_unit float 100 Tile-texture pixels per world unit At least 0.01.
seed int 0 Which way the variation falls where a rule offers alternates; the same seed lays a map out the same way every time At least 0.
terrain list [] What was painted, as rows of terrain values, -1 where nothing was, when the map autotiles: the cells are resolved from this through the tileset's rules
tileset asset · tileset — The tileset naming the texture and tile grid

Asset types this component references: material, tileset.

Script functions

Methods of node.tilemap, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From render:

method what it does
cell(int, int) -> int The tile at a column and row, or -1 for an empty cell or one past the edge.
cell_terrain(int, int) -> int The terrain value painted at a column and row, or -1 where nothing was painted.
set_cell(int, int, int) Put one tile at a column and row; a tile below zero clears the cell, and a cell outside the map grows it in that direction. The mesh rebuilds on the next frame.
set_cell_terrain(int, int, int) Paint a terrain value at a column and row and let the tileset's rules pick the tiles, for that cell and the ring around it; below zero clears it.

timer

Contents

interaction · 5 properties · Other

Counts wait_time seconds down and emits timeout from the node, which bindings hear as emitted:timeout. running or autostart starts it; one_shot stops after one round.

In a scene, timer is the node key that applies it. A script reaches each property below as a field on node.timer: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.timer.get() and node.timer.set(table).

Properties

property type default description
autostart bool false Start counting as soon as the node is in the scene
one_shot bool false Stop after one timeout; off, count the next one at once
running bool false Whether it is counting; set true to start it from wait_time, false to stop it
time_left float 0 Seconds until the next timeout Read-only: engine output the inspector shows but never writes. At least 0.
wait_time float 1 Seconds from starting to timeout At least 0.001.

touch_button

Contents

2d · ui · 10 properties · 2D

An on-screen button that presses an action while a finger is on it. anchor, x and y place it inside the screen's safe area, as they place a widget.

In a scene, touch_button is the node key that applies it. A script reaches each property below as a field on node.touch_button: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.touch_button.get() and node.touch_button.set(table).

Properties

property type default description
action string — The action a finger on this button presses, as [input.actions] names it; the action needs no touch binding
anchor enum bottom_right Screen corner, edge or middle the button sits against, inside the safe area One of top_left, center_top, top_right, center_left, center, center_right, bottom_left, center_bottom, bottom_right.
color color [1,1,1,0.25] Fill while nothing is on it, as channel floats or #rrggbb / #rrggbbaa
height float 120 Touch area height in design pixels At least 0.
kind enum circle The touch area's outline; a circle uses the larger half of the box One of rectangle, circle.
pressed_color color [1,1,1,0.5] Fill while a finger is on it
visibility enum touchscreen touchscreen hides it and stops it taking fingers where the platform has no touch screen One of always, touchscreen.
width float 120 Touch area width in design pixels At least 0.
x float 50 Inward from the anchored side to the button's own, in design pixels; from the middle when the anchor centres it
y float 50 Inward from the anchored top or bottom to the button's own, in design pixels; from the middle when the anchor centres it

touch_stick

Contents

2d · ui · 12 properties · 2D

An on-screen stick that drives action_x and action_y from -1..1 while a thumb drags it, y positive away from the player. anchor, x and y place it, as they place a widget.

In a scene, touch_stick is the node key that applies it. A script reaches each property below as a field on node.touch_stick: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.touch_stick.get() and node.touch_stick.set(table).

Properties

property type default description
action_x string — The action the stick's left and right feed, -1 at the left of its throw
action_y string — The action the stick's up and down feed, 1 pushed away from the player
anchor enum bottom_left Screen corner, edge or middle the stick sits against, inside the safe area One of top_left, center_top, top_right, center_left, center, center_right, bottom_left, center_bottom, bottom_right.
color color [1,1,1,0.18] The base circle's fill, as channel floats or #rrggbb / #rrggbbaa
deadzone float 0.15 Fraction of the throw that reads zero, so a resting thumb does not drift; the rest is rescaled so the first live reading is near zero Range 0–0.95.
knob_color color [1,1,1,0.45] The knob's fill
knob_radius float 38 The knob's own radius in design pixels; drawing only At least 1.
radius float 90 The throw in design pixels: how far the knob travels for a full 1, and the circle a thumb may grab it in At least 1.
recenter bool false Move the stick's centre to the thumb that grabbed it, so an off-centre grab does not jerk
visibility enum touchscreen touchscreen hides it and stops it taking fingers where the platform has no touch screen One of always, touchscreen.
x float 40 Inward from the anchored side to the stick's throw, in design pixels; from the middle when the anchor centres it
y float 40 Inward from the anchored top or bottom to the stick's throw, in design pixels; from the middle when the anchor centres it

transform

Contents

2d · 3d · 4 properties · 2D

The node's position, rotation_euler, scale and skew in its parent's space. A node without one sits at its parent.

In a scene, transform is the node key that applies it. A script reaches each property below as a field on node.transform: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.transform.get() and node.transform.set(table).

Properties

property type default description
position vec3 [0,0,0] Where the node sits in its parent's space
rotation_euler vec3 [0,0,0] Local rotation as euler angles in radians, x then y then z
scale vec3 [1,1,1] Size relative to the parent's
skew float 0 A 2D shear in radians: how far the y axis leans past square with the x axis; children lean with it

Script functions

Methods of node.transform, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From node:

method what it does
global_position() -> Vec3 The node's position in world space, as of the last transform sync.
global_rotation_euler() -> Vec3 The node's world rotation as euler angles in radians, as of the last transform sync.
global_scale() -> Vec3 The node's scale in world space, as of the last transform sync.
look_at(Vec3) Turn the node so its -z, the way a camera and a light face, points at a world point, with +y up. It faces from where its position puts it now, under its parent's pose as of the last transform sync.
set_global_position(Vec3) Put the node at a world point, Godot's global_position = point: it writes the position that lands there under its parent's pose as of the last transform sync, so global_position reads the point once the next sync has run. An axis a zero scale above flattens, or a point that is not finite, keeps the node's own coordinate.

vehicle3d

Contents

3d · physics · 6 properties · 3D

Makes the node's body3d a raycast vehicle chassis, driven by the wheel3d children under it. forward_axis and up_axis orient it.

In a scene, vehicle3d is the node key that applies it. A script reaches each property below as a field on node.vehicle3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.vehicle3d.get() and node.vehicle3d.set(table).

Properties

property type default description
collision_mask flags [] The collision layers the wheels' rays hit; empty hits every layer One of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32.
exclude_kinds flags [] The body kinds the wheels' rays pass through: static takes colliders with no body too. The chassis's own body is never hit One of static, kinematic, dynamic.
forward_axis enum z Which of the chassis's own axes points forward, either way along it: a negative axis drives and steers the other way round, and reads speed the other way One of x, y, z, -x, -y, -z.
hit_sensors bool false Stop the wheels' rays at sensors; off, they pass through them
hit_solids bool true Stop the wheels' rays at colliders that are not sensors; off, they pass through them
up_axis enum y Which of the chassis's own axes points up, either way along it One of x, y, z, -x, -y, -z.

Script functions

Methods of node.vehicle3d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From physics3d:

method what it does
vehicle_speed() -> float How fast the chassis is going along its forward axis, in units per second.

wheel3d

Contents

3d · physics · 11 properties · 3D

One wheel of the vehicle3d above it; the node's position on the chassis is where its ray starts. physics3d.set_engine_force, set_brake and set_steering drive it.

In a scene, wheel3d is the node key that applies it. A script reaches each property below as a field on node.wheel3d: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.wheel3d.get() and node.wheel3d.set(table).

Properties

property type default description
axle vec3 [-1,0,0] The axle the wheel turns about, in the chassis's own space
damping_compression float 0.82 Damping while the suspension is being squashed At least 0.
damping_relaxation float 0.88 Damping while the suspension is coming back At least 0.
friction_slip float 10.5 Grip along the wheel's rolling direction; lower slides more At least 0.
radius float 0.4 The wheel's radius, which is how far off the ground it holds the ray's end At least 0.01.
rest_length float 0.3 How long the suspension is with no weight on it At least 0.
side_friction float 1 Grip sideways: what stops the car sliding out of a corner At least 0.
suspension_direction vec3 [0,-1,0] Which way the suspension pushes, in the chassis's own space: down
suspension_max_force float 6000 The most force this suspension may push the chassis with At least 0.
suspension_stiffness float 30 Spring stiffness, scaled by the chassis's mass: higher is a stiffer, twitchier car At least 0.
suspension_travel float 5 How far the suspension may move either side of its rest length At least 0.

Script functions

Methods of node.wheel3d, the handle a node carrying this component exposes. Every handle also has get(), set(table), patch(table), has() and remove().

From physics3d:

method what it does
set_brake(float) How hard this wheel brakes, as an impulse; ignored while its engine force is not 0.
set_engine_force(float) How hard this wheel drives, in newtons; negative reverses.
set_steering(float) Turn this wheel, in radians.
set_wheel_rotation(float) Set how far the wheel has turned about its axle, in radians: the angle state reads as rotation.
wheel_state() -> physics3d::WheelState What the last step did with this wheel.

widget

Contents

ui · 57 properties · UI

A HUD element drawn every frame: kind picks label, button, panel and more, anchor places it in design pixels. A click on one is its node's pointer_click, which a bindings row or its script's on_pointer_click answers; a label, a panel or an image senses a click only where one is heard.

In a scene, widget is the node key that applies it. A script reaches each property below as a field on node.widget: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget.get() and node.widget.set(table).

Properties

property type default description
absolute bool false Take this child out of its container's run and place it by inset against the container's box inside its border, drawn in its turn among its siblings; a root ignores it
align_self enum auto Where this child sits across its container's direction; auto takes the container's align_items One of auto, start, center, end, stretch, baseline.
anchor enum top_left Corner, edge or middle the offset is measured from: of the surface for a root, of the parent's box inside a stack; fill takes the whole of it less inset One of top_left, top_right, bottom_left, bottom_right, center, center_left, center_right, center_top, center_bottom, fill, fill_top, fill_bottom, fill_left, fill_right, fill_across, fill_down.
announce bool false A screen reader reads its text out as it arrives and as it changes, as a status line
aspect_ratio float 0 Width over height, kept where the layout decides only one of them; 0 keeps none At least 0.
basis float -1 The size this child starts from along its container's direction, before grow and shrink, in design pixels; below zero is 0 for one that grows and its own size otherwise
border vec4 [0,0,0,0] The width of this widget's outline on each side, left, top, right and bottom, in design pixels: the layout keeps it clear inside the edge as it keeps padding, and the stroke is painted in exactly that band. All zero leaves the stroke at the theme's stroke_width, over the padding
constrain bool false Keep a movable root inside its surface while it is dragged
context string — Name of a menu node whose rows open at the pointer on a right click or a long press; give that menu visible = false to show no button of its own
corner_radius float -1 Corner radius in design pixels, a progress_bar's and an image's included; below zero takes the theme's own, which for a button is as round as its text is tall
cursor enum arrow The pointer's shape while it is over the widget: hand over anything that opens on a click, none to hide it; arrow is the platform's own One of arrow, none, hand, text, vertical_text, cross, cell, wait, progress, help, context_menu, move, grab, grabbing, alias, copy, no_drop, forbidden, all_scroll, resize_x, resize_y, resize_n, resize_e, resize_s, resize_w, resize_ne, resize_nw, resize_se, resize_sw, resize_nesw, resize_nwse, resize_col, resize_row, zoom_in, zoom_out.
dashed bool false Draw the outline in dashes, as a guide over a picture is drawn, rather than whole; square at the corners
enabled bool true Off, the widget is greyed out and swallows its clicks
fade_in bool false Fade a root in as it appears, over egui's fade time
fill string — What is painted behind this widget, an image's picture included, as #rrggbb or a name from the theme's [colors]; empty takes the theme's own
focusable bool true Let focus land here. A widget nothing can activate is never focused whatever this says; set it false to skip one that could be
font asset · font — The face it draws in, and how: a face file such as fonts/Inter.ttf, or a font asset. Empty takes the theme's default font
font_size float 0 Text size in design pixels; 0 takes the size the role or the kind carries At least 0.
font_style enum normal Upright, the family's italic face, or the upright face slanted; a family with no italic is slanted either way One of normal, italic, oblique.
font_weight int 400 Weight on the CSS scale, resolved against the faces the project ships: 400 regular, 700 bold Range 100–900.
grow float 0 Share of the leftover space a container hands out along its own direction; 0 takes only what this widget asks for At least 0.
height float 0 Panel height in design pixels; 0 sizes to content At least 0.
height_percent float 0 Height as a percentage of the container's box inside its padding; 0 leaves it to height, which a stated percentage wins over At least 0.
hide_narrower float 0 Not drawn while the room is narrower than this many design pixels. The room is the nearest container that states a size or grows, and the screen for a root: a minimum in numbers, where the class words are not fine enough. Zero is no line At least 0.
hide_shorter float 0 Not drawn while the room is shorter than this many design pixels. Zero is no line At least 0.
hide_taller float 0 Not drawn while the room is this tall or taller, in design pixels. Zero is no line At least 0.
hide_wider float 0 Not drawn while the room is this wide or wider, in design pixels: a control only a small space wants. Zero is no line At least 0.
inset vec4 [0,0,0,0] Left, top, right and bottom margins a root with anchor = "fill" keeps from its surface, and how far an absolute child sits in from each edge of its container inside its border, where a side below zero is left free; in design pixels
interactive bool true Off, the pointer passes through to the scene: the widget is drawn, never hovered or clicked, and ui.wants_pointer() stays false over it. A full-screen container over the world wants this
kind enum label The HUD element the widget layer draws One of label, button, panel, row, column, scroll, tabs, image, text_field, text_area, checkbox, switch, color_picker, dropdown, menu, list, tree, table, slider, number_field, progress_bar, grid, fold, dialog, window, separator, code, stack.
margin vec4 [0,0,0,0] Space outside this widget's edge that its container keeps clear, left, top, right and bottom, in design pixels; below zero lets a neighbour over it
max_height float 0 Largest height a container may give this widget, and a resizable window be dragged to, in design pixels; 0 is no limit At least 0.
max_width float 0 Largest width a container may give this widget, and a resizable window be dragged to, in design pixels; 0 is no limit At least 0.
min_height float 0 Smallest height a container may give this widget, and a resizable window be dragged to, in design pixels At least 0.
min_width float 0 Smallest width a container may give this widget, and a resizable window be dragged to, in design pixels At least 0.
movable bool false Let a drag move this root and write its x and y: a window by its title bar, any other root by its whole box where no child takes the press
neighbour_down string — The same pointing down
neighbour_left string — The same pointing left
neighbour_right string — The same pointing right
neighbour_up string — The widget focus goes to when an arrow, a stick or a d-pad points up from this one, by node name; empty leaves it to where the widgets were drawn
on_top bool false A root drawn above every root that is not, as a message read over whatever is on screen
padding vec4 [-1,-1,-1,-1] Space inside the widget's edge, in design pixels: one number for every side, or left, top, right and bottom. A container keeps it round its children, a button and a label round their text, and every other kind in its box. A side below zero takes the theme's (padding_x across and padding_y down, else padding), else 8 round a panel, 12 either side of a button's or menu's caption and 0 elsewhere; a stated zero is no space at all. On a text_field, text_area or code it is the margin round the text, where below zero takes egui's
role string — A [roles.<name>] entry of the widget's theme, taken over its kind's own style; the one place a look is named rather than spelled
safe_area flags ["left","top","right","bottom"] The edges this root keeps clear of what a notch, a status bar or a home bar covers. A fill root's own colour still reaches the edge, and one with no children is a backdrop and reaches it whole One of left, top, right, bottom.
shrink float -1 Share of the shortfall this child gives up when its container is too small along its direction; below zero is 1 for one that grows and 0 otherwise
stroke string — The outline around this widget, as #rrggbb or a name from the theme's [colors]; empty takes the theme's own
text string — Label or button caption
text_color color [0,0,0,0] Text color; fully transparent takes the theme's colour for this widget's role or kind, and failing that a near-white
text_key string — A localization key drawn in place of text, re-read every frame so a locale switch shows at once
text_style asset · text_style — How it is dressed past its font: line height and spacing, the lines drawn with the glyphs, an outline and a shadow. Empty draws it plain
theme asset · widget_theme — How this widget and everything under it is drawn; inherited from the nearest ancestor that names one
tooltip string — Text shown after the pointer rests on the widget; still shown while enabled is off, which is where it says why
whole_window bool false Whether this root draws over the whole window, whatever ui.set_widget_layer says: what an editor's own chrome does. Ignored on a child.
width float 0 Panel width in design pixels; 0 sizes to content At least 0.
width_percent float 0 Width as a percentage of the container's box inside its padding; 0 leaves it to width, which a stated percentage wins over At least 0.
x float 16 Horizontal offset from the anchor, in design pixels
y float 16 Vertical offset from the anchor, in design pixels

Asset types this component references: font, text_style, widget_theme.

widget_box

Contents

ui · 5 properties · UI

The rarer words about a box, which any kind may carry: what its size measures, what it keeps for what runs past it, and how it lays out on its own.

In a scene, widget_box is the node key that applies it. A script reaches each property below as a field on node.widget_box: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_box.get() and node.widget_box.set(table).

Properties

property type default description
box_sizing enum border What width and height measure: border, the whole box, or content, the box inside padding and border One of border, content.
contain flags [] Containment: layout or paint makes the box lay out on its own, and layout also gives it no baseline for a parent's baseline alignment One of layout, paint.
overflow enum visible What the layout keeps for content past this widget's box: scroll keeps scrollbar_width clear inside its edge, the others nothing. Layout only: a container never gives a child a floor of its own content here (min_width is that floor), a scroll kind is what scrolls, and each kind clips as it draws One of visible, clip, hidden, scroll.
safe_align bool false Where align_items, align_self, align_content or justify would push a child past its container's start, put it at the start instead, so the start stays in view
scrollbar_width float 0 The room a box with overflow = "scroll" keeps clear inside its edge for a bar, in design pixels At least 0.

widget_button

Contents

ui · 7 properties · UI

The rows a button or menu reads: what its face holds beside its caption, and what the pointer may do to it.

In a scene, widget_button is the node key that applies it. A script reaches each property below as a field on node.widget_button: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_button.get() and node.widget_button.set(table).

Properties

property type default description
face_gap float -1 The space between its picture, icon and caption, in design pixels; below zero takes the theme's own, else half the font size
icon string — A glyph from the theme's icon family, drawn before text
icon_color string — What that glyph is tinted with, as #rrggbb or a name from the theme's [colors]; empty takes the role's own
icon_size float -1 That glyph's size in design pixels; below zero takes the caption's
image string — The project-relative picture drawn before the caption at the caption's height
sense enum click What the pointer may do to it: click reports a press let go as a click; under click_and_drag a press that moves past egui's drag distance is a drag and no click; drag and hover never click One of click, click_and_drag, drag, hover.
trailing string — Text drawn against its far edge, dimmer than its caption: a shortcut, or a menu's caret

widget_check

Contents

ui · 4 properties · UI

The rows a checkbox, switch or button reads: whether it is on, and what a click does to that.

In a scene, widget_check is the node key that applies it. A script reaches each property below as a field on node.widget_check: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_check.get() and node.widget_check.set(table).

Properties

property type default description
checked bool false Whether a checkbox or switch is on, every click flipping it and announcing value_changed with the new state; a checked button or menu is held down, wearing its pressed look
indeterminate bool false Draw a checkbox as neither ticked nor clear, for a group whose members disagree; a click still flips checked
radio_group string — A name this checkbox, switch or toggle button shares with the ones it is exclusive with: ticking one unticks the rest, and one already ticked stays ticked. Empty leaves it flipping on its own
toggle bool false A button a click holds down and the next releases, flipping checked as a checkbox does, before its pointer_click is heard: Godot's toggle mode

widget_child

Contents

ui · 4 properties · UI

What a child says to the parent it sits in, whatever its own kind: a grid's cell, a fold's header, a menu's row.

In a scene, widget_child is the node key that applies it. A script reaches each property below as a field on node.widget_child: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_child.get() and node.widget_child.set(table).

Properties

property type default description
column string — On a grid's child: the columns it covers, in the words row takes
keep_open bool false On a menu's row: leave the menu open when clicked, as a toggle does; any other row closes it
row string — On a grid's child: the rows it covers, as a line counted from 1 (2, or from the end below zero), a first and last line (1 / 3), a span (span 2, 2 / span 2), or the name of one of the grid's areas. Empty puts it in the next free cell
title_bar bool false On a fold's child: drawn in the fold's header after its arrow and caption, as Godot's title bar control is

widget_code

Contents

ui · 6 properties · UI

The rows a code widget reads: what it highlights and its gutter.

In a scene, widget_code is the node key that applies it. A script reaches each property below as a field on node.widget_code: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_code.get() and node.widget_code.set(table).

Properties

property type default description
breakpoints list [] The lines a code widget dots in its gutter, counting from 1; whole numbers or the text of them. A click on the gutter announces gutter_clicked with its line and the script decides what the mark means
current_line int 0 The line a code widget fills across its whole width, counting from 1, for the row a debugger is stopped on; 0 fills none At least 0.
gutter_width float 0 How wide a code widget's gutter is, in design pixels; 0 takes the built-in width, which holds four digits At least 0.
language string — The language a code widget highlights
problems list [] The lines a code widget underlines as errors, counting from 1, each also marked on the inner edge of its gutter
warnings list [] The lines a code widget underlines as warnings, counting from 1; an error on the same line outranks it

widget_color_picker

Contents

ui · 3 properties · UI

The rows a color_picker reads: the colour it holds and what it offers.

In a scene, widget_color_picker is the node key that applies it. A script reaches each property below as a field on node.widget_color_picker: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_color_picker.get() and node.widget_color_picker.set(table).

Properties

property type default description
alpha enum blend What a color_picker offers for alpha: none keeps the colour opaque, blend offers transparency, additive that and additive blending One of none, blend, additive.
inline bool false Draw a color_picker's picker in place, rather than behind a swatch that opens it
picked_color color [1,1,1,1] What a color_picker holds; value_changed carries the new one

widget_dropdown

Contents

ui · 3 properties · UI

The rows a dropdown reads: what it offers, how tall its list grows and what shuts it.

In a scene, widget_dropdown is the node key that applies it. A script reaches each property below as a field on node.widget_dropdown: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_dropdown.get() and node.widget_dropdown.set(table).

Properties

property type default description
close_on enum click What shuts a dropdown's list: any click, a pick included, a click outside it, or nothing but Escape One of click_outside, click, never.
list_height float 0 The tallest a dropdown's list grows before it scrolls, in design pixels; 0 takes egui's At least 0.
options list [] The words a dropdown offers; text is the one picked, and value_changed carries every pick

widget_field

Contents

ui · 14 properties · UI

The rows a text_field, text_area or code reads: what may be typed and how the editor behaves.

In a scene, widget_field is the node key that applies it. A script reaches each property below as a field on node.widget_field: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_field.get() and node.widget_field.set(table).

Properties

property type default description
caret_at_end bool true Put the caret at the end of a text_field, text_area or code's text when it first takes focus; off, at the start
clip_text bool true Cut a text_field's text at its edge; off, the field grows to show it whole
editable bool true Let the reader change a text_field, text_area or code's text; off, it can be neither edited nor selected
line_break enum word_smart Where a text_area's wrapped line may break One of word_smart, word, arbitrary.
max_length float 0 The most characters a text_field takes; 0 is no limit At least 0.
numeric bool false Keep a text_field to digits, a sign and a point
placeholder string — What a text_field or text_area shows while it is empty
prefix string — Text drawn before a text_field's or text_area's text
secret bool false Draw a text_field's text as dots, for a password
submit_key string — The chord that submits a text_field, as Enter or cmd+Enter; empty is Enter. A text_area submits when focus leaves it whatever this says
suffix string — Text drawn after a text_field's or text_area's text
tab_inserts bool false Let Tab type a tab into a text_field, text_area or code rather than move focus on
tab_size int 8 Spaces between a text_field's or text_area's tab stops Range 1–64.
text_align enum start Where what a text_field or text_area edits sits in its width One of start, center, end.

widget_fold

Contents

ui · 1 property · UI

The row a fold reads: whether it shows what is under its header.

In a scene, widget_fold is the node key that applies it. A script reaches each property below as a field on node.widget_fold: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_fold.get() and node.widget_fold.set(table).

Properties

property type default description
open bool true Whether a fold shows its children; its header flips it and announces value_changed with the new state

widget_grid

Contents

ui · 6 properties · UI

The rows a grid reads: its tracks and its named areas.

In a scene, widget_grid is the node key that applies it. A script reaches each property below as a field on node.widget_grid: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_grid.get() and node.widget_grid.set(table).

Properties

property type default description
areas list [] A grid's named areas, one string a row of space-separated names with . for a cell in none: ["head head", "side main"]. A child names one in row and column
auto_columns string — The size of each column a grid adds past grid_columns, for a child placed beyond them or flowing down under auto_flow = "column", in the words grid_columns takes without repeat; several take turns. Empty is auto
auto_flow enum row The order a grid fills cells with the children that name none: along each row, or down each column; a _dense order goes back to fill a hole a bigger child left One of row, column, row_dense, column_dense.
auto_rows string — The size of each row a grid adds past grid_rows, in the words auto_columns takes; empty is auto
grid_columns string — A grid's columns, left to right and space-separated: design pixels (120), a share of what is left (1fr), a percentage (25%), auto, min_content, max_content, fit_content(120), minmax(80, 1fr), and repeat(3, 1fr), whose count may be auto_fill or auto_fit. Empty is two equal columns
grid_rows string — A grid's rows, top to bottom, in the words grid_columns takes; empty makes each row as tall as what is in it

widget_image

Contents

ui · 8 properties · UI

The rows an image reads: its picture, the part of it drawn and how it sits in its box.

In a scene, widget_image is the node key that applies it. A script reaches each property below as a field on node.widget_image: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_image.get() and node.widget_image.set(table).

Properties

property type default description
alt_text string — Text an image draws in place of a picture that will not load
angle_degrees float 0 How far an image is turned clockwise about angle_origin, in degrees; a turned image keeps square corners
angle_origin vec2 [0.5,0.5] The point an image turns about, as fractions of its box from the top left: [0.5, 0.5] is its middle
fit enum — How an image sits in the box it was given: contain and cover keep its shape, fill stretches, none leaves it its own size, centred. Empty lets the picture decide the box instead One of ``, contain, `cover`, `fill`, `none`.
image string — The project-relative picture an image draws
region vec4 [0,0,0,0] The part of an image drawn, as left, top, width and height in the picture's own pixels, which is how an atlas shows one tile; a zero width or height draws the whole picture. ui.image takes it too
slice vec4 [0,0,0,0] Left, top, right and bottom borders of an image kept unstretched, in the picture's own pixels; all zero stretches the whole picture
tint color [1,1,1,1] What an image is multiplied by; white draws it as it is

widget_layout

Contents

ui · 9 properties · UI

The rows a container reads: how it lays out what is in it.

In a scene, widget_layout is the node key that applies it. A script reaches each property below as a field on node.widget_layout: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_layout.get() and node.widget_layout.set(table).

Properties

property type default description
align_content enum stretch How a container that wraps spreads its lines across its direction, and a grid its rows, where they leave room: stretch shares the room among them One of start, center, end, stretch, between, around, evenly.
align_items enum stretch Where a container puts its children across its own direction, and a grid each child in its cell down: stretch makes each as wide (or tall) as the container, baseline lines up their first lines of text, the others keep each child's own size One of start, center, end, stretch, baseline.
direction enum left_to_right Which way a row and a grid's columns run: right_to_left starts them at the right edge One of left_to_right, right_to_left.
gap vec2 [-1,-1] Space between a container's children, across and down, in design pixels: a row puts the first between its children and the second between the lines it wraps onto, a column the second between its children, and a grid the first between its columns and the second between its rows. Below zero on an axis takes the theme's own, which is 8 where it says nothing, and a stated zero puts them edge to edge
justify enum start How a container spreads its children along its own direction once they have their sizes, and a grid its columns: stretch grows a grid's auto columns into the room, and in a row or a column is start One of start, center, end, stretch, between, around, evenly.
min_lines int 1 How many lines a wrapping container divides its children between at least: balance evens them over this many, and any wrap shares a known cross size among them At least 1.
reverse bool false Lay a row or a column's children out from its far end
splitter_width float 0 How wide a grab the seams between this container's children get, in design pixels; 0 leaves them fixed. A drag writes the new size onto the neighbour that states one At least 0.
wrap_children enum none Whether a container's children run onto more lines when they do not fit: none keeps them on one line, wrap starts a line when the row is full, balance evens the lines out over at least min_lines, and a _reverse word stacks the lines the other way One of none, wrap, wrap_reverse, balance, balance_reverse.

widget_list

Contents

ui · 4 properties · UI

The rows a list or tree reads: its card faces, and what a drag or a mark on a row does.

In a scene, widget_list is the node key that applies it. A script reaches each property below as a field on node.widget_list: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_list.get() and node.widget_list.set(table).

Properties

property type default description
draggable bool false Let a drag carry a card of a list with grid_columns out of it, drawn under the pointer; dropped says which card was let go
grid_columns string — How many columns a list flows its cards into, in the words a grid's grid_columns takes; empty draws a line a row
reorderable bool false Let a drag move a row of a list or a tree. The kind moves nothing itself: it draws where the row would land and announces moved, and the rows are the script's to reorder
sheet string — The picture a list cuts its card faces from

widget_menu

Contents

ui · 7 properties · UI

The rows a menu reads: where its popup opens and what shuts it.

In a scene, widget_menu is the node key that applies it. A script reaches each property below as a field on node.widget_menu: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_menu.get() and node.widget_menu.set(table).

Properties

property type default description
close_on enum click_outside What shuts a menu's popup besides a row: a click outside it, any click at all, or nothing but Escape One of click_outside, click, never.
options list [] The words a menu of strings offers, its text being the button's caption; value_changed carries every pick
placement enum below Where a menu opens: under its button, above it, to its right or to its left, each from the side's start (below starts at the button's left edge, right at its top) or at _center or _end; at the pointer; or centred on the screen One of below, below_center, below_end, above, above_center, above_end, right, right_center, right_end, left, left_center, left_end, pointer, center.
placement_fallbacks list [] The placements a menu's popup tries, in order, where its own does not fit the screen; empty tries egui's, and naming the placement alone keeps it where it is
popup_gap float -1 The space between a menu's button and its popup, in design pixels; below zero takes egui's
popup_width float 0 How wide a menu's popup starts, in design pixels; 0 sizes it to its rows At least 0.
showing bool false Holds a menu's rows up from the scene, as a click would; for an offscreen run or a tutorial, since nothing can click there

widget_range

Contents

ui · 24 properties · UI

The rows a slider, number_field or progress_bar reads: where it stands in its range, how it moves and how it is drawn.

In a scene, widget_range is the node key that applies it. A script reaches each property below as a field on node.widget_range: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_range.get() and node.widget_range.set(table).

Properties

property type default description
animate bool false Shimmer a progress_bar that is short of full, with a spinner at its end unless it states a corner_radius. It repaints every frame while it is on screen and short of full, and never otherwise
arrows bool false Draw a step up and a step down beside a number_field, each moving it by step within min and max
axis enum both Which way a slider runs: up its box under vertical, along it otherwise One of both, horizontal, vertical.
clamp enum always Whether a slider holds its number inside min and max: always, one the scene set outside them included; edits, only what the reader enters; never, only the track One of always, edits, never.
clamp_existing bool false Pull a number_field's number back inside min and max where the scene set it outside them; off, it is shown as set and only an edit is bounded
decimals int -1 How many decimals a slider's or number_field's number shows; below zero lets egui decide
drag_speed float 0 How far a number_field, or a slider's shown number, moves per design pixel dragged; 0 takes egui's, which is 1 on a number field and scales with the range on a slider At least 0.
handle enum circle A slider's handle: a circle, or a rect handle_aspect times as wide as the track is tall One of circle, rect.
handle_aspect float 0.5 How wide a rect handle is against its height At least 0.
largest_finite float 0 The largest number a logarithmic slider reaches short of an unbounded end; 0 is no limit At least 0.
logarithmic bool false Space a slider's track logarithmically, for a range across orders of magnitude
max float 1 The high end of a slider or progress_bar; a number_field runs free while this pair is the default 0 and 1
min float 0 The low end of a slider or progress_bar; a number_field runs free while this pair is the default 0 and 1
number_format enum decimal The base a slider or number_field writes its number in; the others than decimal write it whole One of decimal, binary, octal, hex.
prefix string — Text drawn before a number_field's or a shown slider's number with a space between
show_percentage bool false Draw a progress_bar's fill as a percentage on it, in place of its text
show_value bool false Draw a slider's number beside its track, for the reader to drag or type into
smallest_positive float 0 The smallest number above zero a logarithmic slider reaches, for a range that starts at or crosses zero; 0 takes egui's millionth At least 0.
smart_aim bool true Round a dragged slider to the simplest number near the pointer
step float 0 The grid a slider snaps to, and how far a number_field's arrows move it; 0 is continuous, and 1 for the arrows At least 0.
suffix string — Units drawn after a number_field's or a shown slider's number with a space between
trailing_fill bool false Fill a slider's track from its start up to the handle
update_while_editing bool true Write a slider's or number_field's number as the reader types it; off, only once the typing is left
value float 0 Where a slider, number_field or progress_bar stands, between min and max; a slider and a drag value write it and announce value_changed with it

widget_rows

Contents

ui · 4 properties · UI

The rows a list, tree or table reads: what it holds and what is picked.

In a scene, widget_rows is the node key that applies it. A script reaches each property below as a field on node.widget_rows: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_rows.get() and node.widget_rows.set(table).

Properties

property type default description
items list [] The rows a list, tree or table holds. text is the key of the one picked, and every row event reports a row by its key
multi_select bool false Let a list, tree or table hold more than one row: the platform's command key toggles a row and shift takes the run from the last one clicked
row_height float 0 The pitch of a list, tree or table row, in design pixels; 0 takes the font's own line height At least 0.
selection list [] The keys of the rows a list, tree or table has picked, one of them where it holds one. text is the key of the last row clicked, which is where a shift range measures from; value_changed carries the whole list where the widget holds many, and the key where it holds one

widget_scroll

Contents

ui · 12 properties · UI

The rows a scroll, list, tree or table reads: its bars, where it is scrolled to and what scrolls it.

In a scene, widget_scroll is the node key that applies it. A script reaches each property below as a field on node.widget_scroll: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_scroll.get() and node.widget_scroll.set(table).

Properties

property type default description
animated bool true Ease a scroll, list, tree or table to where it is sent, such as a row scrolled into view, rather than jump
axis enum both Which way a scroll moves, the other way its contents filling the box it was given One of both, horizontal, vertical.
drag_cursor enum arrow The pointer's shape while a drag scrolls a scroll, list, tree or table's content; arrow leaves it as it is One of arrow, none, hand, text, vertical_text, cross, cell, wait, progress, help, context_menu, move, grab, grabbing, alias, copy, no_drop, forbidden, all_scroll, resize_x, resize_y, resize_n, resize_e, resize_s, resize_w, resize_ne, resize_nw, resize_se, resize_sw, resize_nesw, resize_nwse, resize_col, resize_row, zoom_in, zoom_out.
drag_scroll enum touch When dragging a scroll, list, tree or table's content scrolls it: on a touch screen, always, or never; a scroll_deadzone takes the drag over itself One of touch, always, never.
min_scrolled_height float 0 The shortest a scroll, list, tree or table draws while its content runs past it downwards, in design pixels; 0 takes egui's At least 0.
min_scrolled_width float 0 The narrowest a scroll, list, tree or table draws while its content runs past it sideways, in design pixels; 0 takes egui's At least 0.
scroll_deadzone float 0 How far a finger drags a scroll before it scrolls, in design pixels, so a tap on a child still lands; 0 scrolls at once At least 0.
scroll_offset vec2 [-1,-1] Where a scroll, list, tree or table is scrolled to, across and down, in design pixels: written as the reader scrolls, and a new one written by the scene or a script scrolls it there. Below zero on an axis leaves that axis where it is; ui.scroll takes it too
scrollbar enum auto When a scroll, list, tree or table has its bars: while its content runs past it, always, or never. The bars float, so one shows once the pointer is over the box One of auto, always, never.
stick_to_end bool false Keep a scroll, list, tree or table at its end as content arrives, until the reader scrolls away from it; ui.scroll takes it too
wheel_scroll bool true Let the mouse wheel scroll a scroll, list, tree or table
wheel_speed vec2 [1,1] How far a mouse wheel scrolls a scroll, list, tree or table, across and down, as a multiple of egui's own

widget_separator

Contents

ui · 3 properties · UI

The rows a separator reads: the room it takes and how far its line runs.

In a scene, widget_separator is the node key that applies it. A script reaches each property below as a field on node.widget_separator: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_separator.get() and node.widget_separator.set(table).

Properties

property type default description
axis enum both Which line a separator draws; both leaves it across its parent's direction One of both, horizontal, vertical.
overhang float 0 How far a separator's line runs past each end of the room it was given, in design pixels; below zero stops it short
spacing float -1 The room a separator takes across its line, in design pixels, the line drawn down its middle; below zero is 6

widget_shortcut

Contents

ui · 3 properties · UI

The rows of a chord that clicks a widget, which any kind may carry.

In a scene, widget_shortcut is the node key that applies it. A script reaches each property below as a field on node.widget_shortcut: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_shortcut.get() and node.widget_shortcut.set(table).

Properties

property type default description
shortcut string — A chord that clicks this widget wherever it is, as cmd+shift+KeyS or F5, spelled as [input.actions] spells one; a menu row fires while its menu is shut, and draws the chord against its far edge unless it says its own trailing
takes_typing bool false Whether shortcut takes its key ahead of a field being typed into, a plain key included, so the field never sees it: a completion list's arrows, Enter and Escape while it is up
while_typing bool true Whether shortcut fires while a text field holds the keyboard. A chord without cmd, ctrl or alt never does unless it is a function key, since that is typing; off, no chord does, for one the field has a use for itself, as cmd+KeyZ

widget_table

Contents

ui · 8 properties · UI

The rows a table reads: its columns and how they sort.

In a scene, widget_table is the node key that applies it. A script reaches each property below as a field on node.widget_table: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_table.get() and node.widget_table.set(table).

Properties

property type default description
header bool true Draw the strip that names a table's columns. Off, its columns are still titles', and a table that names none keeps its first row as a row
reverse bool false Take a table's rows the other way round: the sort descending, or the order they were given bottom to top where none is named
sort string — The column the rows are ordered by, by the name in titles; empty leaves them in the order they were given. A cell that starts with a number sorts as one, so 12 KB follows 3 KB. reverse takes them the other way round
sortable bool false Let a click on the header sort by that column, and the next click on the same one turn it round; the column sorted by carries a caret
splitter_width float 0 How wide a grab the seam between two of a table's columns gets, in design pixels; 0 takes six At least 0.
text_align enum start Where every cell of a table sits in its column; a column whose name ends in > pins its own to the right One of start, center, end.
titles list [] A table's column names, in order, and with them how many columns it has: a name ending in > draws its column against the right edge, which is what a column of numbers wants. None takes the first row as the names
widths list [] Each column's share of the width, in the order titles names them: ["2", "1", "1"] gives the first half and the other two a quarter each. Numbers and the text of them both; empty divides the width evenly, and a drag on a seam in the header writes the shares back

widget_tabs

Contents

ui · 1 property · UI

The row a tabs reads: which child it shows.

In a scene, widget_tabs is the node key that applies it. A script reaches each property below as a field on node.widget_tabs: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_tabs.get() and node.widget_tabs.set(table).

Properties

property type default description
current_page string — Which child a tabs shows, by node name; empty shows the first. A click on the strip writes it and announces value_changed with the page's name

widget_text

Contents

ui · 11 properties · UI

The rows a kind drawing a caption reads: how its lines sit, break and are cut, and what the reader may do to them.

In a scene, widget_text is the node key that applies it. A script reaches each property below as a field on node.widget_text: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_text.get() and node.widget_text.set(table).

Properties

property type default description
line_break enum word_smart Where a wrapped line may break One of word_smart, word, arbitrary.
markup bool false Read inline marks in the text: [b], [i], [color=#hex], [center], [right], [wave amp=N freq=N] and [img=path width=N]; off, brackets are text
max_lines int 0 The most lines a wrapped label keeps; zero keeps every line At least 0.
selectable bool false Let a drag over this label select its text, and the platform's copy key take it
show_tooltip_when_elided bool true Show a label's whole text when the pointer rests on it and truncate cut it short
tab_size int 8 Spaces between tab stops Range 1–64.
text_align enum start Where text sits in the width the widget was given One of start, center, end.
text_background color [0,0,0,0] A wash behind the text of the kinds egui draws, a checkbox, dropdown, menu, tabs, panel and the like, where a label and a button shape their own; alpha 0 is none
truncate bool false Cut a caption too long for the width the widget was given and end it with an ellipsis; with neither this nor wrap a button clips it at its edge. A dropdown cuts its picked text
truncate_at enum end Which part of a cut caption the ellipsis stands in for One of end, start, middle.
wrap bool false Break text to the width the widget was given instead of running past it on one line; a dropdown breaks its picked text

widget_window

Contents

ui · 9 properties · UI

The rows a window or a dialog reads: whether it is up, its chrome, and what shuts it.

In a scene, widget_window is the node key that applies it. A script reaches each property below as a field on node.widget_window: reading one asks the running component, and assigning one leaves the rest alone. The whole table is node.widget_window.get() and node.widget_window.set(table).

Properties

property type default description
backdrop_color color [0,0,0,0.549] What a dialog dims the screen behind it with
closable bool true Draw a window's cross
collapsible bool false Give a window's title bar an arrow that folds the window to its bar and back
default_open bool true Whether a collapsible window starts unfolded
dismissable bool true Let Escape or a click on the dim shut a dialog; off, only the scene does
header bool true Draw a window's title bar
hide_on_close bool true Whether a window's close button shuts it; off, the button only emits close_requested and the script decides
open bool true Whether a window or dialog is up; shut, it draws nothing and keeps nothing out
resizable bool false Give a window a grip in its bottom-right corner that a drag resizes it by, writing width and height within min_width, min_height, max_width and max_height

animation_library

Contents

Files live in animations/. Used by animation · library.

A library holds clips, and a clip keys node properties over time. loop_mode is none, linear or pingpong; each track names a target, a property, an interpolation and its keys.

type = "animation_library"

[clips.patrol]           # one clip per file, or several, addressed as file.toml#patrol
length = 4.0             # seconds; left out, the clip ends at its last key
loop_mode = "pingpong"   # none, linear or pingpong

[[clips.patrol.tracks]]
target = ""              # node path relative to the playing node; empty is that node
property = "position"    # rotation_euler, rotation, scale, visible, tint or <component>/<property>
interpolation = "linear" # step, linear or cubic
keys = [
  { time = 0.0, value = [-2.5, 0.25, -2.0] },
  { time = 4.0, value = [-2.5, 0.25, 2.0], ease = "in_out_sine" },
]

[[clips.patrol.tracks]]  # no property: a method track, each key a call on the node's script
keys = [{ time = 2.0, call = "on_halfway" }]

bone_map

Contents

Files live in animations/. Used by no component property yet.

Lets one rig play another's clips: [bones] pairs canonical bone names with node paths on this rig, profile names the skeleton_profile they come from.

type = "bone_map"
# profile = "animations/humanoid.toml"   # left out, the built-in humanoid profile
# Used as node.animation.play(clip, { retarget = "maps/hero.toml" })

[bones]
Hips = "Armature/Hips"
Spine = "Armature/Hips/Spine"
Head = "Armature/Hips/Spine/Neck/Head"

camera_effects

Contents

Files live in camera_effects/. Used by camera2d · effects, camera3d · effects.

The passes a camera's frame resolves through, in order, and how each is tuned. A camera3d or camera2d names one in its effects row, or writes one inline:

type = "camera_effects"
post = ["bloom", "tonemap"]
bloom_intensity = 0.8

font

Contents

Files live in fonts/. Used by text2d · font, text3d · font, widget · font.

The face a text draws in and how its glyphs are picked and drawn. A face file — .ttf, .otf, .ttc, or a .fnt bitmap face — is a font of itself, so a font row takes its path as it is; a definition shapes one differently. font_size, font_weight and font_style stay on the text: weight and style pick a face of the font's family among the project's fonts/.

type = "font"
source = "fonts/Inter-Regular.ttf"
features = ["smcp", "liga=0"]

heightfield

Contents

Files live in heightfields/. Used by no component property yet.

A grid of heights for terrain: rows by columns samples in heights, row-major, one value per grid point. holes lists cells with no ground, each as the [row, column] of its first corner; a 2D collider reads the heights as one line, and a hole there removes the segment starting at that point.

[[assets]]
id = "valley"
type = "heightfield"
rows = 3
columns = 3
heights = [0, 0, 0, 0, -1, 0, 0, 0, 0]
holes = [[1, 1]]

material

Contents

Files live in materials/. Used by boolean2d · material, boolean3d · material, line2d · material, material · source, mesh · material, multimesh2d · material, multimesh3d · material, particles2d · material, particles3d · material, polygon · material, shape2d · material, shape3d · material, sprite · material, text2d · material, text3d · material, tilemap · material.

A shader and its values, or kiss3d's own surface and its values. shader names a .wesl file, [features] sets its @if flags, [params] fills its Params struct by field name. A material with no shader draws a 3D node with kiss3d's own material, and its [params] are that material's; on a 2D node it draws the built-in material, lit per pixel by every light2d when its normal slot names a normal map. Its [surface] is read in both dimensions: how a node blends, which sides draw and whether the scene hides it.

[[assets]]
id = "water"
type = "material"
shader = "shaders/water.wesl"
features = { lit = true }
# a number is an f32, [x, y] a vec2, [x, y, z] a vec3, [x, y, z, w] or "#rrggbb"/"#rrggbbaa" a vec4
params = { speed = 0.4, tint = "#3aa0ff" }

# How a node drawing it rasterizes, rather than what colour it comes out.
[surface]
alpha = "blend"              # auto (the default: solid in 3D, in 2D as the texture was uploaded),
                             # opaque, mask (a cutout), blend, premultiplied (a blend whose colour
                             # carries its alpha; a shader draws it as blend), or the 2D blends
                             # add, multiply and screen, which a 3D surface draws as blend
alpha_cutoff = 0.5           # what a mask drops a fragment below
double_sided = true          # unset is the node's own: the front alone in 3D, both sides in 2D and on text
depth_test = true            # off draws it over everything drawn before it
transmission = 0.9           # above zero is glass: it refracts the scene behind it
ior = 1.5                    # how sharply it bends light
thickness = 0.2              # how far light travels inside it, in world units
attenuation_color = "#dff0ea"
attenuation_distance = 2.0
mirror = true                # show the scene reflected in this surface's own plane
mirror_intensity = 1.0
mirror_falloff = 0.0         # above zero fades the reflection as the surface turns away
mirror_normal = [0.0, 1.0, 0.0]   # which way the plane faces in the node's own space
mirror_resolution_scale = 1.0     # the mirror's picture against the viewport, 0.01 to 4
mirror_render_layers = ["1", "2"] # what the mirror draws, by render_layers; unset follows the camera
trace_surface = "glass"      # what the path tracer takes it for: opaque, glass, metal or light
ssr = true                   # take screen-space reflections, while the camera's post has `ssr`;
                             # a node with a shader material writes none yet
ssr_intensity = 1.0
ssr_infinite_thickness = false    # count every depth crossing as a hit, for thin geometry
ssr_distance_fade = true
ssr_fresnel = false               # stronger at a glancing angle

With no shader, [params] takes kiss3d's surface values and the texture slots:

[[assets]]
id = "lacquer"
type = "material"
# view = "normals"           # or "uvs": draw kiss3d's debug material instead of the surface

[params]
metallic = 0.0
roughness = 0.5
emission_color = "#000000"
specular_tint = "#ffffff"
reflectance = 0.5            # 0.5 is the 4% a common dielectric reflects head-on
clearcoat = 1.0              # a thin glossy layer on top, as car paint has
clearcoat_roughness = 0.05
anisotropy = 0.0             # -1 to 1 stretches the highlight across or along the tangent
anisotropy_rotation_degrees = 0.0
subsurface = 0.0             # read by the path tracer only
subsurface_radius = 0.0      # read by nothing yet
normal = "art/panel_n.png"   # albedo, normal, metallic_roughness, occlusion, emissive, height;
                             # on a 2D node, `normal` lights it per pixel by every light2d
normal_scale = 1.0           # 2D: how far the normal map bends the surface; zero lights it flat
specular_shininess = 16.0    # 2D: how tight a light's highlight is; higher is smaller and sharper
specular_strength = 0.0      # 2D: how bright the highlight is; zero draws none
height = "art/panel_h.png"
parallax_scale = 0.1         # how deep the height map reads, in UV units
parallax_layers = 16
parallax_method = "relief"   # occlusion, or relief refined by parallax_relief_steps
parallax_relief_steps = 8

mesh

Contents

Files live in models/. Used by line2d · mesh, mesh · source, occluder2d · mesh, polygon · mesh, soft_collision2d · collision_mesh, soft_collision3d · collision_mesh, softbody2d · mesh, softbody3d · mesh.

Geometry for mesh properties: a source file, a primitive kind, or its own positions and indices. skin, colors and morphs add bone weights, vertex tints and blend shapes.

[[assets]]
id = "blade"
type = "mesh"
source = "models/blade.obj"      # imported...
part = "stone"                   # glTF only: just this material's triangles
# ...or a primitive, one of sphere, box, capsule, cylinder, cone, plane,
# torus, pyramid, prism, tube:
kind = "torus"
radius = 1.0
tube_radius = 0.3
# ...or a word, shaped and filled from the project's fonts:
kind = "text"
text = "BALAUR"
size = 1.0
underline = "single"             # or "double"; strikethrough and overline take true
# ...or, instead of any of those:
positions = [[0, 0, 0], [1, 0, 0], [0, 1, 0]]
indices = [[0, 1, 2]]
colors = [[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]]   # a tint per vertex
skin = { bones = [{ path = "Rig/Hip", weights = [1, 1, 1] }] }   # one weight per vertex
morphs = [{ name = "smile", positions = [[0, 0, 0], [0.1, 0, 0], [0, 0.1, 0]] }]   # a clip drives it as mesh/morph.smile

multimesh

Contents

Files live in multimeshes/. Used by multimesh2d · source, multimesh3d · source.

Godot's MultiMesh: a mesh and the instances it is drawn at, for multimesh3d.source and multimesh2d.source. Each instance is a transform in the node's space, a color and four floats of custom data a material's shader reads. visible_instance_count draws the first so many; -1 draws them all.

type = "multimesh"
mesh = "models/post.toml"          # a mesh asset, or an inline { type = "mesh", ... }
visible_instance_count = -1
instances = [                      # a 2D instance writes [x, y] and turns about z
  { position = [0.0, 0.0, 0.0] },
  { position = [0.9, 0.0, 0.0], rotation_euler = [0.0, 0.5, 0.0], scale = [1.0, 2.0, 1.0] },
  { position = [1.8, 0.0, 0.0], color = "#ff8080", custom = [1.0, 0.0, 0.0, 0.0] },
  # a 3x3, columns first, in place of rotation_euler and scale: it keeps a shear
  { position = [2.7, 0.0, 0.0], basis = [1.0, 0.0, 0.0, 0.5, 1.0, 0.0, 0.0, 0.0, 1.0] },
  # the node's wireframe and vertex points, for this instance alone; they draw
  # only while the node's own wireframe_width and point_size are above zero
  { position = [3.6, 0.0, 0.0], wireframe_color = "#00ff00", wireframe_width = 2.0, point_color = "#ffff00", point_size = 4.0 },
]

A 2D instance also takes region_origin and region_size, the rectangle of the texture it draws in pixels. multimesh2d draws through Balaur's own pipeline, which reads neither the rectangle nor the four overrides yet.

path2d

Contents

Files live in paths/. Used by no component property yet.

A bezier path: points runs anchor, two handles, next anchor, then three more per segment; closed joins the last segment back to the first anchor.

[[assets]]
id = "outline"
type = "path2d"                  # flat; a path3d takes [x, y, z] points
closed = true
points = [[0, 0], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0]]   # two points alone are a straight line
# A mesh asset fills, extrudes, revolves or sweeps a path; shape2d strokes one.

path3d

Contents

Files live in paths/. Used by no component property yet.

A bezier path: points runs anchor, two handles, next anchor, then three more per segment; closed joins the last segment back to the first anchor.

[[assets]]
id = "outline"
type = "path2d"                  # flat; a path3d takes [x, y, z] points
closed = true
points = [[0, 0], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0]]   # two points alone are a straight line
# A mesh asset fills, extrudes, revolves or sweeps a path; shape2d strokes one.

physics_material

Contents

Files live in physics_materials/. Used by collider2d · physics_material, collider3d · physics_material, softbody2d · physics_material, softbody3d · physics_material, tile_collision · physics_material.

What a collider's surface is made of: friction and restitution, and how each combines with the surface it touches. A collider, a tile_collision or a soft body names one in its physics_material row, or writes one inline:

type = "physics_material"
friction = 0.05
friction_combine = "min"

skeleton_profile

Contents

Files live in animations/. Used by no component property yet.

The canonical skeleton a bone_map names bones from. Each [[bones]] entry has a name, a rest_rotation and a rest_position; no bones means the built-in humanoid.

type = "skeleton_profile"

[[bones]]
name = "Hips"
rest_position = [0.0, 1.0, 0.0]   # its length scales a retargeted position track

[[bones]]
name = "Spine"
rest_rotation = [0.0, 0.0, 0.0]   # euler radians

soft_material

Contents

Files live in soft_materials/. Used by softbody2d · soft_material, softbody3d · soft_material.

What a soft body is made of: how its cells resist, its springs, how it keeps its volume, how it yields and when it tears. A softbody2d or softbody3d names one in its soft_material row, or writes one inline:

type = "soft_material"
cell_model = "neo_hookean"
young_modulus = 50000.0

sprite_sheet

Contents

Files live in sheets/. Used by particles2d · sheet, sprite · sheet.

An image cut into frames, for sprite.sheet. texture names the image; frames each hold a rect and duration; [tags.<name>] and [slices.<name>] add runs and regions.

type = "sprite_sheet"            # balaur import file.aseprite writes one beside the atlas it packs
texture = "art/walk.png"
frames = [                       # rect is [x, y, w, h] texture pixels; sprite.frame indexes this list
  { rect = [0, 0, 32, 32], duration = 0.1 },
  { rect = [32, 0, 32, 32], duration = 0.1 },
]

[tags.walk]                      # a run of frames
from = 0
to = 1
direction = "forward"            # forward, reverse, pingpong or pingpong_reverse
repeat = 0                       # zero for ever

[slices.hitbox]                  # a rect on a frame, in the frame's own pixels
rect = [8, 4, 16, 28]
# center = [4, 4, 8, 20] and pivot = [8, 14] make it a nine-patch with a pivot;
# keys = [...] when the slice moves between frames

state_machine

Contents

Files live in animations/. Used by state_machine · machine.

Switches an animation player between clips. start is the first state, [states] maps states to clips or to nested machines, each [[transitions]] entry names from, to, blend_time, ease or blend_curve, advance_mode, switch_mode, condition, check, priority, reset and break_loop_at_end. A transition to end stops the machine until a travel or a jump.

type = "state_machine"
start = "idle"

[states]                         # state = clip in the player's library; "" is the state's own name
idle = "idle"

[states.move]                    # a nested machine: its states are move/walk and move/run
start = "walk"
states = { walk = "", run = "run_cycle" }

[[transitions]]
from = "idle"
to = "move"                      # entering a nested machine enters its start
blend_time = 0.2                 # seconds
ease = "in_out_sine"             # the curve the blend follows; linear by default
advance_mode = "auto"            # disabled, enabled (fires on state_machine.travel) or auto
switch_mode = "immediate"        # immediate, sync (keeps the playhead) or at_end
condition = "moving"             # turned on by animation.set_condition
check = "can_move"               # a script method that has to answer true, asked each frame
priority = 1                     # lower wins among auto transitions and on travel
reset = true                     # false resumes where the state was last left
break_loop_at_end = false        # true holds a looping clip's end while it blends out

[[transitions]]
from = "move"                    # leaves from any state inside the nested machine
to = "end"
blend_curve = [[0.0, 0.0], [0.3, 0.8], [1.0, 1.0]]   # [u, weight] points, in place of ease

text_style

Contents

Files live in text_styles/. Used by text2d · text_style, text3d · text_style, widget · text_style.

How a text is dressed past its font: the space between its lines and its glyphs, the lines drawn with them, an outline and a shadow. text2d, text3d and a widget name one in their text_style row, or write one inline:

type = "text_style"
outline_size = 2.0
shadow_offset_y = 3.0

texture

Contents

Files live in textures/. Used by boolean2d · texture, boolean3d · texture, line2d · texture, mesh · texture, multimesh2d · texture, multimesh3d · texture, particles2d · texture, particles3d · texture, polygon · texture, shape2d · texture, shape3d · texture, sprite · texture.

An image and the import settings it is read with. A texture property takes a plain image path, which reads the image with its sidecar; this is for one use of a picture that reads it differently. Any key the image's sidecar takes may be written here, and wins over it.

type = "texture"
source = "art/hero.png"
filter = "nearest"                # this use crisp, the sidecar's smooth
pixels_per_unit = 32

tileset

Contents

Files live in tilesets/. Used by tilemap · tileset.

An image cut into equal tiles for tilemap: texture, tile_size in pixels and columns per row. [tiles.<id>] gives a tile collision; [[terrains]] auto-tiles by kind.

type = "tileset"
texture = "art/dungeon.png"
tile_size = 16                   # or [w, h]
columns = 8
spacing = 0                      # gutter between tiles
margin = 0                       # border around the sheet

[tiles.3]                        # tile ids count row by row from the top left
collision = "full"

[tiles.7]
collision = [[[0, 16], [16, 16], [16, 8]]]   # polygons in tile pixels, y down
one_way = true                   # a platform a body passes through from below

[[terrains]]                     # paints by value and picks the tiles
name = "grass"
value = 1
kind = "quarters"                # rules, sides, corners, corners_and_sides or quarters
first_tile = 16
# quarters = [fill, horizontal edge, vertical edge, outer corner, inner corner] tile ids, when they do not follow first_tile

voxels

Contents

Files live in voxels/. Used by no component property yet.

A voxel grid for a collider: size is one cell in world units, cells the filled coordinates. physics3d.set_voxel adds or removes a cell.

[[assets]]
id = "pillar"
type = "voxels"
size = [1.0, 1.0, 1.0]
cells = [[0, 0, 0], [0, 1, 0], [0, 2, 0]]   # signed coordinates

widget_theme

Contents

Files live in themes/. Used by widget · theme.

How each widget kind is drawn, one table per kind. [colors], [sizes] and [fonts] hold the tokens every table may name, and [roles.<name>] is a look a widget picks with role. Seven source colours and four sizes derive every other token; a token the file states wins.

type = "widget_theme"            # a widget takes the theme of the nearest ancestor naming one

[colors]                         # the sources; bg_panel, text_muted, primary_fill, ... derive from them
background = "#151f2a"           # dark or light follows from it; `dark = true` overrides
foreground = "#e6e9ee"
primary = "#4287cc"              # also secondary, success, warning, danger
contrast = 0.05                  # how far apart the surfaces step
row_selected = "#2f6fb0"         # a picked row of a `list`, `tree` or `table`
row_selected_text = "#ffffff"    # and the ink on it
row_hover = "#ffffff12"          # what a row takes under the pointer; `row_active` while held
row_stripe = "#ffffff08"         # a table's every other row; "#00000000" hides it
table_header = "#ffffff08"       # a table's header plate
table_rule = "#00000000"         # the lines down its columns, hidden here
tree_guide = "#8a8a8a8c"         # the lines down a tree's indent

[sizes]                          # font_size, radius, control_height, stroke_width; the rest derive
font_size = 16                   # font_size_small, font_size_large and font_size_title follow
radius = 6                       # radius_small and radius_large follow

[fonts]                          # fonts by name; `default` is every text naming none, `icon` the glyphs
default = "fonts/Inter-Regular.ttf"  # a widget draws beside its caption, `heading` and `mono` egui's own
heading = "fonts/Inter-Semibold.ttf"

[button]                         # one table per kind: [panel], [row], ...; a kind left out keeps the built-in look
fill = "primary_fill"
stroke = "border_default"
stroke_width = 1.0
corner_radius = "radius_large"   # a number, a size's name, or "full" for a pill
padding = 8.0                    # or per side, [left, top, right, bottom]
gap = 4.0
font_size = "font_size_large"
text_color = "text_on_primary"
icon_color = "text_on_primary"
font = "heading"                 # a name [fonts] gives a font, or a font itself
font_weight = 700
text_align = "center"            # start, center or end
cursor = "hand"                  # the pointer over it, a cursor word; a node's own wins

[button.hover]                   # under the pointer; [button.active] while held, [button.focus] with
                                 # keyboard focus, [button.disabled] while off, [button.checked] while on
fill = "primary_fill_hover"

[panel]
image = "art/panel.png"          # a nine-patch, sliced in its own pixels
slice = [8, 8, 8, 8]             # left, top, right, bottom

[table]                          # a row view is dressed like any other kind
fill = "bg_control"
stroke = "border_default"
corner_radius = 6.0
padding_x = 10.0                 # the air either side of a cell's text

[fold]                           # the header; [fold.checked] while open
arrow = "art/folded.png"         # the header's arrow picture; the ▸ and ▾ glyphs where none

[fold.body]                      # the frame around what an open fold shows
fill = "bg_panel"
padding = 8.0

[roles.card]                     # any table may carry a gradient and a shadow
gradient = { kind = "linear", stops = ["primary_fill", "bg_panel"], angle = 90 }  # in place of fill; 0 runs left to right
# kind = "radial" with center = [0.5, 0.5] and radius = 0.5 runs out from the middle; at = [0, 0.3, 1] places three stops
shadow = { y = 2, blur = 8, spread = 0, color = "#00000040" }     # a blurred box under it; x too

[roles.danger]                   # what a widget with role = "danger" takes
fill = "danger_fill"
text_color = "text_on_danger"

animation

Contents

Clip playback on a node's animation component: play, pause, seek and query. tween builds a short clip from a table of steps and returns a handle.

19 functions, 79 constants. Scripts reach it as animation::.

Acts on animation, state_machine: those functions are also methods on the component's handle, without the node argument.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
add_clip(Node, string, animation::Clip) animation Give this node a clip of its own under that name, shaped like a scene file's.
current_clip(Node) -> str? animation The clip playing or paused on this node, and nil once it has ended, been stopped, or never started.
current_state(Node) -> str? state_machine The state the machine is in, or nil before it has entered one.
ease(string, float) -> float — The named curve at t, from 0 to 1: what a tween's ease does to its progress, for a number a script moves itself.
ease_names() -> [str] — Every curve an ease takes, by name: the bare linear, then eleven transitions in four modes each.
is_playing(Node) -> bool animation Whether a clip is advancing on this node; a paused, stopped, finished or absent one answers false.
is_tween_running(int) -> bool — Whether a handle still names a running tween; one that finished, was stopped, or lost its node answers false. Takes a tween handle, where is_playing takes a node and asks about its clip.
jump(Node, string) state_machine Cut the state machine to the named state on the next step, with no fade.
pause(Node) animation Hold the playhead where it is, keeping the clip current so resume has something to go back to.
play(Node, string, animation::PlayOptions?) animation Start the clip of that name on this node; the trailing options table takes speed_scale (a multiplier), from_start, blend_time (seconds to blend out of the clip before), ease (the blend's curve, an EASE_* constant), and retarget (a bone_map reference, so this rig can play another rig's clips).
queue(Node, string) animation Play the clip of that name once the current one ends; a looping clip never ends, so a queue behind one never drains.
resume(Node) animation Carry on from where pause left off; a stopped, finished or never-started node is left alone.
seek(Node, float) animation Move the playhead to a number of seconds and pose the node there, even on a paused or ended clip.
set_condition(Node, string, bool) state_machine Turn on or off a condition that auto transitions wait on.
stop(Node) animation End the clip on this node, leaving the pose where it is; resume cannot revive it.
stop_tween(int) — End the tween a handle names, leaving the pose where it is.
time(Node) -> float animation Seconds of playback since the current clip started, before wrapping; a stopped clip keeps where it stopped.
travel(Node, string) state_machine Head for the named state through the cheapest chain of transitions, each costing its priority and fading as it says; a state no transition reaches is cut to directly.
tween(Node, animation::Tween) -> int — Generate a clip on the node from a table of steps and run it, returning the handle stop_tween and is_tween_running take. The table also takes delay in seconds, then = <handle> to wait for another tween, loops and speed_scale; a step's call names a method; the node's on_tween_finished(handle) is called when it runs out.

Constants

name value
ADVANCE_MODE_AUTO "auto"
ADVANCE_MODE_DISABLED "disabled"
ADVANCE_MODE_ENABLED "enabled"
EASE_IN_BACK "in_back"
EASE_IN_BOUNCE "in_bounce"
EASE_IN_CIRC "in_circ"
EASE_IN_CUBIC "in_cubic"
EASE_IN_ELASTIC "in_elastic"
EASE_IN_EXPO "in_expo"
EASE_IN_OUT_BACK "in_out_back"
EASE_IN_OUT_BOUNCE "in_out_bounce"
EASE_IN_OUT_CIRC "in_out_circ"
EASE_IN_OUT_CUBIC "in_out_cubic"
EASE_IN_OUT_ELASTIC "in_out_elastic"
EASE_IN_OUT_EXPO "in_out_expo"
EASE_IN_OUT_QUAD "in_out_quad"
EASE_IN_OUT_QUART "in_out_quart"
EASE_IN_OUT_QUINT "in_out_quint"
EASE_IN_OUT_SINE "in_out_sine"
EASE_IN_OUT_SPRING "in_out_spring"
EASE_IN_QUAD "in_quad"
EASE_IN_QUART "in_quart"
EASE_IN_QUINT "in_quint"
EASE_IN_SINE "in_sine"
EASE_IN_SPRING "in_spring"
EASE_LINEAR "linear"
EASE_OUT_BACK "out_back"
EASE_OUT_BOUNCE "out_bounce"
EASE_OUT_CIRC "out_circ"
EASE_OUT_CUBIC "out_cubic"
EASE_OUT_ELASTIC "out_elastic"
EASE_OUT_EXPO "out_expo"
EASE_OUT_IN_BACK "out_in_back"
EASE_OUT_IN_BOUNCE "out_in_bounce"
EASE_OUT_IN_CIRC "out_in_circ"
EASE_OUT_IN_CUBIC "out_in_cubic"
EASE_OUT_IN_ELASTIC "out_in_elastic"
EASE_OUT_IN_EXPO "out_in_expo"
EASE_OUT_IN_QUAD "out_in_quad"
EASE_OUT_IN_QUART "out_in_quart"
EASE_OUT_IN_QUINT "out_in_quint"
EASE_OUT_IN_SINE "out_in_sine"
EASE_OUT_IN_SPRING "out_in_spring"
EASE_OUT_QUAD "out_quad"
EASE_OUT_QUART "out_quart"
EASE_OUT_QUINT "out_quint"
EASE_OUT_SINE "out_sine"
EASE_OUT_SPRING "out_spring"
EVENT_ANIMATION_CHANGED "animation_changed"
EVENT_ANIMATION_FINISHED "animation_finished"
EVENT_ANIMATION_LOOPED "animation_looped"
EVENT_ANIMATION_STARTED "animation_started"
EVENT_STATE_ENTERED "state_entered"
EVENT_STATE_EXITED "state_exited"
EVENT_TWEEN_FINISHED "tween_finished"
EVENT_TWEEN_LOOPED "tween_looped"
EVENT_TWEEN_STEP "tween_step"
INTERPOLATION_CUBIC "cubic"
INTERPOLATION_LINEAR "linear"
INTERPOLATION_STEP "step"
LOOP_LINEAR "linear"
LOOP_NONE "none"
LOOP_PINGPONG "pingpong"
MODIFIER_CCDIK "ccdik"
MODIFIER_FABRIK "fabrik"
MODIFIER_JIGGLE "jiggle"
MODIFIER_LOOK_AT "look_at"
MODIFIER_TWO_BONE_IK "two_bone_ik"
PROPERTY_DEFORM "polygon/deform"
PROPERTY_POSITION "position"
PROPERTY_ROTATION "rotation"
PROPERTY_ROTATION_EULER "rotation_euler"
PROPERTY_SCALE "scale"
PROPERTY_TINT "tint"
PROPERTY_VISIBLE "visible"
STATE_END "end"
SWITCH_MODE_AT_END "at_end"
SWITCH_MODE_IMMEDIATE "immediate"
SWITCH_MODE_SYNC "sync"

apple

Contents

Apple services beyond platform.*: Game Center identity, purchases, notifications. Calls answer task::wait on a later tick as a map whose kind is an EVENT_* constant. What arrives unasked is the apple_event event, events::listen(node, "apple_event"): a notification tapped or shown in front, a push and its payload, a URL opened, an invite, an iCloud change, a transaction that landed elsewhere.

18 functions, 25 constants. Scripts reach it as apple::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
access_point(bool, apple::AccessPointOptions?) -> bool — Show or hide Game Center's floating access point, and answer whether it is showing.
available() -> bool — Whether this build has Apple's frameworks behind it.
cancel_notification(string) — Drop a scheduled notification, and take a delivered one out of the shade.
credential_state(string) -> int — Ask whether a saved Sign in with Apple account is still authorized, revoked, transferred or unknown, and return the id the answer carries.
entitlements() -> int — What this player currently owns: returns the id whose entitlements answer holds them as items, each a Transaction.
finish_purchase(string) -> int — Tell StoreKit a transaction is dealt with, and return the id its finished answer carries. One that is never finished comes back on every launch.
identity() -> int — Fetch the items a server needs to verify this Game Center player, and return the id the answer carries.
listen_for_cloud_changes() -> bool — Hear about another device changing the iCloud key-value store, as cloud_changed with the reason and the keys it touched.
listen_for_invites() -> bool — Hear about Game Center invites the player accepts, as invite_accepted with the sender's player id and name, and matches they ask for, as match_requested with the players.
listen_for_urls() -> bool — Hear about URLs the game is asked to open. A URL the game was launched with arrives the same way, once the engine is up.
notify(string, apple::NotifyOptions?) -> int — Schedule a local notification, and return the id its scheduled answer carries.
products([str]) -> int — Ask the App Store about a list of product ids, and return the id whose products answer holds what it knows, each a Product.
purchase(string) -> int — Buy a product, and return the id its answer carries: purchased, cancelled or pending, and a purchase carries the signed jws a server checks.
register_for_push() -> bool — Ask the OS for a push token. It arrives as the apple_event event, not at the caller, because the OS hands it over whenever it likes.
request_notifications() -> int — Ask the player to allow notifications, and return the id whose notifications answer says what they said.
restore_purchases() -> int — Ask the App Store to hand this device's purchases back, the button a review expects a game to have, and return the id its restored answer carries.
show_dashboard(apple::ShowDashboardOptions?) -> int — Open Game Center's dashboard over the game, and return the id its dashboard_closed answer carries.
sign_in() -> int — Sign in with Apple, and return the id the identity token comes back on. Game Center's own sign-in is platform.sign_in.

Constants

name value
EVENT_CANCELLED "cancelled"
EVENT_CLOUD_CHANGED "cloud_changed"
EVENT_CREDENTIAL_STATE "credential_state"
EVENT_DASHBOARD_CLOSED "dashboard_closed"
EVENT_ENTITLEMENTS "entitlements"
EVENT_ERROR "error"
EVENT_FINISHED "finished"
EVENT_IDENTITY "identity"
EVENT_INVITE_ACCEPTED "invite_accepted"
EVENT_MATCH_REQUESTED "match_requested"
EVENT_NOTIFICATIONS "notifications"
EVENT_NOTIFICATION_OPENED "notification_opened"
EVENT_NOTIFICATION_RECEIVED "notification_received"
EVENT_PENDING "pending"
EVENT_PRODUCTS "products"
EVENT_PURCHASED "purchased"
EVENT_PUSH_FAILED "push_failed"
EVENT_PUSH_RECEIVED "push_received"
EVENT_PUSH_TOKEN "push_token"
EVENT_RESTORED "restored"
EVENT_SCHEDULED "scheduled"
EVENT_SIGNED_IN "signed_in"
EVENT_TRANSACTION "transaction"
EVENT_UNSUPPORTED "unsupported"
EVENT_URL "url"

assets

Contents

Asset definitions by reference: a project path, file#entry for one entry, #id for a scene block, or id://<id> from assets/index.toml. A script gets the definition table.

9 functions, 0 constants. Scripts reach it as assets::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
directory(string) -> string — The project-relative directory files of an asset type belong in; empty when the type is unknown or declared none.
exists(string) -> bool — Whether a reference resolves to a definition that is really there; false rather than an error when it does not.
invalidate() — Declare everything derived from project files stale (a shader a material links, say) so it is rebuilt from disk; for a file the watcher does not cover. A script hears this and every reload with events::listen(this.node, "assets_reloaded"), as on_assets_reloaded(generation).
kind_of(string) -> string — Which importer kind a file is by its extension — texture, audio, font or model — or empty for one none claims. A .ttf, .otf, .ttc or .fnt is a font.
load(string) -> any — The definition table behind a reference, from the cache: the script's own copy, so editing it disturbs no other holder. An error when the reference resolves to nothing; reload first for a fresh read of the file.
reload(string) — Forget a reference so the next load re-reads its file, along with every entry cut from that same file.
rename(string, string) -> [str] — Move a file or directory and rewrite every reference to it in the project's .toml files, comments kept; answers the files rewritten. Paths as fs.* takes them, so an editor refactors the game it has open by absolute path. Script sources are not rewritten: a path in a .bs is the script's own value, and id:// is the reference that survives a move.
save(string, any) — Write a definition table to the project-relative file a reference names; an error unless it names a whole file.
schema(string) -> any — The properties a record asset type holds, in the order it writes them; nil for a type that is not a record.

audio

Contents

Sound playback: play starts a node's sound component and returns a handle that is_playing takes; seek and skip move it, and the node's sound properties change it as it plays. play_file plays a file on a node of its own, from a position heard from the listener when given one. A node's sound announces sound_finished (EVENT_SOUND_FINISHED) with the handle when it plays out. devices lists the outputs [audio] device can name.

19 functions, 1 constant. Scripts reach it as audio::.

Acts on sound: those functions are also methods on the component's handle, without the node argument.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
bus_effects(string) -> audio::BusEffects? — One bus's effects as [audio.buses] declares them, applied once to everything the bus mixes. Built when the output device opens, as the limiter is. Nil for a bus with none switched on.
bus_limit(string) -> audio::BusLimit? — One bus's limiter as [audio.buses] declares it. Nil for a bus with none.
bus_volume_linear(string) -> float — One bus's own gain, without its parents'.
buses() -> [str] — Every audio bus, declared in [audio.buses] or made by setting a volume, in name order.
device_ready() -> bool — Whether an output device is open. False on a page until the first gesture, and false for good with no sound card; playing before then hands out handles that make no sound. Recorded: a replay answers what its recording did, whatever the machine it runs on has.
devices() -> [str] — Every output device's name, as [audio] device takes it. Empty when the platform lists none. Recorded, as device_ready is.
distance_gain(int) -> float? — The gain the distance to the listener is costing a positional handle right now: 1 up close, 0 out of range.
emitter_position(int) -> Vec3? — Where a handle played with a position is; nil for a flat or unknown one.
is_playing(int) -> bool — Whether a handle's sound is still going: false once it plays out or is stopped, on the same tick with or without an output device.
listener_position() -> Vec3 — Where the ears are: the current listener node's world position, else the current camera's.
pan(int) -> float? — Where a positional handle sits between the speakers: -1 hard left, 0 centred, 1 hard right.
play(Node) -> int sound Start the node's own sound from the top, replacing what it had going, and return the new handle.
play_file(string, audio::PlayFileOptions?) -> Node — Play a sound file on a node of its own under the scene's root, through bus at volume_linear and pitch_scale, looping when loop is true; a position places it, heard from the listener over min_distance to max_distance. Returns the node, which frees itself once the sound plays out: free it to stop the sound, or set its sound to change it.
seek(Node, float) sound Jump the node's sound to seconds into the file it is playing; playback_time reads it back. A node with nothing playing is left alone.
set_bus_volume_linear(string, float) — Set one bus's gain and re-apply it to everything already playing on it: which is what a volume slider is.
set_emitter_position(int, Vec3) — Move what a handle plays from, so a sound follows something the script is driving; the frame takes its doppler from how far it moved.
skip(Node) sound Move the node's sound on to the next file in its queue. Past the last one it has played out, and the node announces sound_finished.
stop(Node) sound Silence what the node's sound started, over its fade_out_time; a node carrying none is left alone.
stop_all() — Silence everything at once and clear the playback every sound component was holding.

Constants

name value
EVENT_SOUND_FINISHED "sound_finished"

browser

Contents

The page a browser build runs in; off the web every query answers nil. A parent-frame message is the browser_event event: events::listen(node, "browser_event"), heard as on_browser_event(payload).

5 functions, 0 constants. Scripts reach it as browser::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
hardware_concurrency() -> int? — How many threads the browser reports, or nil off the web.
location() -> str? — The page's URL, or nil off the web.
post_message(any) -> bool — Post a value to the page that embeds this one. False off the web, and false while a recording plays.
user_agent() -> str? — The browser's user agent string, or nil off the web.
visible() -> bool — Whether the tab is in front of the player; true off the web.

debugger

Contents

Breakpoints, pausing a script and resuming it. The editor's Debugger dock and the Debug Adapter Protocol server drive the same machinery. The editor has this module; a game's runtime does not.

9 functions, 4 constants. Scripts reach it as debugger::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
break_on_error() -> bool — Whether a script that throws stops rather than being logged.
breakpoints(string) -> [int] — The lines one file's breakpoints landed on.
request_break() — Ask to stop at the next line any script runs; nothing is stopped yet when it returns.
resume(str?) — Let the stopped script go on, in the given step mode (CONTINUE, STEP_OVER, STEP_INTO, STEP_OUT).
scope() -> Node — The node whose subtree a pause holds still, or nil when a pause stops the whole tree.
set_break_on_error(bool) — Stop where a script throws instead of logging it and moving on; off by default.
set_breakpoints(string, [int]) -> [int] — Replace one file's breakpoints with the given lines, returning the lines they landed on.
set_scope(Node?) — Limit the pause to one node's subtree, so an editor keeps running while the game stops; nil means the whole tree.
stop_location() -> debugger::Stop? — Where a script is stopped, or nil while none is. A script hears a stop with events::listen(this.node, "debugger_stopped"), as on_debugger_stopped(stop), and the script going on as debugger_resumed, rather than asking every frame.

Constants

name value
CONTINUE "continue"
STEP_INTO "into"
STEP_OUT "out"
STEP_OVER "over"

dependency

Contents

The projects a game imports whole under deps/<alias>/, declared in [dependencies]. An installed dependency is read-only: fs.* and assets.save refuse to write into one. A relative path a dependency's script builds reads from that dependency's own folder. Every runtime has list and of; the verbs that write a project are the editor's.

6 functions, 0 constants. Scripts reach it as dependency::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
add_path(string, string, string) — Declare alias = { path = "<path>" } in a game's [dependencies], comments kept, and install it. An empty game is the open project.
install(string) — Read a game's [dependencies] again and install each: what a dependency fetched while the editor runs needs to become a root. An empty game is the open project.
list() -> [dependency::Dependency] — Every installed dependency: its alias, where it sits, where it came from and its licence.
make_local(string, string) -> [str] — Copy a dependency's file into the game and point the game's references at the copy; answers the game's files rewritten. The copy never updates. A document's own paths come out as the game names the dependency's files.
move_into([str], string) -> [str] — Move game files into a path dependency, each at the same place under its root, and point the game's references at deps/<alias>/…; answers the files rewritten.
of(string) -> str? — The alias of the dependency a path lies in, or nil for one of the game's own.

encoding

Contents

Bytes to base64 text and back, and UTF-8 bytes back to text.

3 functions, 0 constants. Scripts reach it as encoding::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
base64([int]) -> string — Bytes as standard base64 with padding; a value outside 0 to 255 traps.
from_base64(string) -> [int] — The bytes a base64 string encodes, in the standard alphabet with its padding; text that is not base64 traps.
from_utf8([int]) -> str? — The text UTF-8 bytes spell; nil when they are not UTF-8, a value outside 0 to 255 included.

engine

Contents

The running app: its clock, command-line args, user_data_dir, loaded plugins, quit, and store for state no node owns.

31 functions, 0 constants. Scripts reach it as engine::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
args() -> [str] — The command-line arguments the app was started with, empty when it was given none.
dark_mode() -> bool — Whether the system is in dark mode this tick; every script's on_dark_mode_changed(bool) is called when it changes. False where nothing says.
delta() -> float — Seconds the frame in progress covers, the same number a system is handed.
device_id() -> string — One id per install, made on first use and kept in the user directory: what a device login sends. Recorded with the session.
environment(string) -> str? — An environment variable's value, nil when it is unset. Nil on the web, which has none. Outside the simulation, like args: a replay does not record it.
focused() -> bool — Whether the window is in front of the player this tick; every script's on_focused_changed(bool) is called when it changes. True with no window.
function_costs() -> [engine::FunctionCost] — What each function has cost since set_script_profiling(true), dearest first: a list of { function, calls, instructions }, a function's own statements without its callees'. A function of a module two files use counts once for the two.
open_url(string) — Open an http, https or mailto URL in whatever the player browses with: an opener on a desktop, a new tab on the web, the browser on a phone. An effect on the world outside the game: never recorded, and it does nothing while a recording plays.
paused() -> bool — Whether the game is paused.
plugin_version(string) -> str? — The version of one loaded plugin, or nil when it did not load: how a game shipped without http says so rather than call into a module that is not there.
plugins() -> [str] — Every plugin this build loaded, named, in load order.
quit(int?) — Ask the app to shut down; the frame in flight still finishes, and the process exits with code, 0 when left out.
reload_scripts([str]) -> string — Recompile scripts by their project-relative keys in one build, however many there are, for a tool editing files outside the watched root; answers what kept them from compiling, empty when they did.
reveal(string) — Show a file or directory in the system file manager, selected where the platform can. Desktops only: neither a browser tab nor a phone has a file manager to ask. Never recorded, like open_url.
script_costs() -> [engine::ScriptCost] — What each script has cost since set_script_profiling(true), dearest first: a list of { path, calls, instructions }, calls the engine's calls into it. A file counts the statements it ran: not seconds, so the number is the same on every machine.
set_content_root(string) — Play the content of the project at root: its strings/ catalogues and its fonts/ are read from there, and the subtree debugger.set_scope names draws in them. For a host running a project other than its own: the editor, whose own root has neither. An empty string plays the project's own again.
set_paused(bool) — Pause or resume the game. Every node whose process mode is pausable stops ticking, physics holds both worlds, and the frame loop keeps drawing; an always subtree is what a pause menu runs in. Every script's on_paused_changed(bool) follows, the ones the pause just stopped included.
set_script_profiling(bool) — Start or stop counting what each script costs. Turning it on clears the tally; on from off, or off from on, rebuilds every Balaur Script file between frames, with counters or without, carrying its fields across.
set_time_scale(float) — Multiply wall-clock time before the simulation is owed it: 0.5 is slow motion, 2.0 fast forward, each still whole fixed steps. Zero stops time without stopping a single node. A replay and a networked session drive by tick and ignore it.
store(string, any) — Keep any value under a key for as long as the app runs: state no node owns, like a class's static variable.
stored(string) -> any — What store kept under a key; nil when nothing was.
target() -> engine::Target — Where this runs: { os, web, mobile, touchscreen, editor, dev }, dev being a run from the sources rather than an exported pack. Recorded in a session's header, so a replay on another machine answers as the original did.
tick() -> int — Which frame this is, counted whole: what simulation code branches on instead of time.
tick_hz() -> int — How many fixed steps a second this run takes, from [time] tick_hz. 60 unless the project says otherwise.
time() -> float — Seconds of engine time since the app started, accumulated as a float.
time_scale() -> float — What time is being multiplied by; 1.0 is real time.
timings() -> engine::Timings? — What the last frame cost, in seconds: { frame, fixed_steps, stages, spans }. Presentation only: branching a fixed_update on wall time desyncs, and nothing records it.
unix_time() -> float — The wall clock at the top of this tick, in seconds since 1970. Read once per frame and recorded, so a replay sees the time the recording saw.
user_data_directory() -> string — A writable per-user directory for saves and settings, created on first call and named after the project. A game the editor plays answers with its own, the folder it has when run alone.
user_data_directory_of(string) -> string — The user data directory a project of that name has, not created: where a tool finds another game's saves and logs.
watch(string, [str]) -> bool — Follow a directory outside the project the way a run follows the project: a script loaded from it hot reloads when its file changes. A script hears each burst of changes once with events::listen(this.node, "files_changed"), as on_files_changed(paths), each path spelled from directory and with one of extensions, or any file when that is empty. An empty list is more than the watcher could name, so what is held has to be checked again. Answers false where nothing can be followed: a pack, a browser, a run with watching off. The directory has to be one fs may reach.

events

Contents

Named events between scripts. A node hears its own events, and after listen another node's, as its on_<name>(payload, source) method; node.emit and events.emit send one.

4 functions, 0 constants. Scripts reach it as events::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
emit(string, any) — Queue an event from no particular node, delivered at the top of the next frame's update to whoever listens for the name from anyone.
listen(Node, string, Node?) — Hear an event on this node, as its script's on_<name>(payload, source), source being the node that said it, or nil for one said from no node. Pass the node whose events to hear, or leave it out for every emitter. Listening twice is once.
next(string, Node?) -> int — A token for task.wait that wakes, with the payload, the next time the name is delivered from that node or, left out, from anyone: let payload = task::wait(events::next("finished", door)).await;, a GDScript await door.finished.
stop_listening(Node, string, Node?) — Stop hearing an event on this node, from being the emitter it listened with. Not an error when it never listened.

export

Contents

Exports the project being edited. targets lists what this install can build; start runs one off the frame and reports as the export_event event: events::listen(node, "export_event"), heard as on_export_event, as each export starts, finishes or fails.

5 functions, 0 constants. Scripts reach it as export::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
output(string) -> string — Where an export for this target will be written, as the project's [export] output decides.
preview(string, string) -> export::Preview? — What one file becomes in a target's pack, as the Import tab shows it: { source, before, after, width, height, drawn_width, drawn_height, gpu_bytes }, where source is the file or the variant that ships and drawn_* is zero unless a smaller copy does. Nil when the file does not ship there. An empty target is this machine's own.
running_count() -> int — How many exports are in flight.
start(string, export::StartOptions?) -> bool — Export the edited project for one target, on a thread. download allows fetching a missing template, sign names an identity, output overrides where it lands. Answers false while a recording plays.
targets() -> [export::Target] — Every target, each { name, runtime, bundle, installed, fetchable, note }: the runtime the project's [export] runtime puts it on, whether that is already here, whether a missing one could be fetched, and what a signed build of it would also need.

forge

Contents

Projects kept on Forge, for the editor's pickers, and adding one to a game as a dependency. balaur add and balaur fetch are the same code. BALAUR_FORGE names the Forge and BALAUR_FORGE_TOKEN reads private projects.

5 functions, 0 constants. Scripts reach it as forge::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
add(string, string) -> bool — Add owner/name to the game's [dependencies] and fetch it into deps/<alias>/, on a thread. forge_event hears { kind: "fetched", alias } or failed with job: "add".
copy(string, string) -> bool — Copy owner/name at its default branch into a new folder under parent, with its dependencies fetched, on a thread: the project manager's Open a copy. forge_event hears { kind: "copied", path } or failed with job: "copy".
fetch(string, bool) -> bool — Fill the game's deps/ from project.lock, or with update move each dependency to its newest commit, on a thread. forge_event hears { kind: "fetched", alias: "" } or failed with job: "fetch".
search(string, string) -> bool — List public projects on a thread, either filter empty for none. forge_event hears { kind: "listed", rows }, each { project, description, tags, license } with project as owner/name, or { kind: "failed", job: "search", message }. False while a recording plays.
url() -> string — The Forge this machine asks, without a trailing slash.

fs

Contents

Files on disk, project-relative unless the path is absolute. In a packed build read, exists and list reach what the pack holds.

9 functions, 0 constants. Scripts reach it as fs::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
copy(string, string) — Copy a file byte for byte, creating the destination's parent first. What read and write cannot do for an image or a model.
create_directory(string) — Create a project-relative directory and every parent it needs.
exists(string) -> bool — Whether a project-relative path has anything at it, file or directory.
list(string) -> [fs::Entry] — A directory's entries as { name, is_dir }, sorted, dotfiles skipped; empty for a directory that is not there.
modified_time(string) -> float? — When a file last changed, in seconds since the Unix epoch; nil for one that is not there.
read(string) -> str? — A whole file as text, project-relative unless absolute and found inside the pack in a packed run; nil when it cannot be read.
remove(string) -> bool — Delete a project-relative file, or a directory and everything under it; false when there was nothing there.
rename(string, string) — Move a project-relative file or directory, creating the destination's parent first.
write(string, string) — Write text to a project-relative file, creating the directory it goes in. The text lands in a file beside it, synced, then renamed over it, so a crash mid-write keeps the old file whole.

geometry2d

Contents

Polygons on the plane as lists of Vec2 points in outline order: triangulation, booleans, hulls and containment. Every answer is identical on every platform.

11 functions, 0 constants. Scripts reach it as geometry2d::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
area([Vec2]) -> float — The polygon's area, always positive whatever its winding.
contains([Vec2], Vec2) -> bool — Whether a point lies inside the polygon. A point exactly on an edge may answer either way.
convex_decomposition([Vec2], geometry2d::DecompositionOptions?) -> [[Vec2]] — The polygon cut into convex pieces that overlap across their seams, so nothing wedges into one; overlap from 0 to 1 says how far each piece grows, 0.9 by default.
convex_hull([Vec2]) -> [Vec2] — The smallest convex polygon around the points, counter-clockwise.
difference([Vec2], [Vec2], geometry2d::BooleanOptions?) -> [[[Vec2]]] — Everything inside the first polygon and outside the second, shaped and tuned as union is.
intersection([Vec2], [Vec2], geometry2d::BooleanOptions?) -> [[[Vec2]]] — Everything inside both polygons, shaped and tuned as union is.
is_clockwise([Vec2]) -> bool — Whether the points run clockwise, with y up.
segments_intersect(Vec2, Vec2, Vec2, Vec2) -> Vec2? — Where two segments cross, or nil when they do not; touching at an endpoint counts.
symmetric_difference([Vec2], [Vec2], geometry2d::BooleanOptions?) -> [[[Vec2]]] — Everything inside exactly one of the two polygons, shaped and tuned as union is.
triangulate([Vec2]) -> [[int]] — The polygon cut into triangles, as [i, j, k] triples indexing its points, counter-clockwise; either winding is accepted.
union([Vec2], [Vec2], geometry2d::BooleanOptions?) -> [[[Vec2]]] — Everything inside either polygon: a list of shapes, each a list of paths whose first is the outline and the rest holes. opts takes fill_rule (even_odd, non_zero, positive, negative; even_odd unless given), min_area, keep_collinear and clean_result, as boolean2d does.

geometry3d

Contents

Mesh operations: hulls, convex decomposition, voxelisation, cutting and boolean intersection, on a Mesh that load_mesh reads from an asset or a script builds.

7 functions, 0 constants. Scripts reach it as geometry3d::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
convex_decomposition(geometry3d::Mesh, geometry3d::DecompositionOptions?) -> [geometry3d::Mesh] — The mesh cut into convex pieces, each one a mesh: the only way to collide a concave shape dynamically.
convex_hull(geometry3d::Mesh) -> geometry3d::Mesh — The tightest convex shape containing every point: what a dynamic collider wants when the model is concave.
intersect(geometry3d::Mesh, geometry3d::Mesh) -> geometry3d::Mesh? — The mesh both meshes have in common, or nothing when they do not overlap.
load_mesh(string) -> geometry3d::Mesh — A mesh asset's points and triangles.
pieces(geometry3d::Mesh) -> [geometry3d::Mesh] — The mesh's separate parts, one mesh each: what a model that was already broken is made of.
split(geometry3d::Mesh, geometry3d::Plane) -> [geometry3d::Mesh?] — Cut the mesh with a plane, returning the two halves, nil for a half with nothing in it.
voxelize(geometry3d::Mesh, geometry3d::VoxelizeOptions?) -> geometry3d::Voxels — The mesh as a voxel grid (size and cells, ready to be a voxels asset) so a model can become destructible terrain.

hash

Contents

SHA-256 content hashes of files and strings.

2 functions, 0 constants. Scripts reach it as hash::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
sha256_file(string) -> string — The SHA-256 of a file as lowercase hex, read through the project's file roots; an absolute path is read as given.
sha256_text(string) -> string — The SHA-256 of a string as lowercase hex.

http

Contents

HTTP requests off the frame: method, headers, body, timeout_seconds and save_to options. task::wait on the id answers a map whose kind is response, with status, headers and body, or error; a save_to download reports as the http_progress event with kind progress, and a body over 256 KB going out with kind upload, natively; a browser's fetch does not report one. Each kind is an EVENT_* constant.

2 functions, 5 constants. Scripts reach it as http::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
cancel(int) -> bool — Stop waiting on a request: its reply is dropped, a download stops writing, and any await hears kind cancelled next frame. False when it had already finished.
request(string, http::RequestOptions?) -> int — Start an HTTP request and return the id task::wait answers its reply on. With save_to the body is written under the user directory and the reply says where in path.

Constants

name value
EVENT_CANCELLED "cancelled"
EVENT_ERROR "error"
EVENT_PROGRESS "progress"
EVENT_RESPONSE "response"
EVENT_UPLOAD "upload"

import

Contents

Imports a .glb or .gltf model, an .aseprite sprite, or a .tmx or .ldtk level into the project being edited, with the importers balaur import runs.

6 functions, 0 constants. Scripts reach it as import::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
cancel() — Stop the imports in flight at the end of the file each is writing. What they had written stays where it landed; each reports cancelled with the count it reached.
choose() -> bool — Ask the reader for a file and import what they pick, reporting as start does. On a desktop that is the OS dialog; in a tab it is the page's own chooser, which takes several files at once so a .gltf can be picked with the images it names. Answers whether the asking began.
file(string) -> import::Imported — Import one file into the edited project, in one call. A whole project is the work of seconds, so an editor keeping its frame wants start.
handles(string) -> bool — Whether an importer claims this file, by extension.
running_count() -> int — How many imports are in flight.
start(string, str?) -> bool — Import one file into the edited project, or into project when one is named, a few files per frame, each reported as the import_event event: events::listen(node, "import_event"), heard as on_import_event, as an import starts, writes each file, finishes or fails. Answers false while a recording plays. A model and a sprite are read first and then written a slice at a time; a level walks its own folder and takes one long slice, which says so in files.

input

Contents

One frame of input: keyboard, mouse, touch screen and gamepads, plus what went down or came up this frame. A headless run answers every query neutrally.

52 functions, 188 constants. Scripts reach it as input::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
action_down(string) -> bool — Whether the action is held down now.
action_just_pressed(string) -> bool — Whether the action went down this frame.
action_just_released(string) -> bool — Whether the action came up this frame.
action_value(string) -> float — How far the action is pushed, -1 to 1; a key answers 0 or 1, a stick or keys:KeyA,KeyD the whole range.
actions() -> [str] — Every action [input.actions] declares, so a rebinding screen can list them.
bind(string, [str]) — Rebind the action to a list of bindings, spelled as [input.actions] spells them, replacing what it had and saving to the user data directory.
bindings(string) -> [str] — What the action is bound to now, whether from the project or from the player's own rebinding.
composing() -> string — The text an input method is still composing, for a field to show under its caret; empty once it commits into typed, and always empty without an input method.
gamepad_acceleration(int) -> Vec3 — The pad's acceleration in g, gravity included, so a pad at rest reads 1 on one axis. Read from PlayStation pads on desktop; zero for a pad with no accelerometer.
gamepad_axis(int, string) -> float — How far the pad's GAMEPAD_AXIS_* stick or trigger is pushed: a stick -1 to 1 with up and right positive, a trigger 0 to 1, after [input] gamepad_deadzone; zero at rest and for an absent pad.
gamepad_can_rumble(int) -> bool — Whether the pad has motors to rumble; false for a pad that is not connected.
gamepad_down(int, string) -> bool — Whether the pad's GAMEPAD_BUTTON_* button is held down: pressed past [input] gamepad_press, and not yet back under gamepad_release.
gamepad_gyro(int) -> Vec3 — How fast the pad is turning, in radians per second about each axis. Read from PlayStation pads on desktop; zero for a pad with no gyroscope.
gamepad_info(int) -> input::GamepadInfo? — Who the pad is; nil for an absent pad.
gamepad_just_pressed(int, string) -> bool — Whether the pad's GAMEPAD_BUTTON_* button went down this frame; a press and a release between two frames are both seen.
gamepad_just_released(int, string) -> bool — Whether the pad's GAMEPAD_BUTTON_* button came up this frame; true for that one frame only.
gamepad_name(int) -> string — The pad's name: its mapping's when one matched, else the platform's. Empty when no pad has that id.
gamepad_power(int) -> input::GamepadPower — The pad's power. Read whenever the pad sends anything.
gamepad_pressure(int, string) -> float — How far the pad's GAMEPAD_BUTTON_* button is pressed, 0 to 1, before any deadzone: a digital button reads 0 or 1, a trigger or a pressure-sensitive button anything between.
gamepad_repeated(int, string) -> bool — True the frame the pad's GAMEPAD_BUTTON_* button goes down, then every [input] gamepad_repeat_interval_seconds once it has been held for gamepad_repeat_delay_seconds: for stepping through a menu.
gamepad_rumble(int, input::RumbleOptions?) -> bool — Rumble the pad. Options: strong and weak, the two motors at 0..1; duration in seconds; delay before it starts; pulse and gap to beat on and off; attack, attack_level, fade and fade_level to shape each pulse; position with min_distance, max_distance, falloff (inverse, linear or exponential) and rolloff to weaken it with distance from gamepad_set_listener. Returns whether the pad can rumble; a second rumble replaces the first.
gamepad_set_listener(int, Vec3) — Where the pad's player is, for a rumble given a position; until set, a placed rumble plays at full strength.
gamepad_stop_rumble(int) — Silence the pad now, without the on_gamepad_rumble_finished a rumble's natural end sends.
gamepad_touches(int) -> [input::Touch] — Every finger on the pad's touchpad, oldest first, with x and y running 0 to 1 across the surface. Read from PlayStation pads on desktop; empty for a pad with no touchpad.
gamepads() -> [int] — The ids of every connected pad: player slots from 0. A pad takes the lowest free slot last held by the same model, else the lowest free slot, and keeps it while connected.
key_down(string) -> bool — Whether the KEY_* key is held down right now, however many frames it has been down. KEY_SHIFT, KEY_CONTROL, KEY_ALT and KEY_META answer for either side.
key_just_pressed(string) -> bool — Whether the KEY_* key went down this frame; true for that one frame only.
key_just_released(string) -> bool — Whether the KEY_* key came up this frame; true for that one frame only.
keyboard_height() -> float — How much of the window the on-screen keyboard covers, in pixels from the bottom: what a form moves up by. Zero with no keyboard up, and always zero on a desktop.
long_press() -> Vec2? — Where a finger has been held still past long_press_seconds. Reported once per finger, on the frame the hold passes; nil otherwise.
mouse_delta() -> Vec2 — How far the cursor moved this frame, in pixels; movement, not a position.
mouse_down(int) -> bool — Whether the MOUSE_BUTTON_* button is held down right now, however many frames it has been down.
mouse_just_pressed(int) -> bool — Whether the MOUSE_BUTTON_* button went down this frame; true for that one frame only.
mouse_just_released(int) -> bool — Whether the MOUSE_BUTTON_* button came up this frame; true for that one frame only.
mouse_position() -> Vec2 — The cursor's position in window pixels, with (0, 0) at the top-left corner. A script hears it move with events::listen(this.node, "pointer_moved"), as on_pointer_moved([x, y]), and a button go down or up anywhere, the UI included, as pointer_pressed and pointer_released with { button, x, y }; the wheel turn as pointer_scrolled with [x, y], and two fingers as pointer_gestured with { scale, x, y, pan_x, pan_y }.
pan() -> Vec2 — Two or more fingers moving together: the average movement since last frame, in the same pixels as mouse_position. Zero with fewer than two down.
pinch() -> input::Pinch — Two fingers moving apart or together as { scale, center }: scale above 1 is apart, measured against last frame, and center is the point between them. Empty with fewer than two fingers down.
reset_bindings() — Drop every saved rebinding and go back to what the project declared.
scroll_delta() -> Vec2 — How far the wheel turned this frame, as an (x, y) pair; zero when it did not turn.
set_action_value(string, float) — Put a value into an action for one frame without a binding, the way a touch_button does; the furthest from rest wins where something else feeds the same action. Takes effect on the next tick, since actions derive at the top of one.
set_gamepad(int, input::GamepadReport) — Report a pad as if a backend had, from next frame. A pad fed anything connects; connected: false unplugs it.
set_key_down(string, bool) — Press or release a KEY_* key as if the window had reported it: next frame's edge, and the state until the opposite call.
set_mouse_down(int, bool) — Press or release a MOUSE_BUTTON_* button as if the window had reported it, from next frame.
set_mouse_position(Vec2) — Move the cursor to a window-pixel position as if the window had reported it, from next frame; the delta accumulates for that frame.
set_scroll_delta(Vec2) — Turn the wheel as if the window had reported it, from next frame; adds to that frame's scroll_delta.
set_touch(int, Vec2, string) — Put a finger on the screen as if the window had reported it: phase is start, move, end or cancel, and the position is in the same pixels as mouse_position.
swipe() -> input::Swipe? — A finger that travelled far enough before it lifted. Reported on the frame it lifted and never again; nil otherwise.
touches() -> [input::Touch] — Every finger on the screen, oldest first, in the same pixels as mouse_position.
touches_just_ended() -> [int] — The ids of the fingers that lifted or were cancelled this frame.
touches_just_started() -> [int] — The ids of the fingers that touched down this frame.
typed() -> string — The characters typed this frame, in order: what a text field appends, where key_just_pressed says which key went down.
vibrate(float) — Buzz the device for that many seconds: a phone's motor, or a page's navigator.vibrate. Nothing on a desktop, and never recorded, like rumble.

Constants

name value
GAMEPAD_AXIS_LEFT_TRIGGER "left_trigger"
GAMEPAD_AXIS_LEFT_X "left_x"
GAMEPAD_AXIS_LEFT_Y "left_y"
GAMEPAD_AXIS_RIGHT_TRIGGER "right_trigger"
GAMEPAD_AXIS_RIGHT_X "right_x"
GAMEPAD_AXIS_RIGHT_Y "right_y"
GAMEPAD_BUTTON_BACK "back"
GAMEPAD_BUTTON_C "c"
GAMEPAD_BUTTON_DPAD_DOWN "dpad_down"
GAMEPAD_BUTTON_DPAD_LEFT "dpad_left"
GAMEPAD_BUTTON_DPAD_RIGHT "dpad_right"
GAMEPAD_BUTTON_DPAD_UP "dpad_up"
GAMEPAD_BUTTON_EAST "east"
GAMEPAD_BUTTON_GUIDE "guide"
GAMEPAD_BUTTON_LEFT_SHOULDER "left_shoulder"
GAMEPAD_BUTTON_LEFT_STICK "left_stick"
GAMEPAD_BUTTON_LEFT_TRIGGER "left_trigger"
GAMEPAD_BUTTON_NORTH "north"
GAMEPAD_BUTTON_RIGHT_SHOULDER "right_shoulder"
GAMEPAD_BUTTON_RIGHT_STICK "right_stick"
GAMEPAD_BUTTON_RIGHT_TRIGGER "right_trigger"
GAMEPAD_BUTTON_SOUTH "south"
GAMEPAD_BUTTON_START "start"
GAMEPAD_BUTTON_WEST "west"
GAMEPAD_BUTTON_Z "z"
GAMEPAD_FALLOFF_EXPONENTIAL "exponential"
GAMEPAD_FALLOFF_INVERSE "inverse"
GAMEPAD_FALLOFF_LINEAR "linear"
GAMEPAD_MAPPING_DRIVER "driver"
GAMEPAD_MAPPING_SDL "sdl"
GAMEPAD_POWER_CHARGED "charged"
GAMEPAD_POWER_CHARGING "charging"
GAMEPAD_POWER_NO_BATTERY "no_battery"
GAMEPAD_POWER_ON_BATTERY "on_battery"
GAMEPAD_POWER_UNKNOWN "unknown"
KEY_0 "Digit0"
KEY_1 "Digit1"
KEY_2 "Digit2"
KEY_3 "Digit3"
KEY_4 "Digit4"
KEY_5 "Digit5"
KEY_6 "Digit6"
KEY_7 "Digit7"
KEY_8 "Digit8"
KEY_9 "Digit9"
KEY_A "KeyA"
KEY_ALT "Alt"
KEY_APOSTROPHE "Quote"
KEY_AUDIO_VOLUME_DOWN "AudioVolumeDown"
KEY_AUDIO_VOLUME_MUTE "AudioVolumeMute"
KEY_AUDIO_VOLUME_UP "AudioVolumeUp"
KEY_B "KeyB"
KEY_BACKQUOTE "Backquote"
KEY_BACKSLASH "Backslash"
KEY_BACKSPACE "Backspace"
KEY_BROWSER_BACK "BrowserBack"
KEY_BROWSER_FORWARD "BrowserForward"
KEY_BROWSER_HOME "BrowserHome"
KEY_BROWSER_REFRESH "BrowserRefresh"
KEY_BROWSER_SEARCH "BrowserSearch"
KEY_C "KeyC"
KEY_CAPS_LOCK "CapsLock"
KEY_COMMA "Comma"
KEY_CONTEXT_MENU "ContextMenu"
KEY_CONTROL "Control"
KEY_CONVERT "Convert"
KEY_COPY "Copy"
KEY_CUT "Cut"
KEY_D "KeyD"
KEY_DELETE "Delete"
KEY_DOWN "ArrowDown"
KEY_E "KeyE"
KEY_END "End"
KEY_ENTER "Enter"
KEY_EQUAL "Equal"
KEY_ESCAPE "Escape"
KEY_F "KeyF"
KEY_F1 "F1"
KEY_F10 "F10"
KEY_F11 "F11"
KEY_F12 "F12"
KEY_F13 "F13"
KEY_F14 "F14"
KEY_F15 "F15"
KEY_F16 "F16"
KEY_F17 "F17"
KEY_F18 "F18"
KEY_F19 "F19"
KEY_F2 "F2"
KEY_F20 "F20"
KEY_F21 "F21"
KEY_F22 "F22"
KEY_F23 "F23"
KEY_F24 "F24"
KEY_F3 "F3"
KEY_F4 "F4"
KEY_F5 "F5"
KEY_F6 "F6"
KEY_F7 "F7"
KEY_F8 "F8"
KEY_F9 "F9"
KEY_G "KeyG"
KEY_H "KeyH"
KEY_HOME "Home"
KEY_I "KeyI"
KEY_INSERT "Insert"
KEY_INTERNATIONAL_BACKSLASH "IntlBackslash"
KEY_INTERNATIONAL_RO "IntlRo"
KEY_INTERNATIONAL_YEN "IntlYen"
KEY_J "KeyJ"
KEY_K "KeyK"
KEY_KANA_MODE "KanaMode"
KEY_L "KeyL"
KEY_LAUNCH_MAIL "LaunchMail"
KEY_LEFT "ArrowLeft"
KEY_LEFT_ALT "AltLeft"
KEY_LEFT_BRACKET "BracketLeft"
KEY_LEFT_CONTROL "ControlLeft"
KEY_LEFT_META "MetaLeft"
KEY_LEFT_SHIFT "ShiftLeft"
KEY_M "KeyM"
KEY_MEDIA_PLAY_PAUSE "MediaPlayPause"
KEY_MEDIA_SELECT "MediaSelect"
KEY_MEDIA_STOP "MediaStop"
KEY_MEDIA_TRACK_NEXT "MediaTrackNext"
KEY_MEDIA_TRACK_PREVIOUS "MediaTrackPrevious"
KEY_META "Meta"
KEY_MINUS "Minus"
KEY_N "KeyN"
KEY_NON_CONVERT "NonConvert"
KEY_NUMPAD_0 "Numpad0"
KEY_NUMPAD_1 "Numpad1"
KEY_NUMPAD_2 "Numpad2"
KEY_NUMPAD_3 "Numpad3"
KEY_NUMPAD_4 "Numpad4"
KEY_NUMPAD_5 "Numpad5"
KEY_NUMPAD_6 "Numpad6"
KEY_NUMPAD_7 "Numpad7"
KEY_NUMPAD_8 "Numpad8"
KEY_NUMPAD_9 "Numpad9"
KEY_NUMPAD_ADD "NumpadAdd"
KEY_NUMPAD_COMMA "NumpadComma"
KEY_NUMPAD_DIVIDE "NumpadDivide"
KEY_NUMPAD_ENTER "NumpadEnter"
KEY_NUMPAD_EQUAL "NumpadEqual"
KEY_NUMPAD_MULTIPLY "NumpadMultiply"
KEY_NUMPAD_PERIOD "NumpadDecimal"
KEY_NUMPAD_SUBTRACT "NumpadSubtract"
KEY_NUM_LOCK "NumLock"
KEY_O "KeyO"
KEY_P "KeyP"
KEY_PAGE_DOWN "PageDown"
KEY_PAGE_UP "PageUp"
KEY_PASTE "Paste"
KEY_PAUSE "Pause"
KEY_PERIOD "Period"
KEY_POWER "Power"
KEY_PRINT_SCREEN "PrintScreen"
KEY_Q "KeyQ"
KEY_R "KeyR"
KEY_RIGHT "ArrowRight"
KEY_RIGHT_ALT "AltRight"
KEY_RIGHT_BRACKET "BracketRight"
KEY_RIGHT_CONTROL "ControlRight"
KEY_RIGHT_META "MetaRight"
KEY_RIGHT_SHIFT "ShiftRight"
KEY_S "KeyS"
KEY_SCROLL_LOCK "ScrollLock"
KEY_SEMICOLON "Semicolon"
KEY_SHIFT "Shift"
KEY_SLASH "Slash"
KEY_SLEEP "Sleep"
KEY_SPACE "Space"
KEY_T "KeyT"
KEY_TAB "Tab"
KEY_U "KeyU"
KEY_UP "ArrowUp"
KEY_V "KeyV"
KEY_W "KeyW"
KEY_WAKE_UP "WakeUp"
KEY_X "KeyX"
KEY_Y "KeyY"
KEY_Z "KeyZ"
MOUSE_BUTTON_BACK 3
MOUSE_BUTTON_FORWARD 4
MOUSE_BUTTON_LEFT 0
MOUSE_BUTTON_MIDDLE 2
MOUSE_BUTTON_RIGHT 1

json

Contents

JSON text to and from script values. Its null keeps nil through a round trip.

2 functions, 0 constants. Scripts reach it as json::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
encode(any) -> string — A value written back out as JSON text; NaN, infinity, a node or a callback has no JSON form and is an error.
parse(string) -> any — The value a JSON document describes; nil for text that does not parse, as for null.

log

Contents

The info, warn and error levels a script writes at, and the buffer behind them. Lines go through the engine's own tracing stream.

7 functions, 0 constants. Scripts reach it as log::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
clear() — Empty the buffer, so a console reading it starts again from nothing.
error(string) — Write a line at error level, tagged as coming from a script.
file() -> str? — The file this run's log is written to, or nil when it keeps none. [log] file turns it off and [log] keep says how many past runs stay beside it.
info(string) — Write a line at info level, tagged as coming from a script.
print(string) — Write a line to standard output as it stands, with no level or tag and not into the buffer: what a headless run prints for a tool to read.
since(int?) -> log::Batch — What was logged after cursor (a seq, 0 for all the buffer holds), as { entries, cursor, missed }: pass cursor back next time, and missed counts lines the buffer dropped before they were read. A script hears that there is more with events::listen(this.node, "logged"), as on_logged(total), rather than asking every frame.
warn(string) — Write a line at warning level, tagged as coming from a script.

math

Contents

Deterministic float maths backed by pure-Rust libm: the same inputs give the same bits on every platform.

24 functions, 3 constants. Scripts reach it as math::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
abs(float) -> float — The magnitude, with the sign dropped.
acos(float) -> float — The angle in radians whose cosine is the argument, from 0 to PI; NaN outside -1..1.
asin(float) -> float — The angle in radians whose sine is the argument, from -PI/2 to PI/2; NaN outside -1..1.
atan(float) -> float — The angle in radians whose tangent is the argument, from -PI/2 to PI/2.
atan2(float, float) -> float — The angle in radians from the positive x axis to the point, taking y first and x second.
ceil(float) -> float — The smallest whole number at or above the argument, still a float.
clamp(float, float, float) -> float — The first argument held inside the range given by the second (low) and third (high).
cos(float) -> float — The cosine of an angle in radians.
cosh(float) -> float — The hyperbolic cosine.
exp(float) -> float — e raised to the given power.
floor(float) -> float — The largest whole number at or below the argument, still a float.
log(float) -> float — The natural logarithm; -INF at zero and NaN below it.
log10(float) -> float — The base-10 logarithm; -INF at zero and NaN below it.
max(float, float) -> float — The larger of two numbers.
min(float, float) -> float — The smaller of two numbers.
pow(float, float) -> float — The first argument raised to the power of the second.
round(float) -> float — The nearest whole number, with halfway cases going away from zero.
sin(float) -> float — The sine of an angle in radians.
sinh(float) -> float — The hyperbolic sine.
sqrt(float) -> float — The square root; NaN for a negative argument.
tan(float) -> float — The tangent of an angle in radians.
tanh(float) -> float — The hyperbolic tangent, between -1 and 1.
to_degrees(float) -> float — Radians converted to degrees.
to_radians(float) -> float — Degrees converted to radians.

Constants

name value
INFINITY inf
PI 3.141592653589793
TAU 6.283185307179586

multimesh2d

Contents

Thousands of copies of one sprite in one draw, each with its own transform, colour and custom data, through node.multimesh2d.

13 functions, 0 constants. Scripts reach it as multimesh2d::.

Acts on multimesh2d: those functions are also methods on the component's handle, without the node argument.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
instance_color(Node, int) -> Color multimesh2d The colour one instance draws in.
instance_count(Node) -> int multimesh2d How many instances the node holds.
instance_custom_data(Node, int) -> Color multimesh2d One instance's four floats of custom data, as a colour.
instance_region(Node, int) -> render::InstanceRegion? multimesh2d The texture rectangle one instance's row names with region_origin and region_size, in pixels, or nil when it names none.
instance_transform(Node, int) -> Transform2d multimesh2d One instance's transform.
instances(Node) -> [render::MultimeshInstance] multimesh2d Every instance as the multimesh asset spells it, so assets.save writes a scripted layout into a file.
set_instance_color(Node, int, Color) multimesh2d The colour one instance draws in.
set_instance_count(Node, int) multimesh2d How many instances the node holds. Those below the count keep where they were; new ones are plain, at the node.
set_instance_custom_data(Node, int, Color) multimesh2d Four floats a material's shader reads for one instance, as a colour.
set_instance_transform(Node, int, Transform2d) multimesh2d Place one instance. A shear is kept, as the instance's basis.
set_instances(Node, [render::MultimeshInstance]) multimesh2d Replace every instance with a list in the multimesh asset's shape.
set_visible_instance_count(Node, int) multimesh2d How many instances draw, from the first; -1 draws them all.
visible_instance_count(Node) -> int multimesh2d How many instances draw; -1 is all of them.

multimesh3d

Contents

Thousands of copies of one mesh in one draw, each with its own transform, colour and custom data, through node.multimesh3d.

12 functions, 0 constants. Scripts reach it as multimesh3d::.

Acts on multimesh3d: those functions are also methods on the component's handle, without the node argument.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
instance_color(Node, int) -> Color multimesh3d The colour one instance draws in.
instance_count(Node) -> int multimesh3d How many instances the node holds.
instance_custom_data(Node, int) -> Color multimesh3d One instance's four floats of custom data, as a colour.
instance_transform(Node, int) -> Transform3d multimesh3d One instance's transform.
instances(Node) -> [render::MultimeshInstance] multimesh3d Every instance as the multimesh asset spells it, so assets.save writes a scripted layout into a file.
set_instance_color(Node, int, Color) multimesh3d The colour one instance draws in.
set_instance_count(Node, int) multimesh3d How many instances the node holds. Those below the count keep where they were; new ones are plain, at the node.
set_instance_custom_data(Node, int, Color) multimesh3d Four floats a material's shader reads for one instance, as a colour.
set_instance_transform(Node, int, Transform3d) multimesh3d Place one instance. A shear is kept, as the instance's basis.
set_instances(Node, [render::MultimeshInstance]) multimesh3d Replace every instance with a list in the multimesh asset's shape.
set_visible_instance_count(Node, int) multimesh3d How many instances draw, from the first; -1 draws them all.
visible_instance_count(Node) -> int multimesh3d How many instances draw; -1 is all of them.

multiplayer

Contents

Host, join and play a rollback match. Set this machine's input with set_input and read every slot's with rollback.input(slot); events are the multiplayer_event event: events::listen(node, "multiplayer_event"), heard as on_multiplayer_event, a map with a kind.

14 functions, 18 constants. Scripts reach it as multiplayer::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
add_bot(str?) -> int? — On a host, a slot its own script plays with set_input_for; answers the slot, or nil when the lobby is full.
host(multiplayer::HostOptions?) -> multiplayer::Hosted — Listen and take slot 0; answers { url, cert_hash, transport }, what a joiner needs. Options over [multiplayer]: transport, address, players, scene, depth, timeout_seconds, name, token.
join(string, multiplayer::JoinOptions?) — Dial a host at a ws:// or https:// url; connected or failed follows. Options: cert_hash for a self-signed host, name, token, timeout_seconds.
leave() — Say goodbye and go idle; a host leaving ends the match for everyone.
local_player() -> int? — This machine's own slot, or nil before it has one.
players() -> [multiplayer::Player] — Every slot as { slot, name, bot, local, status }, status as of the tick being simulated.
role() -> str? — ROLE_HOST or ROLE_CLIENT, or nil when idle.
set_input(any) — What this machine's player does on the next tick, until set again; ignored while a tick re-runs.
set_input_for(int, any) — The same for a bot slot this machine plays.
settled_tick() -> int — The tick before which nothing can be rolled back any more.
start() -> bool — On a host, start with whoever is in rather than waiting for players; false when there is no lobby to start.
state() -> string — STATE_IDLE, STATE_CONNECTING, STATE_LOBBY or STATE_PLAYING.
stats(int) -> multiplayer::Stats? — { rtt_ms, loss, bytes_in, bytes_out } for the link a slot is reached over; nil for this machine's own. An observer: never simulate from it.
tick() -> int — The match tick being simulated; what a match branches on instead of engine.tick.

Constants

name value
EVENT_CLOSED "closed"
EVENT_CONNECTED "connected"
EVENT_DESYNC "desync"
EVENT_ERROR "error"
EVENT_JOINED "joined"
EVENT_LEFT "left"
EVENT_STARTED "started"
ROLE_CLIENT "client"
ROLE_HOST "host"
STATE_CONNECTING "connecting"
STATE_IDLE "idle"
STATE_LOBBY "lobby"
STATE_PLAYING "playing"
STATUS_ABSENT "absent"
STATUS_PRESENT "present"
TAG_LOCAL "local"
TRANSPORT_WEBSOCKET "websocket"
TRANSPORT_WEBTRANSPORT "webtransport"

node

Contents

What every node has: name, path, transform, children, components and script. Each function takes the node first; scripts call it as a method, self.node.get_node("Arm").

57 functions, 0 constants. Scripts reach it as node::.

Acts on states, transform: those functions are also methods on the component's handle, without the node argument.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
add_child(Node, string) -> Node — Create a named child node under this one and return it.
add_tag(Node, string) — File the node under a name; scene.tagged finds it from then on.
attach_script(Node, string, any) — Attach the script at a path, with an optional table overriding what the script exports.
authored(Node, string) -> any — The component as a save writes it: every property it holds, an inline asset as its definition, a colour as #rrggbb where it is one, and no read-only property. Nil when the node does not carry it.
call(Node, string, any, any, any, any) -> any — Call a method on the node's script and return what it gives back; nil when there is no such script or method.
call_async(Node, string, any, any, any, any) -> int — Call a method that may suspend, and get a token task.wait resumes with its result once it returns: task::wait(door.call_async("open")).await, a GDScript await door.open().
children(Node) -> [Node] — The node's direct children, an empty list when it has none.
component_names(Node) -> [str] — The names of every component on the node.
component_property(Node, string, string) -> any — One property of the named component, nil when the node does not carry it: what a caller reading a single value should ask for.
descendants(Node) -> [Node] — Every node under this one, in tree order, the node itself excluded.
detach_script(Node) — Drop the script instance on this node, so no further lifecycle call reaches it; the node and its components stay.
effective_tint(Node) -> Color — What the renderer multiplies by: this node's tint with every ancestor's folded in.
emit(Node, string, any) — Emit an event from this node, delivered at the top of the next frame to whoever subscribed to name on this node, and to whoever subscribed to name from anyone. call is the twin that reaches one known script, now.
free(Node) — Destroy the node and its subtree now, scripts detached first: what a tool editing a scene does, where no script of the subtree is running. A game frees with queue_free.
get_component(Node, string) -> any — The named component's properties as a table, nil when the node does not carry it.
get_node(Node, string) -> Node — The node at an A/B/C path relative to this one, .. climbing to the parent and a leading / starting from the root; nil when nothing matches.
global_position(Node) -> Vec3 transform The node's position in world space, as of the last transform sync.
global_rotation_euler(Node) -> Vec3 transform The node's world rotation as euler angles in radians, as of the last transform sync.
global_scale(Node) -> Vec3 transform The node's scale in world space, as of the last transform sync.
has_component(Node, string) -> bool — Whether the node carries the named component.
has_method(Node, string) -> bool — Whether the node's script declares this method, so a caller can tell "no handler" from "a handler that answered nothing".
has_tag(Node, string) -> bool — Whether the node is filed under a name.
instance(Node) -> str? — The prefab file the node instances, nil when it instances none.
is_valid(Node) -> bool — Whether the node is still in the world; false rather than an error when the value is not a node.
look_at(Node, Vec3) transform Turn the node so its -z, the way a camera and a light face, points at a world point, with +y up. It faces from where its position puts it now, under its parent's pose as of the last transform sync.
material(Node) -> string — The material asset the node names itself, empty when it takes its parent's.
name(Node) -> string — The node's own name, empty when it carries none.
overrides(Node) -> any — What the node changes of what the prefab that built it asks: a table by component of the properties it sets differently, and its script's under script. Empty for a node no prefab built.
parent(Node) -> Node — The node's parent, nil at the root.
patch_component(Node, string, any) -> bool — Change the properties the table names and leave the rest of the component where they were. On a node without the component this adds it, the schema defaults being what it currently holds. Answers whether the component took the values: one it refuses goes to the log with its reason, and the script goes on. A component or property nothing has, or a node that is gone, is an error.
path(Node) -> string — The node's slash-separated path, built by climbing parents from the node up to the root.
process(Node) -> string — When this node ticks: "inherit", "pausable", "always" or "disabled". "inherit" is the default and takes the nearest ancestor's answer.
queue_free(Node) — Destroy the node and its subtree at the end of the frame.
remove_component(Node, string) — Take the named component off the node.
remove_tag(Node, string) — Take a name off the node; a name it never had is left alone.
reset_interpolation(Node) — Throw away the poses the node was blending and start again from where it is, so a teleport does not streak across the level. physics3d.teleport and physics2d.teleport call it for you.
script_field(Node, string) -> any — A member the node's script instance holds, read by another script: GDScript's node.speed. Nil for no script or no such member.
script_path(Node) -> string — The path of the script the node names, nil when it names none; named whether or not it runs.
script_props(Node) -> any — What the node sets over its script's exported defaults, as a table; empty when it sets nothing.
set_component(Node, string, any) — Give the node the named component, built from the given table over the component's schema defaults. Every property the table leaves out goes back to its default; patch_component is the one that changes a property and leaves the rest. A script hears every write to the scene, this one and a node added, freed, renamed or moved, with events::listen(this.node, "changed"), as on_changed(entries) at the top of the next frame.
set_global_position(Node, Vec3) transform Put the node at a world point, Godot's global_position = point: it writes the position that lands there under its parent's pose as of the last transform sync, so global_position reads the point once the next sync has run. An axis a zero scale above flattens, or a point that is not finite, keeps the node's own coordinate.
set_name(Node, string) — Rename the node, doing nothing when it carries no name.
set_parent(Node, Node) — Move the node under another, keeping where it is in the world; an error for a cycle or a dead parent.
set_process(Node, string) — Set when the node and its subtree tick. "always" runs through a pause, which is what a pause menu is; "disabled" never runs; "inherit" goes back to the parent's. Physics is one world and is held whole by a pause whatever this says.
set_script(Node, str?, any) — Name the node's script and what it sets, without running it: what a scene's script key says and attach_script also starts. Nil takes the script off.
set_sibling_index(Node, int) — Move the node to that place among its siblings, clamped to the end. Order is draw order in a row or a column, and tree order in the digest.
set_state(Node, string) states Put the node in one of its states: the state's table is patched over the components it names, and on_state_changed(from, to) follows. A node already in that state is left alone.
set_tint(Node, Color) — Multiply a colour into everything the node and its subtree draw, alpha included, one meaning untinted. A renderable's own color is the node's alone; this is the one that inherits.
set_visible(Node, bool) — Show or hide the node and everything under it, emitting visibility_changed with the new value when the flag moves. Physics is untouched: a hidden collider still collides.
set_z_index(Node, int, bool?) — Put the node and its subtree on a draw layer: higher draws later. It adds to the parent's layer unless relative is false, which makes it absolute.
sibling_index(Node) -> int — Where the node sits among its parent's children, counting from zero; 0 at the root.
stable_id(Node) -> string — The node's stable id: what a scene file declared, or what it was given when it was spawned. Survives rename and reparent, which a path does not.
tags(Node) -> [str] — The names the node is filed under, sorted.
tint(Node) -> Color — The node's own tint as r, g, b, a channel floats; an ancestor's multiplies into it on the way to the screen.
visible(Node) -> bool — Whether the node itself is set to draw; an ancestor may still hide it.
visible_in_tree(Node) -> bool — What the renderer sees: false when the node or any ancestor is hidden.
z_index(Node) -> int — The node's own draw layer, added to its parent's unless set absolute.

physics

Contents

What spans both physics worlds: pausing, sleeping, tuning and clearing. Bodies and colliders live in physics2d and physics3d.

12 functions, 0 constants. Scripts reach it as physics::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
clear() — Remove every body and collider from both worlds, as a play-in-editor session does on stop.
counters() -> physics::Counters — What each world's last step spent its time on. The first call turns rapier's profilers on, so the numbers arrive from the step after it.
debug_draw() -> physics::DebugDraw — What the debug renderer is drawing now, every flag and nodes given.
is_paused() -> bool — Whether stepping is stopped.
quarantined() -> physics::Quarantined — What rapier disabled in each world's last step because a position, velocity or shape stopped being a number. Empty lists are the normal answer.
set_debug_draw(physics::DebugDraw) — Draw the physics world over the scene, as modes names it: DebugDraw { colliders: true } is the shapes, and enabled: false nothing. [physics.debug] holds the colours and lengths.
set_paused(bool) — Stop or resume stepping both worlds; nodes keep their poses.
set_sleeping_allowed(bool) — Allow or forbid resting bodies falling asleep, in both worlds and for bodies added later.
set_tuning(physics::TuningOptions) — Change how the solver behaves: solver_iterations, length_unit, ccd_substeps, contact softness, the soft_* rows and a soft_recovery record, the keys [physics] takes. A key at the top reaches both worlds; a physics3d or physics2d record holds keys for that world alone, which win over the top. Every value here changes results, so a recording only replays against the same numbers: prefer [physics], [physics.3d] and [physics.2d] in project.toml.
sleeping_allowed() -> bool — Whether resting bodies are allowed to fall asleep.
threads() -> int — How many threads the solver is using. One in a browser, unless the page is the threaded template and called initThreadPool.
tuning() -> physics::WorldTunings — The solver settings each world is running with, every key set_tuning takes, soft_recovery included.

physics2d

Contents

The 2D rigid-body world: bodies and colliders on nodes, their velocities, raycasts and overlap queries. physics holds what spans both worlds.

118 functions, 106 constants. Scripts reach it as physics2d::.

Acts on body2d, character2d, collider2d, follow2d, joint2d, softbody2d: those functions are also methods on the component's handle, without the node argument.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
aabb(Node) -> physics2d::Aabb collider2d The world-space box the collider currently occupies, from its lowest corner to its highest.
add_constant_force(Node, Vec2) body2d Push the body every step until the constant force is set back to zero; unlike an impulse this is spread over time.
add_constant_force_at_point(Node, Vec2, Vec2) body2d Push at a world point every step, which also turns the body.
add_constant_torque(Node, float) body2d Turn the body every step until the constant torque is set back to zero.
add_particle_force(Node, int, Vec2) softbody2d Push one particle with force each step until reset_forces.
add_softbody_force(Node, Vec2) softbody2d Push every free particle with force each step until reset_forces.
angular_velocity(Node) -> float body2d How fast the body is spinning, in radians per second.
apply_force(Node, Vec2) body2d Push the body for the next step only; add_constant_force keeps pushing.
apply_force_at_point(Node, Vec2, Vec2) body2d Push at a world point for the next step only, which also turns the body.
apply_impulse(Node, Vec2) body2d Add an instant change in momentum, as if the body were struck.
apply_impulse_at_point(Node, Vec2, Vec2) body2d Strike the body at a world point, which spins it as well as moves it.
apply_particle_impulse(Node, int, Vec2) softbody2d Strike one particle.
apply_softbody_impulse(Node, Vec2) softbody2d Change every free particle's velocity by impulse at once, as a kick to the whole body.
apply_softbody_impulse_at_point(Node, Vec2, Vec2, float) softbody2d Strike the particles within radius of point, less the further they are; a radius of 0 strikes them all.
apply_softbody_radial_impulse(Node, Vec2, float, float) softbody2d Push the particles within radius away from center, as a blast does.
apply_torque(Node, float) body2d Turn the body for the next step only; add_constant_torque keeps turning it.
apply_torque_impulse(Node, float) body2d Add an instant change in angular momentum, as if the body were spun.
attach_particle(Node, int, Node) softbody2d Tie one particle to a node's rigid body where it is now: the body and the particle pull on each other.
broad_phase_aabb(Node) -> physics2d::Aabb collider2d The box the broad phase files the collider under, which also reaches ahead by its body's speculative_distance.
closest_point(physics2d::PointQuery) -> physics2d::Closest? — The closest point on any collider to a world point.
closest_points(Node, Node) -> physics2d::ClosestPoints? — The nearest point on each of two nodes' colliders; nothing when they overlap.
collider_mass_properties(Node) -> physics2d::MassProperties collider2d What this collider adds to its body, in its own space.
collider_mesh(Node) -> physics2d::ColliderMesh collider2d A voxel collider's outline as points and the segments between them, for drawing it or for spawning the pieces it broke into.
collider_volume(Node) -> float collider2d How much area the shape encloses.
collision_aabb(Node) -> physics2d::Aabb collider2d The box the narrow phase tests the collider in: its shape's box grown by its collision_margin and the world's prediction distance.
combine_voxels(Node, Node) collider2d Tell two voxel colliders on one lattice about each other's cells, so a body sliding from one onto the other does not catch on the seam. Both must share a cell size and a rotation.
constant_force(Node) -> Vec2 body2d The force every step integrates until it is set back to zero.
constant_torque(Node) -> float body2d The torque every step integrates until it is set back to zero.
contacts(Node) -> [physics2d::Contact] collider2d Every contact point on this node's collider this step. Empty for a sensor, which has no contacts by definition.
crop_voxels(Node, int, int, int, int) collider2d Empty every cell outside the cells from (min_x, min_y) to (max_x, max_y), both included. A range holding no filled cell leaves the grid as it was.
cut_softbody(Node, [Vec2]) -> [physics2d::SoftTear] softbody2d Cut the body along a blade at once, as crossing reads it; answers a record for each piece it changed, the one on_torn hears.
detach_particle(Node, int) -> bool softbody2d Untie one particle from every body it was attached to; answers whether it was attached.
effective_angular_inertia(Node) -> float body2d The inertia the solver turns: zero with rotation locked, and on any body that is not dynamic.
effective_dominance(Node) -> float body2d The dominance rapier will use for this body: its own group, or the rank every non-dynamic body outranks with.
effective_mass(Node) -> Vec2 body2d The mass the solver pushes against along each world axis: zero along a locked axis, and on any body that is not dynamic.
gravity() -> Vec2 — The 2D world's gravity.
handles(Node) -> physics2d::Handles collider2d The rapier handles behind this node, its body and its colliders. For matching a log line against rapier's own output.
has_pending_tears(Node) -> bool softbody2d Whether some edge or cell is marked to tear at the end of the next step.
heightfield_hole(Node, int) -> bool collider2d Whether a heightfield segment has no ground.
intersects(Node, Node) -> bool — Whether two nodes' colliders overlap right now, sensor or not.
is_ccd_active(Node) -> bool body2d Whether the body moved fast enough last step for rapier to sweep it, with or without continuous_collision.
is_moving(Node) -> bool body2d Whether the body is awake and actually going somewhere.
is_sleeping(Node) -> bool body2d Whether the body is asleep and being skipped.
is_softbody_sleeping(Node) -> bool softbody2d Whether the body has come to rest and stopped being simulated.
joint_force(Node) -> physics2d::JointForce joint2d The force and the torque the joint held through the last step. An articulation has none to read, and says so.
joint_state(Node) -> physics2d::JointState joint2d What the joint is doing.
kinetic_energy(Node) -> float body2d The body's kinetic energy, for a rest test the solver agrees with.
linear_velocity(Node) -> Vec2 body2d How fast the body is travelling, in units per second.
local_center_of_mass(Node) -> Vec2 body2d Where the body's whole mass sits, in the body's own space.
max_contact_impulse(Node) -> float body2d The hardest contact this body took in the last step, every collider on it included; zero when nothing touched it.
move_character_by(Node, Vec2) -> physics2d::CharacterMove character2d Move the character by an offset, sliding along walls, climbing steps and staying on the ground. Every solid collider of the character is swept. Call it from fixed_update.
next_position(Node) -> physics2d::Pose body2d The pose a kinematic body has been told to move to.
overlap_aabb(physics2d::BoxQuery) -> [Node] — Every collider whose bounds meet an axis-aligned box.
overlap_point(physics2d::PointQuery) -> [Node] — Every collider containing a world point: what a mouse click asks.
overlap_shape(physics2d::ShapeQuery) -> [Node] — Every collider a shape overlaps where it stands.
overlaps(Node) -> [Node] collider2d The nodes this one currently intersects; rapier reports a pair only when one of the two colliders is a sensor.
pin_particle(Node, int) softbody2d Hold one particle where it is, which is how a cloth hangs from a hook.
pose_in_body(Node) -> physics2d::Pose? collider2d Where the collider sits in its body's frame; nothing for a collider with no body.
potential_energy(Node) -> float body2d The body's gravitational potential energy over one step.
predict_position(Node, float) -> physics2d::Pose body2d Where the body will be after dt seconds at its current velocity.
predict_position_with_forces(Node, float) -> physics2d::Pose body2d The same, with the forces already applied taken into account: where a thrust or a spring will have put it.
raycast(physics2d::RayQuery) -> physics2d::Hit? — The first collider a ray meets, or nothing.
raycast_all(physics2d::RayQuery) -> [physics2d::Hit] — Every collider a ray meets, nearest first.
reset_follow(Node) follow2d Forget what a pid follow summed, so it pulls from now as if it had just started.
reset_plasticity(Node) softbody2d Undo every permanent set the body took: rest lengths, rest angles and rest shapes go back to how it was built, and it springs back from where it is.
reset_softbody_forces(Node) softbody2d Take back every force add_force and add_particle_force gave the body.
set_angular_velocity(Node, float) body2d Set how fast the body spins, in radians per second.
set_cell_tear_resistance(Node, int, float) softbody2d The same for one cell's tear strain.
set_constant_force(Node, Vec2) body2d Replace the constant force with this one; zero stops the push.
set_constant_torque(Node, float) body2d Replace the constant torque with this one; zero stops the turn.
set_edge_tear_resistance(Node, int, float) softbody2d How many times the material's threshold one edge takes to tear; 1 is the material's.
set_gravity(Vec2) — Set the 2D world's gravity, in units per second squared.
set_heightfield_hole(Node, int, bool) collider2d Remove or restore one segment of a heightfield's ground, numbered from the first height.
set_linear_velocity(Node, Vec2) body2d Set how fast the body travels, in units per second.
set_particle_damaged(Node, int, bool) softbody2d Mark one particle as damaged or mend it: a damaged particle tears as an outside one does, which seeds where a crack starts.
set_particle_position(Node, int, Vec2) softbody2d Put one particle at at with no change of velocity.
set_particle_target(Node, int, Vec2) softbody2d Move a held particle to at over the next step, with the velocity that takes, which is how a cloth is dragged.
set_particle_velocity(Node, int, Vec2) softbody2d Set one particle's velocity; a held one keeps moving at it.
set_voxel(Node, int, int, bool) collider2d Fill or empty one cell of a voxel collider: digging a hole, or building a wall, while the game runs.
set_voxel_size(Node, Vec2) collider2d Resize every cell of a voxel collider, keeping which cells are filled.
shapecast(physics2d::ShapeQuery) -> physics2d::Hit? — Sweep a shape along a direction until it hits something: a thick raycast.
sleep(Node) body2d Put the body to sleep now.
softbody_area(Node) -> float softbody2d How much area the body and every piece torn off it enclose right now, against rest_area for how far it is squeezed.
softbody_attachments(Node) -> [physics2d::SoftAttachment] softbody2d Every particle tied to a rigid body.
softbody_boundary(Node) -> [[int]] softbody2d The body's surface as particle indices: segments in 2D, triangles in 3D.
softbody_cell(Node, int) -> physics2d::SoftCell softbody2d Everything one cell holds.
softbody_cells(Node) -> [[int]] softbody2d Every cell as its particle indices: triangles in 2D, tetrahedra in 3D.
softbody_contacts(Node) -> physics2d::SoftContacts softbody2d What the body's surface touched in the last step.
softbody_crossing(Node, [Vec2]) -> physics2d::SoftCrossing softbody2d The edges and cells a blade meets, without cutting: the blade is a segment's two points in 2D, a triangle's three in 3D.
softbody_edge(Node, int) -> physics2d::SoftEdge softbody2d Everything one edge holds.
softbody_edges(Node) -> [[int]] softbody2d Every edge as the two particle indices it joins, in the order stress reports them.
softbody_effective_particle_radius(Node) -> float softbody2d How thick the particles are: what was asked for, or what the layout worked out.
softbody_particle(Node, int) -> physics2d::SoftParticle softbody2d Everything one particle holds.
softbody_particle_count(Node) -> int softbody2d How many particles the body has, every piece torn off it included: a generator decides, not the author.
softbody_rest_area(Node) -> float softbody2d How much they enclose at rest.
softbody_stress(Node) -> [float] softbody2d Each edge's load as a fraction of its tear threshold, smoothed over tear_smoothing: 0 slack, 1 tearing; the larger of its stretch over tear_strain and its force over tear_force, and 0 while neither is set.
softbody_total_mass(Node) -> float softbody2d What the whole body weighs, every piece included.
softbody_volume_pieces(Node) -> [physics2d::SoftVolumePiece] softbody2d Each closed piece of the surface whose volume is held; an open sheet has none.
softbody_world_center_of_mass(Node) -> Vec2 softbody2d The centre of mass of the body and its pieces, which is where it is when a deformable body has no one position.
solve_ik(Node, Vec2, physics2d::IkOptions?) joint2d Move a reduced-coordinates chain so its last link reaches a world position, leaving every joint inside its limits. Options: rotation (radians to turn the link to), constrain (the world axes to match: x, y, rotation; the translation by default, every axis when rotation is given), damping (1.0), iterations (10), tolerance (0.001).
swept_aabb(Node) -> physics2d::Aabb collider2d The box the collider covers over the next fixed step, from where it is to where its body's velocity and forces carry it.
tear_cell(Node, int) softbody2d Tear one cell at the end of the next step: a particle near its middle splits across its main stretch.
tear_edge(Node, int) softbody2d Tear one edge at the end of the next step.
tear_softbody(Node, [int], [int]) -> [physics2d::SoftTear] softbody2d Tear the given edges and cells at once; answers a record for each piece it changed, the one on_torn hears.
teleport(Node, Vec2, physics2d::TeleportOptions?) body2d Move the body to a world position at once, clearing its velocity: what assigning the node's position cannot do, because the step writes that back every tick. A rotation turns it too, in radians.
time_of_impact(Node, Node, physics2d::ImpactOptions) -> physics2d::Impact? — When two moving colliders would meet, given each one's velocity. Nothing when they never do.
time_since_can_sleep(Node) -> float body2d Seconds the body has spent under its sleep thresholds; it sleeps once this reaches time_to_sleep.
total_inertia(Node) -> float body2d The body's resistance to spin, colliders included.
total_mass(Node) -> float body2d The body's total mass: its mass when it states one, or what its colliders weigh.
unpin_particle(Node, int) softbody2d Let a held particle go; it keeps the velocity it had.
velocity_at_point(Node, Vec2) -> Vec2 body2d How fast a world point on the body is moving, spin included.
voxel(Node, int, int) -> bool collider2d Whether one cell of a voxel collider is filled.
voxel_at(Node, Vec2) -> [int] collider2d The cell a world position falls in, as two whole numbers.
voxel_size(Node) -> Vec2 collider2d How big one cell of a voxel collider is, along each axis.
wake_all() — Wake every sleeping body in the 2D world.
wake_up(Node) body2d Wake the body, so the next step moves it.
wake_up_softbody(Node) softbody2d Start simulating a resting body again.
world_center_of_mass(Node) -> Vec2 body2d Where the body's whole mass sits, in world space.

Constants

name value
AXIS_ROTATION "rotation"
AXIS_X "x"
AXIS_Y "y"
BIND_CELLS "cells"
BIND_NEAREST "nearest"
BIND_PARTICLES "particles"
BODY_DYNAMIC "dynamic"
BODY_KINEMATIC "kinematic"
BODY_KINEMATIC_VELOCITY "kinematic_velocity"
BODY_STATIC "static"
CELL_COROTATIONAL "corotational"
CELL_NEO_HOOKEAN "neo_hookean"
CELL_VOLUME "volume"
COLLIDE_DYNAMIC_DYNAMIC "dynamic_dynamic"
COLLIDE_DYNAMIC_KINEMATIC "dynamic_kinematic"
COLLIDE_DYNAMIC_STATIC "dynamic_static"
COLLIDE_KINEMATIC_KINEMATIC "kinematic_kinematic"
COLLIDE_KINEMATIC_STATIC "kinematic_static"
COLLIDE_STATIC_STATIC "static_static"
COMBINE_AVERAGE "average"
COMBINE_CLAMPED_SUM "clamped_sum"
COMBINE_GEOMETRIC_MEAN "geometric_mean"
COMBINE_MAX "max"
COMBINE_MIN "min"
COMBINE_MULTIPLY "multiply"
EDGES_CHAIN "chain"
EDGES_MESH "mesh"
EDGES_OUTLINE "outline"
EXCLUDE_DYNAMIC "dynamic"
EXCLUDE_KINEMATIC "kinematic"
EXCLUDE_STATIC "static"
FILL_SOLID "solid"
FILL_SURFACE "surface"
FIT_AABB "aabb"
FIT_CONVEX_DECOMPOSITION "convex_decomposition"
FIT_CONVEX_HULL "convex_hull"
FIT_OBB "obb"
FLOW_BOTH "both"
FLOW_COMPRESSION "compression"
FLOW_TENSION "tension"
FOLLOW_PD "pd"
FOLLOW_PID "pid"
JOINT_BODY_DISABLED "body_disabled"
JOINT_DISABLED "disabled"
JOINT_ENABLED "enabled"
JOINT_FIXED "fixed"
JOINT_GENERIC "generic"
JOINT_GROOVE "groove"
JOINT_HINGE "hinge"
JOINT_ROPE "rope"
JOINT_SLIDER "slider"
JOINT_SPRING "spring"
JOINT_WAITING "waiting"
LENGTHS_ABSOLUTE "absolute"
LENGTHS_RELATIVE "relative"
METHOD_EXACT "exact"
METHOD_VHACD "vhacd"
METHOD_VOXELS "voxels"
MOTOR_MODEL_ACCELERATION "acceleration"
MOTOR_MODEL_AUTO "auto"
MOTOR_MODEL_FORCE "force"
MOTOR_OFF "off"
MOTOR_POSITION "position"
MOTOR_VELOCITY "velocity"
ORIENTATION_AUTO "auto"
ORIENTATION_SHELL "shell"
ORIENTATION_SOLID "solid"
SHAPE_CAPSULE "capsule"
SHAPE_CIRCLE "circle"
SHAPE_CONVEX_DECOMPOSITION "convex_decomposition"
SHAPE_CONVEX_HULL "convex_hull"
SHAPE_CONVEX_POLYGON "convex_polygon"
SHAPE_FIT "fit"
SHAPE_HEIGHTFIELD "heightfield"
SHAPE_MATCHING_AUTO "auto"
SHAPE_MATCHING_OFF "off"
SHAPE_MATCHING_ON "on"
SHAPE_POLYLINE "polyline"
SHAPE_RECTANGLE "rectangle"
SHAPE_SEGMENT "segment"
SHAPE_TRIANGLE "triangle"
SHAPE_TRIANGLE_MESH "triangle_mesh"
SHAPE_VOXELIZED_MESH "voxelized_mesh"
SHAPE_VOXELIZED_POINTS "voxelized_points"
SHAPE_VOXELS "voxels"
SHAPE_WORLD_BOUNDARY "world_boundary"
SOFT_CIRCLE "circle"
SOFT_CUSTOM "custom"
SOFT_GRID "grid"
SOFT_OUTLINE "outline"
SOFT_POLYGON "polygon"
SOFT_POLYLINE "polyline"
SOFT_ROPE "rope"
SOFT_SOLVER_CONSTRAINTS "constraints"
SOFT_SOLVER_FEM "fem"
SOFT_TRIANGLE_MESH "triangle_mesh"
SOFT_VOLUMETRIC "volumetric"
SWEEP_CONVERGED "converged"
SWEEP_FAILED "failed"
SWEEP_OUT_OF_ITERATIONS "out_of_iterations"
SWEEP_PENETRATING "penetrating"
TENSION_ALL "all"
TENSION_LISTED "listed"
TENSION_NONE "none"
TEST_BOTH "both"
TEST_EITHER "either"

physics3d

Contents

The 3D rigid-body world: bodies and colliders on nodes, their velocities, raycasts and overlap queries. physics holds what spans both worlds.

127 functions, 113 constants. Scripts reach it as physics3d::.

Acts on body3d, character3d, collider3d, follow3d, joint3d, softbody3d, vehicle3d, wheel3d: those functions are also methods on the component's handle, without the node argument.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
aabb(Node) -> physics3d::Aabb collider3d The world-space box the collider currently occupies, from its lowest corner to its highest.
add_constant_force(Node, Vec3) body3d Push the body every step until the constant force is set back to zero; unlike an impulse this is spread over time.
add_constant_force_at_point(Node, Vec3, Vec3) body3d Push at a world point every step, which also turns the body.
add_constant_torque(Node, Vec3) body3d Turn the body every step until the constant torque is set back to zero.
add_particle_force(Node, int, Vec3) softbody3d Push one particle with force each step until reset_forces.
add_softbody_force(Node, Vec3) softbody3d Push every free particle with force each step until reset_forces.
angular_velocity(Node) -> Vec3 body3d How fast the body is spinning, in radians per second about each axis.
apply_force(Node, Vec3) body3d Push the body for the next step only; add_constant_force keeps pushing.
apply_force_at_point(Node, Vec3, Vec3) body3d Push at a world point for the next step only, which also turns the body.
apply_impulse(Node, Vec3) body3d Add an instant change in momentum, as if the body were struck.
apply_impulse_at_point(Node, Vec3, Vec3) body3d Strike the body at a world point, which spins it as well as moves it.
apply_particle_impulse(Node, int, Vec3) softbody3d Strike one particle.
apply_softbody_impulse(Node, Vec3) softbody3d Change every free particle's velocity by impulse at once, as a kick to the whole body.
apply_softbody_impulse_at_point(Node, Vec3, Vec3, float) softbody3d Strike the particles within radius of point, less the further they are; a radius of 0 strikes them all.
apply_softbody_radial_impulse(Node, Vec3, float, float) softbody3d Push the particles within radius away from center, as a blast does.
apply_torque(Node, Vec3) body3d Turn the body for the next step only; add_constant_torque keeps turning it.
apply_torque_impulse(Node, Vec3) body3d Add an instant change in angular momentum, as if the body were spun.
attach_particle(Node, int, Node) softbody3d Tie one particle to a node's rigid body where it is now: the body and the particle pull on each other.
broad_phase_aabb(Node) -> physics3d::Aabb collider3d The box the broad phase files the collider under, which also reaches ahead by its body's speculative_distance.
closest_point(physics3d::PointQuery) -> physics3d::Closest? — The closest point on any collider to a world point.
closest_points(Node, Node) -> physics3d::ClosestPoints? — The nearest point on each of two nodes' colliders.
collider_mass_properties(Node) -> physics3d::MassProperties collider3d What this collider adds to its body, in its own space.
collider_mesh(Node) -> physics3d::ColliderMesh collider3d The collider's shape as points and triangles, including a voxel grid's, for drawing it or for spawning the pieces it broke into.
collider_volume(Node) -> float collider3d How much space the shape encloses.
collision_aabb(Node) -> physics3d::Aabb collider3d The box the narrow phase tests the collider in: its shape's box grown by its collision_margin and the world's prediction distance.
combine_voxels(Node, Node) collider3d Tell two voxel colliders on one lattice about each other's cells, so a body sliding from one onto the other does not catch on the seam. Both must share a cell size and a rotation.
constant_force(Node) -> Vec3 body3d The force every step integrates until it is set back to zero.
constant_torque(Node) -> Vec3 body3d The torque every step integrates until it is set back to zero.
contacts(Node) -> [physics3d::Contact] collider3d Every contact point on this node's collider this step. Empty for a sensor, which has no contacts by definition.
crop_voxels(Node, int, int, int, int, int, int) collider3d Empty every cell outside the cells from (min_x, min_y, min_z) to (max_x, max_y, max_z), both included. A range holding no filled cell leaves the grid as it was.
cut_softbody(Node, [Vec3]) -> [physics3d::SoftTear] softbody3d Cut the body along a blade at once, as crossing reads it; answers a record for each piece it changed, the one on_torn hears.
detach_particle(Node, int) -> bool softbody3d Untie one particle from every body it was attached to; answers whether it was attached.
effective_angular_inertia(Node) -> [Vec3] body3d The world-space inertia the solver turns, rotation locks applied, as its three rows.
effective_dominance(Node) -> float body3d The dominance rapier will use for this body: its own group, or the rank every non-dynamic body outranks with.
effective_mass(Node) -> Vec3 body3d The mass the solver pushes against along each world axis: zero along a locked axis, and on any body that is not dynamic.
gravity() -> Vec3 — The 3D world's gravity.
handles(Node) -> physics3d::Handles collider3d The rapier handles behind this node, its body and its colliders. For matching a log line against rapier's own output.
has_pending_tears(Node) -> bool softbody3d Whether some edge or cell is marked to tear at the end of the next step.
heightfield_hole(Node, int, int) -> bool collider3d Whether a heightfield cell has no ground.
intersects(Node, Node) -> bool — Whether two nodes' colliders overlap right now, sensor or not.
is_ccd_active(Node) -> bool body3d Whether the body moved fast enough last step for rapier to sweep it, with or without continuous_collision.
is_moving(Node) -> bool body3d Whether the body is awake and actually going somewhere.
is_sleeping(Node) -> bool body3d Whether the body is asleep and being skipped.
is_softbody_sleeping(Node) -> bool softbody3d Whether the body has come to rest and stopped being simulated.
joint_force(Node) -> physics3d::JointForce joint3d The force and the torque the joint held through the last step: what break_force and break_torque are measured against. An articulation has none to read, and says so.
joint_state(Node) -> physics3d::JointState joint3d What the joint is doing.
kinetic_energy(Node) -> float body3d The body's kinetic energy, for a rest test the solver agrees with.
linear_velocity(Node) -> Vec3 body3d How fast the body is travelling, in units per second.
local_center_of_mass(Node) -> Vec3 body3d Where the body's whole mass sits, in the body's own space.
max_contact_impulse(Node) -> float body3d The hardest contact this body took in the last step, every collider on it included; zero when nothing touched it.
move_character_by(Node, Vec3) -> physics3d::CharacterMove character3d Move the character by an offset, sliding along walls, climbing steps and staying on the ground. Every solid collider of the character is swept. Call it from fixed_update. It reads the world the step just wrote.
next_position(Node) -> physics3d::Pose body3d The pose a kinematic body has been told to move to.
overlap_aabb(physics3d::BoxQuery) -> [Node] — Every collider whose bounds meet an axis-aligned box; cheaper and looser than shape_hits.
overlap_point(physics3d::PointQuery) -> [Node] — Every collider containing a world point.
overlap_shape(physics3d::ShapeQuery) -> [Node] — Every collider a shape overlaps where it stands: an explosion's reach, a melee arc.
overlaps(Node) -> [Node] collider3d The nodes this one currently intersects; rapier reports a pair only when one of the two colliders is a sensor.
pin_particle(Node, int) softbody3d Hold one particle where it is, which is how a cloth hangs from a hook.
pose_in_body(Node) -> physics3d::Pose? collider3d Where the collider sits in its body's frame; nothing for a collider with no body.
potential_energy(Node) -> float body3d The body's gravitational potential energy over one step.
predict_position(Node, float) -> physics3d::Pose body3d Where the body will be after dt seconds at its current velocity.
predict_position_with_forces(Node, float) -> physics3d::Pose body3d The same, with the forces already applied taken into account: where a thrust or a spring will have put it.
raycast(physics3d::RayQuery) -> physics3d::Hit? — The first collider a ray meets, or nothing.
raycast_all(physics3d::RayQuery) -> [physics3d::Hit] — Every collider a ray meets, nearest first.
reset_follow(Node) follow3d Forget what a pid follow summed, so it pulls from now as if it had just started.
reset_plasticity(Node) softbody3d Undo every permanent set the body took: rest lengths, rest angles and rest shapes go back to how it was built, and it springs back from where it is.
reset_softbody_forces(Node) softbody3d Take back every force add_force and add_particle_force gave the body.
set_angular_velocity(Node, Vec3) body3d Set how fast the body spins, in radians per second about each axis.
set_brake(Node, float) wheel3d How hard this wheel brakes, as an impulse; ignored while its engine force is not 0.
set_cell_tear_resistance(Node, int, float) softbody3d The same for one cell's tear strain.
set_constant_force(Node, Vec3) body3d Replace the constant force with this one; zero stops the push.
set_constant_torque(Node, Vec3) body3d Replace the constant torque with this one; zero stops the turn.
set_edge_tear_resistance(Node, int, float) softbody3d How many times the material's threshold one edge takes to tear; 1 is the material's.
set_engine_force(Node, float) wheel3d How hard this wheel drives, in newtons; negative reverses.
set_gravity(Vec3) — Set the 3D world's gravity, in units per second squared.
set_heightfield_hole(Node, int, int, bool) collider3d Remove or restore the ground of one heightfield cell, named by the row and column of its first corner.
set_linear_velocity(Node, Vec3) body3d Set how fast the body travels, in units per second.
set_particle_damaged(Node, int, bool) softbody3d Mark one particle as damaged or mend it: a damaged particle tears as an outside one does, which seeds where a crack starts.
set_particle_position(Node, int, Vec3) softbody3d Put one particle at at with no change of velocity.
set_particle_target(Node, int, Vec3) softbody3d Move a held particle to at over the next step, with the velocity that takes, which is how a cloth is dragged.
set_particle_velocity(Node, int, Vec3) softbody3d Set one particle's velocity; a held one keeps moving at it.
set_steering(Node, float) wheel3d Turn this wheel, in radians.
set_voxel(Node, int, int, int, bool) collider3d Fill or empty one cell of a voxel collider: digging a hole, or building a wall, while the game runs.
set_voxel_size(Node, Vec3) collider3d Resize every cell of a voxel collider, keeping which cells are filled.
set_wheel_rotation(Node, float) wheel3d Set how far the wheel has turned about its axle, in radians: the angle state reads as rotation.
shapecast(physics3d::ShapeQuery) -> physics3d::Hit? — Sweep a shape along a direction until it hits something: a thick raycast, and how a camera avoids walls.
sleep(Node) body3d Put the body to sleep now.
softbody_attachments(Node) -> [physics3d::SoftAttachment] softbody3d Every particle tied to a rigid body.
softbody_boundary(Node) -> [[int]] softbody3d The body's surface as particle indices: segments in 2D, triangles in 3D.
softbody_cell(Node, int) -> physics3d::SoftCell softbody3d Everything one cell holds.
softbody_cells(Node) -> [[int]] softbody3d Every cell as its particle indices: triangles in 2D, tetrahedra in 3D.
softbody_contacts(Node) -> physics3d::SoftContacts softbody3d What the body's surface touched in the last step.
softbody_crossing(Node, [Vec3]) -> physics3d::SoftCrossing softbody3d The edges and cells a blade meets, without cutting: the blade is a segment's two points in 2D, a triangle's three in 3D.
softbody_dihedral(Node, int) -> physics3d::SoftDihedral softbody3d Everything one hinge holds.
softbody_dihedrals(Node) -> [[int]] softbody3d Every bending hinge between two surface triangles, as four particle indices: the shared edge, then the two opposite particles.
softbody_edge(Node, int) -> physics3d::SoftEdge softbody3d Everything one edge holds.
softbody_edges(Node) -> [[int]] softbody3d Every edge as the two particle indices it joins, in the order stress reports them.
softbody_effective_particle_radius(Node) -> float softbody3d How thick the particles are: what was asked for, or what the layout worked out.
softbody_particle(Node, int) -> physics3d::SoftParticle softbody3d Everything one particle holds.
softbody_particle_count(Node) -> int softbody3d How many particles the body has, every piece torn off it included: a generator decides, not the author.
softbody_rest_volume(Node) -> float softbody3d How much they enclose at rest.
softbody_stress(Node) -> [float] softbody3d Each edge's load as a fraction of its tear threshold, smoothed over tear_smoothing: 0 slack, 1 tearing; the larger of its stretch over tear_strain and its force over tear_force, and 0 while neither is set.
softbody_total_mass(Node) -> float softbody3d What the whole body weighs, every piece included.
softbody_volume(Node) -> float softbody3d How much space the body and every piece torn off it enclose right now, against rest_volume for how far it is squeezed.
softbody_volume_pieces(Node) -> [physics3d::SoftVolumePiece] softbody3d Each closed piece of the surface whose volume is held; an open sheet has none.
softbody_world_center_of_mass(Node) -> Vec3 softbody3d The centre of mass of the body and its pieces, which is where it is when a deformable body has no one position.
solve_ik(Node, Vec3, physics3d::IkOptions?) joint3d Move a reduced-coordinates chain so its last link reaches a world position, leaving every joint inside its limits. Options: rotation (euler radians to turn the link to), constrain (the world axes to match: x, y, z, rotation_x, rotation_y, rotation_z; the translation by default, every axis when rotation is given), damping (1.0), iterations (10), tolerance (0.001).
swept_aabb(Node) -> physics3d::Aabb collider3d The box the collider covers over the next fixed step, from where it is to where its body's velocity and forces carry it.
tear_cell(Node, int) softbody3d Tear one cell at the end of the next step: a particle near its middle splits across its main stretch.
tear_edge(Node, int) softbody3d Tear one edge at the end of the next step.
tear_softbody(Node, [int], [int]) -> [physics3d::SoftTear] softbody3d Tear the given edges and cells at once; answers a record for each piece it changed, the one on_torn hears.
teleport(Node, Vec3, physics3d::TeleportOptions?) body3d Move the body to a world position at once, clearing its velocity: what assigning the node's position cannot do, because the step writes that back every tick. A rotation turns it too, in Euler radians.
time_of_impact(Node, Node, physics3d::ImpactOptions) -> physics3d::Impact? — When two moving colliders would meet, given each one's velocity. Nothing when they never do.
time_since_can_sleep(Node) -> float body3d Seconds the body has spent under its sleep thresholds; it sleeps once this reaches time_to_sleep.
total_inertia(Node) -> Vec3 body3d The body's resistance to spin about each of its principal axes, colliders included.
total_inertia_rotation(Node) -> Vec3 body3d How those principal axes are turned in the body's own space, as Euler radians as rotation_euler reads them.
total_mass(Node) -> float body3d The body's total mass: its mass when it states one, or what its colliders weigh.
unpin_particle(Node, int) softbody3d Let a held particle go; it keeps the velocity it had.
vehicle_speed(Node) -> float vehicle3d How fast the chassis is going along its forward axis, in units per second.
velocity_at_point(Node, Vec3) -> Vec3 body3d How fast a world point on the body is moving, spin included.
voxel(Node, int, int, int) -> bool collider3d Whether one cell of a voxel collider is filled.
voxel_at(Node, Vec3) -> [int] collider3d The cell a world position falls in, as three whole numbers.
voxel_size(Node) -> Vec3 collider3d How big one cell of a voxel collider is, along each axis.
wake_all() — Wake every sleeping body in the 3D world.
wake_up(Node) body3d Wake the body, so the next step moves it.
wake_up_softbody(Node) softbody3d Start simulating a resting body again.
wheel_state(Node) -> physics3d::WheelState wheel3d What the last step did with this wheel.
world_center_of_mass(Node) -> Vec3 body3d Where the body's whole mass sits, in world space.

Constants

name value
AXIS_NEGATIVE_X "-x"
AXIS_NEGATIVE_Y "-y"
AXIS_NEGATIVE_Z "-z"
AXIS_ROTATION_X "rotation_x"
AXIS_ROTATION_Y "rotation_y"
AXIS_ROTATION_Z "rotation_z"
AXIS_X "x"
AXIS_Y "y"
AXIS_Z "z"
BIND_CELLS "cells"
BIND_NEAREST "nearest"
BIND_PARTICLES "particles"
BODY_DYNAMIC "dynamic"
BODY_KINEMATIC "kinematic"
BODY_KINEMATIC_VELOCITY "kinematic_velocity"
BODY_STATIC "static"
CELL_COROTATIONAL "corotational"
CELL_NEO_HOOKEAN "neo_hookean"
CELL_VOLUME "volume"
COLLIDE_DYNAMIC_DYNAMIC "dynamic_dynamic"
COLLIDE_DYNAMIC_KINEMATIC "dynamic_kinematic"
COLLIDE_DYNAMIC_STATIC "dynamic_static"
COLLIDE_KINEMATIC_KINEMATIC "kinematic_kinematic"
COLLIDE_KINEMATIC_STATIC "kinematic_static"
COLLIDE_STATIC_STATIC "static_static"
COMBINE_AVERAGE "average"
COMBINE_CLAMPED_SUM "clamped_sum"
COMBINE_GEOMETRIC_MEAN "geometric_mean"
COMBINE_MAX "max"
COMBINE_MIN "min"
COMBINE_MULTIPLY "multiply"
EDGES_CHAIN "chain"
EDGES_MESH "mesh"
EXCLUDE_DYNAMIC "dynamic"
EXCLUDE_KINEMATIC "kinematic"
EXCLUDE_STATIC "static"
FILL_SOLID "solid"
FILL_SURFACE "surface"
FIT_AABB "aabb"
FIT_CONVEX_DECOMPOSITION "convex_decomposition"
FIT_CONVEX_HULL "convex_hull"
FIT_OBB "obb"
FLOW_BOTH "both"
FLOW_COMPRESSION "compression"
FLOW_TENSION "tension"
FOLLOW_PD "pd"
FOLLOW_PID "pid"
FRICTION_PER_CONTACT "per_contact"
FRICTION_SIMPLIFIED "simplified"
JOINT_BALL_SOCKET "ball_socket"
JOINT_BODY_DISABLED "body_disabled"
JOINT_DISABLED "disabled"
JOINT_ENABLED "enabled"
JOINT_FIXED "fixed"
JOINT_GENERIC "generic"
JOINT_HINGE "hinge"
JOINT_ROPE "rope"
JOINT_SLIDER "slider"
JOINT_SPRING "spring"
JOINT_WAITING "waiting"
LENGTHS_ABSOLUTE "absolute"
LENGTHS_RELATIVE "relative"
METHOD_VHACD "vhacd"
METHOD_VOXELS "voxels"
MOTOR_MODEL_ACCELERATION "acceleration"
MOTOR_MODEL_AUTO "auto"
MOTOR_MODEL_FORCE "force"
MOTOR_OFF "off"
MOTOR_POSITION "position"
MOTOR_VELOCITY "velocity"
ORIENTATION_AUTO "auto"
ORIENTATION_SHELL "shell"
ORIENTATION_SOLID "solid"
SHAPE_BOX "box"
SHAPE_CAPSULE "capsule"
SHAPE_CONE "cone"
SHAPE_CONVEX_DECOMPOSITION "convex_decomposition"
SHAPE_CONVEX_HULL "convex_hull"
SHAPE_CONVEX_MESH "convex_mesh"
SHAPE_CYLINDER "cylinder"
SHAPE_FIT "fit"
SHAPE_HEIGHTFIELD "heightfield"
SHAPE_MATCHING_AUTO "auto"
SHAPE_MATCHING_OFF "off"
SHAPE_MATCHING_ON "on"
SHAPE_POLYLINE "polyline"
SHAPE_SEGMENT "segment"
SHAPE_SPHERE "sphere"
SHAPE_TRIANGLE "triangle"
SHAPE_TRIANGLE_MESH "triangle_mesh"
SHAPE_VOXELIZED_MESH "voxelized_mesh"
SHAPE_VOXELIZED_POINTS "voxelized_points"
SHAPE_VOXELS "voxels"
SHAPE_WORLD_BOUNDARY "world_boundary"
SOFT_BOX "box"
SOFT_CLOTH "cloth"
SOFT_CLOTH_TUBE "cloth_tube"
SOFT_CUSTOM "custom"
SOFT_ROPE "rope"
SOFT_SOLVER_CONSTRAINTS "constraints"
SOFT_SOLVER_FEM "fem"
SOFT_SPHERE "sphere"
SOFT_TRIANGLE_MESH "triangle_mesh"
SOFT_VOLUMETRIC "volumetric"
SWEEP_CONVERGED "converged"
SWEEP_FAILED "failed"
SWEEP_OUT_OF_ITERATIONS "out_of_iterations"
SWEEP_PENETRATING "penetrating"
TENSION_ALL "all"
TENSION_LISTED "listed"
TENSION_NONE "none"
TEST_BOTH "both"
TEST_EITHER "either"

picture

Contents

A picture of a project: its scene through its current camera, at its [window] size, written to a PNG by a second process running balaur run --offscreen --shot.

1 function, 0 constants. Scripts reach it as picture::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
write(string, string) -> str? — Write a picture of the project at project, of scene (project-relative; its main scene when empty), as the files on disk say. Answers where the PNG will be: [export] output's picture folder, or beside the project's manifest. The picture_event event reports it, { kind: "written", path } or { kind: "failed", path, message }. Nil where no second process can run, as in a browser tab.

platform

Contents

Store services every platform shares: sign-in, achievements, leaderboards, cloud saves. A call answers task::wait later with a map whose kind is signed_in, signed_out, done, scores, read, error or unsupported, each an EVENT_* constant. A sign-in or sign-out, asked for or not, is also the platform_event event, events::listen(node, "platform_event").

10 functions, 7 constants. Scripts reach it as platform::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
backend() -> string — The name of the loaded store, or "none".
cloud_read(string) -> int — Read a value the store syncs between the player's devices, and return the id whose read answer holds it as value: a string, or nil when the key holds nothing.
cloud_write(string, string) -> int — Write a value for the store to sync between the player's devices, and return the id its answer carries.
player() -> platform::Player? — Who the store says is playing, or nil before a sign-in has landed.
progress(string, float) -> int — Report an achievement's completion, 0 to 100, and return the id its answer carries.
scores(string, platform::ScoresOptions?) -> int — Read a leaderboard's entries, and return the id whose scores answer holds them as entries, each a Score.
set_presence(string) -> int — Say what the player is doing, where the store shows it, and return the id its answer carries.
sign_in() -> int — Ask the store who is playing, and return the id its answer carries. A later sign-out is the platform_event event.
submit_score(string, int) -> int — Post a score to a leaderboard, and return the id its answer carries.
unlock(string) -> int — Award an achievement whole, and return the id its answer carries.

Constants

name value
EVENT_DONE "done"
EVENT_ERROR "error"
EVENT_READ "read"
EVENT_SCORES "scores"
EVENT_SIGNED_IN "signed_in"
EVENT_SIGNED_OUT "signed_out"
EVENT_UNSUPPORTED "unsupported"

project

Contents

The projects this machine has opened, the templates a new one starts from, and the folder picker the OS provides. What the editor's start screen is made of.

15 functions, 0 constants. Scripts reach it as project::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
copy(string, string) -> project::Project — Copy the project folder at from, one fs.* may read, to into, which must not exist yet, and remember the copy. Answers { path, name }, or { error }.
copy_system_font(string, string) -> bool — Copy an installed face, one system_fonts lists, to to inside the project. Answers whether it was copied; a path the list does not name is refused.
create(string, string) -> project::Project — Write a new project at path from a template id, or from nothing when the id is empty. Answers { path, name }, or { error }.
examples_directory() -> str? — The folder of example projects shipped beside the editor, which fs.* may read and not write from then on. Nil where none ship.
exists(string) -> bool — Whether anything is at path, wherever it is: how a new project's folder is picked clear of one already there.
forget(string) — Drop one project from the list. The folder is not touched.
home() -> string — Where a new project goes unless the reader says otherwise: the home directory on a desktop, and the app's own writable directory where there is no such thing.
in_tab() -> bool — Whether this editor runs in a browser tab, where the page holds the projects and opening one is its call rather than this screen's.
open(string) -> project::Opened — Remember path and start the editor on it, then ask this one to quit. Answers { error } when there is no project there.
open_beside(string) -> project::Opened — Start a second editor on path and keep this one: Edit dependency on a path dependency, whose project is another folder. Answers { error } when there is no project there or no second editor can start.
pick_directory() -> str? — Open the OS folder picker and answer what was chosen, or () when it was dismissed. Blocks while the dialog is up, and answers () on a platform with no picker.
recent() -> [project::Recent] — The projects opened on this machine, newest first: { path, name, opened, exists } each, where opened is a Unix time in seconds and exists says whether the folder is still there.
system_fonts() -> [project::SystemFont] — The faces this machine has installed, by family and style: what the font picker offers to copy into a project, since an exported game cannot count on a face being installed. Empty in a browser tab.
use_data(str?) -> str? — Answer engine::user_data_directory() with the user data directory of the game named name, keep the device id there, and let fs reach it, so a game played here and run alone share saves and a device login. The editor names its own folder with engine::user_data_directory_of. Nil goes back to the editor's own. Answers the directory, or nil.
version() -> string — The version of the binary the editor is running in.

quat

Contents

Rotations as quaternions { x, y, z, w }: from an axis and an angle, from one direction to another or from a rotation_euler, composed, inverted and applied to a vector. Balaur Script over glam's formulas, so every platform turns alike.

8 functions, 0 constants. Scripts reach it as quat::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
from_arc(Vec3, Vec3) -> quat::Quat — The shortest turn that takes the direction from onto to.
from_axis_angle(Vec3, float) -> quat::Quat — A turn of angle radians about axis, which need not be unit length.
from_euler(Vec3) -> quat::Quat — A transform's rotation_euler, in radians, as a quaternion.
identity() -> quat::Quat — The rotation that turns nothing.
inverse(quat::Quat) -> quat::Quat — The turn that undoes q.
mul(quat::Quat, quat::Quat) -> quat::Quat — b, then a: the composed rotation, as a child's turn under its parent's is mul(parent, child).
rotate(quat::Quat, Vec3) -> Vec3 — v turned by q.
to_euler(quat::Quat) -> Vec3 — A quaternion as the rotation_euler a transform takes, in radians.

random

Contents

The engine's one deterministic PCG32 stream: the same seed draws the same numbers on every platform, and a replay reproduces every draw.

6 functions, 0 constants. Scripts reach it as random::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
at(int, int) -> float — The indexth number of the stream seed names, uniform in [0, 1): the same for the same two on every platform, and apart from the engine stream, so a tool's layout draws nothing a game would.
float() -> float — A float from the deterministic engine stream, uniform in [0, 1).
int(int, int) -> int — A whole number from the deterministic engine stream, uniform in [low, high], both ends included.
range(float, float) -> float — A float from the deterministic engine stream, uniform in [low, high): the two arguments.
seed(int) — Restart the deterministic engine stream at the given seed, so every draw after it repeats.
uuid() -> string — A version-4 UUID drawn from the deterministic engine stream, so a replay makes the same ids; not for anything that must be unique across machines.

regex

Contents

Regular expressions, the regex-lite dialect: no look-around or back-references. A pattern is compiled on every call; a match is a Match, with byte offsets and one string per capture group, nil for a group that took no part.

6 functions, 0 constants. Scripts reach it as regex::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
escape(string) -> string — text with every metacharacter escaped, so it matches itself.
matches(string, string) -> bool — Whether the pattern matches anywhere in text.
replace(string, string, string, bool?) -> string — text with the first match replaced, or every match when all is true; $1 and ${name} in with stand for groups.
search(string, string) -> regex::Match? — The first match, or nil.
search_all(string, string) -> [regex::Match] — Every non-overlapping match, in order.
split(string, string) -> [str] — The pieces of text between matches.

release

Contents

Which build of the engine this is, what the channels are publishing, and replacing this install with another. The editor's Engine tab and About sheet; balaur update is the same code.

4 functions, 0 constants. Scripts reach it as release::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
channels() -> [str] — Every release line a build may follow, in the order a version moves through them.
check() -> bool — Read the release feed on a thread. release_event hears { kind: "listed", rows }, newest first, each { tag, id, channel, when, current, order, download }: order is newer, older or same than this build, empty where they do not order, and download is the zipped app a macOS bundle fetches instead. { kind: "failed", job: "check", message } when the feed could not be read. False while a recording plays.
install(string, string, release::InstallOptions?) -> bool — Replace this install with what that channel or tag holds, on a thread; allow_downgrade = true lets an older build replace a newer one. release_event hears downloading with done and total bytes, unpacking, then installed with a note, or failed with job: "install". Refuses where installed().held says why. False while a recording plays.
installed() -> release::Build — This build: { version, id, channel, tag, source, held }, where id is the build id a release was tagged with, tag is the release its assets live under, source is true for a build from a checkout, and held says why this install cannot replace itself, empty when it can.

render

Contents

What a frame is made of: the shape, sprite, mesh or emitter a node draws, the 2D and 3D cameras, the backdrop, debug lines and screenshots. window holds the window itself.

45 functions, 41 constants. Scripts reach it as render::.

Acts on boolean3d, occluder2d, screen_notifier2d, tilemap: those functions are also methods on the component's handle, without the node argument.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
begin_retained(string) — Keep what is drawn from here to end_retained under key, drawn every frame until the key is drawn again or cleared: an overlay redrawn when what it shows moves, not each frame.
bounds(Node) -> [Vec3]? — The box the node's geometry covers in its own space, as a centre xyz and half-extents xyz, with a z of zero for a 2D node; nil for a node that draws nothing. A solver's body reports where it is now, not where it was built; a text, the lines it was last laid out in.
built_mesh(Node) -> render::BuiltMesh? boolean3d The triangles the node's boolean settled on, ready to be written out as a mesh asset; nil when the node draws no built geometry.
camera_2d() -> render::Viewport2d — The 2D camera this frame: its center and its zoom in logical pixels per world unit; all zeros with no window.
camera_matrix() -> [float] — The camera's projection*view matrix this frame, 16 numbers column-major; all zeros with no window.
camera_pose() -> render::CameraPose — The camera the renderer actually used, which is where a backend put it and not what a camera3d asked: its eye and target, the vertical fov in radians and the HiDPI scale_factor. Zeros and a scale of one with no window.
cell(Node, int, int) -> int tilemap The tile at a column and row, or -1 for an empty cell or one past the edge.
cell_terrain(Node, int, int) -> int tilemap The terrain value painted at a column and row, or -1 where nothing was painted.
check_material(string) -> [script::Diagnostic] — Every diagnostic about the material at that path, as [{ file, line, column, severity, message }]; empty when it links.
clear_retained(string) — Stop drawing what key kept. A script hears the camera a frame was drawn with move, to draw a group sized in pixels again, with events::listen(this.node, "camera_moved").
debug_view() -> string — Which channel the viewport is drawing instead of the scene's colour, or empty for the scene as it is.
debug_views() -> [str] — Every channel name set_debug_view accepts, as a list.
draw_arc_2d(Vec2, float, float, float, float?, Color?, render::DrawOptions?) — Stroke an arc between two angles in radians, counter-clockwise from the x axis, for this frame; width is in pixels, and opts takes z_index.
draw_box_3d(Vec3, Vec3, Color?) — Draw a wireframe box centred at a point, size across along each axis in world units, for this frame.
draw_capsule_3d(Vec3, float, float, Color?) — Draw a wireframe capsule centred at a point, height being the straight part along y, for this frame.
draw_circle_2d(Vec2, float, Color?, render::DrawOptions?) — Fill a circle in world units for this frame, over everything the scene drew; opts.z_index places it among the nodes of that index instead.
draw_lines_3d([render::Line3d]) — Draw 3D world-space lines for this frame, each with its own ends, colour, width, perspective and on_top: a frame's worth crosses to the engine once.
draw_polygon_2d([Vec2], Color?, render::DrawOptions?) — Fill a convex outline of world-space points for this frame; geometry2d cuts a concave one into triangles first. opts takes z_index.
draw_polyline_2d([Vec2], float?, Color?, render::DrawOptions?) — Stroke a chain of world-space points for this frame; width is in pixels, and opts takes z_index.
draw_rect_2d(Vec2, Vec2, Color?, render::DrawOptions?) — Fill a rectangle of size centred at position, in world units, for this frame; opts takes z_index.
draw_sphere_3d(Vec3, float, Color?) — Draw a wireframe sphere centred at a point, as three rings in world units, for this frame.
draw_text_2d(Vec2, string, render::TextOptions?) — Draw a line of text in 2D world space for this frame, shaped by the engine's fonts. opts takes the text2d keys (font_size, font_weight, font_style, color, text_align, markup, max_width, font, text_style, …), pixels_per_unit and z_index; font and text_style name an asset.
draw_text_3d(Vec3, string, render::TextOptions?) — The same in 3D world space, on a quad that faces the camera. pixels_per_unit sizes it, so text a metre away reads the same whatever the font size.
draw_texture_2d(string, Vec2, Vec2, Color?, render::TextureOptions?) — Draw a project image over a rectangle of size centred at position, in world units, for this frame; the colour tints it. opts takes z_index, and region_origin and region_size in the image's pixels for part of it.
end_retained() — Keep what was drawn since begin_retained under its key, in place of what the key held.
hold_cameras(Node?) — Let no camera under a node drive the view, whatever its current says, until it is called with nil: an editor looking at a game through its own camera. The cameras keep what the scene asked of them.
is_on_screen(Node) -> bool screen_notifier2d Whether any of the notifier's box was on screen at the end of the last frame.
material_params(string) -> [render::Param] — The material's editable rows, one { name, type, value } per field its linked shader declares; empty when it will not link.
mouse_ray() -> render::Ray — The picking ray through the mouse position, in world units: where it starts and which way it goes.
mouse_world_2d() -> Vec2 — The mouse position in 2D world coordinates, for picking.
outline(Node) -> [Vec2] occluder2d The outline this node blocks 2D light with, as its points in world space, with the first repeated at the end when the outline is closed. Empty on a node with no occluder2d.
pick_ray_at(Vec3, Vec3) -> render::Hit? — The nearest node with a 3D shape that a world-space ray meets, from its origin along its direction, as node and at, how far along the ray it was met; nil when the ray meets nothing.
screenshot(string) — Save the next rendered frame as a PNG at a project-relative path. screenshot_saved goes to every listener with the path once it is on disk, and screenshot_failed with { path, error } when it cannot be, a run with no renderer included.
set_background(Color) — Set the colour the viewport is cleared to behind everything drawn: the colour a #rrggbb writes, each channel from 0 to 1. Its alpha is not read.
set_cell(Node, int, int, int) tilemap Put one tile at a column and row; a tile below zero clears the cell, and a cell outside the map grows it in that direction. The mesh rebuilds on the next frame.
set_cell_terrain(Node, int, int, int) tilemap Paint a terrain value at a column and row and let the tileset's rules pick the tiles, for that cell and the ring around it; below zero clears it.
set_debug_view(string) — Draw one channel of the scene (normals, uv, depth or albedo) instead of its colour; an empty name puts the picture back.
set_shader_preview(string, int) — Draw the value a shader's line computes for every pixel that reaches it; line 0 puts the picture back.
snap_aov(string, string) — Render the 3D scene once more as render.AOV_DEPTH (nearest brightest), AOV_NORMALS (world space), AOV_CAMERA_NORMALS or AOV_SEGMENTATION (a colour per object) and save it as a PNG, announcing it as screenshot does. A read-back of the GPU, as screenshot is.
stats() -> render::Stats — What this frame draws: { draws, triangles, texture_bytes, textures, nodes }, where nodes is a row per node that drew, each { node, draws, triangles, texture_bytes, copies }. Presentation, never simulation: nothing in the digest reads it.
text_size(string, render::TextOptions?) -> Vec2 — The width and height text shapes to, in font pixels, with the project's own fonts and never a system face, so a run with no window open answers as a windowed one does. A width is presentation: writing one into state puts presentation in the digest.
texture_pixels_per_unit(string) -> float — How many of an image's pixels make a world unit when a sprite says 0: its own pixels_per_unit import setting, else 100.
texture_size(string) -> Vec2 — An image's width and height in pixels, read from the file's own header.
trace_texture(string, render::TraceOptions?) -> [[Vec2]] — The outline of an image's opaque pixels, as [x, y] points in a node's own space, ready to be a polygon's positions. opts takes threshold (alpha counted as opaque, 0 to 1, default 0.5), tolerance (how many pixels of detail to drop, default 2), pixels_per_unit (default 100) and holes (every loop, largest first: each other island counter-clockwise and each hole clockwise; default false keeps the largest alone). Counter-clockwise with y up, centred on the origin, the way a sprite at the same pixels_per_unit is drawn.
triangles_of(Node, Node?) -> [Vec3] — The triangles node draws, from its mesh, its shape or its 2D polygon, as three corners each in the space of space, or of the world where it is left out.

Constants

name value
ALIGN_CENTER "center"
ALIGN_END "end"
ALIGN_START "start"
ALPHA_BLEND "blend"
ALPHA_MASK "mask"
ALPHA_OPAQUE "opaque"
ALPHA_PREMULTIPLIED "premultiplied"
AOV_CAMERA_NORMALS "camera_normals"
AOV_DEPTH "depth"
AOV_NORMALS "normals"
AOV_SEGMENTATION "segmentation"
FOG_EXPONENTIAL "exponential"
FOG_EXPONENTIAL_SQUARED "exponential_squared"
FOG_LINEAR "linear"
FOG_NONE "none"
FONT_ITALIC "italic"
FONT_NORMAL "normal"
LIGHT_DIRECTIONAL "directional"
LIGHT_POINT "point"
LIGHT_SPOT "spot"
SHAPE_BOX "box"
SHAPE_CAPSULE "capsule"
SHAPE_CIRCLE "circle"
SHAPE_CONE "cone"
SHAPE_CYLINDER "cylinder"
SHAPE_ELLIPSE "ellipse"
SHAPE_NGON "ngon"
SHAPE_PLANE "plane"
SHAPE_PRISM "prism"
SHAPE_PYRAMID "pyramid"
SHAPE_RECTANGLE "rectangle"
SHAPE_SPHERE "sphere"
SHAPE_STAR "star"
SHAPE_TORUS "torus"
SHAPE_TUBE "tube"
TONEMAP_ACES "aces"
TONEMAP_AGX "agx"
TONEMAP_NEUTRAL "neutral"
TONEMAP_NONE "none"
TONEMAP_REINHARD "reinhard"
TONEMAP_TONY_MCMAPFACE "tony_mcmapface"

replay

Contents

Records what a running game is fed and plays it back. A recording holds each tick's input, network arrivals and events; balaur run --record writes one.

16 functions, 4 constants. Scripts reach it as replay::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
divergence_tick() -> replay::Divergence? — The first tick whose replay did not reproduce the recorded digest, or nil.
events(int, int) -> [replay::Event] — The events recorded between two ticks, each with its tick, kind, label and data.
header() -> replay::Header? — The loaded recording's project, start time, script fingerprint, its frame count and the ticks they span, and how it ended; nil with none loaded.
info(string) -> replay::Header? — The same summary for a recording on disk, without loading it. Nil when it cannot be read.
load(string) -> replay::Header? — Read a recording and put it in front of the engine, paused before its first tick. Nil when it cannot be read, which is logged.
marks(string, str?) -> [replay::Mark] — The ticks at which one replay source held a non-empty list under a key, and what it held.
pause() — Stop between ticks, holding the simulation still while the frame loop keeps drawing.
play() — Run the loaded recording, one recorded tick per frame.
position() -> int — The tick playback has reached.
record(string, replay::RecordOptions?) -> str? — Start recording into a file; call it before the code it records runs. Answers the path, or nil when the file cannot be written, which is logged.
recording() -> str? — The file being recorded into, or nil.
recording_name() -> string — A file-safe name for a recording starting now, so a list of them sorts by when they ran.
seek(int) — Run recorded ticks until playback reaches the given tick; forward only.
state() -> string — What playback is doing: STATE_STOPPED, STATE_PLAYING, STATE_PAUSED or STATE_SEEKING.
stop(str?) -> str? — Close the recording, naming why it ended, and return the file it wrote.
unload() — Drop the loaded recording and let the game run live again.

Constants

name value
STATE_PAUSED "paused"
STATE_PLAYING "playing"
STATE_SEEKING "seeking"
STATE_STOPPED "stopped"

rollback

Contents

Rollback netcode from a script's side. input reads this tick's input, real or predicted; is_resimulating is true when a tick runs again after a late input.

2 functions, 0 constants. Scripts reach it as rollback::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
input(int) -> any — What that player is doing on the tick being simulated, real or predicted; nil outside a session or for a player it does not know.
is_resimulating() -> bool — Whether this tick is a re-run of one already simulated, so a script can skip anything it must not do twice.

scene

Contents

The node tree: its root, lookup by path and instancing, plus the component vocabulary an editor's palette lists.

23 functions, 0 constants. Scripts reach it as scene::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
attach_scripts(Node) — Run every script the nodes under a node name, children first: what starts a scene built with scripts: false.
bindable_events(Node?) -> [str] — Every event a [[nodes.bindings.rows]] row may answer, in the order an editor offers them: the core hooks, and on a node the emitted: events it, its components and its script announce.
binding_actions() -> [str] — Every action a binding row may do, in the order an editor offers them.
component_expects(string) -> [str]? — The components a component type needs something from, for ordering or grouping its sections; nil for a name nothing registered.
component_properties(string, any) -> any — What a component's apply would receive for params: the schema's defaults with a partial table merged over them. This is how a tool compares two spellings of the same component.
component_schema(string) -> any — A component type's property schema as a table, its properties in the order it writes them; nil for a name nothing registered.
component_tags(string) -> [str]? — The facets a component type is filed under, for filtering a palette; nil for a name nothing registered.
component_types() -> [str] — The names of every registered component type, not the components on any node.
instantiate(string, Node?, scene::InstantiateOptions?) — Build a scene document (TOML text, not a path) under a parent. scripts: false names each node's script without running it; root is the project the text names its files from, when it is not this one, and every path is made absolute against it.
keep_changes(Node?) — Keep every change under a node as it happens, each with what it replaced, until take_changes hands them over; nil stops, and what was kept goes. An editor's undo, which the changed event serves a frame late and merged.
node_by_id(string, Node?) -> Node — The node carrying a stable id, which survives the rename and the reparent a path does not; nil when nothing carries it. under bounds the search to one subtree, for a tool holding more than one tree.
parked() -> [str] — Every scene switch kept built, by the path it was asked for, oldest first.
root() -> Node — The tree's root node.
set_variable(string, any) — Write a scene variable, coerced to the type it was declared with. Every node declaring on_variable_changed hears about it at the end of the tick; writing the value it already holds says nothing.
switch(string, scene::SwitchOptions?) — Go to another scene at the end of this tick, so a script asking inside update is not moving the tree it runs in. The scene left stays built and parked, and a scene already parked comes back as it was, with no node built and no init run; each of their scripts is told on_parked_changed. A parked scene does not update, draw, take input or hear a hook, an event or a call, and a task its script awaits holds until it returns. A script reaching it can still read and write its components; it takes no new node or script. A digest and a snapshot cover it, a save holds nothing of it, and the change log says nothing of a park or a return. A file edited since the scene was built is built again on the way back. fade is seconds of crossover: the old scene's roots fade out to the clear colour over the first half, the switch happens, and the new scene's fade in over the second. What stays parked is bounded by itself: past 20,000 parked nodes the scene left longest ago is freed, and a system memory warning frees them all; a scene freed is built again the next time it is asked for, its init running. Reset is a switch to the file already there, which frees it and builds it again; to come back to a scene new from elsewhere, unload it first.
tagged(string) -> [Node] — Every node filed under a tag, in tree order; what a scene's tags key and node.add_tag feed.
take_changes() -> [scene::Change] — The changes kept since the last take, oldest first, emptying the list: { node, kind, id } with kind one of component (component, properties, was: the table asked before), attached, removed (was), added (parent), freed (parent, place, was: the subtree as scene text), renamed (was), moved (parent, was: { parent, place }), script (was: { source, props }, nil for none) and keys (was: every one of the node's own keys, visible to tags). Parents are stable ids, so a change outlives the nodes it names.
to_toml(Node, scene::ToTomlOptions?) -> string — The scene under a node, that node its root, as a scene file's text: what instantiate builds again. Each component is what was asked of it, a prefab's nodes are their instance's overrides, and root writes every path under that project's root as it spells it.
unload(string) — Lets go of a scene: frees it if it is parked, its scripts' on_free running as for any node freed, and drops what its file and prefabs have cached, the parsed text and the pictures they name. The scene running stays where it is, and a picture something still draws is read again when it next asks.
variable(string) -> any — A scene variable's value, or nil for a name nothing declared. A scene declares them under [variables].
variables() -> [scene::Variable] — Every declared variable as { name, type, value }, in name order.
warnings(Node) -> [scene::Warning] — What is off about the node, as { component, property, message }: a component missing one it expects, a write its component refused, and what a component says of itself. property is nil for the whole component; advisory only.
with_component(string) -> [Node] — Every node carrying the named component, in tree order. What a script asks instead of walking the tree itself.

script

Contents

What a tool asks about a script file. The editor and balaur check have it; a game's runtime does not.

13 functions, 0 constants. Scripts reach it as script::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
api() -> [script::ApiModule] — Every module a script can reach: its functions, their signatures and what each does, and its constants.
check(string, string) -> [script::Diagnostic] — Every compiler error in the source, read as the file at the path: one for each function that does not compile.
complete(string, string, int, int) -> [script::Completion] — Every completion valid at that caret; an editor passes the buffer it is showing.
definition(string, string, int, int) -> script::Place? — Where the name at that caret is declared in the file; nil when it is not.
exports(string) -> any — The pub fields of the script's struct, which a scene tunes, with their types and defaults.
find(string, string, string) -> [script::Place] — Every place that text appears in the file, matched as text rather than as a name.
format(string, string) -> string — The source laid out as balaur fmt lays it out; unchanged when it will not parse.
hover(string, string, int, int) -> script::Hover? — What the name at that caret is: its type, or its signature; nil when it is nothing.
references(string, string, string) -> [script::Place] — Every use of that name in the file.
rename(string, string, string, string) -> [script::Edit] — The file with a name renamed; nothing is written, so a caller can show it first.
replace(string, string, string, string) -> [script::Edit] — The file with that text replaced; nothing is written, so a caller can show it first.
signature(string, string, int, int) -> script::Signature? — The call the caret is inside, and which argument it is on.
symbols(string, string) -> [script::Symbol] — What the file declares: its structs, their fields and methods, its functions, and each event with its description for a detail.

settings

Contents

Every setting the engine, its plugins and the game declare, by path: physics/solver_iterations is [physics] solver_iterations in project.toml. define adds your own; [override.<platform>] tables answer per platform.

10 functions, 0 constants. Scripts reach it as settings::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
all() -> [settings::Setting] — Every defined setting as { path, scope, spec }, in definition order.
base(string) -> any — What the file says, ignoring every override: what a settings screen edits.
clear(string) — Forget one value, so the next write drops the key: how an override is removed.
define(string, any) — Declare a setting of your own: type, default, and optionally min, max, options, help, order and applies. A path starting editor/ is kept on this machine; anything else ships with the game.
get(string) -> any — One setting's value here: the narrowest [override.<tag>] this platform answers to, else what was set, else what its definition defaults to, else nil.
known_tags() -> [str] — Every tag a project may write an override for: the engine's, then the project's own from [export] tags.
merge_toml(string) — Read values out of a TOML text, folding them onto what is already loaded.
overrides(string) -> [str] — The tags this project holds an override for at path, in tag order.
set(string, any) — Change one setting, in memory. Whether it takes effect now or on the next run is the setting's own business; all reports it as applies.
to_toml(string, string) -> string — The text one scope would write, starting from existing so anything no setting describes survives. Scope is "project" or "editor".

skeleton

Contents

Bones under a rig node, in the order a skin numbers joints in. A bone is any node carrying bone2d or bone3d, which holds its rest pose.

1 function, 0 constants. Scripts reach it as skeleton::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
bones(Node) -> [Node] — The bones under the node in tree order, the order a skin numbers them in, the node itself first when it is one.

strings

Contents

Localization: one strings/<locale>.toml per language, keys to strings. [locale] in project.toml sets the starting locale and the fallback; a key neither has comes back as itself.

5 functions, 0 constants. Scripts reach it as strings::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
locale() -> string — The locale in force.
locales() -> [str] — Every locale the project ships a strings/<locale>.toml for, in name order.
set_locale(string) — Switch locale; the next tr answers in it, which for a widget showing a key is the next frame.
system_locale() -> str? — The locale the operating system reports, like en-US, or nil when it says nothing; recorded with the session. A run starts in the shipped locale nearest it unless [locale] initial says.
tr(string, any) -> string — The string for a key in the current locale. {name} in it is replaced by the argument called name, and an n argument also picks the plural form the locale's language calls for.

task

Contents

Waiting inside an async method: init and event handlers may await; update is synchronous.

3 functions, 0 constants. Scripts reach it as task::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
frames(int) — Park an async method for a number of fixed steps; counted on the tick, so a replay waits exactly as long.
seconds(float) — Park an async method for a span of simulation time, woken on fixed step ceil(seconds * tick_hz), so 4/60 at 60 Hz is 4 steps; the wall clock never enters it.
wait(int) -> any — Park an async method until the engine wakes the token a binding gave it, and answer what it woke with.

toml

Contents

TOML text to and from script tables, the format of scene files, asset definitions and component properties.

3 functions, 0 constants. Scripts reach it as toml::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
encode(any) -> string — A table written back out as TOML text; a node or callback in it is not data and is an error.
parse(string) -> any — The table a TOML document describes; nil for text that does not parse.
patch(string, any) -> string — The document's text with this table's keys written into it, keeping every comment, the key order and any table the value does not name. What a tool saving a hand-written file uses instead of encode.

types

Contents

The names of a value's type: what kind() answers on an any.

0 functions, 8 constants. Scripts reach it as types::.

Constants

name value
KIND_NIL "nil"
KIND_BOOL "bool"
KIND_INT "int"
KIND_FLOAT "float"
KIND_STRING "str"
KIND_LIST "list"
KIND_MAP "map"
KIND_NODE "node"

ui

Contents

What a script asks of the UI and tells it: where a widget node drew, focus, the screen's classes, the scale, the theme, the clipboard, when a pass runs and the pooled rows. Nothing here draws; a UI is widget nodes in a scene.

37 functions, 63 constants. Scripts reach it as ui::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
clear_focus() — Focus nothing, as a pad's back button leaves a menu; the widget focus leaves hears focus_exited.
click(Node, ui::ClickOptions?) -> bool — Click a widget node as the pointer would, at the next tick and with no window needed: what a test harness drives the game with. False for a node a pointer could not click, hidden, disabled or not a widget; { hidden: true } clicks a hidden one anyway, as a test emitting its signal would.
colors_apart(any) -> [ui::ColorsApart] — Every pair of a widget_theme document's colours that say something by hue (primary, success, warning, danger), closest first, as { first, second, distance, vision }: how far apart they stand in CIELAB for the colour vision that sees them closest. Under 10 the two read as one colour to that reader.
complete_theme(any) -> any — The theme document with every colour and size it leaves out derived from its sources, and dark stated.
contrast(string, string) -> float — The WCAG contrast ratio between two #rrggbb colours, 1 to 21. Body text wants 4.5, large or bold text 3.
contrast_pairs(any, string) -> [ui::ContrastPair] — Every ink a widget_theme document's roles draw on the fill each draws it on, as { role, ink, fill, ratio, need }. A role with no fill is read on the ground token; need is 3 for large or bold text and 4.5 otherwise.
edit(Node, any) -> bool — Change a widget's value as the reader would, at the next tick, so it announces value_changed: a number for a slider or a number field, text for a text field, a dropdown's pick, a list's row or a tab, a colour for a swatch, a boolean for a fold. False for a disabled widget or a value its kind does not take.
fill_slot(Node, int, ui::Control?) -> bool — One child of host, the one at slot, filled as fill_strip fills each, made with any before it that are missing, or hidden for nil. The others are left as they are, so a list of hundreds of rows writes the few on screen and, as they scroll, the ones entering. True when the control's table differed from the last one written to it.
fill_strip(string, [ui::Control]) -> bool — Put one widget node per control table under the node at host, made, reused and hidden as the list changes; a node is written only when its table changed. A control's on_click or on_change hears the reader's edit and on_submit hears Enter as they happen: the name of a method, called on the nearest node above the control whose script has it with the control's data, then the edit, then the control's node. So a strip that did not change need not be filled again, and a control carrying controls is a row holding them. True when a control's table differed from the last one written to it.
finish_loading() — Say the load is through, which lets a held splash go once splash_seconds has also passed. The editor calls it once its shell has settled.
focus_down() — The same downwards, by neighbour_down.
focus_left() — The same to the left, by neighbour_left.
focus_next() — Move focus to the next widget in scene order, wrapping past the last.
focus_previous() — Move focus to the previous widget in scene order, wrapping past the first.
focus_right() — The same to the right, by neighbour_right.
focus_up() — Move focus to the nearest widget above, as the up arrow does: the one the focused widget names in neighbour_up, else by where the widgets were drawn, round to the bottom past the top. What a stick or a d-pad's action calls.
focused_widget() -> Node — The widget node focus is on, or nil.
height_class() -> string — How much height this screen has, as ui::SHORT or ui::TALL.
pasted_text() -> string — The text the last UI pass saw pasted, empty when it saw none: the platform clipboard is not readable on demand. The pasted event carries text no field took as it arrives.
patch_control(Node, [int], ui::Control) -> bool — What patch names written to the pooled control at at, child indices down from host, and remembered, so the next fill compares against it. For a value that follows the node: what the patch leaves out is not asked about, and a handler's name is a fill's to give. False where no control is there or nothing moved.
pixels_per_design() -> float — How many of the window's own pixels a design pixel covers this frame: the UI scale, the display's scale and the reader's text size together. Divide input::mouse_position() by it for design pixels.
request_repaint(ui::RepaintOptions?) — Run the frame and its UI pass under [window] low_processor; call it every frame something on screen moves without input, such as while the scene plays. after seconds asks for one that far ahead instead.
save_pasted_image(string) -> bool — Write the image last pasted where no field took it, which the image_pasted event announced with its { width, height }, to path as a PNG. Answers false when there is none, or it was written already.
scale() -> float — The global UI scale: how many screen pixels a design pixel is drawn at, on top of the display's own.
set_clipboard(string) — Copy text to the system clipboard. The next UI pass hands it over, and asks for itself.
set_focus(Node) — Put focus on a widget node. A node focus cannot activate is refused at the next draw.
set_load_progress(float, str?) — Report how far a load is, zero to one. This is what holds [application] splash past its seconds, and what draws the bar under it.
set_scale(float) — Set the global UI scale, clamped to between 0.25 and 3.0. It is egui's zoom factor, so it grows every control and every font; screen_size already answers in the design pixels it leaves.
set_theme(any) — Put a theme in force over [ui] theme and theme_dark, for every widget and egui's own controls: a widget_theme file's path, or a theme document, with source colours under colors and sizes under sizes. What the document leaves out is derived from its sources. A root's own theme still dresses its subtree with that one, and nil goes back to the project's.
set_widget_layer(bool, Vec2?, Vec2?) — Turn drawing of the scene's widget nodes on or off, and confine it to the rect at position of size, in design pixels; the whole window when either is left out.
tab_rect(Node) -> ui::Rect? — Where a tabs page's own button in the strip was last drawn, as { x, y, width, height } in design pixels; empty before the strip has drawn. widget_rect on the same node answers with the page body.
takes_pointer_at(Vec2) -> bool — Whether the UI would take a press at this point, in design pixels, by the same layers as wants_pointer: what an editor asks of a point it is about to act on.
wants_keyboard() -> bool — Whether a UI widget held keyboard focus when the last pass ended, so the game should leave key presses alone.
wants_pointer() -> bool — Whether the UI has the pointer or finger, so the game should leave it alone: what stops a tap on a HUD button also firing the shot behind it. A press is routed once, from the top: an open dialog, then a popup or window, then a widget that is not interactive = false or a seam between boxes, and the world last; it keeps that answer until the button comes up. False without a window.
widget_rect(Node) -> ui::Rect? — Where a widget node was last drawn, as { x, y, width, height } in design pixels; empty until it has drawn once.
width_class() -> string — How much width this screen has, as ui::NARROW, ui::MEDIUM or ui::WIDE. Read every frame: a rotation changes it. A run with no window answers ui::WIDE.
window_size() -> Vec2 — The window's width and height, in design pixels; a headless run, and a script's init before the window opens, answer the [window] size the project states at the UI scale.

Constants

name value
ALIGN_BASELINE "baseline"
ALIGN_CENTER "center"
ALIGN_END "end"
ALIGN_START "start"
ALIGN_STRETCH "stretch"
ANCHOR_BOTTOM_LEFT "bottom_left"
ANCHOR_BOTTOM_RIGHT "bottom_right"
ANCHOR_CENTER "center"
ANCHOR_CENTER_BOTTOM "center_bottom"
ANCHOR_CENTER_LEFT "center_left"
ANCHOR_CENTER_RIGHT "center_right"
ANCHOR_CENTER_TOP "center_top"
ANCHOR_FILL "fill"
ANCHOR_FILL_ACROSS "fill_across"
ANCHOR_FILL_BOTTOM "fill_bottom"
ANCHOR_FILL_DOWN "fill_down"
ANCHOR_FILL_LEFT "fill_left"
ANCHOR_FILL_RIGHT "fill_right"
ANCHOR_FILL_TOP "fill_top"
ANCHOR_TOP_LEFT "top_left"
ANCHOR_TOP_RIGHT "top_right"
FONT_STYLE_ITALIC "italic"
FONT_STYLE_NORMAL "normal"
FONT_STYLE_OBLIQUE "oblique"
HEIGHT_SHORT "short"
HEIGHT_TALL "tall"
INPUT_POINTER "pointer"
INPUT_TOUCH "touch"
MODIFIER_ALT "alt"
MODIFIER_CMD "cmd"
MODIFIER_CTRL "ctrl"
MODIFIER_SHIFT "shift"
WIDGET_BUTTON "button"
WIDGET_CHECKBOX "checkbox"
WIDGET_CODE "code"
WIDGET_COLOR_PICKER "color_picker"
WIDGET_COLUMN "column"
WIDGET_DIALOG "dialog"
WIDGET_DROPDOWN "dropdown"
WIDGET_FOLD "fold"
WIDGET_GRID "grid"
WIDGET_IMAGE "image"
WIDGET_LABEL "label"
WIDGET_LIST "list"
WIDGET_MENU "menu"
WIDGET_NUMBER_FIELD "number_field"
WIDGET_PANEL "panel"
WIDGET_PROGRESS_BAR "progress_bar"
WIDGET_ROW "row"
WIDGET_SCROLL "scroll"
WIDGET_SEPARATOR "separator"
WIDGET_SLIDER "slider"
WIDGET_STACK "stack"
WIDGET_SWITCH "switch"
WIDGET_TABLE "table"
WIDGET_TABS "tabs"
WIDGET_TEXT_AREA "text_area"
WIDGET_TEXT_FIELD "text_field"
WIDGET_TREE "tree"
WIDGET_WINDOW "window"
WIDTH_MEDIUM "medium"
WIDTH_NARROW "narrow"
WIDTH_WIDE "wide"

websocket

Contents

A long-lived socket for text or binary frames. Events reach the node's on_websocket_event (or on_event) as a map with socket and kind: open, message, binary, closed or error, each an EVENT_* constant. An error carries its reason, and the HTTP status when a server refused the upgrade.

5 functions, 9 constants. Scripts reach it as websocket::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
close(int) -> bool — Ask the connection to close, which still delivers a closed event with its code; false when it was already gone.
connect(Node?, string, websocket::ConnectOptions?) -> int — Open a connection and return the id send_text, send_bytes and close take, which task.wait resumes on with the open or error event; options are on_event, compression and headers. With no node, only a task.wait hears it.
send_bytes(int, [int]) -> bool — Queue a binary frame on the connection; false when it is already gone.
send_text(int, string) -> bool — Queue a text frame on the connection; false when it is already gone.
state(int) -> string — Where the connection is: connecting, open, closing or closed, each a STATE_* constant.

Constants

name value
EVENT_BINARY "binary"
EVENT_CLOSED "closed"
EVENT_ERROR "error"
EVENT_MESSAGE "message"
EVENT_OPEN "open"
STATE_CLOSED "closed"
STATE_CLOSING "closing"
STATE_CONNECTING "connecting"
STATE_OPEN "open"

window

Contents

The OS window and the display under it: mode, cursor, app icon, keep-awake, the safe area and the refresh rate.

7 functions, 0 constants. Scripts reach it as window::.

Functions

Argument kinds are the script values a call passes: node is a node handle, any a table or value of any kind, fn a callback.

function acts on what it does
refresh_rate() -> float — Frames per second the display refreshes at, as measured over the last frames; 60 with no window.
safe_area() -> window::SafeArea — The display's insets in pixels, { left, top, right, bottom }: what a notch or a home bar covers, read once per frame and recorded. Zero on a desktop.
set_app_icon(string, window::AppIconOptions?) — Set the application icon, the dock or taskbar one, from a PNG or an SVG in the project. opts.plate colours the disc a macOS dock icon sits on, white by default. Replaces [application] icon for the run.
set_cursor_grab(bool) — Confine the cursor to the window, for FPS-style mouse look.
set_cursor_hidden(bool) — Hide or show the mouse cursor over the window.
set_keep_awake(bool) — Keep the screen from dimming while the game runs: a page takes a wake lock, a phone its equivalent, a desktop needs nothing.
set_window_mode(string) — windowed, maximized, fullscreen (borderless) or exclusive (the monitor's largest video mode): the same choice as [window] mode.

Forge

Contents

Forge builds your Balaur game for every platform, from one repository, without a Mac, a Windows machine or an Android toolchain of your own. Push to GitHub and each platform you picked comes back as a download, signed where you gave it the keys, with a check on the commit saying how it went.

It is the same export you run on your own machine with balaur export <project> --target <platform>. Forge runs it for all your targets at once, on Linux, and keeps the result.

What it does

Start with Your first build.

What happens to your code

Forge runs code you wrote, on machines you do not own, so here is exactly what it does with it.

First build

Contents

Before you start

1. Register the repository

Open Projects and press New project. It asks for the repository, three ways, with an optional icon and group:

Every project then does the same things, whichever way it came: Play, Edit, Public and Add to project. Forge keeps a copy of a repository on GitHub or at a URL, and the editor's save goes to that repository first. GitHub takes it through the App; a URL takes it only if it accepts a push without a password, which public hosts do not.

The project is named after the repository (you name one started from an example), builds its default branch (main for a URL), and has every target on. Registering opens its dashboard; the three change on its Repository and Targets tabs, and the next build uses them. A target with no signing set up yet builds unsigned and says so.

The eight targets are linux-x64, linux-arm64, macos-universal, windows-x64, windows-arm64, ios, android and web. Builds and artifacts says what each one produces. For a first build, turning every target off but linux-x64 on Targets is the fastest way to see everything work.

2. Build it

On Projects, press Build now on the project's card, or on its Builds tab. You land on the build's page: one card per target, and the build's output underneath, streaming as it runs — the clone first, then the export.

A target goes queued → running → succeeded or failed. Targets build independently, so a failed ios does not stop linux-x64.

3. Download

A succeeded target has a Download button. Its badge says whether it was signed; the first build almost certainly was not, and says what it would need. Downloads are kept for 30 days.

Next

GitHub

Contents

Forge talks to GitHub through the Balaur Engine GitHub App. Installing it on a repository is what lets Forge clone it when it is private, hear about every push, and put a check on each commit.

Connect and install

  1. On New project, open From GitHub and press Connect GitHub. GitHub asks you to authorise Forge once; Forge uses that to ask GitHub which App installations you can see, and nothing else.
  2. If the App is not installed anywhere yet, press Install the App. Pick your account or an organisation you administer, and choose All repositories or only the ones Forge should build. GitHub sends you back and your installations appear.
  3. On New project → From GitHub, pick the installation, then the repository. The name and default branch come from it and every target is on; press Register project.

Installing on an organisation needs an owner of that organisation. A member can request the installation, and an owner approves it on GitHub.

A repository is missing from the list? The installation was given selected repositories and that is not one of them. Use Grant the App access to it under the list, add the repository on GitHub, then reconnect.

What the App can see and do

Permission Why
Contents: read and write clone the repository, and push the editor's saves
Metadata: read list the repositories you granted
Checks: write put a Forge / <target> check on the commit it built
Email addresses: read only for Log in with GitHub, to find your existing account

It pushes only the editor's saves, to the branch the project builds. It cannot open issues or pull requests, or read repositories you did not grant. Forge decides which installations your account may build from by asking GitHub with your own authorisation, so nobody else can bind a project to your repositories.

Every push builds

Once a project is registered from GitHub, every push to that repository starts a build of the pushed branch or tag, with the project's targets, at the exact commit that was pushed. A project registered by URL builds on push too, if the App is installed on its repository.

A save in the editor is a push by the App, and it builds nothing, like a save on a project kept on Forge. Press Build now on the Builds tab for that.

Renaming the repository or moving it to another account on GitHub does not break anything: Forge follows the repository by GitHub's id, not its name.

Pushes share your limit of three builds running at once, and a push over it waits: its build and checks show as queued, and it starts on its own when one of the three finishes. Up to ten pushes wait at a time; past that a push is dropped, which only a runaway script pushing in a loop should ever reach. A push past this month's free builds is not built.

Checks on the commit

Each target shows on the commit, and on its pull request, as Forge / <target>: queued when the push lands, in progress while it builds, then success with the file's size and digest, or failure with the reason. Details opens the build on Forge with the full output.

Taking access away

Both are done on GitHub, under the account's Settings → Applications (or the organisation's Settings → GitHub Apps).

Builds and artifacts

Contents

A build is one commit of one project, exported once per target. Each target runs on its own, in its own container, and produces exactly one file.

Targets

Target You download Signed with
linux-x64 the executable, or a .zip of it and what sits beside it —
linux-arm64 the executable, or a .zip of it and what sits beside it —
macos-universal a universal executable, for Intel and Apple silicon, or a .zip of it and what sits beside it macOS, then notarised
windows-x64 the .exe, or a .zip of it and what sits beside it Windows
windows-arm64 the .exe, or a .zip of it and what sits beside it Windows
ios an archive of the app, packaged for the App Store iOS
android an .apk, an App Bundle (.aab), or both — see Build settings Android
web a .zip with index.html, the wasm and the export pack — upload it as is —

Every target is exported on Linux, macOS and iOS included: an export fuses your scripts, scenes and assets onto a prebuilt engine for that platform, so no compiler for it has to run.

Build settings

A project's admins set what its builds do on its tabs. The same fields are on the API as PATCH /api/v1/forge/projects/:id.

[export] in the game's project.toml is used as committed.

What a build can reach

Dependencies

A build copies the dependencies project.lock names before the sandbox starts.

Reading a build's page

Each target's card shows its status, and once it succeeds:

Under the cards is the build's Output: the clone, then the export, line by line as it happens. A failed target's reason is on its card; the lines above it in the output say why. Troubleshooting has the common ones.

A build is queued until a builder picks it up, running while any target is, and succeeded or failed once all of them have finished — failed if any one did.

Limits on balaurengine.org

Builds at once 3 per account; a push over it waits for a slot, Build now and the API are refused until one finishes
Builds a month 20 per account without Pro, per calendar month in UTC, pushes included; Pro has no limit and goes first in the queue
Projects 20 per account
Time per target 45 minutes, then the target fails as timed out
Per target 4 CPUs, 8 GB of memory, 16 GB of scratch space
Downloads kept 30 days, then deleted with the build's files

A target that fails is not retried: a red export is almost always the project, and running it again would fail the same way on your time.

Deleting your account deletes everything Forge keeps for it: every build's downloads, every hosted game, and every signing credential and store key. The account goes at once; the files follow within minutes.

The same commit, the same file

Exports are reproducible: the same commit, target and engine version produce the same bytes before signing, whichever builder ran them. The digest on a GitHub check is therefore something you can check a download against.

Signing

Contents

An unsigned build runs, but every platform warns about it — SmartScreen on Windows, Gatekeeper on macOS — and iOS and Google Play will not take one at all. Give Forge a platform's credentials once and every build of that platform comes back signed.

Where

Open the project from Projects and go to its Signing tab. It has a section per platform:

Section Signs Guide
Windows windows-x64, windows-arm64 Windows
macOS macos-universal macOS
Apple notarisation macos-universal, after signing Apple notarisation
iOS ios iOS
Android android Android

Linux and web builds are not signed; there is nothing for them to be signed with.

Each guide says where to get the credential, how to export it, and which field takes what.

Missing, and wrong, are different

How the keys are kept

Signing for Windows

Contents

Without a signature, SmartScreen warns every person who downloads your game, and keeps warning until enough people click through. With one, it stops.

What you need

A code signing certificate from a certificate authority — DigiCert, Sectigo, SSL.com and others sell them. There are two grades:

Both now generally arrive on a hardware token or in a cloud HSM rather than as a file you can download, because the CA/Browser Forum required it. If yours is a file you can export, it is an older certificate.

Getting a .pfx

If your certificate is still exportable, export it with its private key:

  1. Open certmgr.msc on Windows, find it under Personal → Certificates.
  2. Right click → All Tasks → Export.
  3. Choose Yes, export the private key — a certificate without it cannot sign anything.
  4. Pick PFX, set a password, and save the file.

On macOS or Linux, if you have the certificate and key as PEM:

openssl pkcs12 -export -out certificate.pfx -inkey private.key -in certificate.crt

What to put in Forge

Field What
Code signing certificate the .pfx file
Certificate password the password you set on export
Timestamp server optional, see below

About the timestamp server

Set it. http://timestamp.digicert.com works for most certificates.

Without a timestamp, your signature stops being valid when the certificate expires — which means every copy of your game you ever shipped starts warning on the same day, including the ones people already downloaded. With one, the signature stays valid for what it was when it was signed.

If your certificate lives on a token

Forge cannot use it. A hardware token needs a machine with the token plugged in, and a cloud HSM needs that provider's signing plug-in. This is the one place where the industry is moving faster than most build services; if this is your situation, tell us and we will work out what is possible.

Signing for macOS

Contents

An unsigned Mac build refuses to open at all on a modern macOS — the user gets "cannot be opened because the developer cannot be verified", and the way past it is obscure enough that most people give up.

Two things fix that, and they are separate: signing proves the build came from you, and notarising proves Apple has scanned it. You need both for a download. Signing alone is enough for a build you hand to a colleague.

What you need

An Apple Developer Program membership (99 USD a year) and a Developer ID Application certificate.

Note the name. Apple issues several kinds and they are not interchangeable:

Certificate For
Developer ID Application a build people download from your own site — this one
Mac App Distribution a build going to the Mac App Store
Mac Installer Distribution the installer package around a Mac App Store build

Getting the .p12

  1. On a Mac, open Keychain Access → Certificate Assistant → Request a Certificate from a Certificate Authority. Save the request to disk. This generates the private key locally — the request is useless to anyone else, and the certificate Apple gives back is useless without it.
  2. Go to Certificates, Identifiers & Profiles, create a Developer ID Application certificate and upload that request.
  3. Download the certificate and double click it to install it into Keychain.
  4. In Keychain Access, find it under My Certificates — it must show a disclosure triangle with a private key underneath. If it does not, you are on a different Mac from the one that made the request.
  5. Right click → Export → .p12, and set a password.

Do not create two certificates with the same name. Exporting then becomes a guess about which one you picked.

What to put in Forge

Field What
Developer ID Application (.p12) the exported file
Certificate password the password you set on export

Forge signs on Linux using rcodesign, a clean-room implementation of Apple's format. We verified the output with Apple's own codesign on a Mac: valid on disk, satisfies its Designated Requirement, full chain to the Apple Root CA. You do not need a Mac.

Then notarise

Signing is half of it. See Apple notarisation for the other half — without it, macOS still warns on anything downloaded from the internet.

Apple notarisation

Contents

Notarising sends your signed build to Apple, which scans it and returns a ticket. Gatekeeper checks for that ticket on anything downloaded from the internet. Without one, a signed build still warns; with one, it opens.

It applies to macOS builds only. An iOS build is never notarised: it goes to App Store Connect instead.

What you need

An App Store Connect API key. This is not the same thing as your signing certificate, and not the same as an app-specific password — that older method is being retired.

  1. Go to Users and Access → Integrations → App Store Connect API.
  2. You need the Admin or App Manager role to create one.
  3. Create a key. Give it the Developer role — notarisation needs no more.
  4. Download the .p8 file.

The .p8 downloads exactly once. Apple will not show it again. If you lose it, revoke the key and make another.

While you are on that page, note two values beside the key:

What to put in Forge

Field What
Issuer ID the UUID from the top of the Integrations page
Key ID the ten-character id beside your key
API key (.p8) the file you downloaded once

What to expect

Notarisation is a round trip to Apple and takes minutes, not seconds — occasionally much longer when Apple is busy. Forge submits after signing and waits for the answer, so a notarised build takes longer than an unnotarised one. That is Apple's queue, not ours.

If Apple rejects a build it says why, and the reason is usually a component that is not signed or is signed with the wrong kind of certificate.

Honest status

This is the one step in Forge's signing path that has not yet been run against a real Apple account. Everything else here — signing macOS, iOS, Windows and Android on Linux — has been verified end to end. Notarisation is implemented to Apple's documented API and will get the same treatment before it is offered as a finished feature.

Signing for iOS

Contents

An iOS build must be signed before any device will install it — there is no "open anyway". The signature also has to match a provisioning profile that names your app and, for anything short of an App Store build, the devices allowed to run it.

What you need

An Apple Developer Program membership, an Apple Distribution certificate, and a provisioning profile.

The certificate

Same procedure as macOS, different certificate type:

  1. Keychain Access → Certificate Assistant → Request a Certificate — save the request to disk.
  2. At Certificates, Identifiers & Profiles, create an Apple Distribution certificate with that request.
  3. Install it, then export it from My Certificates as .p12 with its private key and a password.

Apple Distribution covers the App Store and ad-hoc distribution. Apple Development is for running on your own devices from Xcode and is not what a build service wants.

The provisioning profile

  1. Register an App ID matching your game's bundle identifier under Identifiers.
  2. Under Profiles, create a distribution profile for that App ID:
    • App Store to submit to the App Store.
    • Ad Hoc to install on a fixed list of registered devices — you must add each device's UDID first.
  3. Download the .mobileprovision.

A profile expires after a year, and an Ad Hoc profile stops working for any device added after it was made. Both mean regenerating and re-uploading it.

What to put in Forge

Field What
Apple Distribution (.p12) the exported certificate
Certificate password the password you set on export
Provisioning profile the .mobileprovision

The bundle identifier in your profile has to match the one your project exports with. A mismatch is the single most common iOS signing failure, and the error Apple returns does not always say so plainly.

Then publish

An iOS build is never notarised. For the App Store it goes to App Store Connect.

Signing for Android

Contents

Every Android build is signed — Forge signs with a throwaway debug key when you have given it nothing else, which installs on a device and is refused by Google Play. To publish there, you need your own key.

What you need

An upload keystore: a .jks or .keystore file, its password, the alias of the key inside it, and that key's password.

Note upload key. If you use Play App Signing — the default for new apps — Google holds the key that actually signs what users install, and yours is the one that proves an upload is from you. That is a good arrangement: losing your upload key is recoverable, losing an app signing key is not.

Creating one

keytool ships with any JDK:

keytool -genkeypair -v \
  -keystore upload-keystore.jks \
  -keyalg RSA -keysize 2048 -validity 10000 \
  -alias upload

It asks for a keystore password, then some identifying details, then a key password. -validity 10000 is about 27 years; Play requires a key valid past 2033, and a key that expires is a problem with no good answer.

Back this file up somewhere that is not your laptop, along with both passwords. If you are not using Play App Signing, losing it means you can never update your app again — you would have to publish a new listing and lose your reviews and installs.

What to put in Forge

Field What
Upload keystore the .jks file
Keystore password the first password keytool asked for
Key alias upload, above — whatever you passed to -alias
Key password the second password; often the same as the first

To check what is in a keystore you already have:

keytool -list -v -keystore upload-keystore.jks

What you get

With these set, Forge signs each Android artifact with your key, the .apk and the .aab alike. Without them it still produces them, signed with the debug key — fine for sending to a tester over a cable, refused by Play.

Build settings choose which of the two a build makes.

Stores

Contents

Forge can upload a finished build to a store. It never does so on its own: a green build is not a release, so publishing is a button you press on the build, and it asks you to confirm. Web hosting can be the exception, once you turn on its switch: then every green web build goes live by itself.

Set up a store

A store's login is an account, and it is yours rather than one project's. On Stores, Add account, name it and Create: the name is its URL, /stores/<name>, unique among your accounts. It holds the API key or key file, and every project of yours can use it. Add a second for the same store if you publish as more than one.

Then open the project from Projects, go to its Stores tab, pick the account for each store, and fill in what is the game's own: its itch.io page, or its Play track. Web hosting needs no account.

Store Takes Guide
itch.io every target except ios; the APK for android itch.io
Google Play android, as an APK or an App Bundle Google Play
App Store Connect ios App Store
Web hosting web, served by Forge at the project's address on balaur.app Web hosting

Credentials here are kept like signing keys: encrypted when saved, never shown again, and handed only to the upload for that store.

Publish

On a build's page, every succeeded target that a configured store takes has a Publish to … button. Press it, confirm, and the upload runs on a builder and reports back on the same card — the store, whether it worked, and what the store said if it did not.

Stores check signatures, so sign first: Google Play and the App Store refuse an unsigned android or ios build. See Signing.

itch.io

Contents

itch.io is where a Balaur game is most likely to be published first: one API key, no review queue, and a page the moment the upload lands. Forge uploads with butler, itch's own tool, into a channel per platform — linux-x64, windows-x64, macos, android, html5 — so one game page carries every build.

What you need

What Forge does with them

Nothing until you press the button. On a build's page, beside every artifact itch.io takes, there is Publish to itch.io; it asks once, then uploads that artifact to user/game:<channel> on a builder and reports back on the same page. A red upload says what butler said — most often a key that has been revoked, or a game that does not exist under that user.

The key is encrypted at rest and never shown again once saved. Forge keeps a row per upload, so the page can say what happened last time and when.

Channels

butler reads the platform from the channel name, so the browser build goes to html5 and the Mac build to macos; the rest use the target's own name. itch.io does not host iOS builds, so there is no button on an iOS artifact.

Google Play

Contents

Google Play takes builds through its Developer API, with no human in the loop until a release reaches a track that has one. Forge uploads the artifact, puts it on a track, and commits the edit — the same four calls a fastlane supply run makes, without the Ruby.

What you need

The app must already exist in Play Console, with one release made by hand — Play will not accept the first upload of a new app through the API.

What Forge does with them

Nothing until you press the button. On a build's page, beside an Android artifact, Publish to Google Play asks once and then, on a builder: gets a token from the service account, opens an edit, uploads the artifact, puts its version code on the track as a completed release, and commits. A red upload says what Play said — most often a permission the service account does not have, or a version code Play already holds.

Bundles

Play requires an Android App Bundle for new apps, and has since 2021; existing apps may keep uploading APKs to testing tracks. A project builds both by default: its Targets tab has Android APK and Android AAB. The .aab is signed with your Android key, and its Publish to Google Play uploads it to Play's bundles endpoint. Keep Android APK ticked as well if you also publish to itch.io, which takes the APK only.

App Store Connect

Contents

An iOS build is never notarised; it is uploaded to App Store Connect, where TestFlight hands it to testers and App Review takes it from there. Forge uploads through Apple's build upload API — the same reservation, upload and commit that Transporter performs — from a Linux container, with no Mac and no Java in the path.

What you need

What Forge does with them

Nothing until you press the button. On a build's page, beside an iOS artifact, Publish to App Store Connect asks once and then, on a builder: mints a short-lived token from the key, finds the app by bundle id, reserves an upload for that version and build number, sends the file in the parts Apple asks for, and marks it uploaded. Then it waits a few minutes for Apple's processing. A build that finishes processing in that window is reported as such; one still processing is reported as accepted, and Apple mails the outcome as it always has. A red upload quotes Apple's own sentence — most often a build number App Store Connect already holds, or a key without the role.

What it does not do

It does not submit for review, add testers, or write release notes. Those are App Store Connect's forms, and a build that appears in TestFlight is the whole of what a build system should decide.

Web hosting

Contents

A project's web build can go live on Forge itself, at an address of its own on balaur.app, such as https://my-game.balaur.app/. Its zip is unpacked into Forge's storage and served from there. Once a build is live, the project's dashboard plays it from that address.

The address

Publishing

Plans

An account without Pro hosts 1 game, and a Pro account 10. An account that leaves Pro keeps its addresses, and publishes again once it hosts no more games than its plan allows.

Play it

Play on the dashboard runs the game at a phone's, tablet's or desktop's size, with Fullscreen beside it. A project not published plays there too, for its members, on the site's own engine.

What the address is, and is not

Take it down

Take down on the project's Stores tab deletes the files and frees the address. Deleting your account takes down every game it hosts. A game that breaks the terms is taken down by us.

API

Contents

Everything the dashboard does with a build, a script can do over HTTP. For building on every push you do not need any of this — the GitHub App does it without a token. The API is for the rest: a release script, a build from another CI, a button in your own tools.

The base URL is https://balaurengine.org/api/v1. Every answer is JSON, with the result under data.

A token

Make a personal API token under account settings → API tokens: give it a name and a lifetime (30, 90 or 365 days, or never) and copy what it shows — it is shown once. It starts with gamend_pat_. Put it in your CI's secret store and send it as a header:

export TOKEN=gamend_pat_…
curl -s https://balaurengine.org/api/v1/forge/projects \
  -H "authorization: Bearer $TOKEN"

It acts as you on the API until it expires or you press Revoke. Changing your password or email revokes every token you made before, so a CI job needs a new one after either. A token cannot make another, and it works whether you signed up with a password or with GitHub.

For something interactive, a login works too: POST /api/v1/login with your email and password answers a data.access_token good for 15 minutes.

Projects

curl -s https://balaurengine.org/api/v1/forge/projects \
  -H "authorization: Bearer $TOKEN"

Each project has an id, name, repo_url, default_ref, targets, engine_version and build_options. To register a public repository without the dashboard:

curl -s https://balaurengine.org/api/v1/forge/projects \
  -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' \
  -d '{"name": "my-game", "repo_url": "https://github.com/you/my-game",
       "default_ref": "main", "targets": ["linux-x64", "windows-x64", "web"]}'

A name is lowercase letters and digits joined by - or _. A private repository is registered from the dashboard, through the GitHub App.

To change what a project builds — the same fields as its tabs:

curl -s -X PATCH https://balaurengine.org/api/v1/forge/projects/$PROJECT \
  -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' \
  -d '{"engine_version": "0.4.1",
       "build_options": {"android_packages": ["apk", "aab"]}}'

Any of name, default_ref, targets, engine_version and build_options may be sent; the repository cannot change. engine_version is latest, nightly or a version. android_packages is apk, aab or both, and a build with both has two android entries, told apart by their variant: "" for the APK, aab for the bundle.

Start a build

curl -s https://balaurengine.org/api/v1/forge/projects/$PROJECT/builds \
  -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' \
  -d '{"ref": "v1.2.0", "targets": ["windows-x64", "macos-universal"]}'

Every field is optional:

Field Default
ref the project's default branch; a branch or a tag
sha the head of ref; set it to build one exact commit
targets the project's targets; any of the eight

It answers 201 with the build, whose id you follow.

Wait for it

curl -s https://balaurengine.org/api/v1/forge/builds/$BUILD \
  -H "authorization: Bearer $TOKEN"

Poll until data.status is succeeded or failed. Each entry in data.targets has its own status, an error when it failed, and, once it succeeded, artifact_url — a download link — and artifact_bytes.

When it says no

Status error Meaning
401 invalid_token the token is expired or revoked
401 unauthenticated no token was sent
402 free_builds_used this month's free builds are used; Pro has no limit
404 not_found no such project or build on your account
422 no_targets neither the request nor the project names a target
422 unknown_targets a target that is not one of the eight
429 build_limit_reached three builds are already queued or running; wait for one

Troubleshooting

Contents

A failed target's reason is on its card. The build's Output above that line says why; start there.

The clone failed

The card says clone failed, and the output has Git's own message.

Git says Fix
Remote branch … not found the branch or tag does not exist; check the project's default branch, or the ref you asked for
Authentication failed, Repository not found, could not read Username the repository is private and Forge cannot reach it: it was registered by URL, or the App lost access. Register it from GitHub, or grant the App access to it again

The same table holds for the steps after the clone. submodules failed: a submodule is private and the App is not installed on it, or it points at a local path or file://, which Forge refuses — submodules are fetched over https only. git lfs pull failed: an LFS object is missing on the server, or the repository's LFS quota on GitHub is used up.

The export failed

The card says build exited and a number. This is the same balaur export you run locally, and it failed the same way it would there. Run it:

balaur export . --target <the target that failed>

If it passes on your machine and fails on Forge, the difference is almost always one of these:

Timed out

The target ran past 45 minutes and was stopped. A warm export takes seconds and a cold one minutes, so this usually means something in the project waits forever — a script that loops at import, for instance. The last lines of the output show where it stopped.

"Wait for a running build to finish."

Three builds are already queued or running on your account. Open one from Projects and let it finish, then press Build now again. Pushes do not need this: a push over the limit waits for a slot on its own.

"This month's free builds are used."

An account without Pro starts 20 builds a calendar month, in UTC, and they come back on the first of the next one. Pro has no limit.

The build is unsigned

The card's badge says unsigned with a note: that platform's section on the project's Signing tab is not filled in. It is not an error; fill it in and build again. See Signing.

Signing failed

The target is red after a green export, and the output names the signing step. The credentials are there but do not work: a wrong certificate password, an expired certificate, a provisioning profile for another app, an Android key alias that is not in the keystore. The platform's guide under Signing says what each field has to be. Saving a corrected value replaces the old one.

No check on my commit

Something else

Write to us from the community page with the build's link — it is the URL of its page. The output on that page is what we will read first.

Roadmap

Contents

Discord · Issues · Discussions

0.1 Hello Balaur

Contents

Feature Area Status
The editor Editor Built
Tile maps Editor Built
Script completion and hover Editor Built
Rune scripting Scripts and assets Built
Scenes, assets and export packs Scripts and assets Built
Rapier in 2D and 3D Physics and animation Built
Rigs and animation Physics and animation Built
Widgets, text and the batteries User interface Built
What draws today Rendering Built
Post-process materials Rendering Built
The deterministic core Networking Built
Apple and the platform module Tools and services Built
Export, the web and the CLI Shipping Built

0.2 Balaur v2

Contents

Feature Area Status
Focused script editing Editor Built
Project manager Editor Built
Editor themes Editor Built
Theme pairs that follow the system Editor Built
An import that does not stop the editor Editor Built
The User data dock Editor Built
The Physics panel Editor Built
A bad call caught before it runs Scripts and assets Built
Addons as modules Scripts and assets Built
Enums and match Scripts and assets Built
Properties that hold properties Scripts and assets Built
Follow controllers Physics and animation Built
Concave 2D colliders Physics and animation Built
Pause, time scale and smooth frames Physics and animation Built
One way to hear every event Gameplay and audio Planned
Lists, trees and tables User interface Built
Menus, popups and tooltips User interface Built
Text a game can edit User interface Built
Dark mode on every platform User interface Built
The 3D look Rendering Built
Lit normal-mapped sprites Rendering Built
2D global illumination Rendering Built
Particles in 3D Rendering Built
2D batching Rendering Built
Log files Tools and services Built
A splash while a game loads Shipping Built
A smaller web template Shipping Built

0.3 Balaur Again

Contents

Feature Area Status
Semantic tokens, inlay hints and code actions Editor Planned
Curve editor and onion skin Editor Planned
A sequencer Physics and animation Planned
Theme states and icons User interface Planned
Aspect and camera containers User interface Planned
A rendered still Rendering Planned
Immediate shapes in the draw order Rendering Built
Richer particles Rendering Planned
Culling and level of detail Rendering Planned
Voxels and terrain Rendering Planned
More than one view Rendering Planned
Video playback Rendering Planned

0.4 Balaur Multiplayer

Contents

Feature Area Status
Multiplayer dock and Play as two Editor Planned
Decals and volumetric fog Rendering Planned
WebTransport in the browser Networking Planned
Multiplayer from a script Networking Planned
Late join, reconnect and host migration Networking Planned
State replication and RPC Networking Planned
Client prediction and reconciliation Networking Planned
Lag compensation and interest management Networking Planned
The Gamend SDK Gamend Built
A game server per lobby Gamend Planned
Lobby tokens and rejoin Gamend Planned
The match record Gamend Planned
The Gamend client as a script Gamend Built
A Gamend dock Gamend Built

0.5 Balaur Scripting

Contents

Feature Area Status
A graph that writes a script Editor Planned
Scripts you can take Scripts and assets Planned
Extensions, tier two Scripts and assets Planned
Navigation Gameplay and audio Planned
Voice in a match Gameplay and audio Planned
A graph canvas User interface Planned
Pickers, and drag and drop User interface Planned
An MCP server Tools and services Planned
A crash report that reproduces itself Tools and services Planned

0.6 Balaur Web

Contents

Feature Area Status
The editor in a browser Editor Planned
Asset streaming Scripts and assets Planned
Accessibility User interface Planned
A layout that fits the screen User interface Built
WebGL2 beside WebGPU Rendering Planned
Steam Tools and services Planned
Google Play Tools and services Planned
One-click deploy Shipping Planned
A web module that loads in parts Shipping Planned
Embedding on a page Shipping Planned
Sealed export packs and stripped binaries Shipping Planned

0.7 Big Balaur

Contents

Feature Area Status
FBX import Scripts and assets Planned
Scripts compiled to WebAssembly Scripts and assets Built
One way to do each thing Scripts and assets Built
Soft bodies Physics and animation Built
Cloth and rope Physics and animation Built
Root motion Physics and animation Planned
WebRTC data channels Networking Planned
A WebRTC relay for browsers Gamend Planned
Skill matchmaking Gamend Planned
Projects in the cloud Tools and services Planned

0.8 Balaur Inputs

Contents

Feature Area Status
The editor on a tablet and a phone Editor Planned
Motion and haptics beyond one pad Gameplay and audio Planned
A controller-only shell User interface Planned
What a phone lends a game Shipping Planned
A game on a small machine Shipping Planned
Suspend and resume Shipping Planned
Console export Shipping Planned
XR Shipping Planned

0.9 Balaur Physics

Contents

Feature Area Status
Procedural noise Scripts and assets Planned
A world bigger than a float Scripts and assets Planned
Tearing Physics and animation Built
Falling sand Physics and animation Planned
Fluids Physics and animation Planned
Sound that fills a room Gameplay and audio Planned
Terrain sculpting and foliage Rendering Planned
Occlusion culling Rendering Planned
Global illumination Rendering Planned

1.0 Balaur Editor

Contents

Feature Area Status
More than one window Editor Planned
A shader graph Editor Planned
Modelling in the viewport Editor Planned
Gases and smoke Physics and animation Planned
Granular materials Physics and animation Planned
Behaviour trees Gameplay and audio Planned
Dialogue Gameplay and audio Planned
Translations as a pipeline Gameplay and audio Planned

1.1 Balaur Packages

Contents

Feature Area Status
More importers Scripts and assets Planned
Extensions in WebAssembly Scripts and assets Planned
A library others publish to Tools and services Planned

Cloud builds

Contents

Feature Status
A build on every push, with a check on the commit Built
Every target on Linux, macOS and iOS included Built
Signing for Windows, macOS, iOS and Android Built
Publishing to itch.io, Google Play, App Store Connect and the web Built
An HTTP API and personal API tokens Built
Artifacts that expire Built
balaur ship in the engine's command line Planned
Publishing to Steam Planned
Steps of your own before and after a build Planned
Hardware-isolated build sandboxes Planned
Console targets Planned
Godot projects Planned