Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Bevy Mod Scripting

Script your Bevy game: hot-reloadable Lua & Rune with full ECS access

BMS (bevy_mod_scripting) runs Lua and Rune scripts inside a Bevy app. Scripts reach the world through reflection, so any Reflect type, including ones from other crates, can be used from scripts without writing glue code.

  • Update game logic without recompiling, with hot reloading of script assets
  • Let modders add content through the same bindings your own scripts use
  • Bindings are written once in Rust and work in every supported language
  • Scripts can add their own systems, components and events
  • Generated docs and Lua language server definitions for your bindings

How a script runs

Loading a script asset runs nothing. A script runs code when it is attached, reloaded or detached, which the script pipeline handles, and when one of its callbacks is invoked by name. The schedule each one runs in is in italics.

flowchart TB
    COMP(["ScriptComponent added / removed"]) -- "<i>PreUpdate</i>" --> PIPE[["script pipeline"]]
    CMDS(["AttachScript / DetachScript"]) -- "<i>immediately</i>" --> PIPE
    PIPE --> LIVE((attached))
    subgraph CALLBACKS ["callbacks, run by name"]
        direction LR
        EH["event_handler<br/><i>your schedule</i>"] ~~~ CMD["RunScriptCallback<br/><i>on command flush</i>"] ~~~ SYS["script systems<br/><i>their schedule</i>"]
        OBS["observers<br/><i>on trigger</i>"] ~~~ OTHER["other scripts<br/><i>immediately or queued</i>"]
    end
    LIVE <--> CALLBACKS
    LIVE -. "asset modified, <i>PreUpdate</i>" .-> PIPE

    click PIPE href "#the-script-pipeline"

The script pipeline

flowchart LR
    subgraph PRE ["script pipeline"]
        direction LR
        A(["attached"]) --> L["context initializers<br/>top level code<br/>on_script_loaded"]
        M(["asset modified"]) --> R["on_script_unloaded<br/>top level code<br/>on_script_loaded<br/>on_script_reloaded"]
        D(["detached"]) --> U["on_script_unloaded<br/>context removed<br/>with its last script"]
    end
  • The attachment (entity + script, or a static script) is the script’s identity, see Managing Scripts. Scripts sharing a context share globals.
  • Callbacks run the function passed to register_callback, else the top level function of that name, see Running Scripts and Calling Other Scripts.
  • on_script_* are the core callbacks. on_script_unloaded can return state, which on_script_reloaded receives.
  • Ordering and budgeting are covered in Script Pipeline.

Where to start

You areRead
Adding scripting to a Bevy gameInstallation, then the User Guide
Writing scripts or modsThe Scripting Reference
Upgrading BMSThe Release Notes
Contributing to BMSDeveloping BMS

Glossary

The key concepts of BMS. Each entry’s first paragraph is shown when hovering over the term elsewhere in the book.

Attachment

Where a script lives: pinned to an entity, or “static”, pinned to nothing. A script file only runs once attached, and the same file attached twice runs twice, so the attachment, not the file, is what callbacks target.

In Rust it is a ScriptAttachment: EntityScript(entity, handle), made by adding a ScriptComponent, or StaticScript(handle), made with the AttachScript command. See Managing Scripts.

Binding

A Rust function or type made available to scripts. Written once in Rust, bindings work in every supported language, and are documented in the generated reference.

Functions are registered with #[script_bindings] or a NamespaceBuilder, on a type or a namespace. See Controlling Script Bindings and Core Bindings.

Callback

A function in a script that BMS calls by name, like an event listener. Everything a script does after loading happens inside a callback.

A callback is the function passed to register_callback, or else the top level function with that name. Callbacks are triggered by event_handler systems, RunScriptCallback commands, script systems, observers and other scripts. See Running Scripts and Callbacks.

Callback label

The name a callback is called by, as a Rust type, so Rust code can’t misspell it.

Defined with callback_labels!(OnEvent => "on_event") and used by event_handler::<OnEvent, _> and ScriptCallbackMessages. See Running Scripts.

Context

The sandbox a script runs in, holding its global variables and functions, like a separate Lua state. Scripts in different contexts can’t see each other’s globals.

Contexts are created when scripts are attached, and removed with their last script. While one of its callbacks runs, a context is busy. See Contexts.

Context policy

The rule deciding which scripts share a context: by default each entity-script pair gets its own, at the other end all scripts share one.

Set with set_context_policy on the scripting plugin. See Contexts.

Core callbacks

The callbacks BMS calls by itself around loading: on_script_loaded, on_script_unloaded and on_script_reloaded. Use them to set up a script and to carry state across hot reloads.

See Core Callbacks.

Event handler

A Bevy system which delivers ScriptCallbackMessages with one callback label to the scripts of one language, the usual way for Rust to call scripts every frame.

Added as event_handler::<Label, Plugin> in the schedule you want the callbacks to run in. See Running Scripts.

Hot reloading

Editing a script file while the game runs, and having the new code take effect without a restart. The script’s top level code runs again in its existing context.

Needs Bevy’s file_watcher feature. on_script_unloaded can return state which on_script_reloaded receives. See Managing Scripts.

Initializer

A Rust function run on a context, or runtime, to customize it, i.e. to set globals before the script’s code runs.

Context initializers run when a context is created or reloaded, pre handling initializers before every callback, runtime initializers once. See Customizing Contexts.

LAD file

A language agnostic JSON description of every type and function scripts can use. It drives the generated reference pages and the Lua language server definitions.

See Editor Support.

Namespace

A named group of types and functions which scripts import, i.e. import_namespace("math"). Types are not globals, so namespaces keep same named types apart.

Rust types live in the namespace of their crate or binding category, scripts register their own components and events into script.* namespaces. See Namespaces.

Reflect reference

A script’s pointer into the Bevy world: to a component, a resource, or a value BMS allocated. Reading or writing its fields reads or writes the real value, through reflection.

Its base is a component, a resource, an allocation or an asset. In Rust it is a ReflectReference, received as R<T>, M<T> or V<T> in binding signatures. See References.

Runtime

The engine state shared by all contexts of one language, if the language has one. Contexts are the sandboxes, the runtime is what they run on. Lua has no separate runtime, Rune does.

Customized with runtime initializers. See Customizing Contexts.

Script

A Lua or Rune source file, loaded as a Bevy asset (ScriptAsset). Loading it runs nothing: it runs once attached.

See Managing Scripts.

Script pipeline

The machinery which turns attachments, detachments and modified assets into loaded, reloaded or unloaded scripts, running the core callbacks along the way.

Runs in PreUpdate, and immediately for AttachScript / DetachScript. See Script Pipeline.

Script system

A Bevy system added by a script, which calls one of the script’s callbacks each time its schedule runs, with the queries and resources it asked for.

Built with bms.system_builder and added with world.add_system. See Script Systems.

Script value

The language neutral value passed between Rust and scripts: integers, strings, lists, functions, references and so on. Each language converts it to and from its own values.

In Rust it is ScriptValue, converted with FromScript and IntoScript. See Controlling Script Bindings.

Static script

A script attached to nothing rather than to an entity, i.e. game wide logic.

Attached and detached with the AttachScript and DetachScript commands. See Managing Scripts.

Installation

Cargo

Add BMS to your Cargo.toml with a language feature:

bevy_mod_scripting = { version = "0.24", features = ["lua54"] }

Each BMS release supports one Bevy version, see the compatibility table.

Language Features

LanguageFeature Flag
Lua 5.1lua51
Lua 5.2lua52
Lua 5.3lua53
Lua 5.4lua54
LuaJITluajit
LuaJIT 5.2luajit52
Luauluau
Runerune

Only one Lua feature can be enabled at a time. Lua and Rune can be enabled together.

Bevy Plugin

Add the BMS plugin group to your app:

app.add_plugins(BMSPlugin);

Each plugin in the group can be replaced with a configured one using BMSPlugin.set(MySubPlugin). Next, load and attach your first script.

Extra Features

The default features are core_functions and the ecs, input, math, time, transform, color and window bindings. Disable default features if you only need BMS for script lifecycle management and want to register the bindings yourself.

FeatureDescription
core_functionsThe core functions, i.e. world and the other ways to interact with Bevy via reflection
bevy_<crate>_bindingsBindings for a Bevy crate, i.e. bevy_math_bindings, bevy_transform_bindings. See the [features] of the Cargo manifest for the full list
lua_language_server_filesGenerates Lua language server definitions, see Editor Support
mlua_asyncEnables mlua/async
mlua_serializeEnables mlua/serialize
mlua_macrosEnables mlua/macros
unsafe_lua_modulesAllows loading native modules via require in Lua
profile_with_tracyAdds tracy profiling spans

Mobile

CI type-checks bevy_mod_scripting for aarch64-linux-android and aarch64-apple-ios; nothing is run on a device. Both need the target’s C toolchain (Android NDK, Xcode) as the Lua runtimes are built from source, and Android needs a bevy activity feature in your app (e.g. bevy/android-native-activity).

LanguageAndroidiOS
Lua 5.1, 5.2, 5.3yesno: the Lua sources call system, which the iOS SDK marks unavailable (fixed upstream in Lua 5.4)
Lua 5.4yesyes
LuaJIT, LuaJIT 5.2yesno: luajit-src can’t build for iOS, which also forbids JIT
Luauyesyes
Runeyesyes

unsafe_lua_modules loads native libraries at runtime, which iOS restricts.

Managing Scripts

Scripts are Bevy assets (ScriptAsset), loaded from the assets directory like any other asset. A loaded script does nothing until it is attached, which evaluates it:

  • parsing the script body,
  • creating or updating the script’s context, the environment holding its globals.

Script attachments

A ScriptAttachment says where a script “lives”, and is the identity scripts are addressed by:

  • ScriptAttachment::EntityScript(entity, handle): attached to an entity through its ScriptComponent,
  • ScriptAttachment::StaticScript(handle): attached to nothing, activated through the AttachScript command.

Inserting or removing a ScriptComponent sends ScriptLifecycleMessages (Attached / Detached), which the script pipeline processes. Static scripts are attached and detached with the AttachScript and DetachScript commands.

Loading

Load scripts with the AssetServer, or create them in memory:

let handle = asset_server.load::<ScriptAsset>("my_script.lua");

let mut script = ScriptAsset::from("x = 0".to_string());
script.language = Language::Lua;
let handle = script_assets.add(script);

Neither runs any code yet.

Note

Scripts are identified by their handle, not their path. The path is only used in logs and error messages, so scripts created in memory show up by asset id instead.

Attaching scripts to entities

Add a ScriptComponent to an entity:

fn load_script(asset_server: Res<AssetServer>, mut commands: Commands) {
    let handle = asset_server.load::<ScriptAsset>("my_script.lua");
    commands.spawn(ScriptComponent::new(vec![handle]));
}

In the script, import_namespace("bms").current_entity() returns the entity the script is attached to.

Static scripts

Scripts which don’t belong to an entity are attached as static scripts:

fn add_static_script(asset_server: Res<AssetServer>, mut commands: Commands) {
    let handle = asset_server.load("scripts/my_script.lua");
    commands.queue(AttachScript::<LuaScriptingPlugin>::new(
        ScriptAttachment::StaticScript(handle),
    ));
}

fn remove_static_script(handle: Local<Handle<ScriptAsset>>, mut commands: Commands) {
    commands.queue(DetachScript::<LuaScriptingPlugin>::new(
        ScriptAttachment::StaticScript(handle.clone()),
    ));
}

The commands run the script pipeline until the attachment is processed. To avoid frame time spikes, write ScriptLifecycleMessages instead, and let the pipeline pick them up as normal.

Unloading

BMS keeps a handle to each attached script, so dropping your own handles does not unload it. To unload a script, and run its on_script_unloaded callback, remove it from its ScriptComponent or detach it with DetachScript. Once no handles are left, Bevy drops the asset.

A context is removed together with the last script in it.

Hot reloading

Enable Bevy’s file_watcher feature, and changes to script assets are picked up and the scripts reloaded. Use on_script_unloaded and on_script_reloaded to keep state across reloads.

File extensions

Each language plugin maps file extensions to its language, i.e. lua and luau for Lua. To add more:

app.add_plugins(LuaScriptingPlugin::default().add_supported_extension("pua"));

Next, run your scripts.

Running Scripts

Once attached, a script runs its top level code, then waits for callbacks: functions the script defines, which Rust (or other scripts) invoke by name.

print("hello from load time")

function on_event(arg1)
    print("hello from event time", arg1)
end

This prints “hello from load time” when the script is loaded, and “hello from event time” whenever an on_event callback targets this script. Besides your own callbacks, BMS calls the core callbacks (on_script_loaded, …) on its own.

Sending callback messages

Define a label for the callback, then write a ScriptCallbackMessage with it:

#[derive(Reflect)]
pub struct MyReflectType;

// define as many labels as you like here
callback_labels!(OnEvent => "on_event");

fn send_event(mut writer: MessageWriter<ScriptCallbackMessage>) {
    // allocated values live as long as references to them
    let payload = ReflectReference::new_allocated(MyReflectType);

    writer.write(ScriptCallbackMessage::new_for_all_scripts(
        OnEvent,
        vec![payload.into()],
    ));
}

The second argument is the list of arguments the callback receives. Any Reflect type can be sent as a ReflectReference, and the other ScriptValue variants carry plain data, i.e. ScriptValue::Integer(5).

Besides new_for_all_scripts, messages can target one script (new_for_static_script, new_for_script_entity) or each context once (new_for_all_contexts).

Event handlers

Messages are only delivered by an event_handler system for their label and language:

app.add_systems(
    Update,
    (
        send_event,
        event_handler::<OnEvent, LuaScriptingPlugin>.after(send_event),
    ),
);

The handler runs the on_event callback on every targeted script which defines it. Order the systems writing the messages before the handler, otherwise messages are only handled in the next frame.

Commands

To run a callback right away, queue a RunScriptCallback command for a single script:

commands.queue(RunScriptCallback::<LuaScriptingPlugin>::new(
    ScriptAttachment::StaticScript(handle),
    OnEvent.into_callback_label(),
    vec![ScriptValue::Integer(5)],
    false, // don't send a `ScriptCallbackResponseMessage`
));

To keep a callback’s logic across reloads, or share contexts between scripts, see Callbacks.

Callbacks

Callbacks are script functions which BMS calls by name, through an event handler or a RunScriptCallback command, from other scripts, or as one of the core callbacks.

They come in two variants:

  • freestanding: top level functions,
  • registered: functions passed to register_callback, which are “frozen”.

Freestanding callbacks

function on_script_loaded()
    print("doing things")
end

The callback is looked up by name each time it runs, so when the script is reloaded, the new version of the function runs.

Registered callbacks

local function my_registered_callback()
    print("doing things")
end

register_callback("on_script_loaded", my_registered_callback)

Registered callbacks take priority over freestanding ones, and are “frozen”: once registered, reloading other scripts won’t change them.

This matters with shared contexts, where scripts overwrite each other’s top level functions when loaded. Register each script’s callbacks while it loads, and every callback will reach the right script.

Registered callbacks are implemented by each language plugin, Lua and Rune both support them.

Contexts

Each script runs in a context: the environment holding its global variables and functions. Which scripts share a context is decided by the context policy of the scripting plugin. By default each entity-script pair gets its own context, isolated from all other scripts.

Context policies

PolicyScripts sharing a context
ContextPolicy::per_entity_and_script() (default)None, the most isolated
ContextPolicy::per_entity()All scripts attached to the same entity
ContextPolicy::per_script()All attachments of the same script, i.e. one script on many entities
ContextPolicy::shared()All scripts, there is only one context

Set the policy on the scripting plugin:

app.add_plugins(LuaScriptingPlugin::default().set_context_policy(
    ContextPolicy::shared(),
));

Sharing a context makes it easy to share data between scripts, at the cost of scripts being able to interfere with each other.

Warning

In a shared context, scripts overwrite each other’s top level functions when loaded. Use registered callbacks so each callback reaches the right script.

A script’s context is busy while one of its callbacks runs, which limits which scripts it can call immediately.

Custom policies

A policy is a list of rules, tried in order until one applies. per_script() could be written as:

let policy = ContextPolicy {
    priorities: vec![Arc::new(ContextRule::Script), Arc::new(ContextRule::Shared)],
};

Each rule maps the script’s attachment to a ContextKey, and scripts with the same key share a context:

pub struct ContextKey {
    pub entity: Option<Entity>,
    pub script: Option<AssetId<ScriptAsset>>,
}

So the policy reads: if there is a script, the key is just the script. Failing that, ContextRule::Shared always applies, returning the empty key.

For entirely custom rules, implement ContextKeySelector, or pass a closure Fn(&ScriptAttachment) -> Option<ContextKey>.

To change what is in a context, see Customizing Contexts.

Customizing Contexts

Most of the time, registering script functions is all you need: they work in every language, and show up in the generated docs. For anything else, scripting plugins take initializers which run on each context or runtime:

InitializerRuns
add_context_initializerOnce a context is created, and when its script is reloaded, before any callbacks
add_context_pre_handling_initializerBefore every callback, and on load and reload
add_runtime_initializerOnce, on the runtime shared by all contexts

Initializers are plain functions (fn pointers), so they can’t capture variables.

Context initializers

i.e. setting some globals for every Lua script:

let plugin = LuaScriptingPlugin::default().add_context_initializer(|_attachment, context| {
    let globals = context.globals();
    for i in 0..10 {
        globals.set(i, i).map_err(IntoInteropError::to_bms_error)?;
    }
    Ok(())
});

app.add_plugins(plugin);

Pre handling initializers

These receive the attachment of the script about to run, i.e. to expose its name:

app.add_plugins(LuaScriptingPlugin::default().add_context_pre_handling_initializer(
    |attachment, context| {
        let name = attachment.script().path().map(|p| p.to_string());
        context
            .globals()
            .set("script_name", name)
            .map_err(IntoInteropError::to_bms_error)?;
        Ok(())
    },
));

Runtime initializers

Some languages have a runtime, shared by all contexts, which is customized with add_runtime_initializer(|runtime| { ... }). Lua’s runtime type is (), as mlua has no separate runtime.

Accessing the world

During initializers, the world is available through the ThreadWorldContainer thread local:

LuaScriptingPlugin::default().add_context_initializer(|_attachment, _context| {
    let world = ThreadWorldContainer::try_get_context()?.world;
    world.with_resource(|res: &MyResource| println!("My resource: {res:?}"))?;
    Ok(())
});

Controlling Script Bindings

A binding is anything a script can access to communicate with your Rust code, i.e. binding script code to rust code. Bindings are written once in Rust, and work in every supported language.

Functions are registered on a type or a namespace, see where functions can live. Scripts reach them through namespaces.

Dynamic Functions

Everything callable by scripts must first be registered in the dynamic function registry. Notably we do not make use of the normal bevy function registry to improve performance and usability. This means you cannot call just any function.

In order for a function to be callable by a script it must adhere to a few requirements:

  • Each argument must implement FromScript.
  • Each return type must implement IntoScript.
  • Each argument must also implement GetTypeDependencies
  • Each return type must also implement GetTypeDependencies

The into/from requirements allow us to convert these types to ScriptValue’s, and each supported scripting language can then marshall these into the script.

These traits are implemented for primitives, but if you want to interact with one of your Reflect implementing types, you will need to use one of R<T>, M<T> or V<T> wrappers in place of &T, &mut T and T respectively.

These wrappers enable us to safely interact with bevy, and claim any necessary mutex’es on Resources, Components or Allocations.

The GetTypeDependencies, trait is simply a local trait alias for GetTypeRegistration with less strict type requirements. It allows us to register all the types necessary for the function calls, so that you don’t have to register anything manually. If your type implements GetTypeRegistration you should not face any issues on this front.

Registering Script Functions

Registering functions can be done via the NamespaceBuilder like below:

    NamespaceBuilder::<ReflectReference>::new(&mut world)
        .register(
            "hello_world",
            |_self: ReflectReference, s: String| {
                println!("{s}")
            },
        );

    NamespaceBuilder::in_namespace(&mut world, "my_game")
        .register(
            "hello_world2",
            |s: String| {
                println!("{s}")
            },
        );

This will allow you to call this function within Lua like so:

some_value:hello_world("hi from method!")
import_namespace("my_game").hello_world2("hi from my_game!")

new also registers the type in the type registry. Functions on ReflectReference are available on every value, and receive it as their first argument, see where functions can live.

Macros

The above is a bit tedious, so instead you can use the script_bindings macro, which applies to impl blocks like so:

#[script_bindings(name = "test_fn")]
impl TestStruct {
    /// My docs !!
    /// 
    /// Arguments:
    /// * `_self` - the first argument
    /// * `arg1` - the second argument
    /// Returns:
    /// * `return` - nothing
    fn test_fn(_self: R<TestStruct>, mut arg1: usize) {}
}


pub fn main() {
    let mut app = App::new();
    register_test_fn(app.world_mut())
}

Note the documentation will automatically be picked up and stored for the purposes of reflection and documentation generation, including argument/return type specific docs.

Deriving FromScript and IntoScript

Generally all reflect types are wrapped in: R<T> V<T> or M<T> when writing script bindings. However some types may opt in to implement FromScript or IntoScript directly.

Doing this requires implementing a set of other traits which tell the runtime how to manage your type in conversion and function dispatch.

The most trivial way to allow your type to be used directly in bindings is to apply derive macros like so:

#![allow(unused)]
fn main() {
#[derive(Reflect, ScriptType)]
pub struct MyThing(usize);


#[script_bindings]
impl MyThing {
    // Can now be used directly without V<> wrapper, acts exactly like V<MyThing>
    pub fn test(thing: MyThing) -> MyThing {
        thing
    }
}
}

ScriptType implements FromScript, IntoScript, ArgMeta, GetTypeDependencies and TypedThrough at once, converting through V<Self>.

If you wish to customize one of the conversions, write that impl by hand and use #[script_type(from = custom)] or #[script_type(into = custom)]. This skips the generated impl and documents the type as opaque in generated docs. See the custom conversions example for more information.

Context Arguments

Each script function call always receives an additional context argument: FunctionCallContext. You can opt-in to receive this argument in your own function definitions by adding it as the first argument.

The context contains requests from the caller to your function, such as “I am calling you from a 1-indexed array system, please convert the index first”, This argument is only relevant if you’re targeting multiple languages.

It also allows you to retrieve the world via FunctionCallContext::world().

You can use this as follows:

    NamespaceBuilder::<ReflectReference>::new(&mut world)
        .register(
            "hello_world",
            |ctx: FunctionCallContext, _self: ReflectReference, s: String| {
                let world = ctx.world()?;
                let should_use_0_indexing = ctx.convert_to_0_indexed();
                println!("{should_use_0_indexing} {s}");
                Ok(())
            },
        );

Dynamic Arguments

To accept any kind of value, i.e. numbers or strings alike, take ScriptValue arguments:

    NamespaceBuilder::<ReflectReference>::new(&mut world)
        .register(
            "is_integer",
            |s: ScriptValue| {
                match s {
                    ScriptValue::Integer(i) => true,
                    _ => false
                }
            },
        );

You can treat return values similarly. To accept a reference of any type while keeping it typed in the docs, see Generics. To accept callbacks, names or tables of options, see Typed arguments.

Typed arguments

These wrappers and derives keep the exact type of arguments which aren’t reflected values, in the book and the Lua language server files:

/// Spawns an enemy
#[derive(ScriptData)]
#[script_data(namespace = "game")]
struct SpawnOptions {
    name: String,
    speed: Option<Speed>,                                   // optional
    on_death: Option<FunctionOf<fn(V<Entity>) -> ()>>,
}

#[derive(ScriptData)]
#[script_data(namespace = "game")]
enum Speed {
    Named(ByName<Pace>),     // "Slow" | "Fast", for `enum Pace { Slow, Fast }`
    Exact(f32),              // 2.5
}

#[script_bindings(remote, namespace = "game")]
impl NamespaceMembers {
    fn spawn(ctxt: FunctionCallContext, options: SpawnOptions) -> Result<V<Entity>, InteropError> { .. }
}
game.spawn({ name = "goblin", speed = "Fast", on_death = function(entity) end })   -- `entity` is an ecs.Entity
game.spawn({ name = "goblin", sped = 2 })      -- flagged by the language server, an error at runtime
scripts passdocumented as
FunctionOf<fn(A, B) -> R>a function, which is a DynamicScriptFunction in Rustfun(arg1: A, arg2: B): R
ByName<E>a unit variant of the reflected enum E by its name as in Rust, or a reference to an E"Slow" | "Fast"
#[derive(ScriptData)] structa map of its fields: a table in Lua, an object in Runethe class of its fields, a data type in the book
#[derive(ScriptData)] enumthe value of any variant, each holding one value: the first variant whose type converts itan alias of the union of the variants’ types (game.Speed), a data type in the book

ScriptData is plain data, copied across: a struct is read from the map when passed and written to a new map when returned, so changing one doesn’t change the other. Use it for what crosses once (options, properties, events, results). Use a reflected type for what scripts hold a handle to, or Rust keeps as state. A type is one or the other: deriving both Reflect and ScriptData doesn’t compile.

Each field converts like a function argument of its type. A missing field takes its type’s default, so Option<T> fields can be left out. Unknown fields, missing fields without a default and mistyped fields are errors naming the field.

An enum’s variants are tried in order, so put the more specific of two types taking the same kind of value first, i.e. ByName before String.

Unions only try the types which could convert a value, as told by FromScript::could_convert. When implementing FromScript by hand, override it to rule out the kinds of values your type never converts.

Generics

Reflection only knows concrete types (Handle<Image>, Time<Virtual>), so generic signatures and types use markers standing for their parameters: A, B and C, from bevy_mod_scripting::bindings::function::generics. Markers only change the documentation and the Lua language server files, the values are references at runtime.

Note

The markers are real types: A is a reflected unit struct implementing Asset, Default, Clone and the other traits generic parameters are usually bounded by, so Handle<A> and Time<A> are real types too. A Handle<Image> is not a Handle<A>, so V<Handle<A>>, which copies the value out, can’t receive one. Use ValueOf<Handle<A>>. See the A API docs.

Generic functions

Two wrappers carry the markers in signatures:

  • ValueOf<T, R>: a value converted as R, a ReflectReference unless given, documented as a T.
  • TypeOf<R, A>: a type argument passed as R, i.e. a registration, documented as the parameter A.

Using the same marker ties them together, so get_component returns a value of the type it is given:

fn get_component(
    ctxt: FunctionCallContext,
    entity: V<Entity>,
    registration: TypeOf<V<ScriptComponentRegistration>, A>,
) -> Result<Option<ValueOf<A>>, InteropError>
local bms = import_namespace("bms")
local Transform = import_namespace("transform").Transform

local transform = bms.world.get_component(assert(bms.current_entity()), Transform) -- typed as a Transform
print(transform)

A marker can also stand inside a type, i.e. ValueOf<Handle<A>> accepts the handle of any asset type, see References.

For values which aren’t references, give the conversion: ValueOf<A, ScriptValue> takes any value, typed as whatever the script passed:

// with `MyBox` declared as a generic type (see below): `boxed(5)` is a `MyBox<integer>`
fn boxed(initial: ValueOf<A, ScriptValue>) -> V<MyBox<A>> { .. }

Generic types

Instantiations of a generic type would be documented as unrelated types. Declare the generic type from your plugin, instantiated with markers, with its namespace, parameter names and docs:

use bevy_mod_scripting::bindings::function::generics::{A, GenericTypesAppExt};

app.register_generic_type::<Time<A>>("time", &["T"], "A clock, i.e. `Time<Virtual>`.");

Fields of type A are then documented as being of the parameter T, and instantiations as Time<T> applied to their arguments. Further parameters use B and C (Hashed<A, B>). A parameter with bounds the markers don’t satisfy gets a marker of its own:

bevy_mod_scripting::bindings::generic_marker! {
    /// Stands for the material of `MyMaterialHolder<M>`
    pub struct M;
}
impl MyMaterial for M {}

app.register_type::<M>()
    .register_generic_type::<MyMaterialHolder<M>>("my_crate", &["M"], "...");

Fallible functions

Your script functions can return errors either by:

  • Returning Result<T: IntoScript, InteropError>
  • Returning ScriptValue and manually creating the ScriptValue::Error(into_interop_error.into()) variant.

Reserved Functions

There are a few reserved functions that you can override by registering them on a specific type:

Function NameDescriptionOverridable?Has Default Implementation?
geta getter function, used for indexing into a typenoyes
seta setter function, used for setting a value on a typenoyes
suba subtraction function, used for subtracting two valuesyesno
addan addition function, used for adding two valuesyesno
mula multiplication function, used for multiplying two valuesyesno
diva division function, used for dividing two valuesyesno
rema remainder function, used for getting the remainder of two valuesyesno
nega negation function, used for negating a valueyesno
powa power function, used for raising a value to a poweryesno
rsub, rdiv, rrem, rpowthe reflected sub, div, rem and pow, called on the right operand when the left one is not a value, i.e. 1 - v calls rsub(v, 1). add and mul are called with their operands swapped insteadyesno
eqan equality function, used for checking if two values are equalyesno
lta less than function, used for checking if a value is less than anotheryesno
iteran iterator function, used for iterating over a valuenoyes
displaya display function, used for pretty printing valuesno*yes
debuga display function, used for displaying the internals of a valueno*yes

* - You can register an instance of ReflectDisplayWithTypeInfo type data on Reflect implementing types to override their printing behavior

In this context overridable indicates whether language implementations will look for a specific function on your type before looking at the generic ReflectReference namespace. You can still remove the existing registration for these functions on the ReflectReference namespace if you want to replace them with your own implementation.

Note the ReflectReference namespace is special, in that functions defined on it, act like a fallback and hence apply to ALL references.

Where functions can live

The type in the impl block you apply script_bindings to (or the one passed to NamespaceBuilder) decides where the functions are available:

impl targetAvailable onReceives
MyTypeMyType values and the MyType type, as imported from its namespacewhatever you declare
ReflectReferenceevery value, after MyType’s own functionsthe value
StaticTypeRefevery type, after MyType’s own functionsthe type, filled in automatically
NamespaceMembersthe namespace given by namespace = "..." (or NamespaceBuilder::in_namespace), i.e. import_namespace("my_game")whatever you declare

When the same name exists in more than one place, the most specific one wins. These types are defined by BMS, so script_bindings blocks on ReflectReference, StaticTypeRef or NamespaceMembers in your crate need the remote attribute.

Functions available on every type

The StaticTypeRef namespace is the equivalent for types, i.e. Vec3 in Vec3.new(..). Functions registered on it are available on every type, and receive the type as their first argument, which is filled in automatically:

NamespaceBuilder::<StaticTypeRef>::new(app.world_mut()).register(
    "describe",
    |ctxt: FunctionCallContext, type_ref: V<StaticTypeRef>| -> Result<String, InteropError> {
        Ok(type_ref.type_info(&ctxt.world()?)?.type_path().to_string())
    },
);
local Vec3 = import_namespace("math").Vec3
print(Vec3.describe()) -- "glam::Vec3"

A function registered on the type itself always takes priority over one on StaticTypeRef. The new constructor is implemented this way, see Constructing Arbitrary Types.

Types scripts don’t make or use this way, such as handles the runtime gives out, opt out with #[reflect(NoTypeFunctions)] (ReflectNoTypeFunctions): only their own functions remain, in scripts and in the generated docs.

Signatures which depend on the type

A shared function’s signature can refer to the type it is bound to, using the placeholder types BoundValue (a value of the type), BoundFields (a table of the type’s fields) and BoundHandle (a handle to an asset of the type). Wherever the function is bound to a type, these are replaced with the type, so the documentation and the Lua language server files show, for example, MyStruct.new(payload: MyStruct.Fields): MyStruct rather than a generic table and reference, or Image.load(path: string): Handle<Image>. Functions using BoundHandle are only documented on asset types, i.e. types registered with register_asset_reflect. The same placeholders work for functions on EnumVariantRef, which are bound to each variant of each enum when the LAD file is built (as functions in the Variant namespace). Placeholders left unbound are documented as what they are at runtime, a ReflectReference and a table.

The enum variants of a type are also available on the type, i.e. MyEnum.Variant, after the functions.

Namespace members

Each type registered with the type registry is an entry in the table import_namespace returns for its namespace, i.e. import_namespace("math").Vec3.

Functions which don’t belong to a type are members of a namespace, declared on impl NamespaceMembers:

#[script_bindings(remote, namespace = "my_game")]
impl NamespaceMembers {
    fn spawn_enemy(health: f32) { /* ... */ }
}
local my_game = import_namespace("my_game")
my_game.spawn_enemy(5.0)

Values are registered per namespace with AppScriptNamespaceMembers::register_value, and are made each time the namespace is imported.

The only globals are the builtins: import_namespace, export_namespace and register_callback. world is in the bms namespace: import_namespace("bms").world.

Types are not globals, which keeps types with the same name from shadowing each other. Use the filter of CoreScriptGlobalsPlugin to choose which types scripts can look up by name.

Script Systems

Warning

Script systems are an experimental feature.

Scripts can add their own systems to Bevy schedules. Each system runs a callback of the script which added it.

Systems introduced by scripts can run in parallel to other systems, and can be freely inserted between any other system, including other script systems.

BMS also provides utilities for visualising schedules using dot graphs, allowing low-effort modding frameworks for game authors.

Schedules

Bevy doesn’t support reflecting schedules, so BMS rolls its own schedule registry resource: AppScheduleRegistry, which can be used to add any custom schedules you want to interact with. The default Bevy schedules will be pre-populated for you.

Once you’ve registered your schedule you will be able to interact with it in scripts like below:

local world = import_namespace("bms").world
local update_schedule = world.get_schedule_by_name("Update")
local systems = update_schedule:systems()
local system_with_name = update_schedule:get_system_by_name("my_system")

Inserting Systems

To insert a system you will need to use bms.system_builder like below:

local bms = import_namespace("bms")
local attachment = bms.ScriptAttachment.new_entity_script(bms.current_entity(), bms.current_script())
local system = bms.system_builder("my_system", attachment)
    :exclusive()
    :after(some_other_system)
    :before(another_system)

This will let you call world.add_system like so:

local world = import_namespace("bms").world
world.add_system(update_schedule,system)

Ordering and sets

Besides systems (after/before), script systems can be ordered against:

  • other script systems, by callback label and script, which must have been added before: :after_script_system("on_physics", attachment)
  • sets: :after_set(set), :before_set(set), and put in sets: :in_set(set)

Scripts register their own sets into a script.* namespace, i.e. to group and order the systems of a mod. A set is removed from its namespace when its script unloads, registering it again gives the same set:

local ai = world.register_new_system_set("script.my_mod", "ai")
-- other scripts: import_namespace("script.my_mod").ai

Rust sets the game registers are members of their namespace, the BMS bindings register the main Bevy sets (i.e. transform.TransformSystems.Propagate, time.TimeSystems):

app.register_script_system_set("transform.TransformSystems", "Propagate", TransformSystems::Propagate);
local propagate = import_namespace("transform.TransformSystems").Propagate
builder:in_set(ai):after_set(propagate)

world.get_system_set_by_name finds either kind by its full name, i.e. "transform.TransformSystems.Propagate" or "script.my_mod.ai".

Run conditions

:run_if only runs the system if the condition holds, conditions are evaluated in Rust without calling the script. Every condition passed to run_if must hold:

local c = bms.conditions
builder:run_if(c.any_with_component(Enemy))
       :run_if(c.not_(c.resource_exists(Paused)))
       :run_if(c.on_timer(0.5))

Conditions: resource_exists, resource_changed, resource_added, any_with_component, on_timer(seconds), run_once and the combinators not_, and_, or_ (named so as not, and, or are Lua keywords).

Lifetime

A script system is identified by its attachment and callback label: adding it again replaces the old one (with a warning). Script systems are removed when their script unloads or reloads, a reloading script adds them again in on_script_loaded.

Bevy cannot change a schedule while it runs, i.e. PreUpdate where scripts are loaded. Systems added to (or removed from) a running schedule are added (or removed) once it finishes, removed systems stop running right away. world.add_system then returns a system which can be used for ordering, but has no node in the schedule yet.

Errors in script systems are sent as ScriptErrorMessages, like those of other callbacks. Script systems can call other scripts with the limits described in Calling Other Scripts.

Parameters

The system builder allows script authors to parameterise systems, using resource and query functions. The order in which those functions are called, will define the order in which arguments will be provided to the specified script callback.

For example:

local bms = import_namespace("bms")
local world = bms.world
bms.system_builder("my_system")
    :query(
        world.query()
            :component(ComponentA)
            :component(ComponentB)
            :with(ComponentC)
            :without(ComponentD)
    )
    :resource(ResourceA)

will create a system which calls the specified callback my_system with 2 arguments:

  • The results of the query, each a list of the entity followed by the components in the order they were added: {entity, a, b}
  • The ReflectReference to ResourceA
function my_system(results, resource_a)
    for _, result in ipairs(results) do
        local entity, a, b = result[1], result[2], result[3]
    end
end

resource and component give read and write access. Use resource_read and component_read for read only access, systems reading the same resources and components can run in parallel, while systems writing them cannot:

bms.system_builder("my_system", attachment)
    :query(world.query():component_read(ComponentA):component(ComponentB))
    :resource_read(Time)

Queries can also retrieve components entities don’t need to have (optional, optional_read, nil for entities without them), and only match entities whose components were added or changed since the system last ran (added, changed, filters like with). Outside of systems, added and changed are relative to the last app update:

world.query()
    :component(Transform)
    :optional_read(Velocity)
    :changed(Health)

Queries of a system may access the same components if they can’t match the same entities, i.e. component(A):with(B) and component(A):without(B), otherwise the system reports an error and doesn’t run.

Exclusive systems

An exclusive system can be created using the exclusive function call on the system builder.

This allows the system to access everything as in a normal event handler.

Non-exclusive systems, will only be able to access the set of components and resources as parameterized when building the system. This is why we can run the system in parallel to other non-overlapping systems.

Components are only accessible on the entities matched by the queries declaring them, i.e. with world.query():component(A):with(B) the system can’t access A on entities without B, since Bevy runs it in parallel with systems accessing A on those. Components only used as filters (with, without) can’t be accessed.

Exclusive systems on the other hand, cannot run in parallel.

Callback

The system injected will be similar to an event handler, however it will only trigger the specified script, and without any entity, in the first example you’d see the following lua callback:

function my_system()
    print("I am a dynamic system")
end

get triggered every update.

Script Pipeline

The script pipeline processes script attachments and detachments, and runs the core callbacks along the way.

Before 0.16.0 scripts were processed atomically by load and unload commands. Since then the pipeline allows:

  • Customizing callbacks during the process
  • Budgeting the work done by the pipeline each frame
  • Allowing async steps in the process

The pipeline works like this:

  • A set of systems in PreUpdate “filter” incoming ScriptLifecycleMessages (attachments and detachments, processed in the order they were written) as well as ScriptAssetModifiedMessages (some generated from asset events, others from component hooks). The filtered events are wrapped in ForPlugin<P>(inner) events based on the language of the underlying events.
  • A set of other systems then converts those into active ScriptMachines
  • Then inside the ScriptProcessingSchedule<P>, which is only run in PreUpdate if there are active machines, we tick each machine until it either errors or reaches its final state.

Script Machines

State Machine

Script loading is handled by the following state machines:

graph TD;
    A[Loading Initialized]
    B[Reloading Initialized 
Enter: OnUnloaded callback]

    A --[ new context ]--> C
    B --[ existing context]--> C
    C[Context Assigned
Enter: OnLoaded, then OnReloaded callbacks]

    C --> D

    D[Loading Completed]

    E[Unloading Initialized
Enter: OnUnloaded callback]
    F[Context Removed]
    G[Resident Removed]
    E --[Last resident]--> F
    E --[More residents]--> G
    H[Unloading Completed]
    F --> H
    G --> H

Hooks, such as on_script_loaded, are implemented using Bevy observers, so you can hook into each step of the process with your own observers, i.e.:

app.add_observer(|_: On<LoadingCompleted<LuaScriptingPlugin>>| {
    info!("a script finished loading");
});

Timing & Order

By default all machines are ticked to completion in the frame they start. Setting ScriptLoadingPipeline::tick_budget limits the amount of machine ticks (steps in the state machine above) per frame, spreading the loading of many scripts over multiple frames. The budget counts steps, not time, so a step running a slow callback can still take up the frame.

You can override this and many other settings (including disabling the core callbacks) by changing the ScriptLoadingPipeline<P> settings via your scripting plugin’s set_pipeline_settings.

The script loading/unloading order will look as follows:

  • the order in which components are attached/detached, determines the order in which scripts are processed
  • an attachment whose script asset is still loading holds back the attachments and detachments after it, until it finishes loading
  • scripts are processed one-by-one, i.e. each machine is ticked to completion before the next one is started
    • meaning for example if two scripts are loaded, their on_script_loaded hooks will not run at the same “lockstep”.
  • loading/unloading might happen over multiple frames, depending on the pipeline’s settings.

Determinism

Given the same inputs (the same order of attachments, detachments and app updates), scripts load in the same order and callbacks reach scripts in the same order, on every run and machine: script contexts are kept in insertion ordered maps, and the pipeline budget counts steps rather than time.

What BMS cannot control:

  • which frame a script asset finishes loading in, as asset IO is asynchronous. Wait for scripts to load (see below) before relying on frame timing.
  • language internals, for example Lua iterates tables with string keys (pairs) in a different order on each run. BMS seeds Lua’s math.random with 0 when creating a context, call math.randomseed to change it.

Waiting for scripts to load

In order to check on the pipeline and figure out when everything is ready, you can use the ScriptPipelineState<P> system parameter in a system as shown in the script_loading example.

Editor Support

BMS generates documentation and editor definitions for all bindings registered in your app, including your own.

LADfiles

BMS provides a custom Language Agnostic Declaration format (LAD), which can be used to integrate with other tooling.

If you use #[script_bindings] macros, these files will magically contain your code comments, bindings as well as everything else required to drive other powerful integrations.

The declaration file is generated from the type registry and serves as a light abstraction layer simplifying the traversal of all available types, namespaces and functions.

You can customize how / where and if these files are stored using the main BMS plugin group:

    app.add_plugins(BMSPlugin.set::<ScriptingFilesGenerationPlugin>(
        ScriptingFilesGenerationPlugin::new(
            true, // enabled, you can use a compilation feature to disable this here
            PathBuf::from("assets").join("definitions"),
            Some(PathBuf::from("bindings.lad.json")), // do also save the ladfile itself
            "Core BMS framework bindings",
            true,
            true,
        ),
    ));

This plugin is only available when one of the sub features (like lua_language_server_files) mentioned in this chapter is enabled.

You might not want to run this pipeline in your final binary, but rather bundle some of the generated files into some sort of development pack for modding. You can use compiler flags like #[cfg(not(debug_assertions))] to disable ladfile generation at runtime, or simply disable the lower level features within BMS to avoid compiling related dependencies too.

Lua Language Server

Note

This feature is in early stages: the definitions get you 90% of the way there, but there are rough edges.

LuaLS is an open source language server which integrates with many IDEs.

It is powered by lua specific annotation or definition files which BMS can generate directly from its own LADfiles.

To enable this simply enable the lua_language_server_files feature, and a bindings.d.lua definition file, plus a bindings.<namespace>.d.lua file per namespace, will be generated in the LADfile output directory in the Startup schedule.

Script writers can then use this generated file by pointing their .luarc.json file to these definitions:

{
    "$schema": "https://raw.githubusercontent.com/LuaLS/vscode-lua/master/setting/schema.json",
    "workspace.library": [
        "assets/definitions"
    ],
    "runtime.version": "Lua 5.4",
    "hint.enable": false,
    "workspace.preloadFileSize": 10000
}

The generated definitions file is large (over a megabyte with the default bindings), and the language server skips Lua files bigger than workspace.preloadFileSize (in KB, 500 by default). If completions for BMS types are missing, i.e. Vec3. suggests nothing, raise this limit above the size of the generated file and restart the language server.

Examples

Rust examples live in the examples folder:

ExampleShows
game_of_lifeA full app driven by Lua or Rune scripts, with callbacks, static scripts and custom bindings
runscriptRunning script files given on the command line
script_loadingWaiting for scripts to load with ScriptPipelineState
custom_conversionsHand-written FromScript / IntoScript conversions
docgenGenerating LAD files and Lua language server definitions

Run one with cargo run --example <name> --features lua54 (docgen needs lua_language_server_files).

For example scripts, see the regression test suite in assets/tests, which covers every scripting function in Lua and Rune.

Scripting Reference

This part of the book covers the user-facing API of the scripting languages supported by BMS. This will be where you will want to forward your script users to get started with scripting in BMS.

If you are a modder, welcome! 👋 Apologies for the Rust-centricity of this guide, we are working on it!

Globals

Scripts have only a few builtin globals:

  • import_namespace(namespace): returns the types and functions of a namespace
  • export_namespace(namespace, name, callback): see Exporting functions
  • register_callback(label, function): registers a function as a callback handler

Everything else is imported. world is a static reference to the world, with all sorts of functions available: import_namespace("bms").world. BMS’ own functions are in bms, i.e. bms.current_entity() (the entity the script is attached to, or nil) and bms.current_script() (the script’s handle):

local bms = import_namespace("bms")
print(bms.current_entity())

In this section

PageCovers
NamespacesImporting types, script defined components and events, exporting functions
ReferencesWhat script values point at, assets and handles
Core Callbackson_script_loaded, on_script_unloaded, on_script_reloaded
Constructing Arbitrary TypesType.new, enums and bms.construct
Calling Other Scriptsbms.run_script_callback and bms.queue_script_callback
Events and MessagesSending and observing Bevy events and messages
BundlesInserting and spawning bundles
Core BindingsEvery type and function available to scripts

Namespaces

Every type known to scripts lives in a namespace, and scripts reach types through their namespace: there are no globals named after types.

TypesNamespace
bevy types covered by the bevy bindings, grouped by categorymath, ecs, time, transform, color, input, window, asset, camera, render, sprite, text, ui, gizmos, animation, audio, state
BMS’ own types (ScriptAttachment, ReflectReference, …)bms
any other typethe name of the crate defining it, i.e. my_game
primitives like i32the root namespace, ""

A category namespace holds every type of the bevy crates it covers, i.e. math holds the types of glam and bevy_math, render those of bevy_render, bevy_pbr, bevy_light, bevy_mesh and bevy_image.

Type:namespace() returns a type’s namespace. Script registered components and events live in script.* namespaces, see below.

Importing a namespace

import_namespace(namespace) returns a table of the namespace’s types (and, for script namespaces, events and exported functions) by short name. Each type can be used to call its static functions, to access its enum variants, and wherever a type is expected:

local bms = import_namespace("bms")
local world = bms.world
local Vec3 = import_namespace("math").Vec3
local transform = import_namespace("transform")

local t = transform.Transform.from_translation(Vec3.new(0, 1, 0))
world.add_default_component(bms.current_entity(), transform.Transform)

Import once at the top of a script, and keep the types you use in locals. In Lua, don’t name the table of the math namespace math: that would hide Lua’s own math library.

  • If two types in a namespace share a short name, the first one registered wins.
  • Each call reads the shared type catalogue, so the result is always up to date. A table imported earlier does not pick up later registrations: import again.
  • A namespace which does not exist is an error, with suggestions: namespace "transfrom" does not exist. ... Did you mean: transform?

Overriding the namespace of a type

// on types with script bindings: keeps a namespace set before (with a warning)
#[script_bindings(namespace = "my_namespace")]
impl MyType { /* ... */ }

// on any type: always wins, before or after `script_bindings`
app.override_script_namespace::<MyType>("my_namespace"); // bevy_mod_scripting::bindings::ScriptNamespaceAppExt
// or directly
registry.register_type_data_with::<MyType, ScriptNamespace, _>("my_namespace");

Namespaces defined by scripts

Scripts register components and events into namespaces they pass explicitly. These start with script., followed by dot-separated segments of letters, digits and underscores:

local bms = import_namespace("bms")
local world = bms.world
local Enemy = world.register_new_component("script.game.ai", "Enemy")
local Hit = world.register_new_event("script.game.ai", "Hit")

-- anywhere, including other scripts
local ai = import_namespace("script.game.ai")
world.add_default_component(bms.current_entity(), ai.Enemy)
world.trigger_event(ai.Hit, { damage = 3 })
  • Names are unique within a namespace, across components, events and exports: script.game.ai.Enemy and script.game.ui.Enemy are different components.
  • Registering a taken name is an error. allow_existing returns the existing registration instead, which is useful for scripts which run again.
  • A script namespace exists once something is registered or exported into it.
  • Components and events stay registered when their script unloads, as Bevy cannot unregister components.

Values of script components are DynamicComponents, holding any value in data. Tables read from data are copies: assign a new table to change them.

local bms = import_namespace("bms")
local world = bms.world
local DynamicComponent = bms.DynamicComponent
world.insert_component(bms.current_entity(), Enemy, DynamicComponent.new({ data = { hp = 5 } }))
local enemy = world.get_component(bms.current_entity(), Enemy)
enemy.data = { hp = enemy.data.hp - 1 } -- `enemy.data.hp = 4` would not write through

Exporting functions

export_namespace(namespace, name, callback) makes a callback of the calling script callable by other scripts, in any language:

-- script A
local world = import_namespace("bms").world
register_callback("spawn_enemy_impl", function(health)
    return world.spawn()
end)
export_namespace("script.game", "spawn_enemy", "spawn_enemy_impl")

-- script B, once script A has run
local enemy = import_namespace("script.game").spawn_enemy(5)
  • callback is a function registered with register_callback, or a top level function of that name. Only functions can be exported.
  • Calls run in the exporting script’s context, like bms.run_script_callback (see Calling Other Scripts), and return the callback’s result.
  • A script cannot call its own exports, or those of scripts sharing its context, from one of its callbacks: its context is busy. Call the function directly instead.
  • Exports are looked up on every call, so replaced exports are picked up and removed ones fail with an error.
  • A path can only be exported by one script. Exporting it again from the same script replaces it. Exports can’t share a path with a component.
  • export_namespace only works inside a script callback.

When a script unloads or is about to reload, its exports and observers are removed right after its on_script_unloaded callback. Export from a callback which runs on load (e.g. on_script_loaded), so a reloaded script exports again.

Editor support

LAD files record each type’s namespace. The Lua language server definitions declare a namespace.<name> class per native namespace, and import_namespace("transform") returns the matching class, so completion works on imported tables. Script namespaces only exist at runtime and are untyped.

References

Most values scripts get from Rust are references: they point at a value living somewhere else, and reading or writing through them reads or writes that value. A reference is a base, saying where the value lives, plus a path to the field being accessed.

BasePoints atScripts get one fromValid until
ComponentA component of an entityworld.get_component, queriesThe component is removed or the entity despawned
ResourceA resourceworld.get_resource, script system parametersThe resource is removed
AllocationA value BMS owns for scriptsType.new, :clone(), values returned by functionsKept alive as long as any reference to it is
AssetAn asset in Assets<T>, by handleType.get_asset, world.get_assetThe asset is removed

Accessing a field extends the path, so the result still points into the same value:

local bms = import_namespace("bms")
local world = bms.world
local Transform = import_namespace("transform").Transform

local transform = assert(world.get_component(assert(bms.current_entity()), Transform))
transform.translation.x = 5        -- writes the component

local copy = transform:clone()     -- a new allocation, independent of the component
copy.translation.x = 0             -- the component keeps 5

Access is checked when a reference is used, not when it is made: a reference to a removed component fails with an error, and so does writing a value something else is reading at the same time, i.e. inside a query iteration. Script systems can only access what they declared, and assets, whose access is checked for all assets at once, only from exclusive script systems.

Assets

Handles are plain values (allocations holding a Handle<T>), and asset references point into the Assets<T> resource through one:

local world = import_namespace("bms").world
local Image = import_namespace("render").Image

local handle = Image.load("textures/icon.png")  -- a Handle<Image>, loading in the background
-- later
if world.is_loaded(handle) then
    local image = Image.get_asset(handle)       -- a reference into Assets<Image>
    print(image)                                -- reading or writing its fields reads or writes the asset
end

Warning

For now, reading or writing through an asset reference needs exclusive access to the whole world: Bevy’s ReflectAsset only reaches assets through the world as a whole, not through the Assets<T> resource alone. Asset access therefore conflicts with any other access held at the same time (i.e. inside a query iteration), and isn’t possible in non-exclusive script systems.

Every asset type has load, add_asset and get_asset, and world has the same operations taking the asset type, plus is_loaded, load_state and asset_path for any handle. They are listed with their types in Core Bindings. An asset type needs app.register_asset_reflect::<T>() to be usable from scripts.

References in Rust

Binding signatures choose how they receive references: R<T> borrows, M<T> borrows mutably, V<T> copies the value out, see Controlling Script Bindings. Return a ReflectReference to give scripts a reference, i.e. ReflectReference::new_allocated(value).

For references whose type matters only to the docs, use ValueOf<T>: a ReflectReference at runtime, documented as T. Combined with the A marker for a generic parameter, a function can take the handle of any asset type, and still show up as taking a Handle<A> in the docs and the Lua language server files:

use bevy_mod_scripting::bindings::function::generics::{A, ValueOf};

#[script_bindings(remote, namespace = "my_game")]
impl NamespaceMembers {
    /// Works with the handles `Image.load`, `world.load_asset` and others return.
    fn asset_id(ctxt: FunctionCallContext, handle: ValueOf<Handle<A>>) -> Result<String, InteropError> {
        let untyped: UntypedHandle = handle.try_untyped_asset_handle(ctxt.world()?)?;
        Ok(untyped.id().to_string())
    }

    /// Gives scripts a reference to an asset, as `Image.get_asset` does.
    fn icon(ctxt: FunctionCallContext) -> Result<ValueOf<Image>, InteropError> {
        let world = ctxt.world()?;
        // `Icons` is a resource of your game, holding `Handle<Image>`s
        let handle = world.with_resource(|icons: &Icons| icons.default.clone().untyped())?;
        ReflectReference::new_asset_ref(handle, TypeId::of::<Image>(), world).map(ValueOf::new)
    }
}

For a handle of one asset type, take ValueOf<Handle<Image>>. V<Handle<Image>> works too, but copies the handle out first.

Core Callbacks

On top of callbacks which are registered by your application, BMS provides a set of core callbacks which are always available (unless disabled via plugin settings).

The three core callbacks are:

  • on_script_loaded
  • on_script_unloaded
  • on_script_reloaded

For how callbacks work in general, see Callbacks. They run as part of the script pipeline.

on_script_loaded

This will be called right after a script has been loaded or reloaded. This is a good place to initialize your script. You should avoid placing a lot of logic into the global body of your script, and instead put it into this callback. Otherwise errors in the initialization will fail the loading of the script.

print("you can also use this space, but it's not recommended")
function on_script_loaded()
    print("Hello world")
end

on_script_unloaded

This will be called right before a script is unloaded. This is a good place to clean up any resources that your script has allocated. This is called both before a script is removed as well as before a script is reloaded. If you want to preserve the state of your script across reloads, you can return a value from this callback, which will be passed to on_script_reloaded when the script is reloaded.

function on_script_unloaded()
    print("Goodbye world")
    return "house key"
end

on_script_reloaded

Called right after on_script_loaded but only if the script was reloaded. The callback is passed a state argument, this state is exactly what is returned by the script through on_script_unloaded before a reload happens.

mode = 1
function on_script_reloaded(value)
    if value then
        print("I'm back. Thanks for the keys!")
    else
        print('I have not saved any state before unloading')
    end
end

Using on_script_reloaded one can make a script reload preserve its current state.

Constructing Arbitrary Types

When interfacing with bevy, we do this via reflection. While the bevy bindings do not cover constructors for every single type that bevy or other libraries provide, reflection allows us to construct some (not all types implement FromReflect) types from dynamic structs.

BMS exposes this ability to all script writers via the new function available on every type, as well as the more verbose bms.construct.

Type.new

Every type has a new function, taking a table of the fields to set. Types are reached through their namespace, i.e. import_namespace("my_game").MyStruct:

pub struct MyStruct {
    pub my_field: String,
    pub other_field: usize,
}
local MyStruct = import_namespace("my_game").MyStruct
local my_struct = MyStruct.new({
    my_field = "hello",
    other_field = 5,
})
pub struct MyTupleStruct(pub String);

Tuple structs and tuples are constructed using the index of the field as the key, the keys follow the indexing convention of the language, i.e. in Lua the first field is "1":

local my_tuple_struct = MyTupleStruct.new({
    ["1"] = "hello",
})

A list is taken to be the fields in order, which is usually the more natural way to write tuple structs:

local my_tuple_struct = MyTupleStruct.new({ "hello" })

Types which are not structs, tuple structs, tuples or enums, can be constructed only if they implement Default, using Type.new({}).

Defaults

Fields which are not provided are filled in, in the following order of priority:

  1. the value from the type’s Default implementation, if it has one. For enums, only if the default is the variant being constructed
  2. the Default of the field’s type, if it has one

If neither is available the construction fails, and the error names the missing field. Entries which are not fields of the type, i.e. a misspelled field name, are an error too, rather than being ignored in favour of a default. The generated Lua language server files mark exactly these fields as optional, see Editor support.

Naming and priority

new is a single function shared by all types, and is made available on every type. A function with the same name registered on the type itself always takes priority, i.e. Vec3.new(x, y, z) is the Vec3 constructor from the math bindings, not the shared one. For such types use bms.construct, which works for every type.

The name of the function is configurable via the ConstructorsPlugin:

app.add_plugins(BMSPlugin.set(ConstructorsPlugin {
    constructor_name: "create".into(),
}));

The function is registered under the StaticTypeRef type, which is where functions available on all types are registered.

Enums

The following enum:

pub enum MyEnum {
    VariantA {
        field: String
    },
    VariantB(usize),
    VariantC,
}

has its variants available as MyEnum.VariantA, MyEnum.VariantB and MyEnum.VariantC, which can be used to construct values of the variant using :new:

local a = MyEnum.VariantA:new({ field = "hello" })
local b = MyEnum.VariantB:new({ 5 })
local c = MyEnum.VariantC:new({})

The enum’s Default only fills in fields if it is the variant being constructed.

You can also pick the variant by name using MyEnum.new({ variant = "VariantA", field = "hello" }).

Discriminating variants

The variant a value is in can be obtained with :variant(), and compared with the variants of the enum:

if my_enum:variant() == MyEnum.VariantA then
    print(my_enum.field)
end

This is also useful with enums that carry no data, such as keys:

local KeyCode = import_namespace("input").KeyCode
if event.key_code:variant() == KeyCode.KeyA then
    print("A was pressed")
end

:variant() returns nil if the value is not an enum. If you need the name of the variant, :variant_name() is also available on both values and variants.

Variants named like functions

Functions on the type take priority over variants, so a variant named like a function cannot be accessed with MyEnum.Name. Use world.get_enum_variant to get at it in that case:

local world = import_namespace("bms").world
local variant = world.get_enum_variant(import_namespace("my_game").MyEnum, "Name")

bms.construct

The bms.construct function constructs types from a registration. It works for every type, including those whose own new function shadows the shared one, and is useful if you only have the type as a value:

local bms = import_namespace("bms")
local my_game = import_namespace("my_game") -- the crate defining the types
local concrete_my_struct = bms.construct(my_game.MyStruct, {
    my_field = "hello"
})

local variantA = bms.construct(my_game.MyEnum, {
    variant = "VariantA",
    field = "hello"
})

local vec = bms.construct(import_namespace("math").Vec3, { x = 1, y = 2, z = 3 })

Missing fields are filled in from defaults in the same way as for new.

Editor support

The Lua language server files describe the table each constructor takes, so editors can complete and check the fields. A field is optional exactly when a default can fill it in, as described in Defaults:

#[derive(Reflect)]
pub struct MyStruct {
    pub my_field: String,
    pub handle: MyHandle, // no `Default`
}
---@class (exact) MyStruct.Fields
---@field my_field? string
---@field handle MyHandle
---@field [any] 'never'

---@param payload MyStruct.Fields
---@return MyStruct
function MyStruct.new(payload) end

The language server then warns about missing required fields, fields of the wrong type, and unknown fields, i.e. a misspelled my_feild. The last line rejects unknown fields: until the language server checks exact classes against tables passed to functions (LuaLS/lua-language-server#1990), any undeclared field has to be of a type no value has, so the warning reads “Cannot assign string to 'never'”.

Tuple fields are declared under their integer keys, i.e. [1], which a list such as { "hello" } fills in, so prefer lists for tuple structs. Types and variants without fields all take NoFields, i.e. {}.

Each enum variant has a class of its own, i.e. MyEnum.VariantA, so MyEnum.VariantA:new{ completes the fields of VariantA and returns a MyEnum.

The table of MyEnum.new{ variant = "VariantA", ... } is not described, as the language server cannot narrow its fields down by the variant given. Prefer MyEnum.VariantA:new{...}, which is checked.

Since the type of bms.construct’s first argument is only known when the script runs, its table is not described.

Calling Other Scripts

Scripts can run callbacks of other scripts, in any scripting language, using two functions:

FunctionWhen the callback runsReturns
bms.run_script_callback(label, target, ...args)Immediately, before the call returnsWhat the callback returned
bms.queue_script_callback(label, target, ...args)As soon as the current callback finishes, in the same frameNothing
local bms = import_namespace("bms")
local ScriptAttachment, Recipients = bms.ScriptAttachment, bms.Recipients
local enemy_script = ScriptAttachment.new_entity_script(enemy, bms.current_script())

-- runs `take_damage(10, "fire")` in the enemy's script right away
local remaining_health = bms.run_script_callback("take_damage", enemy_script, 10, "fire")

-- runs `on_hit()` in every script once this callback is done
bms.queue_script_callback("on_hit", Recipients.all_scripts())
let bms = import_namespace("bms");
let ScriptAttachment = bms.ScriptAttachment;
let Recipients = bms.Recipients;
let enemy_script = ScriptAttachment.new_entity_script(enemy, bms.current_script());

// runs `take_damage(10, "fire")` in the enemy's script right away
let remaining_health = bms.run_script_callback("take_damage", enemy_script, 10, "fire");

// runs `on_hit()` in every script once this callback is done
bms.queue_script_callback("on_hit", Recipients.all_scripts());

Targets

The target is either a single script:

  • ScriptAttachment.new_static_script(script)
  • ScriptAttachment.new_entity_script(entity, script)

or a set of Recipients:

  • Recipients.all_scripts(): every loaded script, once per script even if scripts share a context
  • Recipients.all_contexts(): every loaded context once
  • Recipients.static_script(script)
  • Recipients.entity_script(entity, script)

For a single script, bms.run_script_callback returns the callback’s value. For recipients it returns a list with the value of each script which ran the callback. Scripts which are still loading or unloading are skipped when targeting many scripts, while targeting a specific script which is not loaded is an error.

Errors

  • bms.run_script_callback raises the callback’s error in the calling script, so it can be handled like any other error. For recipients, the first error is raised after all scripts ran the callback.
  • Errors of queued callbacks cannot reach the script which queued them, they are reported like other script errors (logged by default).

Which scripts can be called immediately

While a callback runs, its script context is busy, so bms.run_script_callback cannot run a callback in a busy context. This includes:

  • the calling script itself (call the function directly instead),
  • scripts sharing a context with the calling script,
  • scripts further up the current chain of callbacks, e.g. A calls B, which calls A again.

These calls return an error instead. bms.queue_script_callback works for all of them, since queued callbacks only run once the current callback has finished.

Which scripts share a context depends on the context policy of the scripting plugin, by default none do.

Queued callbacks

  • Queued callbacks run in the order they were queued, and can queue further callbacks, which run in the same go.
  • They never run in the middle of the callback which queued them, even if it keeps using the world afterwards.
  • To stop callbacks from queueing each other endlessly, at most 1024 queued callbacks run in one go. Any beyond that run later, and an error is reported.

Script systems

Script systems running in parallel with other systems (i.e. not marked exclusive) cannot use bms.run_script_callback, as another system might be running the target script at the same time. Callbacks they queue run at the end of the frame instead, in the ScriptingSystemSet::RunQueuedCallbacks system set in the Last schedule.

Limits

  • Callbacks can be nested at most 64 levels deep, i.e. a callback running another callback which runs another one and so on.

Events and Messages

Scripts can send Bevy events (observer-style, run immediately) and messages (buffered, read later by MessageReaders) using the reflection data Bevy generates for them.

FunctionRust type data requiredBehaviour
world.trigger_event(type, value)ReflectEventTriggers the event. Observers run, and all pending commands are applied, before the call returns. Also triggers script events.
world.write_message(type, value)ReflectMessageWrites the message to its Messages<T> buffer, readers see it later in the frame.
local world = import_namespace("bms").world
local my_game = import_namespace("my_game") -- the crate defining the types
world.trigger_event(my_game.MyEvent, my_game.MyEvent.new({ amount = 3 }))
world.write_message(my_game.MyMessage, my_game.MyMessage.new({ amount = 3 }))

The value is copied when sent, so the same value can be sent again, and changing it afterwards does not affect events already sent.

Registration requirements

Only types which are registered with the matching reflect attribute can be sent, anything else errors with a missing type data error:

#[derive(Event, Reflect)]
#[reflect(Event)]
struct MyEvent { amount: usize }

#[derive(Message, Reflect)]
#[reflect(Message)]
struct MyMessage { amount: usize }

app.register_type::<MyEvent>()
   .register_type::<MyMessage>()
   // messages must also be added as usual, otherwise there is nothing to write them to
   .add_message::<MyMessage>();
  • The type must be registered with register_type, otherwise scripts cannot import it.
  • #[reflect(Event)] is only generated for events using the default (global) trigger. Events with custom triggers, such as entity events, need a hand-written ReflectEvent.
  • Types which do not implement FromReflect (all fields must be reflectable) cannot be sent.
  • Bevy’s own events and messages are not usable unless they have the reflect attributes.

Things to be aware of

  • trigger_event needs exclusive access to the world, so it fails with an access error if the script is currently holding a borrowed reference elsewhere in the same call (e.g. inside a query iteration or with_* access). Trigger events from regular callbacks.
  • Observers run before trigger_event returns, and so do the commands they queue (as for other operations such as spawning). A Rust observer or command which runs a callback in the currently executing script context fails with an error. Use bms.run_script_callback or bms.queue_script_callback instead (see Calling Other Scripts).

Observing events from scripts

world.add_observer(event, callback, components?, entities?) runs the calling script’s callback callback (registered with register_callback, or a top level function of that name) with a copy of the event, whenever the event is triggered. It returns the observer entity: despawn it to remove the observer.

local world = import_namespace("bms").world
local ecs = import_namespace("ecs")
local Mana = world.register_new_component("script.my_game", "Mana")

register_callback("on_mana_added", function(event)
    print("Mana was added to", event.entity)
end)

local observer = world.add_observer(ecs.AddEvent, "on_mana_added", { Mana })
world.despawn(observer) -- later
  • The lifecycle events AddEvent, InsertEvent, DiscardEvent, RemoveEvent and DespawnEvent (in ecs) work for any native or script component. Other events need #[reflect(Event)].
  • As in Bevy, components is an OR filter, and entities restricts the observer to those entities.
  • Callbacks run right after the triggering operation, in unspecified order. If the script’s context is busy (e.g. it triggered the event), the callback runs as soon as the busy callback finishes, so observers never re-enter a running script.
  • The world is already past the change: removed component data can’t be read in RemoveEvent callbacks.
  • Errors are reported like those of other callbacks (ScriptErrorMessage), and don’t fail the triggering operation.
  • add_observer only works inside a script callback.

Script defined events

Scripts can define events carrying any value:

local world = import_namespace("bms").world
local Damaged = world.register_new_event("script.my_game", "Damaged")

register_callback("on_damaged", function(payload)
    print("took damage:", payload.amount)
end)

world.add_observer(Damaged, "on_damaged")
world.trigger_event(Damaged, { amount = 5 })
  • register_new_event fails if the name is taken, unless allow_existing (third argument) is passed.
  • Script events are global: components and entities are ignored.
  • Other scripts get them with import_namespace, i.e. import_namespace("script.my_game").Damaged.

Built-in messages

The following BMS messages are reflected and can be written from scripts:

  • ScriptCallbackMessage: runs a callback on other scripts, processed later in the frame by the handler systems set up for its callback label. Labels without a handler system are never processed, prefer bms.queue_script_callback to run callbacks from scripts.
  • ScriptLifecycleMessage (Attached / Detached), ScriptAssetModifiedMessage: drive the script loading pipeline

The internal loading pipeline state events (LoadingCompleted, ContextAssigned, …) are intentionally not reflected.

Bundles

Scripts can insert bundles defined in Rust, all components at once:

FunctionBehaviour
world.insert_bundle(entity, type, value)Inserts the bundle’s components into the entity.
world.spawn_bundle(type, value)Spawns an entity with the bundle and returns it.

Bundles need ReflectBundle type data, and are constructed like any other type:

#[derive(Bundle, Reflect, Default)]
#[reflect(Bundle, Default)]
struct EnemyBundle {
    health: Health,
    transform: Transform,
}

app.register_type::<EnemyBundle>();
// tuples and foreign bundles: app.register_type_data::<(Health, Transform), ReflectBundle>()
local world = import_namespace("bms").world
local EnemyBundle = import_namespace("my_game").EnemyBundle
world.spawn_bundle(EnemyBundle, EnemyBundle.new({ health = Health.new({ hp = 10 }) }))

Core Bindings

Contents

This is an automatically generated file, you’ll find links to the contents below

Builtins

The only globals of scripts. Everything else is imported from a namespace, see the namespace pages under Types, i.e. import_namespace("bms").world.

Functions

NameSummary
export_namespaceExports a callback of the calling script as a function in a script namespace, so that any script (in any language) can…
import_namespaceImports a namespace, returning a table of the types, functions, values, events, system sets and exports in it by name.
register_callbackRegisters a function as the handler of a callback, taking precedence over a top level function of that name.

export_namespace

export_namespace(name: String, callback: String, arg3: String)

Exports a callback of the calling script as a function in a script namespace, so that any script (in any language) can call it.

The callback is either a function registered with register_callback, or a top level function with that name. Calls run in the exporting script and return what the callback returns.

register_callback("spawn_enemy_impl", function(health) ... end)
export_namespace("script.game", "spawn_enemy", "spawn_enemy_impl")
-- in another script, once the first one has run
import_namespace("script.game").spawn_enemy(5)

Arguments

  • name: the name of the function within the namespace.
  • callback: the label of the callback of this script to export.

Returns: Nothing if the function was exported.

import_namespace

import_namespace(arg1: String) -> ScriptValue

Imports a namespace, returning a table of the types, functions, values, events, system sets and exports in it by name.

Bevy types with bindings live in a namespace per category (math, ecs, transform, ui, …), BMS’ own types and functions in bms, any other type in the namespace named after the crate defining it. Namespaces defined by scripts start with script..

local bms = import_namespace("bms")
local Vec3 = import_namespace("math").Vec3
bms.world.spawn()

Fails with a list of similar namespaces if the namespace does not exist.

Returns: a table of the contents of the namespace keyed by name.

register_callback

register_callback(callback: String, function: DynamicFunction)

Registers a function as the handler of a callback, taking precedence over a top level function of that name.

register_callback("on_script_unloaded", function() print("unloading!") end)

Arguments

  • callback: the callback label to register the function against.
  • function: the function handling the callback.

Types

Namespaces

Types are grouped by the namespace scripts import them from, i.e. import_namespace("math").

NamespaceContents
alloc1 type
animation10 types
asset9 types, 2 values
audio4 types
bevy_platform3 types
bevy_shader1 type
bms30 types, 13 functions, 2 values
camera17 types, 1 value
camera.VisibilitySystems5 values
color14 types
core5 types
ecs9 types
gizmos1 type, 3 values
input11 types, 1 value
input.InputFocusSystems2 values
math43 types
petgraph1 type
render23 types
smol_str1 type
sprite15 types
text21 types, 2 values
time9 types, 1 value
transform2 types
transform.TransformSystems1 value
ui37 types, 1 value
ui.UiSystems7 values
uuid1 type
wgpu_types1 type
window16 types, 1 value
window.CursorSystems1 value
root27 types

alloc

The types and functions in the alloc namespace, as returned by import_namespace("alloc").

Types

TypeSummary
Cow

Cow

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Cow>) -> Cow

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

animation

The types and functions in the animation namespace, as returned by import_namespace("animation").

Types

TypeSummary
ActiveAnimationAn animation that an AnimationPlayer is currently either playing or was playing, but is presently paused.
AnimationClipA list of VariableCurves and the AnimationTargetIds to which they apply.
AnimationEventData
AnimationEventTarget
AnimationGraphA graph structure that describes how animation clips are to be blended together.
AnimationPlayerAnimation controls.
AnimationTargetIdA component that identifies which parts of an AnimationClip asset can be applied to an entity.
NodeIndex
RepeatAnimationRepetition behavior of an animation.
TimedAnimationEvent

ActiveAnimation

An animation that an AnimationPlayer is currently either playing or was playing, but is presently paused.

A stopped animation is considered no longer active.

Fields

FieldType
weightf32
repeatRepeatAnimation
speedf32
elapsedf32
seek_timef32
last_seek_timeOptional<f32>
completionsu32
just_completedbool
pausedbool

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ActiveAnimation>) -> ActiveAnimation

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

AnimationClip

A list of VariableCurves and the AnimationTargetIds to which they apply.

Because animation clips refer to targets by UUID, they can target any entity with that ID.

Fields

FieldType
eventsHashMap<AnimationEventTarget, Vec<TimedAnimationEvent>>
durationf32

Functions

NameSummary
add_assetAdds a value of this type as a new asset, returning a strong handle to it.
get_assetThe asset a handle points to, or nil if it isn’t loaded or added yet.
loadStarts loading an asset of this type from a path, returning a handle to it right away.
newConstructs a new instance of the type from a table of its fields.

add_asset

add_asset(value: AnimationClip) -> Handle<AnimationClip>

Adds a value of this type as a new asset, returning a strong handle to it.

Arguments

  • value: The asset value.

Returns: A handle to the new asset.

get_asset

get_asset(handle: Handle<AnimationClip>) -> Optional<AnimationClip>

The asset a handle points to, or nil if it isn’t loaded or added yet.

Changes to the returned value change the asset.

Arguments

  • handle: The handle to the asset.

Returns: The asset, or nil.

load

load(path: String) -> Handle<AnimationClip>

Starts loading an asset of this type from a path, returning a handle to it right away.

Arguments

  • path: The asset path, relative to the assets folder.

Returns: A handle to the asset, which is loaded in the background.

new

new(payload: Fields<AnimationClip>) -> AnimationClip

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

AnimationEventData

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<AnimationEventData>) -> AnimationEventData

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

AnimationEventTarget

Variants

VariantFields
Root
Node(AnimationTargetId)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<AnimationEventTarget>) -> AnimationEventTarget

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

NameSummary
Node.new
Root.new

Node.new

new(variant: EnumVariantRef, payload: Fields<AnimationEventTarget::Node>) -> AnimationEventTarget

Root.new

new(variant: EnumVariantRef, payload: Fields<AnimationEventTarget::Root>) -> AnimationEventTarget

AnimationGraph

A graph structure that describes how animation clips are to be blended together.

Applications frequently want to be able to play multiple animations at once and to fine-tune the influence that animations have on a skinned mesh. Bevy uses an animation graph to store this information. Animation graphs are a directed acyclic graph (DAG) that describes how animations are to be weighted and combined together. Every frame, Bevy evaluates the graph from the root and blends the animations together in a bottom-up fashion to produce the final pose.

There are three types of nodes: blend nodes, add nodes, and clip nodes, all of which can have an associated weight. Blend nodes and add nodes have no associated animation clip and combine the animations of their children according to those children’s weights. Clip nodes specify an animation clip to play. When a graph is created, it starts with only a single blend node, the root node.

For example, consider the following graph:

┌────────────┐                                      
│            │                                      
│    Idle    ├─────────────────────┐                
│            │                     │                
└────────────┘                     │                
                                   │                
┌────────────┐                     │  ┌────────────┐
│            │                     │  │            │
│    Run     ├──┐                  ├──┤    Root    │
│            │  │  ┌────────────┐  │  │            │
└────────────┘  │  │   Blend    │  │  └────────────┘
                ├──┤            ├──┘                
┌────────────┐  │  │    0.5     │                   
│            │  │  └────────────┘                   
│    Walk    ├──┘                                   
│            │                                      
└────────────┘                                      

In this case, assuming that Idle, Run, and Walk are all playing with weight 1.0, the Run and Walk animations will be equally blended together, then their weights will be halved and finally blended with the Idle animation. Thus the weight of Run and Walk are effectively half of the weight of Idle.

Nodes can optionally have a mask, a bitfield that restricts the set of animation targets that the node and its descendants affect. Each bit in the mask corresponds to a mask group, which is a set of animation targets (bones). An animation target can belong to any number of mask groups within the context of an animation graph.

When the appropriate bit is set in a node’s mask, neither the node nor its descendants will animate any animation targets belonging to that mask group. That is, setting a mask bit to 1 disables the animation targets in that group. If an animation target belongs to multiple mask groups, masking any one of the mask groups that it belongs to will mask that animation target. (Thus an animation target will only be animated if all of its mask groups are unmasked.)

A common use of masks is to allow characters to hold objects. For this, the typical workflow is to assign each character’s hand to a mask group. Then, when the character picks up an object, the application masks out the hand that the object is held in for the character’s animation set, then positions the hand’s digits as necessary to grasp the object. The character’s animations will continue to play but will not affect the hand, which will continue to be depicted as holding the object.

Animation graphs are assets and can be serialized to and loaded from RON files. Canonically, such files have an .animgraph.ron extension.

The animation graph implements RFC 51. See that document for more information.

Fields

FieldType
graphDiGraph<Unknown, Unknown, u32>
rootNodeIndex
mask_groupsHashMap<AnimationTargetId, u64>

Functions

NameSummary
from_clipA new graph that plays handle on its own at full weight.
newConstructs a new instance of the type from a table of its fields.

from_clip

from_clip(handle: Handle<AnimationClip>) -> AnimationGraph

A new graph that plays handle on its own at full weight.

new

new(payload: Fields<AnimationGraph>) -> AnimationGraph

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
add_clipAdds the clip handle under the node parent, with weight relative to its siblings. Returns the new node.
root_nodeThe index of the root node of the graph, which all of its animations are blended into.

add_clip

add_clip(self: AnimationGraph, handle: Handle<AnimationClip>, weight: f32, parent: NodeIndex) -> NodeIndex

Adds the clip handle under the node parent, with weight relative to its siblings. Returns the new node.

root_node

root_node(self: AnimationGraph) -> NodeIndex

The index of the root node of the graph, which all of its animations are blended into.

AnimationPlayer

Component

Animation controls.

Automatically added to any root animations of a scene when it is spawned.

Fields

FieldType
active_animationsHashMap<NodeIndex, ActiveAnimation>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<AnimationPlayer>) -> AnimationPlayer

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
all_finishedWhether every playing animation has finished. True when nothing is playing.
all_pausedWhether every playing animation is paused. True when nothing is playing.
animation_is_finishedWhether the animation node has finished, or nil if it is not playing.
is_playing_animationWhether the animation node is playing or paused.
pause_allPauses all playing animations.
playStarts playing the animation node. Does nothing if it is already playing.
resume_allResumes all paused animations.
seek_toJumps the animation node to seconds into its clip. Errors if it is not playing.
set_repeat_foreverMakes the animation node repeat forever. Errors if it is not playing.
set_speedSets the playback speed of the animation node, where 1.0 is normal speed. Errors if it is not playing.
stopStops the animation node and removes it from the player.
stop_allStops all animations and removes them from the player.

all_finished

all_finished(self: AnimationPlayer) -> bool

Whether every playing animation has finished. True when nothing is playing.

all_paused

all_paused(self: AnimationPlayer) -> bool

Whether every playing animation is paused. True when nothing is playing.

animation_is_finished

animation_is_finished(self: AnimationPlayer, node: NodeIndex) -> Optional<bool>

Whether the animation node has finished, or nil if it is not playing.

is_playing_animation

is_playing_animation(self: AnimationPlayer, node: NodeIndex) -> bool

Whether the animation node is playing or paused.

pause_all

pause_all(self: AnimationPlayer)

Pauses all playing animations.

play

play(self: AnimationPlayer, node: NodeIndex)

Starts playing the animation node. Does nothing if it is already playing.

resume_all

resume_all(self: AnimationPlayer)

Resumes all paused animations.

seek_to

seek_to(self: AnimationPlayer, node: NodeIndex, seconds: f32)

Jumps the animation node to seconds into its clip. Errors if it is not playing.

set_repeat_forever

set_repeat_forever(self: AnimationPlayer, node: NodeIndex)

Makes the animation node repeat forever. Errors if it is not playing.

set_speed

set_speed(self: AnimationPlayer, node: NodeIndex, speed: f32)

Sets the playback speed of the animation node, where 1.0 is normal speed. Errors if it is not playing.

stop

stop(self: AnimationPlayer, node: NodeIndex)

Stops the animation node and removes it from the player.

stop_all

stop_all(self: AnimationPlayer)

Stops all animations and removes them from the player.

AnimationTargetId

Component

A component that identifies which parts of an AnimationClip asset can be applied to an entity. Typically used alongside the AnimatedBy component.

AnimationTargetId is implemented as a UUID. When importing an armature or an animation clip, asset loaders typically use the full path name from the armature to the bone to generate these UUIDs. The ID is unique to the full path name and based only on the names. So, for example, any imported armature with a bone at the root named Hips will assign the same AnimationTargetId to its root bone. Likewise, any imported animation clip that animates a root bone named Hips will reference the same AnimationTargetId. Any animation is playable on any armature as long as the bone names match, which allows for easy animation retargeting.

Note that asset loaders generally use the full path name to generate the AnimationTargetId. Thus a bone named Chest directly connected to a bone named Hips will have a different ID from a bone named Chest that’s connected to a bone named Stomach.

Fields

IndexType
0Uuid

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<AnimationTargetId>) -> AnimationTargetId

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

NodeIndex

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newA node index from its number.

new

new(index: u32) -> NodeIndex

A node index from its number.

Scripts see this type as NodeIndex.

local NodeIndex = import_namespace("animation").NodeIndex
local node = NodeIndex.new(3)
assert(node:index() == 3)
let NodeIndex = import_namespace("animation").NodeIndex;
let node = NodeIndex.new(3);
assert!(node.index() == 3);

Methods

NameSummary
indexThe number of this node index.

index

index(self: NodeIndex) -> u32

The number of this node index.

RepeatAnimation

Repetition behavior of an animation.

Variants

VariantFields
Never
Count(u32)
Forever

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<RepeatAnimation>) -> RepeatAnimation

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Count.new

new(variant: EnumVariantRef, payload: Fields<RepeatAnimation::Count>) -> RepeatAnimation

Forever.new

new(variant: EnumVariantRef, payload: Fields<RepeatAnimation::Forever>) -> RepeatAnimation

Never.new

new(variant: EnumVariantRef, payload: Fields<RepeatAnimation::Never>) -> RepeatAnimation

TimedAnimationEvent

Fields

FieldType
timef32
eventAnimationEventData

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<TimedAnimationEvent>) -> TimedAnimationEvent

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

asset

The types and functions in the asset namespace, as returned by import_namespace("asset").

Types

TypeSummary
ArcMutexValue<T>A shared value of an asset of type T.
AssetId<A>The id of an asset of type A.
AssetIndexA generational runtime-only identifier for a specific Asset stored in Assets.
AssetPathRepresents a path to an asset in a “virtual filesystem”.
Handle<A>A handle to an asset of type A.
HandleTemplate<T>A template for a handle to an asset of type T.
LoadedFolderNot reflected: scripts can only pass values of it around.
LoadedUntypedAssetNot reflected: scripts can only pass values of it around.
RenderAssetUsagesDefines where the asset will be used.

Values

NameType
AssetEventSystemsReflectSystemSet
AssetTrackingSystemsReflectSystemSet

ArcMutexValue<T>

Generic

A shared value of an asset of type T.

Opaque: scripts can't access its fields, only its functions.

Instantiations

ArcMutexValue<ShaderBuffer>, ArcMutexValue<TextureAtlasLayout>, ArcMutexValue<ScriptAsset>, ArcMutexValue<Image>, ArcMutexValue<Mesh>, ArcMutexValue<ColorMaterial>, ArcMutexValue<SpriteMeshMaterial>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

On ArcMutexValue<ShaderBuffer>, ArcMutexValue<TextureAtlasLayout>, ArcMutexValue<ScriptAsset>, ArcMutexValue<Image>, ArcMutexValue<Mesh>, ArcMutexValue<ColorMaterial>, ArcMutexValue<SpriteMeshMaterial>

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

AssetId<A>

Generic

The id of an asset of type A.

Variants

VariantFields
Index{ index: AssetIndex }
Uuid{ uuid: Uuid }

Instantiations

AssetId<ScriptAsset>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

On AssetId<ScriptAsset>

new(payload: Fields<AssetId<ScriptAsset>>) -> AssetId<ScriptAsset>

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

AssetIndex

A generational runtime-only identifier for a specific Asset stored in Assets. This is optimized for efficient runtime usage and is not suitable for identifying assets across app runs.

Fields

FieldType
generationu32
indexu32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<AssetIndex>) -> AssetIndex

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

AssetPath

Represents a path to an asset in a “virtual filesystem”.

Asset paths consist of three main parts:

  • AssetPath::source: The name of the AssetSource to load the asset from. This is optional. If one is not set the default source will be used (which is the assets folder by default).
  • AssetPath::path: The “virtual filesystem path” pointing to an asset source file.
  • AssetPath::label: An optional “named sub asset”. When assets are loaded, they are allowed to load “sub assets” of any type, which are identified by a named “label”.

Asset paths are generally constructed (and visualized) as strings:

# use bevy_asset::{Asset, AssetServer, Handle};
# use bevy_reflect::TypePath;
#
# #[derive(Asset, TypePath, Default)]
# struct Mesh;
#
# #[derive(Asset, TypePath, Default)]
# struct Scene;
#
# let asset_server: AssetServer = panic!();
// This loads the `my_scene.scn` base asset from the default asset source.
let scene: Handle<Scene> = asset_server.load("my_scene.scn");

// This loads the `PlayerMesh` labeled asset from the `my_scene.scn` base asset in the default asset source.
let mesh: Handle<Mesh> = asset_server.load("my_scene.scn#PlayerMesh");

// This loads the `my_scene.scn` base asset from a custom 'remote' asset source.
let scene: Handle<Scene> = asset_server.load("remote://my_scene.scn");

AssetPath implements From for &'static str, &'static Path, and &'a String, which allows us to optimize the static cases. This means that the common case of asset_server.load("my_scene.scn") when it creates and clones internal owned AssetPaths. This also means that you should use AssetPath::parse in cases where &str is the explicit type.

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<AssetPath>) -> AssetPath

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Handle<A>

Generic

A handle to an asset of type A.

Variants

VariantFields
Strong(Arc<Unknown>)
Uuid(Uuid)

Instantiations

Handle<ScriptAsset>, Handle<AnimationClip>, Handle<ShaderBuffer>, Handle<TextureAtlasLayout>, Handle<Image>, Handle<ColorMaterial>, Handle<()>, Handle<Mesh>, Handle<SpriteMeshMaterial>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

On Handle<ScriptAsset>, Handle<AnimationClip>, Handle<ShaderBuffer>, Handle<TextureAtlasLayout>, Handle<Image>, Handle<ColorMaterial>, Handle<()>, Handle<Mesh>, Handle<SpriteMeshMaterial>

new(payload: Fields<Handle<ScriptAsset>>) -> Handle<ScriptAsset>

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
asset_pathRetrieves the path of the script asset if present.

asset_path

On Handle<ScriptAsset>

asset_path(handle: Handle<ScriptAsset>) -> Optional<String>

Retrieves the path of the script asset if present. Assets can be unloaded, and as such if the given handle is no longer active, this will return None.

Arguments

  • handle: The handle to the script asset.

Returns: The asset path of the script asset.

HandleTemplate<T>

Generic

A template for a handle to an asset of type T.

Variants

VariantFields
Path(AssetPath)
Handle(Handle<T>)
Value(ArcMutexValue<T>)

Instantiations

HandleTemplate<ScriptAsset>, HandleTemplate<TextureAtlasLayout>, HandleTemplate<ShaderBuffer>, HandleTemplate<Mesh>, HandleTemplate<Image>, HandleTemplate<ColorMaterial>, HandleTemplate<SpriteMeshMaterial>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

On HandleTemplate<ScriptAsset>, HandleTemplate<TextureAtlasLayout>, HandleTemplate<ShaderBuffer>, HandleTemplate<Mesh>, HandleTemplate<Image>, HandleTemplate<ColorMaterial>, HandleTemplate<SpriteMeshMaterial>

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

LoadedFolder

Not reflected: scripts can only pass values of it around.

Opaque: scripts can't access its fields, only its functions.

LoadedUntypedAsset

Not reflected: scripts can only pass values of it around.

Opaque: scripts can't access its fields, only its functions.

RenderAssetUsages

Defines where the asset will be used.

If an asset is set to the RENDER_WORLD but not the MAIN_WORLD, the asset data (pixel data, mesh vertex data, etc) will be removed from the cpu-side asset once it’s been extracted and prepared in the render world. The asset will remain in the assets collection, but with only metadata.

Unloading the asset data saves on memory, as for most cases it is no longer necessary to keep it in RAM once it’s been uploaded to the GPU’s VRAM. However, this means you cannot access the asset data from the CPU (via the Assets<T> resource) once unloaded (without re-loading it).

If you never need access to the asset from the CPU past the first frame it’s loaded on, or only need very infrequent access, then set this to RENDER_WORLD. Otherwise, set this to RENDER_WORLD | MAIN_WORLD.

If you have an asset that doesn’t actually need to end up in the render world, like an Image that will be decoded into another Image asset, use MAIN_WORLD only.

Platform-specific

On Wasm, it is not possible for now to free reserved memory. To control memory usage, load assets in sequence and unload one before loading the next. See this discussion about memory management for more details.

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<RenderAssetUsages>) -> RenderAssetUsages

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

audio

The types and functions in the audio namespace, as returned by import_namespace("audio").

Types

TypeSummary
PlaybackModeThe way Bevy manages the sound playback.
PlaybackSettingsInitial settings to be used when audio starts playing.
SpatialScaleA scale factor applied to the positions of audio sources and listeners for spatial audio.
VolumeA Volume represents an audio source’s volume level.

PlaybackMode

The way Bevy manages the sound playback.

Variants

Variant
Once
Loop
Despawn
Remove

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<PlaybackMode>) -> PlaybackMode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Despawn.new

new(variant: EnumVariantRef, payload: Fields<PlaybackMode::Despawn>) -> PlaybackMode

Loop.new

new(variant: EnumVariantRef, payload: Fields<PlaybackMode::Loop>) -> PlaybackMode

Once.new

new(variant: EnumVariantRef, payload: Fields<PlaybackMode::Once>) -> PlaybackMode

Remove.new

new(variant: EnumVariantRef, payload: Fields<PlaybackMode::Remove>) -> PlaybackMode

PlaybackSettings

Component

Initial settings to be used when audio starts playing.

If you would like to control the audio while it is playing, query for the AudioSink or SpatialAudioSink components. Changes to this component will not be applied to already-playing audio.

Fields

FieldType
modePlaybackMode
volumeVolume
speedf32
pausedbool
mutedbool
spatialbool
spatial_scaleOptional<SpatialScale>
start_positionOptional<Duration>
durationOptional<Duration>

Functions

NameSummary
despawnSettings that play the sound once, then despawn the entity.
loopingSettings that repeat the sound forever.
newConstructs a new instance of the type from a table of its fields.
onceSettings that play the sound once, then do nothing.
removeSettings that play the sound once, then remove the audio components from the entity.

despawn

despawn() -> PlaybackSettings

Settings that play the sound once, then despawn the entity.

looping

looping() -> PlaybackSettings

Settings that repeat the sound forever.

new

new(payload: Fields<PlaybackSettings>) -> PlaybackSettings

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

once

once() -> PlaybackSettings

Settings that play the sound once, then do nothing.

remove

remove() -> PlaybackSettings

Settings that play the sound once, then remove the audio components from the entity.

Methods

NameSummary
with_spatialA copy of the settings with spatial audio turned on or off.
with_speedA copy of the settings with the starting speed set to speed, where 1 is normal speed.
with_volumeA copy of the settings with the starting volume set to linear, where 1 is the original volume and 0 is silent.

with_spatial

with_spatial(self: PlaybackSettings, spatial: bool) -> PlaybackSettings

A copy of the settings with spatial audio turned on or off.

with_speed

with_speed(self: PlaybackSettings, speed: f32) -> PlaybackSettings

A copy of the settings with the starting speed set to speed, where 1 is normal speed.

with_volume

with_volume(self: PlaybackSettings, linear: f32) -> PlaybackSettings

A copy of the settings with the starting volume set to linear, where 1 is the original volume and 0 is silent.

SpatialScale

A scale factor applied to the positions of audio sources and listeners for spatial audio.

Default is Vec3::ONE.

Fields

IndexType
0Vec3

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<SpatialScale>) -> SpatialScale

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Volume

A Volume represents an audio source’s volume level.

To create a new Volume from a linear scale value, use Volume::Linear.

To create a new Volume from decibels, use Volume::Decibels.

Variants

VariantFields
Linear(f32)
Decibels(f32)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Volume>) -> Volume

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

NameSummary
Decibels.new
Linear.new

Decibels.new

new(variant: EnumVariantRef, payload: Fields<Volume::Decibels>) -> Volume

Linear.new

new(variant: EnumVariantRef, payload: Fields<Volume::Linear>) -> Volume

bevy_platform

The types and functions in the bevy_platform namespace, as returned by import_namespace("bevy_platform").

Types

TypeSummary
Arc<Unknown>
FixedHasherNot reflected: scripts can only pass values of it around.
Hashed<V, S>A value with its hash computed once, S builds the hasher.

Arc<Unknown>

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Arc<Unknown>>) -> Arc<Unknown>

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

FixedHasher

Not reflected: scripts can only pass values of it around.

Opaque: scripts can't access its fields, only its functions.

Hashed<V, S>

Generic

A value with its hash computed once, S builds the hasher.

Opaque: scripts can't access its fields, only its functions.

Instantiations

Hashed<Cow, FixedHasher>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

On Hashed<Cow, FixedHasher>

new(payload: Fields<Hashed<Cow, FixedHasher>>) -> Hashed<Cow, FixedHasher>

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

bevy_shader

The types and functions in the bevy_shader namespace, as returned by import_namespace("bevy_shader").

Types

TypeSummary
ShaderNot reflected: scripts can only pass values of it around.

Shader

Not reflected: scripts can only pass values of it around.

Opaque: scripts can't access its fields, only its functions.

bms

The types and functions in the bms namespace, as returned by import_namespace("bms").

Types

TypeSummary
CallbackLabelA string which disallows common invalid characters in callback labels, particularly at the start of the string
DynamicComponentA dynamic script component
EnumVariantRefA reference to a variant of an enum, independent of any value of that enum.
FunctionArgInfoInformation about a function argument.
FunctionInfoInformation about a function.
FunctionReturnInfoInformation about a function return value.
FunctionScopeWhere a function lives, for its documentation and errors
InteropErrorAn error occurring when converting between rust and a script context.
LanguageRepresents a scripting language.
RecipientsDescribes the designated recipients of a script event
ReflectableScheduleLabel
ReflectScheduleA reflectable schedule.
ReflectSystemA reflectable system.
ReflectSystemSetA reflectable system set: a set node of a schedule graph, or a set scripts put and order their systems in.
ScriptAssetRepresents a script loaded into memory as an asset
ScriptAssetModifiedMessageEmitted when a script asset is modified and all its attachments require re-loading
ScriptAttachmentSpecifies a unique attachment of a script.
ScriptBundleRegistrationA reference to a bundle type’s reflection registration, i.e. a type with ReflectBundle type data.
ScriptCallbackMessageA callback message meant to trigger a callback in a subset/set of scripts in the world with the given arguments
ScriptComponentA component which identifies the scripts existing on an entity.
ScriptComponentRegistrationA reference to a component type’s reflection registration.
ScriptEventRegistrationA handle to a script registered event type.
ScriptLifecycleMessageEmitted when a script is attached or detached.
ScriptQueryBuilderThe query builder is used to build ECS queries which retrieve spefific components filtered by specific conditions.
ScriptQueryResultA result from a query.
ScriptResourceRegistrationA reference to a resource type’s reflection registration.
ScriptRunConditionA run condition of a script system, evaluated in Rust without calling into the script, see…
ScriptSystemBuilderA builder for systems living in scripts
ScriptTypeRegistrationA reference to a type which is not a Resource or Component.
VariadicTupleA tuple variant of script value

Values

NameType
conditionsType<ScriptRunCondition>
worldWorld

Functions

NameSummary
constructAttempts to construct the given type, given an arbitrary map of values.
current_entityThe entity the running script is attached to, or nil if it isn’t attached to one.
current_scriptThe asset handle of the running script, or nil outside of a script callback.
log_debugLogs a Debug level message to the console * message: the message to log
log_errorLogs a Error level message to the console * message: the message to log
log_infoLogs a Information level message to the console
log_traceLogs a Trace level message to the console * message: the message to log
log_warnLogs a Warning level message to the console * message: the message to log
pack_argsPacks, a variable amount of values, into a single list.
queue_script_callbackQueues a callback to run on other scripts as soon as the current callback finishes, in the same frame.
run_script_callbackRuns a callback on other scripts immediately, and returns what it returned.
system_builderCreates a new script system builder, which can be used to add new systems to the world.
unpack_argsUnpacks, a list of values, into many separate values.

construct

construct<A>(registration: Type<A>, payload: HashMap<String, ScriptValue>) -> A

Generic over A, the type given as registration.

Attempts to construct the given type, given an arbitrary map of values.

Unlike Type.new, this works for every type, including ones with a new function of their own. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types, as for Type.new.

Arguments

  • registration: The type to construct.
  • payload: The values to use to construct the type, keyed by field name or index, or a list of the fields in order.

Returns: The constructed type.

current_entity

current_entity() -> Optional<Entity>

The entity the running script is attached to, or nil if it isn’t attached to one.

Returns: The entity, or nil.

current_script

current_script() -> Optional<Handle<ScriptAsset>>

The asset handle of the running script, or nil outside of a script callback.

If the asset is ever unloaded, the handle will be less useful.

Returns: The handle, or nil.

log_debug

log_debug(message: String)

Logs a Debug level message to the console

  • message: the message to log

log_error

log_error(message: String)

Logs a Error level message to the console

  • message: the message to log

log_info

log_info(message: String)

Logs a Information level message to the console

Arguments

  • message: the message to log

log_trace

log_trace(message: String)

Logs a Trace level message to the console

  • message: the message to log

log_warn

log_warn(message: String)

Logs a Warning level message to the console

  • message: the message to log

pack_args

pack_args(tuple: …) -> Vec<ScriptValue>

Packs, a variable amount of values, into a single list.

Arguments

  • tuple: The tuple of values to curry

Returns: The list of values destructured from the tuple

queue_script_callback

queue_script_callback(label: String, target: ScriptAttachment | Recipients, args: …)

Queues a callback to run on other scripts as soon as the current callback finishes, in the same frame.

Unlike run_script_callback, this works for any script, including the calling script itself and scripts sharing its context. Queued callbacks run in the order they were queued, and their errors are reported as script errors instead of being raised here.

Arguments

  • label: The name of the callback to run.
  • target: The script attachment or recipients to run the callback on.
  • args: The arguments to pass to the callback.

Returns: Nothing if the callback was queued.

run_script_callback

run_script_callback(label: String, target: ScriptAttachment | Recipients, args: …) -> ScriptValue

Runs a callback on other scripts immediately, and returns what it returned.

For example run_script_callback("take_damage", ScriptAttachment.new_entity_script(enemy, script), 10) calls take_damage(10) in that script before this function returns.

The target is either a single script attachment, returning that callback’s value, or Recipients, returning a list with the value of each script which ran the callback. Errors of the callbacks are raised in the calling script, for recipients only after all of them ran.

Callbacks cannot run immediately in a script whose context is busy, i.e. the calling script itself, scripts sharing its context (depending on the context policy), or scripts further up the current chain of callbacks. Use queue_script_callback for those. It is also unavailable in script systems running in parallel with other systems.

Arguments

  • label: The name of the callback to run.
  • target: The script attachment or recipients to run the callback on.
  • args: The arguments to pass to the callback.

Returns: The value returned by the callback, or a list of the values returned by each recipient.

system_builder

system_builder(callback: String, attachment: ScriptAttachment) -> ScriptSystemBuilder

Creates a new script system builder, which can be used to add new systems to the world.

Arguments

  • callback: The function name in the script this system should call when run.
  • attachment: The script attachment to use for the system. This is the attachment that will be used for the system’s callback.

Returns: The system builder

unpack_args

unpack_args(values: Vec<ScriptValue>) -> …

Unpacks, a list of values, into many separate values.

Arguments

  • values: The list of values to uncurry

Returns: The tuple of all values provided

CallbackLabel

A string which disallows common invalid characters in callback labels, particularly at the start of the string

a valid callback label starts with a letter or underscore, and contains only ascii characters, as well as disallows some common keywords

Fields

IndexType
0String

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<CallbackLabel>) -> CallbackLabel

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

DynamicComponent

A dynamic script component

Fields

FieldType
dataScriptValue

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<DynamicComponent>) -> DynamicComponent

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

EnumVariantRef

A reference to a variant of an enum, independent of any value of that enum.

This is what scripts see when accessing MyEnum.Variant, it can be compared to the result of value:variant() and used to construct values of the variant.

Fields

FieldType
type_idTypeId
variant_indexusize

Methods

NameSummary
newConstructs a value of this enum variant from a table of its fields.
variant_nameRetrieves the name of the variant.

new

new(variant: EnumVariantRef, payload: HashMap<String, ScriptValue>) -> ReflectReference

Constructs a value of this enum variant from a table of its fields. Missing fields are filled in from the enum’s default if it is this variant, then from the defaults of the fields’ types.

Arguments

  • variant: The variant to construct.
  • payload: The fields of the variant, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

variant_name

variant_name(variant: EnumVariantRef) -> String

Retrieves the name of the variant.

Arguments

  • variant: The variant.

Returns: The name of the variant.

Operators

NameSummary
eqChecks whether two variants are the same variant of the same enum, or whether a value is in this variant.

eq

eq(variant: EnumVariantRef, other: ScriptValue) -> bool

Checks whether two variants are the same variant of the same enum, or whether a value is in this variant.

Arguments

  • variant: The variant.
  • other: The variant or value to compare with.

Returns: Whether the other value is the same variant.

FunctionArgInfo

Information about a function argument.

Fields

FieldType
nameOptional<Cow>
arg_indexusize
type_idTypeId

FunctionInfo

Information about a function.

Fields

FieldType
nameCow
namespaceFunctionScope
arg_infoVec<FunctionArgInfo>
return_infoFunctionReturnInfo
docsOptional<Cow>

FunctionReturnInfo

Information about a function return value.

Fields

FieldType
type_idTypeId

FunctionScope

Where a function lives, for its documentation and errors

Variants

VariantFields
OnType(TypeId)
Member
Builtin

Variant Functions

Builtin.new

new(variant: EnumVariantRef, payload: Fields<FunctionScope::Builtin>) -> FunctionScope

Member.new

new(variant: EnumVariantRef, payload: Fields<FunctionScope::Member>) -> FunctionScope

OnType.new

new(variant: EnumVariantRef, payload: Fields<FunctionScope::OnType>) -> FunctionScope

InteropError

An error occurring when converting between rust and a script context.

Opaque: scripts can't access its fields, only its functions.

Language

Represents a scripting language. Languages which compile into another language should use the target language as their language.

Variants

VariantFields
Lua
Rune
External{ name: Cow, one_indexed: bool }
Unknown

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Language>) -> Language

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

External.new

new(variant: EnumVariantRef, payload: Fields<Language::External>) -> Language

Lua.new

new(variant: EnumVariantRef, payload: Fields<Language::Lua>) -> Language

Rune.new

new(variant: EnumVariantRef, payload: Fields<Language::Rune>) -> Language

Unknown.new

new(variant: EnumVariantRef, payload: Fields<Language::Unknown>) -> Language

Recipients

Describes the designated recipients of a script event

Variants

VariantFields
AllScripts
AllContexts
ScriptEntity(Handle<ScriptAsset>, Entity)
StaticScript(Handle<ScriptAsset>)

Functions

NameSummary
all_contextsTargets every loaded context once, i.e. scripts sharing a context only run the callback once.
all_scriptsTargets every loaded script, once per script even if scripts share a context.
entity_scriptTargets a single script attached to an entity.
newConstructs a new instance of the type from a table of its fields.
static_scriptTargets a single static script.

all_contexts

all_contexts() -> Recipients

Targets every loaded context once, i.e. scripts sharing a context only run the callback once.

Returns:

  • recipients: The recipients.

all_scripts

all_scripts() -> Recipients

Targets every loaded script, once per script even if scripts share a context.

Returns:

  • recipients: The recipients.

entity_script

entity_script(entity: Entity, script: Handle<ScriptAsset>) -> Recipients

Targets a single script attached to an entity.

Arguments

  • entity: The entity the script is attached to.
  • script: The script asset.

Returns: The recipients.

new

new(payload: Fields<Recipients>) -> Recipients

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

static_script

static_script(script: Handle<ScriptAsset>) -> Recipients

Targets a single static script.

Arguments

  • script: The script asset.

Returns: The recipients.

Variant Functions

AllContexts.new

new(variant: EnumVariantRef, payload: Fields<Recipients::AllContexts>) -> Recipients

AllScripts.new

new(variant: EnumVariantRef, payload: Fields<Recipients::AllScripts>) -> Recipients

ScriptEntity.new

new(variant: EnumVariantRef, payload: Fields<Recipients::ScriptEntity>) -> Recipients

StaticScript.new

new(variant: EnumVariantRef, payload: Fields<Recipients::StaticScript>) -> Recipients

ReflectableScheduleLabel

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ReflectSchedule

A reflectable schedule.

Fields

FieldType
type_pathstr
labelReflectableScheduleLabel

Methods

NameSummary
get_system_by_nameRetrieves the system with the given name in the schedule
render_dotRenders the schedule as a dot graph string.
systemsRetrieves all the systems in the schedule.

get_system_by_name

get_system_by_name(schedule: ReflectSchedule, name: String) -> Optional<ReflectSystem>

Retrieves the system with the given name in the schedule

Arguments

  • schedule: The schedule to retrieve the system from.
  • name: The identifier or full path of the system to retrieve.

Returns: The system with the given name, if it exists.

render_dot

render_dot(schedule: ReflectSchedule) -> String

Renders the schedule as a dot graph string.

Useful for debugging scheduling.

Arguments

  • schedule: The schedule to render.

Returns: The dot graph string.

systems

systems(schedule: ReflectSchedule) -> Vec<ReflectSystem>

Retrieves all the systems in the schedule.

Arguments

  • schedule: The schedule to retrieve the systems from.

Returns: The systems in the schedule.

ReflectSystem

A reflectable system.

Opaque: scripts can't access its fields, only its functions.

Methods

NameSummary
identifierRetrieves the identifier of the system
pathRetrieves the full path of the system

identifier

identifier(system: ReflectSystem) -> String

Retrieves the identifier of the system

Arguments

  • system: The system to retrieve the identifier from.

Returns: The identifier of the system, e.g. my_system

path

path(system: ReflectSystem) -> String

Retrieves the full path of the system

Arguments

  • system: The system to retrieve the path from.

Returns: The full path of the system, e.g. my_crate::systems::my_system<T>

ReflectSystemSet

A reflectable system set: a set node of a schedule graph, or a set scripts put and order their systems in.

Bevy does not expose the interned sets of a schedule graph, so set nodes of a graph only have a node id, while sets made from an interned set (i.e. the ones scripts use) only have the set.

Opaque: scripts can't access its fields, only its functions.

Methods

NameSummary
nameRetrieves the name of the system set

name

name(set: ReflectSystemSet) -> String

Retrieves the name of the system set

Arguments

  • set: The system set to retrieve the name from.

Returns: The debug name of the set, e.g. TransformSystems::Propagate or ScriptNamedSet("script.my_game.ai")

ScriptAsset

Asset

Represents a script loaded into memory as an asset

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
add_assetAdds a value of this type as a new asset, returning a strong handle to it.
get_assetThe asset a handle points to, or nil if it isn’t loaded or added yet.
loadStarts loading an asset of this type from a path, returning a handle to it right away.
newConstructs a new instance of the type from a table of its fields.

add_asset

add_asset(value: ScriptAsset) -> Handle<ScriptAsset>

Adds a value of this type as a new asset, returning a strong handle to it.

Arguments

  • value: The asset value.

Returns: A handle to the new asset.

get_asset

get_asset(handle: Handle<ScriptAsset>) -> Optional<ScriptAsset>

The asset a handle points to, or nil if it isn’t loaded or added yet.

Changes to the returned value change the asset.

Arguments

  • handle: The handle to the asset.

Returns: The asset, or nil.

load

load(path: String) -> Handle<ScriptAsset>

Starts loading an asset of this type from a path, returning a handle to it right away.

Arguments

  • path: The asset path, relative to the assets folder.

Returns: A handle to the asset, which is loaded in the background.

new

new(payload: Fields<ScriptAsset>) -> ScriptAsset

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ScriptAssetModifiedMessage

Emitted when a script asset is modified and all its attachments require re-loading

Fields

IndexType
0AssetId<ScriptAsset>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ScriptAttachment

Specifies a unique attachment of a script. These attachments are mapped to bevy_mod_scripting_core::ContextKey’s depending on the context policy used.

Variants

VariantFields
EntityScript(Entity, Handle<ScriptAsset>)
StaticScript(Handle<ScriptAsset>)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.
new_entity_scriptCreates a new script attachment descriptor for an entity attached script.
new_static_scriptCreates a new script attachment descriptor from a script asset.

new

new(payload: Fields<ScriptAttachment>) -> ScriptAttachment

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

new_entity_script

new_entity_script(entity: Entity, script: Handle<ScriptAsset>) -> ScriptAttachment

Creates a new script attachment descriptor for an entity attached script.

Arguments

  • entity: The entity to attach the script to.
  • script: The script asset to attach to the entity.

Returns: The new script attachment for the entity.

new_static_script

new_static_script(script: Handle<ScriptAsset>) -> ScriptAttachment

Creates a new script attachment descriptor from a script asset.

Arguments

  • script: The script asset to create the attachment from.

Returns: The new script attachment.

Variant Functions

EntityScript.new

new(variant: EnumVariantRef, payload: Fields<ScriptAttachment::EntityScript>) -> ScriptAttachment

StaticScript.new

new(variant: EnumVariantRef, payload: Fields<ScriptAttachment::StaticScript>) -> ScriptAttachment

ScriptBundleRegistration

A reference to a bundle type’s reflection registration, i.e. a type with ReflectBundle type data.

In general think of this as a handle to a type.

Opaque: scripts can't access its fields, only its functions.

Methods

NameSummary
namespaceRetrieves the script namespace of the type, by default the name of the crate defining it.
short_nameRetrieves the short name of the type. The short name is a more human-readable version of the type name.
type_nameRetrieves the name of the type.

namespace

namespace(registration: ScriptBundleRegistration) -> String

Retrieves the script namespace of the type, by default the name of the crate defining it. Types in the root namespace have the empty string as namespace.

Arguments

  • registration: The type registration.

Returns: The namespace of the type.

short_name

short_name(registration: ScriptBundleRegistration) -> str

Retrieves the short name of the type. The short name is a more human-readable version of the type name.

Arguments

  • registration: The type registration.

Returns: The short name of the

type_name

type_name(registration: ScriptBundleRegistration) -> str

Retrieves the name of the type.

Arguments

  • registration: The type registration.

Returns: The name of the type.

ScriptCallbackMessage

A callback message meant to trigger a callback in a subset/set of scripts in the world with the given arguments

Fields

FieldType
labelCallbackLabel
recipientsRecipients
languageOptional<Language>
argsVec<ScriptValue>
trigger_responsebool
iterationusize

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ScriptCallbackMessage>) -> ScriptCallbackMessage

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ScriptComponent

Component

A component which identifies the scripts existing on an entity.

Event handlers search for components with this component to figure out which scripts to run and on which entities.

Fields

IndexType
0Vec<Handle<ScriptAsset>>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ScriptComponent>) -> ScriptComponent

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ScriptComponentRegistration

A reference to a component type’s reflection registration.

In general think of this as a handle to a type.

Not to be confused with script registered dynamic components, although this can point to a script registered component.

Opaque with private fields: world accessors trust that component_id belongs to registration’s type.

Opaque: scripts can't access its fields, only its functions.

Methods

NameSummary
namespaceRetrieves the script namespace of the type, by default the name of the crate defining it.
short_nameRetrieves the short name of the type. The short name is a more human-readable version of the type name.
type_nameRetrieves the name of the type.

namespace

namespace(registration: ScriptComponentRegistration) -> String

Retrieves the script namespace of the type, by default the name of the crate defining it. Types in the root namespace have the empty string as namespace.

Arguments

  • registration: The type registration.

Returns: The namespace of the type.

short_name

short_name(registration: ScriptComponentRegistration) -> str

Retrieves the short name of the type. The short name is a more human-readable version of the type name.

Arguments

  • registration: The type registration.

Returns: The short name of the

type_name

type_name(registration: ScriptComponentRegistration) -> str

Retrieves the name of the type.

Arguments

  • registration: The type registration.

Returns: The name of the type.

ScriptEventRegistration

A handle to a script registered event type.

Opaque: scripts can't access its fields, only its functions.

Methods

NameSummary
namespaceRetrieves the script namespace the event was registered in, i.e. script.game for script.game.Hit.
short_nameRetrieves the name of the event within its namespace, i.e. Hit for script.game.Hit.

namespace

namespace(registration: ScriptEventRegistration) -> String

Retrieves the script namespace the event was registered in, i.e. script.game for script.game.Hit.

Arguments

  • registration: The event registration.

Returns: The namespace of the event.

short_name

short_name(registration: ScriptEventRegistration) -> String

Retrieves the name of the event within its namespace, i.e. Hit for script.game.Hit.

Arguments

  • registration: The event registration.

Returns: The name of the event.

ScriptLifecycleMessage

Emitted when a script is attached or detached.

Both are one message type, so the pipeline processes them in the order they were written.

Variants

VariantFields
Attached(ScriptAttachment)
Detached(ScriptAttachment)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Attached.new

new(variant: EnumVariantRef, payload: Fields<ScriptLifecycleMessage::Attached>) -> ScriptLifecycleMessage

Detached.new

new(variant: EnumVariantRef, payload: Fields<ScriptLifecycleMessage::Detached>) -> ScriptLifecycleMessage

ScriptQueryBuilder

The query builder is used to build ECS queries which retrieve spefific components filtered by specific conditions.

For example:

builder.component(componentA)
    .component(componentB)
    .with(componentC)
    .without(componentD)  

Will retrieve entities which:

  • Have componentA
  • Have componentB
  • Have componentC
  • Do not have componentD

As well as references to components:

  • componentA
  • componentB

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ScriptQueryBuilder>) -> ScriptQueryBuilder

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
addedOnly matches entities whose component was added since the system last ran (outside of systems: since the last update).
buildBuilds the query and retrieves the entities and component references.
changedOnly matches entities whose component was changed since the system last ran (outside of systems: since the last…
componentAdds a component to be retrieved by the query
component_readAdds a component to be retrieved by the query, which can only be read.
optionalAdds a component to be retrieved by the query, which entities don’t need to have, it is nil for those which don’t.
optional_readLike optional, but the component can only be read.
withAdds a component to filter the query by. This component will NOT be retrieved.
withoutAdds a component to filter the query by. This component will NOT be retrieved.

added

Only matches entities whose component was added since the system last ran (outside of systems: since the last update). This component will NOT be retrieved.

Arguments

  • query: The query to add the filter to
  • component: The component to filter by

Returns: The query with the filter added

build

build(query: ScriptQueryBuilder) -> Vec<(Entity, …Optional<ReflectReference>)>

Builds the query and retrieves the entities and component references.

Each result is a list of the entity followed by the components in the order they were added to the query, i.e. local entity, a, b = result[1], result[2], result[3] in Lua, absent optional components are nil.

Arguments

  • query: The query to build.

Returns: The entities and component references that match the query.

changed

Only matches entities whose component was changed since the system last ran (outside of systems: since the last update). This component will NOT be retrieved.

Arguments

  • query: The query to add the filter to
  • component: The component to filter by

Returns: The query with the filter added

component

Adds a component to be retrieved by the query

Arguments

  • query: The query to add the component to

Returns: The query with the component added

component_read

component_read(query: ScriptQueryBuilder, component: ScriptComponentRegistration) -> ScriptQueryBuilder

Adds a component to be retrieved by the query, which can only be read.

Script systems reading a component can run in parallel with each other, unlike ones writing it.

Arguments

  • query: The query to add the component to
  • component: The component to add

Returns: The query with the component added

optional

Adds a component to be retrieved by the query, which entities don’t need to have, it is nil for those which don’t.

Arguments

  • query: The query to add the component to
  • component: The component to add

Returns: The query with the component added

optional_read

Like optional, but the component can only be read.

Arguments

  • query: The query to add the component to
  • component: The component to add

Returns: The query with the component added

with

Adds a component to filter the query by. This component will NOT be retrieved.

Arguments

  • query: The query to add the component to

Returns: The query with the component added

without

Adds a component to filter the query by. This component will NOT be retrieved.

Arguments

  • query: The query to add the component to

Returns: The query with the component added

ScriptQueryResult

A result from a query.

Scripts receive it as a plain list, the entity followed by the components in the order they were added to the query, i.e. {entity, a, b} in Lua, with nil for absent optional components. Nothing is allocated for the result itself.

Opaque: scripts can't access its fields, only its functions.

ScriptResourceRegistration

A reference to a resource type’s reflection registration.

In general think of this as a handle to a type.

Opaque with private fields: world accessors trust that resource_id belongs to registration’s type.

Opaque: scripts can't access its fields, only its functions.

Methods

NameSummary
namespaceRetrieves the script namespace of the type, by default the name of the crate defining it.
short_nameRetrieves the short name of the type. The short name is a more human-readable version of the type name.
type_nameRetrieves the name of the type.

namespace

namespace(registration: ScriptResourceRegistration) -> String

Retrieves the script namespace of the type, by default the name of the crate defining it. Types in the root namespace have the empty string as namespace.

Arguments

  • registration: The type registration.

Returns: The namespace of the type.

short_name

short_name(registration: ScriptResourceRegistration) -> str

Retrieves the short name of the type. The short name is a more human-readable version of the type name.

Arguments

  • registration: The type registration.

Returns: The short name of the

type_name

type_name(registration: ScriptResourceRegistration) -> str

Retrieves the name of the type.

Arguments

  • registration: The type registration.

Returns: The name of the type.

ScriptRunCondition

A run condition of a script system, evaluated in Rust without calling into the script, see ScriptSystemBuilder::run_if.

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
any_with_componentHolds if any entity has the component.
newConstructs a new instance of the type from a table of its fields.
on_timerHolds once every given amount of seconds, measured with Time.
resource_addedHolds if the resource was added since the system last ran.
resource_changedHolds if the resource changed since the system last ran, doesn’t hold if it doesn’t exist.
resource_existsHolds if the resource exists.
run_onceHolds the first time it is evaluated only.

any_with_component

any_with_component(component: ScriptComponentRegistration) -> ScriptRunCondition

Holds if any entity has the component.

Arguments

  • component: The component.

Returns: The condition.

new

new(payload: Fields<ScriptRunCondition>) -> ScriptRunCondition

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

on_timer

on_timer(seconds: f64) -> ScriptRunCondition

Holds once every given amount of seconds, measured with Time.

Arguments

  • seconds: The interval in seconds.

Returns: The condition.

resource_added

resource_added(resource: ScriptResourceRegistration) -> ScriptRunCondition

Holds if the resource was added since the system last ran.

Arguments

  • resource: The resource.

Returns: The condition.

resource_changed

resource_changed(resource: ScriptResourceRegistration) -> ScriptRunCondition

Holds if the resource changed since the system last ran, doesn’t hold if it doesn’t exist.

Arguments

  • resource: The resource.

Returns: The condition.

resource_exists

resource_exists(resource: ScriptResourceRegistration) -> ScriptRunCondition

Holds if the resource exists.

Arguments

  • resource: The resource.

Returns: The condition.

run_once

run_once() -> ScriptRunCondition

Holds the first time it is evaluated only.

Returns:

  • condition: The condition.

Methods

NameSummary
and_Holds if both conditions hold, the second one is only evaluated if the first one holds.
not_Holds if the condition doesn’t hold. Named not_ as not is a keyword in Lua.
or_Holds if either condition holds, the second one is only evaluated if the first one doesn’t hold.

and_

Holds if both conditions hold, the second one is only evaluated if the first one holds.

Arguments

  • a: The first condition.
  • b: The second condition.

Returns: The combined condition.

not_

Holds if the condition doesn’t hold. Named not_ as not is a keyword in Lua.

Arguments

  • condition: The condition.

Returns: The negated condition.

or_

Holds if either condition holds, the second one is only evaluated if the first one doesn’t hold.

Arguments

  • a: The first condition.
  • b: The second condition.

Returns: The combined condition.

ScriptSystemBuilder

A builder for systems living in scripts

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ScriptSystemBuilder>) -> ScriptSystemBuilder

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
afterSpecifies the system is to run after the given system
after_script_systemSpecifies the system is to run after the script system with the given callback label of the given script.
after_setSpecifies the system is to run after the given set.
beforeSpecifies the system is to run before the given system.
before_script_systemSpecifies the system is to run before the script system with the given callback label of the given script.
before_setSpecifies the system is to run before the given set.
exclusiveSpecifies the system is to run exclusively, meaning it can access anything, but will not run in parallel with other…
in_setPuts the system in the given set, ordering the set orders the system.
queryAdds a query to the system builder.
resourceRequests the system have access to the given resource.
resource_readRequests the system have read only access to the given resource.
run_ifOnly runs the system if the condition holds, see bms.conditions. All conditions must hold for the system to run.

after

Specifies the system is to run after the given system

Note: this is an experimental feature, and the ordering might not work correctly for script initialized systems

Arguments

  • builder: The system builder to add the dependency to.
  • system: The system to run after.

Returns: The system builder with the dependency added.

after_script_system

after_script_system(builder: ScriptSystemBuilder, label: String, attachment: ScriptAttachment) -> ScriptSystemBuilder

Specifies the system is to run after the script system with the given callback label of the given script. That system must have been added before this one.

Arguments

  • builder: The system builder to add the dependency to.
  • label: The callback label of the other script system.
  • attachment: The script the other script system belongs to.

Returns: The system builder with the dependency added.

after_set

Specifies the system is to run after the given set. Sets are registered by scripts with register_new_system_set, game sets are found with get_system_set_by_name.

Arguments

  • builder: The system builder to add the dependency to.
  • set: The system set.

Returns: The system builder with the dependency added.

before

Specifies the system is to run before the given system.

Note: this is an experimental feature, and the ordering might not work correctly for script initialized systems

Arguments

  • builder: The system builder to add the dependency to.
  • system: The system to run before.

Returns: The system builder with the dependency added.

before_script_system

before_script_system(builder: ScriptSystemBuilder, label: String, attachment: ScriptAttachment) -> ScriptSystemBuilder

Specifies the system is to run before the script system with the given callback label of the given script. That system must have been added before this one.

Arguments

  • builder: The system builder to add the dependency to.
  • label: The callback label of the other script system.
  • attachment: The script the other script system belongs to.

Returns: The system builder with the dependency added.

before_set

Specifies the system is to run before the given set. Sets are registered by scripts with register_new_system_set, game sets are found with get_system_set_by_name.

Arguments

  • builder: The system builder to add the dependency to.
  • set: The system set.

Returns: The system builder with the dependency added.

exclusive

exclusive(builder: ScriptSystemBuilder) -> ScriptSystemBuilder

Specifies the system is to run exclusively, meaning it can access anything, but will not run in parallel with other systems.

Arguments

  • builder: The system builder to make exclusive.

Returns: The system builder that is now exclusive.

in_set

Puts the system in the given set, ordering the set orders the system. Sets are registered by scripts with register_new_system_set, game sets are found with get_system_set_by_name.

Arguments

  • builder: The system builder to put in the set.
  • set: The system set.

Returns: The system builder in the set.

query

Adds a query to the system builder.

Arguments

  • builder: The system builder to add the query to.
  • query: The query to add.

Returns: The system builder with the query added.

resource

Requests the system have access to the given resource. The resource will be added to the list of arguments of the callback in the order they’re provided.

Arguments

  • builder: The system builder to add the resource to.
  • resource: The resource to add.

Returns: The system builder with the resource added.

resource_read

Requests the system have read only access to the given resource. The resource will be added to the list of arguments of the callback in the order they’re provided.

Script systems reading a resource can run in parallel with each other, unlike ones writing it.

Arguments

  • builder: The system builder to add the resource to.
  • resource: The resource to add.

Returns: The system builder with the resource added.

run_if

Only runs the system if the condition holds, see bms.conditions. All conditions must hold for the system to run.

Conditions are evaluated without calling into the script.

Arguments

  • builder: The system builder to add the condition to.
  • condition: The condition.

Returns: The system builder with the condition added.

ScriptTypeRegistration

A reference to a type which is not a Resource or Component.

In general think of this as a handle to a type.

Opaque: scripts can't access its fields, only its functions.

Methods

NameSummary
namespaceRetrieves the script namespace of the type, by default the name of the crate defining it.
short_nameRetrieves the short name of the type. The short name is a more human-readable version of the type name.
type_nameRetrieves the name of the type.

namespace

namespace(registration: ScriptTypeRegistration) -> String

Retrieves the script namespace of the type, by default the name of the crate defining it. Types in the root namespace have the empty string as namespace.

Arguments

  • registration: The type registration.

Returns: The namespace of the type.

short_name

short_name(registration: ScriptTypeRegistration) -> String

Retrieves the short name of the type. The short name is a more human-readable version of the type name.

Arguments

  • registration: The type registration.

Returns: The short name of the

type_name

type_name(registration: ScriptTypeRegistration) -> String

Retrieves the name of the type.

Arguments

  • registration: The type registration.

Returns: The name of the type.

VariadicTuple

A tuple variant of script value

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<VariadicTuple>) -> VariadicTuple

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

camera

The types and functions in the camera namespace, as returned by import_namespace("camera").

Types

TypeSummary
CameraThe defining Component for camera entities, storing information about how and what to render through this camera.
CameraOutputModeControl how this Camera outputs once rendering is completed.
ClearColorConfigFor a camera, specifies the color used to clear the viewport before rendering or when writing to the final render…
ComputedCameraValuesHolds internally computed Camera values.
ImageRenderTargetA render target that renders to an Image.
InheritedVisibilityWhether or not an entity is visible in the hierarchy.
ManualTextureViewHandleA unique id that corresponds to a specific ManualTextureView in the ManualTextureViews collection.
MsaaWritebackControls when MSAA writeback occurs for a camera.
OrthographicProjectionProject a 3D space onto a 2D surface using parallel lines, i.e., unlike PerspectiveProjection, the size of objects…
RenderLayersDefines which rendering layers an entity belongs to.
RenderTargetThe “target” that a Camera will render to. For example, this could be a Window swapchain or an Image.
RenderTargetInfoInformation about the current RenderTarget.
ScalingModeScaling mode for OrthographicProjection.
SubCameraViewSettings to define a camera sub view.
ViewportRender viewport configuration for the Camera component.
ViewVisibilityAlgorithmically computed indication of whether an entity is visible and should be extracted for rendering.
VisibilityUser indication of whether an entity is visible. Propagates down the entity hierarchy.

Values

NameType
CameraUpdateSystemsReflectSystemSet

Camera

Component

The defining Component for camera entities, storing information about how and what to render through this camera.

The Camera component is added to an entity to define the properties of the viewpoint from which rendering occurs. It defines the position of the view to render, the projection method to transform the 3D objects into a 2D image, as well as the render target into which that image is produced.

Note that a Camera needs a CameraRenderGraph to render anything. This is typically provided by adding a Camera2d or Camera3d component, but custom render graphs can also be defined. Inserting a Camera with no render graph will emit an error at runtime.

Fields

FieldType
viewportOptional<Viewport>
orderisize
is_activebool
computedComputedCameraValues
output_modeCameraOutputMode
msaa_writebackMsaaWriteback
clear_colorClearColorConfig
invert_cullingbool
sub_camera_viewOptional<SubCameraView>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Camera>) -> Camera

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
logical_viewport_rectThe rectangle of the viewport in logical pixels, or nil if the camera has no target yet.
logical_viewport_sizeThe size of the viewport in logical pixels, or nil if the camera has no target yet.
physical_viewport_sizeThe size of the viewport in physical pixels, or nil if the camera has no target yet.
viewport_to_worldA ray from the camera through a point on its viewport, or nil if the point cannot be converted.
viewport_to_world_2dThe point in the 2D world seen through a point on the viewport, or nil if the point cannot be converted.
world_to_viewportThe position on the viewport of a point in the world, or nil if the point cannot be converted.

logical_viewport_rect

logical_viewport_rect(self: Camera) -> Optional<Rect>

The rectangle of the viewport in logical pixels, or nil if the camera has no target yet.

logical_viewport_size

logical_viewport_size(self: Camera) -> Optional<Vec2>

The size of the viewport in logical pixels, or nil if the camera has no target yet.

physical_viewport_size

physical_viewport_size(self: Camera) -> Optional<UVec2>

The size of the viewport in physical pixels, or nil if the camera has no target yet.

viewport_to_world

viewport_to_world(self: Camera, camera_transform: GlobalTransform, viewport_position: Vec2) -> Optional<Ray3d>

A ray from the camera through a point on its viewport, or nil if the point cannot be converted.

viewport_to_world_2d

viewport_to_world_2d(self: Camera, camera_transform: GlobalTransform, viewport_position: Vec2) -> Optional<Vec2>

The point in the 2D world seen through a point on the viewport, or nil if the point cannot be converted.

world_to_viewport

world_to_viewport(self: Camera, camera_transform: GlobalTransform, world_position: Vec3) -> Optional<Vec2>

The position on the viewport of a point in the world, or nil if the point cannot be converted.

CameraOutputMode

Control how this Camera outputs once rendering is completed.

Variants

VariantFields
Write{ blend_state: Optional<BlendState>, clear_color: ClearColorConfig }
Skip

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<CameraOutputMode>) -> CameraOutputMode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

NameSummary
Skip.new
Write.new

Skip.new

new(variant: EnumVariantRef, payload: Fields<CameraOutputMode::Skip>) -> CameraOutputMode

Write.new

new(variant: EnumVariantRef, payload: Fields<CameraOutputMode::Write>) -> CameraOutputMode

ClearColorConfig

For a camera, specifies the color used to clear the viewport before rendering or when writing to the final render target texture.

Variants

VariantFields
Default
Custom(Color)
None

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ClearColorConfig>) -> ClearColorConfig

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Custom.new

new(variant: EnumVariantRef, payload: Fields<ClearColorConfig::Custom>) -> ClearColorConfig

Default.new

new(variant: EnumVariantRef, payload: Fields<ClearColorConfig::Default>) -> ClearColorConfig

None.new

new(variant: EnumVariantRef, payload: Fields<ClearColorConfig::None>) -> ClearColorConfig

ComputedCameraValues

Holds internally computed Camera values.

Fields

FieldType
clip_from_viewMat4
target_infoOptional<RenderTargetInfo>
old_viewport_sizeOptional<UVec2>
old_sub_camera_viewOptional<SubCameraView>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ComputedCameraValues>) -> ComputedCameraValues

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ImageRenderTarget

A render target that renders to an Image.

Fields

FieldType
handleHandle<Image>
scale_factorf32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ImageRenderTarget>) -> ImageRenderTarget

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

InheritedVisibility

Component

Whether or not an entity is visible in the hierarchy.

This is a computed component that users should not change manually. To set the visibility of an entity, use Visibility instead. For more information, see module level documentation.

This property is updated in VisibilityPropagate in the PostUpdate schedule. Until then, it is not up to date with Visibility if it was changed in the same frame.

If this is false, then ViewVisibility should also be false.

Fields

IndexType
0bool

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<InheritedVisibility>) -> InheritedVisibility

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
getWhether the entity is visible, taking its parents into account.

get

get(self: InheritedVisibility) -> bool

Whether the entity is visible, taking its parents into account.

ManualTextureViewHandle

Component

A unique id that corresponds to a specific ManualTextureView in the ManualTextureViews collection.

See ManualTextureViews in bevy_camera for more details.

Fields

IndexType
0u32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

MsaaWriteback

Controls when MSAA writeback occurs for a camera.

MSAA writeback copies the previous camera’s output into the MSAA sampled texture before rendering, allowing multiple cameras to layer their results when MSAA is enabled.

Variants

Variant
Off
Auto
Always

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<MsaaWriteback>) -> MsaaWriteback

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Always.new

new(variant: EnumVariantRef, payload: Fields<MsaaWriteback::Always>) -> MsaaWriteback

Auto.new

new(variant: EnumVariantRef, payload: Fields<MsaaWriteback::Auto>) -> MsaaWriteback

Off.new

new(variant: EnumVariantRef, payload: Fields<MsaaWriteback::Off>) -> MsaaWriteback

OrthographicProjection

Project a 3D space onto a 2D surface using parallel lines, i.e., unlike PerspectiveProjection, the size of objects remains the same regardless of their distance to the camera.

The volume contained in the projection is called the view frustum. Since the viewport is rectangular and projection lines are parallel, the view frustum takes the shape of a cuboid.

Note that the scale of the projection and the apparent size of objects are inversely proportional. As the size of the projection increases, the size of objects decreases.

Examples

Configure the orthographic projection to one world unit per 100 window pixels:

let projection = Projection::Orthographic(OrthographicProjection {
    scaling_mode: ScalingMode::WindowSize,
    scale: 0.01,
    ..OrthographicProjection::default_2d()
});

Fields

FieldType
nearf32
farf32
viewport_originVec2
scaling_modeScalingMode
scalef32
areaRect

Functions

NameSummary
default_2dThe default projection for 2D cameras.
default_3dThe default projection for 3D cameras.
newConstructs a new instance of the type from a table of its fields.

default_2d

default_2d() -> OrthographicProjection

The default projection for 2D cameras.

default_3d

default_3d() -> OrthographicProjection

The default projection for 3D cameras.

new

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

RenderLayers

Component

Defines which rendering layers an entity belongs to.

A camera renders an entity only when their render layers intersect.

The Default instance of RenderLayers contains layer 0, the first layer. Entities without this component also belong to layer 0.

An empty RenderLayers makes the entity invisible.

Fields

IndexType
0Vec<u64>

Functions

NameSummary
layerRender layers containing only the given layer.
newConstructs a new instance of the type from a table of its fields.
noneRender layers containing no layers, so nothing is rendered with them.

layer

layer(n: usize) -> RenderLayers

Render layers containing only the given layer.

new

new(payload: Fields<RenderLayers>) -> RenderLayers

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

none

none() -> RenderLayers

Render layers containing no layers, so nothing is rendered with them.

Methods

NameSummary
intersectsWhether these render layers share at least one layer with another set.
withA copy of these render layers that also contains the given layer.
withoutA copy of these render layers without the given layer.

intersects

intersects(self: RenderLayers, other: RenderLayers) -> bool

Whether these render layers share at least one layer with another set.

with

with(self: RenderLayers, n: usize) -> RenderLayers

A copy of these render layers that also contains the given layer.

without

without(self: RenderLayers, n: usize) -> RenderLayers

A copy of these render layers without the given layer.

Operators

NameSummary
iterThe numbers of all layers in these render layers.

iter

iter(self: RenderLayers) -> Vec<usize>

The numbers of all layers in these render layers.

RenderTarget

Component

The “target” that a Camera will render to. For example, this could be a Window swapchain or an Image.

Variants

VariantFields
Window(WindowRef)
Image(ImageRenderTarget)
TextureView(ManualTextureViewHandle)
None{ size: UVec2 }

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<RenderTarget>) -> RenderTarget

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Image.new

new(variant: EnumVariantRef, payload: Fields<RenderTarget::Image>) -> RenderTarget

None.new

new(variant: EnumVariantRef, payload: Fields<RenderTarget::None>) -> RenderTarget

TextureView.new

new(variant: EnumVariantRef, payload: Fields<RenderTarget::TextureView>) -> RenderTarget

Window.new

new(variant: EnumVariantRef, payload: Fields<RenderTarget::Window>) -> RenderTarget

RenderTargetInfo

Information about the current RenderTarget.

Fields

FieldType
physical_sizeUVec2
scale_factorf32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<RenderTargetInfo>) -> RenderTargetInfo

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ScalingMode

Scaling mode for OrthographicProjection.

The effect of these scaling modes are combined with the OrthographicProjection::scale property.

For example, if the scaling mode is ScalingMode::Fixed { width: 100.0, height: 300 } and the scale is 2.0, the projection will be 200 world units wide and 600 world units tall.

Examples

Configure the orthographic projection to two world units per window height:

let projection = Projection::Orthographic(OrthographicProjection {
   scaling_mode: ScalingMode::FixedVertical { viewport_height: 2.0 },
   ..OrthographicProjection::default_2d()
});

Variants

VariantFields
WindowSize
Fixed{ width: f32, height: f32 }
AutoMin{ min_width: f32, min_height: f32 }
AutoMax{ max_width: f32, max_height: f32 }
FixedVertical{ viewport_height: f32 }
FixedHorizontal{ viewport_width: f32 }

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ScalingMode>) -> ScalingMode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

AutoMax.new

new(variant: EnumVariantRef, payload: Fields<ScalingMode::AutoMax>) -> ScalingMode

AutoMin.new

new(variant: EnumVariantRef, payload: Fields<ScalingMode::AutoMin>) -> ScalingMode

Fixed.new

new(variant: EnumVariantRef, payload: Fields<ScalingMode::Fixed>) -> ScalingMode

FixedHorizontal.new

new(variant: EnumVariantRef, payload: Fields<ScalingMode::FixedHorizontal>) -> ScalingMode

FixedVertical.new

new(variant: EnumVariantRef, payload: Fields<ScalingMode::FixedVertical>) -> ScalingMode

WindowSize.new

new(variant: EnumVariantRef, payload: Fields<ScalingMode::WindowSize>) -> ScalingMode

SubCameraView

Settings to define a camera sub view.

When Camera::sub_camera_view is Some, only the sub-section of the image defined by size and offset (relative to the full_size of the whole image) is projected to the cameras viewport.

Take the example of the following multi-monitor setup:

┌───┬───┐
│ A │ B │
├───┼───┤
│ C │ D │
└───┴───┘

If each monitor is 1920x1080, the whole image will have a resolution of 3840x2160. For each monitor we can use a single camera with a viewport of the same size as the monitor it corresponds to. To ensure that the image is cohesive, we can use a different sub view on each camera:

  • Camera A: full_size = 3840x2160, size = 1920x1080, offset = 0,0
  • Camera B: full_size = 3840x2160, size = 1920x1080, offset = 1920,0
  • Camera C: full_size = 3840x2160, size = 1920x1080, offset = 0,1080
  • Camera D: full_size = 3840x2160, size = 1920x1080, offset = 1920,1080

However since only the ratio between the values is important, they could all be divided by 120 and still produce the same image. Camera D would for example have the following values: full_size = 32x18, size = 16x9, offset = 16,9

Fields

FieldType
full_sizeUVec2
offsetVec2
sizeUVec2

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<SubCameraView>) -> SubCameraView

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Viewport

Render viewport configuration for the Camera component.

The viewport defines the area on the render target to which the camera renders its image. You can overlay multiple cameras in a single window using viewports to create effects like split screen, minimaps, and character viewers.

Note that the physical position is in actual screen coordinates and not virtual pixels for window targets.
You should use the scaling factor reported by the window, which on some OS’s defaults to a value other than 1. Please see the example code (which assumes a single camera and window)

# use bevy_camera::{Camera, Projection, Viewport};
# use bevy_transform::prelude::Transform;
# use bevy_ecs::prelude::*;
# use bevy_math::UVec2;
# use bevy_window::Window;
# use bevy_utils::default;

fn update_viewport(
   mut camera_query: Query<(&mut Camera, &mut Transform, &mut Projection)>,
   windows: Query<&Window>
) {
    let Ok((mut camera, _, _)) = camera_query.single_mut() else { return; };

    let window = windows.single().expect("Window not found");
    let scale = window.resolution.scale_factor();

    camera.viewport = Some(Viewport {
        physical_position: (UVec2::new(10, 10).as_vec2() * scale).as_uvec2(),
        physical_size: (UVec2::new(100, 100).as_vec2() * scale).as_uvec2(),
        ..default()
    });
}

Fields

FieldType
physical_positionUVec2
physical_sizeUVec2
depthRange<f32>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Viewport>) -> Viewport

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ViewVisibility

Component

Algorithmically computed indication of whether an entity is visible and should be extracted for rendering.

Not to be confused with Visibility and InheritedVisibility. For more information, see module level documentation.

If you wish to add a custom visibility system that sets this value, be sure to add it to the CheckVisibility set.

Fields

IndexType
0u8

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ViewVisibility>) -> ViewVisibility

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
getWhether the entity is visible to a camera this frame.

get

get(self: ViewVisibility) -> bool

Whether the entity is visible to a camera this frame.

Visibility

Component

User indication of whether an entity is visible. Propagates down the entity hierarchy.

If an entity is hidden in this way, all Children (and all of their children and so on) who are set to Inherited will also be hidden.

Users should set this component if they wish to change the visibility of an entity.

To read the visibility of an entity, query for its InheritedVisibility instead. For more information, see module level documentation.

Variants

Variant
Inherited
Hidden
Visible

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Visibility>) -> Visibility

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
toggle_inherited_visibleSwitches between inherited and visible. A hidden entity stays hidden.
toggle_visible_hiddenSwitches between visible and hidden. An inherited entity stays inherited.

toggle_inherited_visible

toggle_inherited_visible(self: Visibility)

Switches between inherited and visible. A hidden entity stays hidden.

toggle_visible_hidden

toggle_visible_hidden(self: Visibility)

Switches between visible and hidden. An inherited entity stays inherited.

Variant Functions

Hidden.new

new(variant: EnumVariantRef, payload: Fields<Visibility::Hidden>) -> Visibility

Inherited.new

new(variant: EnumVariantRef, payload: Fields<Visibility::Inherited>) -> Visibility

Visible.new

new(variant: EnumVariantRef, payload: Fields<Visibility::Visible>) -> Visibility

camera.VisibilitySystems

The types and functions in the camera.VisibilitySystems namespace, as returned by import_namespace("camera.VisibilitySystems").

Values

NameType
CalculateBoundsReflectSystemSet
CheckVisibilityReflectSystemSet
MarkNewlyHiddenEntitiesInvisibleReflectSystemSet
UpdateFrustaReflectSystemSet
VisibilityPropagateReflectSystemSet

color

The types and functions in the color namespace, as returned by import_namespace("color").

Types

TypeSummary
ColorAn enumerated type that can represent any of the color types in this crate.
HslaColor in Hue-Saturation-Lightness (HSL) color space with alpha.
HsvaColor in Hue-Saturation-Value (HSV) color space with alpha.
HwbaColor in Hue-Whiteness-Blackness (HWB) color space with alpha.
LabaColor in LAB color space, with alpha
LchaColor in LCH color space, with alpha
LinearRgbaLinear RGB color with alpha.
OkhslaColor in Okhsl color space with alpha.
OkhsvaColor in Okhsv color space with alpha.
OkhwbaColor in Okhwb color space with alpha.
OklabaColor in Oklab color space, with alpha
OklchaColor in Oklch color space, with alpha
SrgbaNon-linear standard RGB with alpha.
XyzaCIE 1931 color space, also known as XYZ, with an alpha channel.

Color

An enumerated type that can represent any of the color types in this crate.

This is useful when you need to store a color in a data structure that can’t be generic over the color type.

Operations

Color supports all the standard color operations, such as mixing, luminance and hue adjustment, and diffing. These operations delegate to the concrete color space contained by Color, but will convert to Oklch for operations which aren’t supported in the current space. After performing the operation, if a conversion was required, the result will be converted back into the original color space.

let red_hsv = Color::hsv(0., 1., 1.);
let red_srgb = Color::srgb(1., 0., 0.);

// HSV has a definition of hue, so it will be returned.
red_hsv.hue();

// SRGB doesn't have a native definition for hue.
// Converts to Oklch and returns that result.
red_srgb.hue();

Oklch has been chosen as the intermediary space in cases where conversion is required due to its perceptual uniformity and broad support for Bevy’s color operations. To avoid the cost of repeated conversion, and ensure consistent results where that is desired, first convert this Color into your desired color space.

Variants

VariantFields
Srgba(Srgba)
LinearRgba(LinearRgba)
Hsla(Hsla)
Hsva(Hsva)
Hwba(Hwba)
Laba(Laba)
Lcha(Lcha)
Oklaba(Oklaba)
Oklcha(Oklcha)
Xyza(Xyza)
Okhsla(Okhsla)
Okhsva(Okhsva)
Okhwba(Okhwba)

Functions

NameSummary
blackOpaque black.
hexA color from a hex string such as "#ff8800" or "#ff880080", or an error if the string is not valid hex.
hslA color from hue (in degrees), saturation and lightness, fully opaque.
hslaA color from hue (in degrees), saturation, lightness and alpha.
hsvA color from hue (in degrees), saturation and value, fully opaque.
hsvaA color from hue (in degrees), saturation, value and alpha.
linear_rgbA color from red, green and blue in the linear RGB space, each from 0 to 1, fully opaque.
linear_rgbaA color from red, green, blue and alpha in the linear RGB space, each from 0 to 1.
namedA named CSS color such as "rebecca_purple" (case-insensitive), or nil if there is no color with that name.
newConstructs a new instance of the type from a table of its fields.
noneA fully transparent color.
srgbA color from red, green and blue in the sRGB space, each from 0 to 1, fully opaque.
srgb_u8A color from red, green and blue in the sRGB space, each from 0 to 255, fully opaque.
srgbaA color from red, green, blue and alpha in the sRGB space, each from 0 to 1.
srgba_u8A color from red, green, blue and alpha in the sRGB space, each from 0 to 255.
whiteOpaque white.

black

black() -> Color

Opaque black.

hex

hex(hex: String) -> Color

A color from a hex string such as "#ff8800" or "#ff880080", or an error if the string is not valid hex.

hsl

hsl(hue: f32, saturation: f32, lightness: f32) -> Color

A color from hue (in degrees), saturation and lightness, fully opaque.

hsla

hsla(hue: f32, saturation: f32, lightness: f32, alpha: f32) -> Color

A color from hue (in degrees), saturation, lightness and alpha.

hsv

hsv(hue: f32, saturation: f32, value: f32) -> Color

A color from hue (in degrees), saturation and value, fully opaque.

hsva

hsva(hue: f32, saturation: f32, value: f32, alpha: f32) -> Color

A color from hue (in degrees), saturation, value and alpha.

linear_rgb

linear_rgb(red: f32, green: f32, blue: f32) -> Color

A color from red, green and blue in the linear RGB space, each from 0 to 1, fully opaque.

linear_rgba

linear_rgba(red: f32, green: f32, blue: f32, alpha: f32) -> Color

A color from red, green, blue and alpha in the linear RGB space, each from 0 to 1.

named

named(name: String) -> Optional<Color>

A named CSS color such as "rebecca_purple" (case-insensitive), or nil if there is no color with that name.

new

new(payload: Fields<Color>) -> Color

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

none

none() -> Color

A fully transparent color.

srgb

srgb(red: f32, green: f32, blue: f32) -> Color

A color from red, green and blue in the sRGB space, each from 0 to 1, fully opaque.

local Color = import_namespace("color").Color
local red = Color.srgb(1.0, 0.0, 0.0)
assert(red:to_srgba().red == 1.0)
let Color = import_namespace("color").Color;
let red = Color.srgb(1.0, 0.0, 0.0);
assert!(red.to_srgba().red == 1.0);

srgb_u8

srgb_u8(red: u8, green: u8, blue: u8) -> Color

A color from red, green and blue in the sRGB space, each from 0 to 255, fully opaque.

srgba

srgba(red: f32, green: f32, blue: f32, alpha: f32) -> Color

A color from red, green, blue and alpha in the sRGB space, each from 0 to 1.

srgba_u8

srgba_u8(red: u8, green: u8, blue: u8, alpha: u8) -> Color

A color from red, green, blue and alpha in the sRGB space, each from 0 to 255.

white

white() -> Color

Opaque white.

Methods

NameSummary
alphaThe alpha (opacity) of the color, from 0 (transparent) to 1 (opaque).
darkerA darker copy of the color, amount from 0 to 1.
is_fully_transparentWhether the color is completely transparent.
lighterA lighter copy of the color, amount from 0 to 1.
luminanceThe perceived brightness of the color, from 0 (black) to 1 (white).
mixA color between this one and other, t = 0 gives this color and t = 1 gives other.
set_alphaSets the alpha (opacity) of the color in place.
to_hexThe color as an uppercase hex string such as "#FF8800", with alpha appended unless fully opaque.
to_linearThe color converted to the linear RGB space.
to_srgbaThe color converted to the sRGB space.
with_alphaA copy of the color with its alpha set to alpha.

alpha

alpha(self: Color) -> f32

The alpha (opacity) of the color, from 0 (transparent) to 1 (opaque).

darker

darker(self: Color, amount: f32) -> Color

A darker copy of the color, amount from 0 to 1.

is_fully_transparent

is_fully_transparent(self: Color) -> bool

Whether the color is completely transparent.

lighter

lighter(self: Color, amount: f32) -> Color

A lighter copy of the color, amount from 0 to 1.

luminance

luminance(self: Color) -> f32

The perceived brightness of the color, from 0 (black) to 1 (white).

mix

mix(self: Color, other: Color, t: f32) -> Color

A color between this one and other, t = 0 gives this color and t = 1 gives other.

set_alpha

set_alpha(self: Color, alpha: f32)

Sets the alpha (opacity) of the color in place.

to_hex

to_hex(self: Color) -> String

The color as an uppercase hex string such as "#FF8800", with alpha appended unless fully opaque.

to_linear

to_linear(self: Color) -> LinearRgba

The color converted to the linear RGB space.

to_srgba

to_srgba(self: Color) -> Srgba

The color converted to the sRGB space.

with_alpha

with_alpha(self: Color, alpha: f32) -> Color

A copy of the color with its alpha set to alpha.

Operators

NameSummary
eqWhether both colors are the same color in the same color space.

eq

eq(self: Color, other: Color) -> bool

Whether both colors are the same color in the same color space.

Variant Functions

Hsla.new

new(variant: EnumVariantRef, payload: Fields<Color::Hsla>) -> Color

Hsva.new

new(variant: EnumVariantRef, payload: Fields<Color::Hsva>) -> Color

Hwba.new

new(variant: EnumVariantRef, payload: Fields<Color::Hwba>) -> Color

Laba.new

new(variant: EnumVariantRef, payload: Fields<Color::Laba>) -> Color

Lcha.new

new(variant: EnumVariantRef, payload: Fields<Color::Lcha>) -> Color

LinearRgba.new

new(variant: EnumVariantRef, payload: Fields<Color::LinearRgba>) -> Color

Okhsla.new

new(variant: EnumVariantRef, payload: Fields<Color::Okhsla>) -> Color

Okhsva.new

new(variant: EnumVariantRef, payload: Fields<Color::Okhsva>) -> Color

Okhwba.new

new(variant: EnumVariantRef, payload: Fields<Color::Okhwba>) -> Color

Oklaba.new

new(variant: EnumVariantRef, payload: Fields<Color::Oklaba>) -> Color

Oklcha.new

new(variant: EnumVariantRef, payload: Fields<Color::Oklcha>) -> Color

Srgba.new

new(variant: EnumVariantRef, payload: Fields<Color::Srgba>) -> Color

Xyza.new

new(variant: EnumVariantRef, payload: Fields<Color::Xyza>) -> Color

Hsla

Color in Hue-Saturation-Lightness (HSL) color space with alpha. Further information on this color model can be found on Wikipedia.

Fields

FieldType
huef32
saturationf32
lightnessf32
alphaf32

Functions

NameSummary
newreates a color from hue (degrees), saturation, lightness and alpha.

new

new(a: f32, b: f32, c: f32, alpha: f32) -> Hsla

reates a color from hue (degrees), saturation, lightness and alpha.

Methods

NameSummary
to_colorThe color as a Color, in the same color space.

to_color

to_color(self: Hsla) -> Color

The color as a Color, in the same color space.

Hsva

Color in Hue-Saturation-Value (HSV) color space with alpha. Further information on this color model can be found on Wikipedia.

Fields

FieldType
huef32
saturationf32
valuef32
alphaf32

Functions

NameSummary
newreates a color from hue (degrees), saturation, value and alpha.

new

new(a: f32, b: f32, c: f32, alpha: f32) -> Hsva

reates a color from hue (degrees), saturation, value and alpha.

Methods

NameSummary
to_colorThe color as a Color, in the same color space.

to_color

to_color(self: Hsva) -> Color

The color as a Color, in the same color space.

Hwba

Color in Hue-Whiteness-Blackness (HWB) color space with alpha. Further information on this color model can be found on Wikipedia.

Fields

FieldType
huef32
whitenessf32
blacknessf32
alphaf32

Functions

NameSummary
newreates a color from hue (degrees), whiteness, blackness and alpha.

new

new(a: f32, b: f32, c: f32, alpha: f32) -> Hwba

reates a color from hue (degrees), whiteness, blackness and alpha.

Methods

NameSummary
to_colorThe color as a Color, in the same color space.

to_color

to_color(self: Hwba) -> Color

The color as a Color, in the same color space.

Laba

Color in LAB color space, with alpha

Fields

FieldType
lightnessf32
af32
bf32
alphaf32

Functions

NameSummary
newreates a color from lightness, a, b and alpha.

new

new(a: f32, b: f32, c: f32, alpha: f32) -> Laba

reates a color from lightness, a, b and alpha.

Methods

NameSummary
to_colorThe color as a Color, in the same color space.

to_color

to_color(self: Laba) -> Color

The color as a Color, in the same color space.

Lcha

Color in LCH color space, with alpha

Fields

FieldType
lightnessf32
chromaf32
huef32
alphaf32

Functions

NameSummary
newreates a color from lightness, chroma, hue (degrees) and alpha.

new

new(a: f32, b: f32, c: f32, alpha: f32) -> Lcha

reates a color from lightness, chroma, hue (degrees) and alpha.

Methods

NameSummary
to_colorThe color as a Color, in the same color space.

to_color

to_color(self: Lcha) -> Color

The color as a Color, in the same color space.

LinearRgba

Linear RGB color with alpha.

SDR colors are in [0.0, 1.0]. Values above 1.0 are HDR intensities.

Fields

FieldType
redf32
greenf32
bluef32
alphaf32

Functions

NameSummary
newA color from linear red, green, blue and alpha, each from 0 to 1.
rgbA fully opaque color from linear red, green and blue, each from 0 to 1.

new

new(red: f32, green: f32, blue: f32, alpha: f32) -> LinearRgba

A color from linear red, green, blue and alpha, each from 0 to 1.

local LinearRgba = import_namespace("color").LinearRgba
local c = LinearRgba.new(1.0, 0.0, 0.0, 1.0)
assert(c.red == 1.0)
let LinearRgba = import_namespace("color").LinearRgba;
let c = LinearRgba.new(1.0, 0.0, 0.0, 1.0);
assert!(c.red == 1.0);

rgb

rgb(red: f32, green: f32, blue: f32) -> LinearRgba

A fully opaque color from linear red, green and blue, each from 0 to 1.

Methods

NameSummary
to_colorThe color as a Color.

to_color

to_color(self: LinearRgba) -> Color

The color as a Color.

Operators

NameSummary
eqWhether both colors have the same red, green, blue and alpha.
mulA copy with red, green and blue multiplied by factor, keeping alpha. Useful for making emissive colors brighter.

eq

eq(self: LinearRgba, other: LinearRgba) -> bool

Whether both colors have the same red, green, blue and alpha.

mul

mul(self: LinearRgba, factor: f32) -> LinearRgba

A copy with red, green and blue multiplied by factor, keeping alpha. Useful for making emissive colors brighter.

Okhsla

Color in Okhsl color space with alpha. Further information on this color model can be found on https://bottosson.github.io/posts/colorpicker.

Okhsl is defined relative to the sRGB (Rec. 709) gamut. Converting a wide-gamut or HDR color clamps the lightness to 1.0 but can push saturation outside [0.0, 1.0].

Fields

FieldType
huef32
saturationf32
lightnessf32
alphaf32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Okhsla>) -> Okhsla

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Okhsva

Color in Okhsv color space with alpha. Further information on this color model can be found on https://bottosson.github.io/posts/colorpicker.

Okhsv is defined relative to the sRGB (Rec. 709) gamut. Converting a wide-gamut or HDR color can push saturation and value outside [0.0, 1.0].

Fields

FieldType
huef32
saturationf32
valuef32
alphaf32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Okhsva>) -> Okhsva

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Okhwba

Color in Okhwb color space with alpha. Further information on this color model can be found on https://bottosson.github.io/posts/colorpicker.

Fields

FieldType
huef32
whitenessf32
blacknessf32
alphaf32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Okhwba>) -> Okhwba

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Oklaba

Color in Oklab color space, with alpha

Fields

FieldType
lightnessf32
af32
bf32
alphaf32

Functions

NameSummary
newreates a color from lightness, a, b and alpha.

new

new(a: f32, b: f32, c: f32, alpha: f32) -> Oklaba

reates a color from lightness, a, b and alpha.

Methods

NameSummary
to_colorThe color as a Color, in the same color space.

to_color

to_color(self: Oklaba) -> Color

The color as a Color, in the same color space.

Oklcha

Color in Oklch color space, with alpha

Fields

FieldType
lightnessf32
chromaf32
huef32
alphaf32

Functions

NameSummary
newreates a color from lightness, chroma, hue (degrees) and alpha.

new

new(a: f32, b: f32, c: f32, alpha: f32) -> Oklcha

reates a color from lightness, chroma, hue (degrees) and alpha.

Methods

NameSummary
to_colorThe color as a Color, in the same color space.

to_color

to_color(self: Oklcha) -> Color

The color as a Color, in the same color space.

Srgba

Non-linear standard RGB with alpha.

SDR colors are in [0.0, 1.0]. Values above 1.0 are HDR intensities.

Fields

FieldType
redf32
greenf32
bluef32
alphaf32

Functions

NameSummary
hexA color from a hex string such as "#ff8800" or "#ff880080", or an error if the string is not valid hex.
newA color from red, green, blue and alpha, each from 0 to 1.
rgbA fully opaque color from red, green and blue, each from 0 to 1.

hex

hex(hex: String) -> Srgba

A color from a hex string such as "#ff8800" or "#ff880080", or an error if the string is not valid hex.

new

new(red: f32, green: f32, blue: f32, alpha: f32) -> Srgba

A color from red, green, blue and alpha, each from 0 to 1.

local Srgba = import_namespace("color").Srgba
local c = Srgba.new(1.0, 0.0, 0.0, 0.5)
assert(c.alpha == 0.5)
let Srgba = import_namespace("color").Srgba;
let c = Srgba.new(1.0, 0.0, 0.0, 0.5);
assert!(c.alpha == 0.5);

rgb

rgb(red: f32, green: f32, blue: f32) -> Srgba

A fully opaque color from red, green and blue, each from 0 to 1.

Methods

NameSummary
to_colorThe color as a Color.
to_hexThe color as an uppercase hex string such as "#FF8800", with alpha appended unless fully opaque.
with_alphaA copy of the color with its alpha set to alpha.

to_color

to_color(self: Srgba) -> Color

The color as a Color.

to_hex

to_hex(self: Srgba) -> String

The color as an uppercase hex string such as "#FF8800", with alpha appended unless fully opaque.

with_alpha

with_alpha(self: Srgba, alpha: f32) -> Srgba

A copy of the color with its alpha set to alpha.

Operators

NameSummary
eqWhether both colors have the same red, green, blue and alpha.

eq

eq(self: Srgba, other: Srgba) -> bool

Whether both colors have the same red, green, blue and alpha.

Xyza

CIE 1931 color space, also known as XYZ, with an alpha channel.

The SDR channel bounds below are the D65 white point, (0.9505, 1.0, 1.0889).

Fields

FieldType
xf32
yf32
zf32
alphaf32

Functions

NameSummary
newreates a color from x, y, z and alpha.

new

new(a: f32, b: f32, c: f32, alpha: f32) -> Xyza

reates a color from x, y, z and alpha.

Methods

NameSummary
to_colorThe color as a Color, in the same color space.

to_color

to_color(self: Xyza) -> Color

The color as a Color, in the same color space.

core

The types and functions in the core namespace, as returned by import_namespace("core").

Types

TypeSummary
NonZeroI16
NonZeroU16
NonZeroU32
Range<T>A range of values, from start up to but not including end.
TypeId

NonZeroI16

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<NonZeroI16>) -> NonZeroI16

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

NonZeroU16

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<NonZeroU16>) -> NonZeroU16

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

NonZeroU32

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<NonZeroU32>) -> NonZeroU32

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Range<T>

Generic

A range of values, from start up to but not including end.

Opaque: scripts can't access its fields, only its functions.

Instantiations

Range<f32>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

On Range<f32>

new(payload: Fields<Range<f32>>) -> Range<f32>

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

TypeId

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<TypeId>) -> TypeId

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ecs

The types and functions in the ecs namespace, as returned by import_namespace("ecs").

Types

TypeSummary
AddEventTrigger emitted when a component is inserted onto an entity that does not already have that component.
ChildOfStores the parent entity of this child entity with this component.
DespawnEventEntityEvent emitted for each component on an entity when it is despawned.
DiscardEventTrigger emitted when a component is removed from an entity, regardless of whether or not it is later replaced.
EntityUnique identifier for an entity in a World.
HashedStrA wrapper over Hashed.
InsertEventTrigger emitted when a component is inserted, regardless of whether or not the entity already had that component.
NameComponent used to identify an entity. Stores a hash for faster comparisons.
RemoveEventTrigger emitted when a component is removed from an entity, and runs before the component is removed, so you can still…

AddEvent

Trigger emitted when a component is inserted onto an entity that does not already have that component. Runs before Insert. See ComponentHooks::on_add for more information.

Fields

FieldType
entityEntity

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<AddEvent>) -> AddEvent

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ChildOf

Component

Stores the parent entity of this child entity with this component.

This is a Relationship component, and creates the canonical “parent / child” hierarchy. This is the “source of truth” component, and it pairs with the Children RelationshipTarget.

This relationship should be used for things like:

  1. Organizing entities in a scene
  2. Propagating configuration or data inherited from a parent, such as “visibility” or “world-space global transforms”.
  3. Ensuring a hierarchy is despawned when an entity is despawned.

ChildOf contains a single “target” Entity. When ChildOf is inserted on a “source” entity, the “target” entity will automatically (and immediately, via a component hook) have a Children component inserted, and the “source” entity will be added to that Children instance.

If the ChildOf component is replaced with a different “target” entity, the old target’s Children will be automatically (and immediately, via a component hook) be updated to reflect that change.

Likewise, when the ChildOf component is removed, the “source” entity will be removed from the old target’s Children. If this results in Children being empty, Children will be automatically removed.

When a parent is despawned, all children (and their descendants) will also be despawned.

You can create parent-child relationships in a variety of ways. The most direct way is to insert a ChildOf component:

let root = world.spawn_empty().id();
let child1 = world.spawn(ChildOf(root)).id();
let child2 = world.spawn(ChildOf(root)).id();
let grandchild = world.spawn(ChildOf(child1)).id();

assert_eq!(&**world.entity(root).get::<Children>().unwrap(), &[child1, child2]);
assert_eq!(&**world.entity(child1).get::<Children>().unwrap(), &[grandchild]);

world.entity_mut(child2).remove::<ChildOf>();
assert_eq!(&**world.entity(root).get::<Children>().unwrap(), &[child1]);

world.entity_mut(root).despawn();
assert!(world.get_entity(root).is_err());
assert!(world.get_entity(child1).is_err());
assert!(world.get_entity(grandchild).is_err());

However if you are spawning many children, you might want to use the EntityWorldMut::with_children helper instead:

let mut child1 = None;
let mut child2 = None;
let mut grandchild = None;
let root = world.spawn_empty().with_children(|p| {
    child1 = Some(p.spawn_empty().with_children(|p| {
        grandchild = Some(p.spawn_empty().id());
    }).id());
    child2 = Some(p.spawn_empty().id());
}).id();

assert_eq!(&**world.entity(root).get::<Children>().unwrap(), &[child1.unwrap(), child2.unwrap()]);
assert_eq!(&**world.entity(child1.unwrap()).get::<Children>().unwrap(), &[grandchild.unwrap()]);

Fields

IndexType
0Entity

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ChildOf>) -> ChildOf

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
parentThe parent entity.

parent

parent(self: ChildOf) -> Entity

The parent entity.

DespawnEvent

EntityEvent emitted for each component on an entity when it is despawned. See ComponentHooks::on_despawn for more information.

Fields

FieldType
entityEntity

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<DespawnEvent>) -> DespawnEvent

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

DiscardEvent

Trigger emitted when a component is removed from an entity, regardless of whether or not it is later replaced.

Runs before the value is replaced, so you can still access the original component data. See ComponentHooks::on_discard for more information.

Fields

FieldType
entityEntity

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<DiscardEvent>) -> DiscardEvent

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Entity

Unique identifier for an entity in a World. Note that this is just an id, not the entity itself. Further, the entity this id refers to may no longer exist in the World. For more information about entities, their ids, and how to use them, see the module docs.

Aliasing

Once an entity is despawned, it ceases to exist. However, its Entity id is still present, and may still be contained in some data. This becomes problematic because it is possible for a later entity to be spawned at the exact same id! If this happens, which is rare but very possible, it will be logged.

Aliasing can happen without warning. Holding onto a Entity id corresponding to an entity well after that entity was despawned can cause un-intuitive behavior for both ordering, and comparing in general. To prevent these bugs, it is generally best practice to stop holding an Entity or EntityGeneration value as soon as you know it has been despawned. If you must do otherwise, do not assume the Entity id corresponds to the same entity it originally did. See EntityGeneration’s docs for more information about aliasing and why it occurs.

Stability warning

For all intents and purposes, Entity should be treated as an opaque identifier. The internal bit representation is liable to change from release to release as are the behaviors or performance characteristics of any of its trait implementations (i.e. Ord, Hash, etc.). This means that changes in Entity’s representation, though made readable through various functions on the type, are not considered breaking changes under SemVer.

In particular, directly serializing with Serialize and Deserialize make zero guarantee of long term wire format compatibility. Changes in behavior will cause serialized Entity values persisted to long term storage (i.e. disk, databases, etc.) will fail to deserialize upon being updated.

Usage

This data type is returned by iterating a Query that has Entity as part of its query fetch type parameter (learn more). It can also be obtained by calling EntityCommands::id or EntityWorldMut::id.

fn setup(mut commands: Commands) {
    // Calling `spawn` returns `EntityCommands`.
    let entity = commands.spawn(SomeComponent).id();
}

fn exclusive_system(world: &mut World) {
    // Calling `spawn` returns `EntityWorldMut`.
    let entity = world.spawn(SomeComponent).id();
}

It can be used to refer to a specific entity to apply EntityCommands, or to call Query::get (or similar methods) to access its components.

fn dispose_expired_food(mut commands: Commands, query: Query<Entity, With<Expired>>) {
    for food_entity in &query {
        commands.entity(food_entity).despawn();
    }
}

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
from_bitsThe entity from a number returned by to_bits, or nil if the number is not a valid entity.
newConstructs a new instance of the type from a table of its fields.

from_bits

from_bits(bits: u64) -> Optional<Entity>

The entity from a number returned by to_bits, or nil if the number is not a valid entity.

new

new(payload: Fields<Entity>) -> Entity

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
generationHow many times the index of this entity has been reused.
indexThe index of the entity. Indices of despawned entities are reused, so compare whole entities to tell them apart.
to_bitsThe entity as a single number, which can be turned back into the entity with from_bits.

generation

generation(self: Entity) -> u32

How many times the index of this entity has been reused.

index

index(self: Entity) -> u32

The index of the entity. Indices of despawned entities are reused, so compare whole entities to tell them apart.

to_bits

to_bits(self: Entity) -> u64

The entity as a single number, which can be turned back into the entity with from_bits.

Only meaningful while the app is running, don’t save it.

Operators

NameSummary
eqWhether two entities are the same.

eq

eq(self: Entity, other: Entity) -> bool

Whether two entities are the same.

HashedStr

A wrapper over Hashed. This exists to make Name(“value”.into()) possible, which plays nicely with contexts like the bsn! macro.

Fields

IndexType
0Hashed<Cow, FixedHasher>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<HashedStr>) -> HashedStr

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

InsertEvent

Trigger emitted when a component is inserted, regardless of whether or not the entity already had that component. Runs after Add, if it ran. See ComponentHooks::on_insert for more information.

Fields

FieldType
entityEntity

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<InsertEvent>) -> InsertEvent

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Name

Component

Component used to identify an entity. Stores a hash for faster comparisons.

The hash is eagerly re-computed upon each update to the name.

Name should not be treated as a globally unique identifier for entities, as multiple entities can have the same name. Entity should be used instead as the default unique identifier.

Fields

IndexType
0HashedStr

Functions

NameSummary
newCreates a new Name component, used to identify entities.

new

new(name: String) -> Name

Creates a new Name component, used to identify entities.

local Name = import_namespace("ecs").Name
local name = Name.new("player")
assert(name:as_str() == "player")
let Name = import_namespace("ecs").Name;
let name = Name.new("player");
assert!(name.as_str() == "player");

Methods

NameSummary
as_strThe name as a string.
setChanges the name.

as_str

as_str(self: Name) -> String

The name as a string.

set

set(self: Name, name: String)

Changes the name.

Operators

NameSummary
eqWhether the name is the same as another name or a string.

eq

eq(self: Name, other: Name | String) -> bool

Whether the name is the same as another name or a string.

In Lua, == only compares a name with another name, use name:eq("text") for strings.

RemoveEvent

Trigger emitted when a component is removed from an entity, and runs before the component is removed, so you can still access the component data. See ComponentHooks::on_remove for more information.

Fields

FieldType
entityEntity

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<RemoveEvent>) -> RemoveEvent

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

gizmos

The types and functions in the gizmos namespace, as returned by import_namespace("gizmos").

Types

TypeSummary
GizmosImmediate mode debug drawing: lines and shapes drawn this frame.

Values

NameType
FrustumGizmoSystemsReflectSystemSet
GizmoMeshSystemsReflectSystemSet
TransformGizmoSystemsReflectSystemSet

Gizmos

Immediate mode debug drawing: lines and shapes drawn this frame.

Every function draws straight away, the shapes are shown for the current frame only. Needs the gizmo plugin, without it the functions fail with an error.

local Color = import_namespace("color").Color
local Gizmos = import_namespace("gizmos").Gizmos
local Vec3 = import_namespace("math").Vec3
Gizmos.line(Vec3.zero(), Vec3.new(1, 0, 0), Color.white())
let Color = import_namespace("color").Color;
let Gizmos = import_namespace("gizmos").Gizmos;
let Vec3 = import_namespace("math").Vec3;
Gizmos.line(Vec3.zero(), Vec3.new(1.0, 0.0, 0.0), Color.white());

Functions

NameSummary
arrowDraws an arrow from the start to the end point.
arrow_2dDraws an arrow from the start to the end point in 2D.
axesDraws the red, green and blue axes of the transform, scaled by the length.
circleDraws a circle around the position, lying in the XY plane so it faces +Z.
circle_2dDraws a circle around the position in 2D.
crossDraws a cross of the given half size along the three axes, centred on the position.
cuboidDraws a unit cube, with the transform applied to it.
lineDraws a line between two points.
line_2dDraws a line between two points in 2D.
linestripDraws connected lines through the points, in order.
linestrip_2dDraws connected lines through the points in 2D, in order.
newConstructs a new instance of the type from a table of its fields.
rayDraws a line from the origin along the vector.
ray_2dDraws a line from the origin along the vector in 2D.
rectDraws a rectangle of the given size centred on the position, lying in the XY plane.
rect_2dDraws a rectangle of the given size centred on the position in 2D.
sphereDraws a wireframe sphere around the position.

arrow

arrow(start: Vec3, end: Vec3, color: Color)

Draws an arrow from the start to the end point.

arrow_2d

arrow_2d(start: Vec2, end: Vec2, color: Color)

Draws an arrow from the start to the end point in 2D.

axes

axes(transform: Transform, length: f32)

Draws the red, green and blue axes of the transform, scaled by the length.

circle

circle(position: Vec3, radius: f32, color: Color)

Draws a circle around the position, lying in the XY plane so it faces +Z.

circle_2d

circle_2d(position: Vec2, radius: f32, color: Color)

Draws a circle around the position in 2D.

cross

cross(position: Vec3, half_size: f32, color: Color)

Draws a cross of the given half size along the three axes, centred on the position.

cuboid

cuboid(transform: Transform, color: Color)

Draws a unit cube, with the transform applied to it.

line

line(start: Vec3, end: Vec3, color: Color)

Draws a line between two points.

line_2d

line_2d(start: Vec2, end: Vec2, color: Color)

Draws a line between two points in 2D.

linestrip

linestrip(points: Vec<Vec3>, color: Color)

Draws connected lines through the points, in order.

linestrip_2d

linestrip_2d(points: Vec<Vec2>, color: Color)

Draws connected lines through the points in 2D, in order.

new

new(payload: Fields<Gizmos>) -> Gizmos

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ray

ray(origin: Vec3, vector: Vec3, color: Color)

Draws a line from the origin along the vector.

ray_2d

ray_2d(origin: Vec2, vector: Vec2, color: Color)

Draws a line from the origin along the vector in 2D.

rect

rect(position: Vec3, size: Vec2, color: Color)

Draws a rectangle of the given size centred on the position, lying in the XY plane.

rect_2d

rect_2d(position: Vec2, size: Vec2, color: Color)

Draws a rectangle of the given size centred on the position in 2D.

sphere

sphere(position: Vec3, radius: f32, color: Color)

Draws a wireframe sphere around the position.

input

The types and functions in the input namespace, as returned by import_namespace("input").

Types

TypeSummary
Axis<T>The position of the inputs of type T on an axis, i.e. GamepadInput.
ButtonInput<T>The pressed state of the inputs of type T, i.e. KeyCode.
FocusCauseThe cause for a FocusGained
GamepadStores a connected gamepad’s metadata such as the name and its GamepadButton and GamepadAxis.
GamepadAxisRepresents gamepad input types that are mapped in the range -1.0, 1.0.
GamepadButtonRepresents gamepad input types that are mapped in the range 0.0, 1.0.
GamepadInputEncapsulation over GamepadAxis and GamepadButton.
InputFocusResource representing which entity has input focus, if any.
KeyCodeThe key code of a KeyboardInput.
MouseButtonA button on a mouse device.
NativeKeyCodeContains the platform-native physical key identifier

Values

NameType
InputSystemsReflectSystemSet

Axis<T>

Generic

The position of the inputs of type T on an axis, i.e. GamepadInput.

Fields

FieldType
axis_dataHashMap<T, f32>

Instantiations

Axis<GamepadInput>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

On Axis<GamepadInput>

new(payload: Fields<Axis<GamepadInput>>) -> Axis<GamepadInput>

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ButtonInput<T>

Generic

The pressed state of the inputs of type T, i.e. KeyCode.

Fields

FieldType
pressedHashSet<T>
just_pressedHashSet<T>
just_releasedHashSet<T>

Instantiations

ButtonInput<MouseButton>, ButtonInput<KeyCode>, ButtonInput<GamepadButton>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

On ButtonInput<MouseButton>, ButtonInput<KeyCode>, ButtonInput<GamepadButton>

new(payload: Fields<ButtonInput<MouseButton>>) -> ButtonInput<MouseButton>

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
get_pressedThe buttons which are held down.
just_pressedWhether the button was pressed during the last update.
just_releasedWhether the button was released during the last update.
pressHolds the button down, as if it was pressed.
pressedWhether the button is held down.
releaseLets go of the button, as if it was released.

get_pressed

On ButtonInput<MouseButton>, ButtonInput<KeyCode>, ButtonInput<GamepadButton>

get_pressed(self: ButtonInput<MouseButton>) -> Vec<MouseButton>

The buttons which are held down.

just_pressed

On ButtonInput<MouseButton>, ButtonInput<KeyCode>, ButtonInput<GamepadButton>

just_pressed(self: ButtonInput<MouseButton>, button: MouseButton) -> bool

Whether the button was pressed during the last update.

just_released

On ButtonInput<MouseButton>, ButtonInput<KeyCode>, ButtonInput<GamepadButton>

just_released(self: ButtonInput<MouseButton>, button: MouseButton) -> bool

Whether the button was released during the last update.

press

On ButtonInput<MouseButton>, ButtonInput<KeyCode>, ButtonInput<GamepadButton>

press(self: ButtonInput<MouseButton>, button: MouseButton)

Holds the button down, as if it was pressed.

pressed

On ButtonInput<MouseButton>, ButtonInput<KeyCode>, ButtonInput<GamepadButton>

pressed(self: ButtonInput<MouseButton>, button: MouseButton) -> bool

Whether the button is held down.

release

On ButtonInput<MouseButton>, ButtonInput<KeyCode>, ButtonInput<GamepadButton>

release(self: ButtonInput<MouseButton>, button: MouseButton)

Lets go of the button, as if it was released.

FocusCause

The cause for a FocusGained

Sometimes widgets would like to know how their focus was gained so they can act accordingly.

For example, a text input may want to select all text when navigated into, but not when pressed.

Variants

Variant
Navigated
Pressed
Auto

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<FocusCause>) -> FocusCause

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Auto.new

new(variant: EnumVariantRef, payload: Fields<FocusCause::Auto>) -> FocusCause

new(variant: EnumVariantRef, payload: Fields<FocusCause::Navigated>) -> FocusCause

Pressed.new

new(variant: EnumVariantRef, payload: Fields<FocusCause::Pressed>) -> FocusCause

Gamepad

Component

Stores a connected gamepad’s metadata such as the name and its GamepadButton and GamepadAxis.

An entity with this component is spawned automatically after GamepadConnectionEvent and updated by gamepad_event_processing_system.

See also GamepadSettings for configuration.

Examples

fn gamepad_usage_system(gamepads: Query<(&Name, &Gamepad)>) {
    for (name, gamepad) in &gamepads {
        println!("{name}");

        if gamepad.just_pressed(GamepadButton::North) {
            println!("{} just pressed North", name)
        }

        if let Some(left_stick_x) = gamepad.get(GamepadAxis::LeftStickX)  {
            println!("left stick X: {}", left_stick_x)
        }
    }
}

Fields

FieldType
vendor_idOptional<u16>
product_idOptional<u16>
digitalButtonInput<GamepadButton>
analogAxis<GamepadInput>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Gamepad>) -> Gamepad

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
dpadThe direction of the d-pad, from -1 to 1 on each axis.
getThe value of the button or axis, from 0 to 1 for buttons and from -1 to 1 for axes, or nil if the gamepad has…
just_pressedWhether the button was pressed during the last update.
just_releasedWhether the button was released during the last update.
left_stickThe position of the left stick, from -1 to 1 on each axis.
pressedWhether the button is held down.
right_stickThe position of the right stick, from -1 to 1 on each axis.

dpad

dpad(self: Gamepad) -> Vec2

The direction of the d-pad, from -1 to 1 on each axis.

get

get(self: Gamepad, axis: GamepadAxis) -> Optional<f32>

The value of the button or axis, from 0 to 1 for buttons and from -1 to 1 for axes, or nil if the gamepad has no such input.

just_pressed

just_pressed(self: Gamepad, button: GamepadButton) -> bool

Whether the button was pressed during the last update.

just_released

just_released(self: Gamepad, button: GamepadButton) -> bool

Whether the button was released during the last update.

left_stick

left_stick(self: Gamepad) -> Vec2

The position of the left stick, from -1 to 1 on each axis.

pressed

pressed(self: Gamepad, button: GamepadButton) -> bool

Whether the button is held down.

right_stick

right_stick(self: Gamepad) -> Vec2

The position of the right stick, from -1 to 1 on each axis.

GamepadAxis

Represents gamepad input types that are mapped in the range -1.0, 1.0.

Usage

This is used to determine which axis has changed its value when receiving a gamepad axis event. It is also used in the Gamepad component.

Variants

VariantFields
LeftStickX
LeftStickY
LeftZ
RightStickX
RightStickY
RightZ
Other(u32)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<GamepadAxis>) -> GamepadAxis

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

LeftStickX.new

new(variant: EnumVariantRef, payload: Fields<GamepadAxis::LeftStickX>) -> GamepadAxis

LeftStickY.new

new(variant: EnumVariantRef, payload: Fields<GamepadAxis::LeftStickY>) -> GamepadAxis

LeftZ.new

new(variant: EnumVariantRef, payload: Fields<GamepadAxis::LeftZ>) -> GamepadAxis

Other.new

new(variant: EnumVariantRef, payload: Fields<GamepadAxis::Other>) -> GamepadAxis

RightStickX.new

new(variant: EnumVariantRef, payload: Fields<GamepadAxis::RightStickX>) -> GamepadAxis

RightStickY.new

new(variant: EnumVariantRef, payload: Fields<GamepadAxis::RightStickY>) -> GamepadAxis

RightZ.new

new(variant: EnumVariantRef, payload: Fields<GamepadAxis::RightZ>) -> GamepadAxis

GamepadButton

Represents gamepad input types that are mapped in the range 0.0, 1.0.

Usage

This is used to determine which button has changed its value when receiving gamepad button events. It is also used in the Gamepad component.

Variants

VariantFields
South
East
North
West
C
Z
LeftTrigger
LeftTrigger2
RightTrigger
RightTrigger2
Select
Start
Mode
LeftThumb
RightThumb
DPadUp
DPadDown
DPadLeft
DPadRight
Other(u32)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<GamepadButton>) -> GamepadButton

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

C.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::C>) -> GamepadButton

DPadDown.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::DPadDown>) -> GamepadButton

DPadLeft.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::DPadLeft>) -> GamepadButton

DPadRight.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::DPadRight>) -> GamepadButton

DPadUp.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::DPadUp>) -> GamepadButton

East.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::East>) -> GamepadButton

LeftThumb.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::LeftThumb>) -> GamepadButton

LeftTrigger.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::LeftTrigger>) -> GamepadButton

LeftTrigger2.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::LeftTrigger2>) -> GamepadButton

Mode.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::Mode>) -> GamepadButton

North.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::North>) -> GamepadButton

Other.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::Other>) -> GamepadButton

RightThumb.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::RightThumb>) -> GamepadButton

RightTrigger.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::RightTrigger>) -> GamepadButton

RightTrigger2.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::RightTrigger2>) -> GamepadButton

Select.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::Select>) -> GamepadButton

South.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::South>) -> GamepadButton

Start.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::Start>) -> GamepadButton

West.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::West>) -> GamepadButton

Z.new

new(variant: EnumVariantRef, payload: Fields<GamepadButton::Z>) -> GamepadButton

GamepadInput

Encapsulation over GamepadAxis and GamepadButton.

Variants

VariantFields
Axis(GamepadAxis)
Button(GamepadButton)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<GamepadInput>) -> GamepadInput

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

NameSummary
Axis.new
Button.new

Axis.new

new(variant: EnumVariantRef, payload: Fields<GamepadInput::Axis>) -> GamepadInput

Button.new

new(variant: EnumVariantRef, payload: Fields<GamepadInput::Button>) -> GamepadInput

InputFocus

ComponentResource

Resource representing which entity has input focus, if any. Input events (other than pointer-like inputs) will be dispatched to the current focus entity, or to the primary window if no entity has focus.

Changing the input focus is as easy as modifying this resource.

To detect when an entity gains or loses focus, listen for the FocusGained and FocusLost events.

Examples

From within a system:

use bevy_ecs::prelude::*;
use bevy_input_focus::{FocusCause, InputFocus};

fn clear_focus(mut input_focus: ResMut<InputFocus>) {
  input_focus.clear();
}

With exclusive (or deferred) world access:

use bevy_ecs::prelude::*;
use bevy_input_focus::{FocusCause, InputFocus};

fn set_focus_from_world(world: &mut World) {
    let entity = world.spawn_empty().id();

    // Fetch the resource from the world
    let mut input_focus = world.resource_mut::<InputFocus>();
    // Then mutate it!
    input_focus.set(entity, FocusCause::Navigated);

    // Or you can just insert a fresh copy of the resource
    // which will overwrite the existing one.
    world.insert_resource(InputFocus::from_entity(entity));
}

Fields

FieldType
current_focusOptional<Entity>
recorded_changesVec<Optional<(Entity, FocusCause)>>
original_focusOptional<Entity>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<InputFocus>) -> InputFocus

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
clearTakes the focus away from every entity.
getThe entity which has the focus, or nil if no entity has it.
setGives the focus to the entity, so it receives keyboard input.

clear

clear(self: InputFocus)

Takes the focus away from every entity.

get

get(self: InputFocus) -> Optional<Entity>

The entity which has the focus, or nil if no entity has it.

set

set(self: InputFocus, entity: Entity)

Gives the focus to the entity, so it receives keyboard input.

KeyCode

The key code of a KeyboardInput.

Usage

It is used as the generic T value of an ButtonInput to create a Res<ButtonInput<KeyCode>>.

Code representing the location of a physical key This mostly conforms to the UI Events Specification's KeyboardEvent.code with a few exceptions:

  • The keys that the specification calls MetaLeft and MetaRight are named SuperLeft and SuperRight here.
  • The key that the specification calls “Super” is reported as Unidentified here.

Updating

The resource is updated inside of the keyboard_input_system.

Variants

VariantFields
Unidentified(NativeKeyCode)
Backquote
Backslash
BracketLeft
BracketRight
Comma
Digit0
Digit1
Digit2
Digit3
Digit4
Digit5
Digit6
Digit7
Digit8
Digit9
Equal
IntlBackslash
IntlRo
IntlYen
KeyA
KeyB
KeyC
KeyD
KeyE
KeyF
KeyG
KeyH
KeyI
KeyJ
KeyK
KeyL
KeyM
KeyN
KeyO
KeyP
KeyQ
KeyR
KeyS
KeyT
KeyU
KeyV
KeyW
KeyX
KeyY
KeyZ
Minus
Period
Quote
Semicolon
Slash
AltLeft
AltRight
Backspace
CapsLock
ContextMenu
ControlLeft
ControlRight
Enter
SuperLeft
SuperRight
ShiftLeft
ShiftRight
Space
Tab
Convert
KanaMode
Lang1
Lang2
Lang3
Lang4
Lang5
NonConvert
Delete
End
Help
Home
Insert
PageDown
PageUp
ArrowDown
ArrowLeft
ArrowRight
ArrowUp
NumLock
Numpad0
Numpad1
Numpad2
Numpad3
Numpad4
Numpad5
Numpad6
Numpad7
Numpad8
Numpad9
NumpadAdd
NumpadBackspace
NumpadClear
NumpadClearEntry
NumpadComma
NumpadDecimal
NumpadDivide
NumpadEnter
NumpadEqual
NumpadHash
NumpadMemoryAdd
NumpadMemoryClear
NumpadMemoryRecall
NumpadMemoryStore
NumpadMemorySubtract
NumpadMultiply
NumpadParenLeft
NumpadParenRight
NumpadStar
NumpadSubtract
Escape
Fn
FnLock
PrintScreen
ScrollLock
Pause
BrowserBack
BrowserFavorites
BrowserForward
BrowserHome
BrowserRefresh
BrowserSearch
BrowserStop
Eject
LaunchApp1
LaunchApp2
LaunchMail
MediaPlayPause
MediaSelect
MediaStop
MediaTrackNext
MediaTrackPrevious
Power
Sleep
AudioVolumeDown
AudioVolumeMute
AudioVolumeUp
WakeUp
Meta
Hyper
Turbo
Abort
Resume
Suspend
Again
Copy
Cut
Find
Open
Paste
Props
Select
Undo
Hiragana
Katakana
F1
F2
F3
F4
F5
F6
F7
F8
F9
F10
F11
F12
F13
F14
F15
F16
F17
F18
F19
F20
F21
F22
F23
F24
F25
F26
F27
F28
F29
F30
F31
F32
F33
F34
F35

Functions

NameSummary
any_just_pressedWhether any of the keys was pressed during the last update.
any_pressedWhether any of the keys is held down.
get_just_pressedThe keys which were pressed during the last update.
get_pressedThe keys which are held down.
newConstructs a new instance of the type from a table of its fields.

any_just_pressed

any_just_pressed(keys: Vec<KeyCode>) -> bool

Whether any of the keys was pressed during the last update.

any_pressed

any_pressed(keys: Vec<KeyCode>) -> bool

Whether any of the keys is held down.

get_just_pressed

get_just_pressed() -> Vec<KeyCode>

The keys which were pressed during the last update.

get_pressed

get_pressed() -> Vec<KeyCode>

The keys which are held down.

new

new(payload: Fields<KeyCode>) -> KeyCode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
just_pressedWhether the key was pressed during the last update.
just_releasedWhether the key was released during the last update.
pressedWhether the key is held down, false if the input resource is missing.

just_pressed

just_pressed(key: KeyCode) -> bool

Whether the key was pressed during the last update.

just_released

just_released(key: KeyCode) -> bool

Whether the key was released during the last update.

pressed

pressed(key: KeyCode) -> bool

Whether the key is held down, false if the input resource is missing.

Variant Functions

NameSummary
Abort.new
Again.new
AltLeft.new
AltRight.new
ArrowDown.new
ArrowLeft.new
ArrowRight.new
ArrowUp.new
AudioVolumeDown.new
AudioVolumeMute.new
AudioVolumeUp.new
Backquote.new
Backslash.new
Backspace.new
BracketLeft.new
BracketRight.new
BrowserBack.new
BrowserFavorites.new
BrowserForward.new
BrowserHome.new
BrowserRefresh.new
BrowserSearch.new
BrowserStop.new
CapsLock.new
Comma.new
ContextMenu.new
ControlLeft.new
ControlRight.new
Convert.new
Copy.new
Cut.new
Delete.new
Digit0.new
Digit1.new
Digit2.new
Digit3.new
Digit4.new
Digit5.new
Digit6.new
Digit7.new
Digit8.new
Digit9.new
Eject.new
End.new
Enter.new
Equal.new
Escape.new
F1.new
F10.new
F11.new
F12.new
F13.new
F14.new
F15.new
F16.new
F17.new
F18.new
F19.new
F2.new
F20.new
F21.new
F22.new
F23.new
F24.new
F25.new
F26.new
F27.new
F28.new
F29.new
F3.new
F30.new
F31.new
F32.new
F33.new
F34.new
F35.new
F4.new
F5.new
F6.new
F7.new
F8.new
F9.new
Find.new
Fn.new
FnLock.new
Help.new
Hiragana.new
Home.new
Hyper.new
Insert.new
IntlBackslash.new
IntlRo.new
IntlYen.new
KanaMode.new
Katakana.new
KeyA.new
KeyB.new
KeyC.new
KeyD.new
KeyE.new
KeyF.new
KeyG.new
KeyH.new
KeyI.new
KeyJ.new
KeyK.new
KeyL.new
KeyM.new
KeyN.new
KeyO.new
KeyP.new
KeyQ.new
KeyR.new
KeyS.new
KeyT.new
KeyU.new
KeyV.new
KeyW.new
KeyX.new
KeyY.new
KeyZ.new
Lang1.new
Lang2.new
Lang3.new
Lang4.new
Lang5.new
LaunchApp1.new
LaunchApp2.new
LaunchMail.new
MediaPlayPause.new
MediaSelect.new
MediaStop.new
MediaTrackNext.new
MediaTrackPrevious.new
Meta.new
Minus.new
NonConvert.new
NumLock.new
Numpad0.new
Numpad1.new
Numpad2.new
Numpad3.new
Numpad4.new
Numpad5.new
Numpad6.new
Numpad7.new
Numpad8.new
Numpad9.new
NumpadAdd.new
NumpadBackspace.new
NumpadClear.new
NumpadClearEntry.new
NumpadComma.new
NumpadDecimal.new
NumpadDivide.new
NumpadEnter.new
NumpadEqual.new
NumpadHash.new
NumpadMemoryAdd.new
NumpadMemoryClear.new
NumpadMemoryRecall.new
NumpadMemoryStore.new
NumpadMemorySubtract.new
NumpadMultiply.new
NumpadParenLeft.new
NumpadParenRight.new
NumpadStar.new
NumpadSubtract.new
Open.new
PageDown.new
PageUp.new
Paste.new
Pause.new
Period.new
Power.new
PrintScreen.new
Props.new
Quote.new
Resume.new
ScrollLock.new
Select.new
Semicolon.new
ShiftLeft.new
ShiftRight.new
Slash.new
Sleep.new
Space.new
SuperLeft.new
SuperRight.new
Suspend.new
Tab.new
Turbo.new
Undo.new
Unidentified.new
WakeUp.new

Abort.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Abort>) -> KeyCode

Again.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Again>) -> KeyCode

AltLeft.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::AltLeft>) -> KeyCode

AltRight.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::AltRight>) -> KeyCode

ArrowDown.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::ArrowDown>) -> KeyCode

ArrowLeft.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::ArrowLeft>) -> KeyCode

ArrowRight.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::ArrowRight>) -> KeyCode

ArrowUp.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::ArrowUp>) -> KeyCode

AudioVolumeDown.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::AudioVolumeDown>) -> KeyCode

AudioVolumeMute.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::AudioVolumeMute>) -> KeyCode

AudioVolumeUp.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::AudioVolumeUp>) -> KeyCode

Backquote.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Backquote>) -> KeyCode

Backslash.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Backslash>) -> KeyCode

Backspace.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Backspace>) -> KeyCode

BracketLeft.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::BracketLeft>) -> KeyCode

BracketRight.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::BracketRight>) -> KeyCode

BrowserBack.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::BrowserBack>) -> KeyCode

BrowserFavorites.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::BrowserFavorites>) -> KeyCode

BrowserForward.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::BrowserForward>) -> KeyCode

BrowserHome.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::BrowserHome>) -> KeyCode

BrowserRefresh.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::BrowserRefresh>) -> KeyCode

BrowserSearch.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::BrowserSearch>) -> KeyCode

BrowserStop.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::BrowserStop>) -> KeyCode

CapsLock.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::CapsLock>) -> KeyCode

Comma.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Comma>) -> KeyCode

ContextMenu.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::ContextMenu>) -> KeyCode

ControlLeft.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::ControlLeft>) -> KeyCode

ControlRight.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::ControlRight>) -> KeyCode

Convert.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Convert>) -> KeyCode

Copy.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Copy>) -> KeyCode

Cut.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Cut>) -> KeyCode

Delete.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Delete>) -> KeyCode

Digit0.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit0>) -> KeyCode

Digit1.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit1>) -> KeyCode

Digit2.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit2>) -> KeyCode

Digit3.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit3>) -> KeyCode

Digit4.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit4>) -> KeyCode

Digit5.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit5>) -> KeyCode

Digit6.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit6>) -> KeyCode

Digit7.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit7>) -> KeyCode

Digit8.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit8>) -> KeyCode

Digit9.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit9>) -> KeyCode

Eject.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Eject>) -> KeyCode

End.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::End>) -> KeyCode

Enter.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Enter>) -> KeyCode

Equal.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Equal>) -> KeyCode

Escape.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Escape>) -> KeyCode

F1.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F1>) -> KeyCode

F10.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F10>) -> KeyCode

F11.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F11>) -> KeyCode

F12.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F12>) -> KeyCode

F13.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F13>) -> KeyCode

F14.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F14>) -> KeyCode

F15.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F15>) -> KeyCode

F16.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F16>) -> KeyCode

F17.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F17>) -> KeyCode

F18.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F18>) -> KeyCode

F19.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F19>) -> KeyCode

F2.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F2>) -> KeyCode

F20.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F20>) -> KeyCode

F21.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F21>) -> KeyCode

F22.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F22>) -> KeyCode

F23.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F23>) -> KeyCode

F24.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F24>) -> KeyCode

F25.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F25>) -> KeyCode

F26.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F26>) -> KeyCode

F27.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F27>) -> KeyCode

F28.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F28>) -> KeyCode

F29.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F29>) -> KeyCode

F3.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F3>) -> KeyCode

F30.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F30>) -> KeyCode

F31.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F31>) -> KeyCode

F32.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F32>) -> KeyCode

F33.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F33>) -> KeyCode

F34.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F34>) -> KeyCode

F35.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F35>) -> KeyCode

F4.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F4>) -> KeyCode

F5.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F5>) -> KeyCode

F6.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F6>) -> KeyCode

F7.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F7>) -> KeyCode

F8.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F8>) -> KeyCode

F9.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::F9>) -> KeyCode

Find.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Find>) -> KeyCode

Fn.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Fn>) -> KeyCode

FnLock.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::FnLock>) -> KeyCode

Help.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Help>) -> KeyCode

Hiragana.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Hiragana>) -> KeyCode

Home.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Home>) -> KeyCode

Hyper.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Hyper>) -> KeyCode

Insert.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Insert>) -> KeyCode

IntlBackslash.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::IntlBackslash>) -> KeyCode

IntlRo.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::IntlRo>) -> KeyCode

IntlYen.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::IntlYen>) -> KeyCode

KanaMode.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KanaMode>) -> KeyCode

Katakana.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Katakana>) -> KeyCode

KeyA.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyA>) -> KeyCode

KeyB.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyB>) -> KeyCode

KeyC.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyC>) -> KeyCode

KeyD.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyD>) -> KeyCode

KeyE.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyE>) -> KeyCode

KeyF.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyF>) -> KeyCode

KeyG.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyG>) -> KeyCode

KeyH.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyH>) -> KeyCode

KeyI.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyI>) -> KeyCode

KeyJ.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyJ>) -> KeyCode

KeyK.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyK>) -> KeyCode

KeyL.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyL>) -> KeyCode

KeyM.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyM>) -> KeyCode

KeyN.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyN>) -> KeyCode

KeyO.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyO>) -> KeyCode

KeyP.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyP>) -> KeyCode

KeyQ.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyQ>) -> KeyCode

KeyR.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyR>) -> KeyCode

KeyS.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyS>) -> KeyCode

KeyT.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyT>) -> KeyCode

KeyU.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyU>) -> KeyCode

KeyV.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyV>) -> KeyCode

KeyW.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyW>) -> KeyCode

KeyX.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyX>) -> KeyCode

KeyY.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyY>) -> KeyCode

KeyZ.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyZ>) -> KeyCode

Lang1.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Lang1>) -> KeyCode

Lang2.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Lang2>) -> KeyCode

Lang3.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Lang3>) -> KeyCode

Lang4.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Lang4>) -> KeyCode

Lang5.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Lang5>) -> KeyCode

LaunchApp1.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::LaunchApp1>) -> KeyCode

LaunchApp2.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::LaunchApp2>) -> KeyCode

LaunchMail.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::LaunchMail>) -> KeyCode

MediaPlayPause.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::MediaPlayPause>) -> KeyCode

MediaSelect.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::MediaSelect>) -> KeyCode

MediaStop.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::MediaStop>) -> KeyCode

MediaTrackNext.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::MediaTrackNext>) -> KeyCode

MediaTrackPrevious.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::MediaTrackPrevious>) -> KeyCode

Meta.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Meta>) -> KeyCode

Minus.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Minus>) -> KeyCode

NonConvert.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NonConvert>) -> KeyCode

NumLock.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumLock>) -> KeyCode

Numpad0.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad0>) -> KeyCode

Numpad1.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad1>) -> KeyCode

Numpad2.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad2>) -> KeyCode

Numpad3.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad3>) -> KeyCode

Numpad4.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad4>) -> KeyCode

Numpad5.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad5>) -> KeyCode

Numpad6.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad6>) -> KeyCode

Numpad7.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad7>) -> KeyCode

Numpad8.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad8>) -> KeyCode

Numpad9.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad9>) -> KeyCode

NumpadAdd.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadAdd>) -> KeyCode

NumpadBackspace.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadBackspace>) -> KeyCode

NumpadClear.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadClear>) -> KeyCode

NumpadClearEntry.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadClearEntry>) -> KeyCode

NumpadComma.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadComma>) -> KeyCode

NumpadDecimal.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadDecimal>) -> KeyCode

NumpadDivide.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadDivide>) -> KeyCode

NumpadEnter.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadEnter>) -> KeyCode

NumpadEqual.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadEqual>) -> KeyCode

NumpadHash.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadHash>) -> KeyCode

NumpadMemoryAdd.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadMemoryAdd>) -> KeyCode

NumpadMemoryClear.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadMemoryClear>) -> KeyCode

NumpadMemoryRecall.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadMemoryRecall>) -> KeyCode

NumpadMemoryStore.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadMemoryStore>) -> KeyCode

NumpadMemorySubtract.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadMemorySubtract>) -> KeyCode

NumpadMultiply.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadMultiply>) -> KeyCode

NumpadParenLeft.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadParenLeft>) -> KeyCode

NumpadParenRight.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadParenRight>) -> KeyCode

NumpadStar.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadStar>) -> KeyCode

NumpadSubtract.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadSubtract>) -> KeyCode

Open.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Open>) -> KeyCode

PageDown.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::PageDown>) -> KeyCode

PageUp.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::PageUp>) -> KeyCode

Paste.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Paste>) -> KeyCode

Pause.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Pause>) -> KeyCode

Period.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Period>) -> KeyCode

Power.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Power>) -> KeyCode

PrintScreen.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::PrintScreen>) -> KeyCode

Props.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Props>) -> KeyCode

Quote.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Quote>) -> KeyCode

Resume.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Resume>) -> KeyCode

ScrollLock.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::ScrollLock>) -> KeyCode

Select.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Select>) -> KeyCode

Semicolon.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Semicolon>) -> KeyCode

ShiftLeft.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::ShiftLeft>) -> KeyCode

ShiftRight.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::ShiftRight>) -> KeyCode

Slash.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Slash>) -> KeyCode

Sleep.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Sleep>) -> KeyCode

Space.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Space>) -> KeyCode

SuperLeft.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::SuperLeft>) -> KeyCode

SuperRight.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::SuperRight>) -> KeyCode

Suspend.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Suspend>) -> KeyCode

Tab.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Tab>) -> KeyCode

Turbo.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Turbo>) -> KeyCode

Undo.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Undo>) -> KeyCode

Unidentified.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::Unidentified>) -> KeyCode

WakeUp.new

new(variant: EnumVariantRef, payload: Fields<KeyCode::WakeUp>) -> KeyCode

MouseButton

A button on a mouse device.

Usage

It is used as the generic T value of an ButtonInput to create a bevy resource.

Updating

The resource is updated inside of the mouse_button_input_system.

Variants

VariantFields
Left
Right
Middle
Back
Forward
Other(u16)

Functions

NameSummary
any_just_pressedWhether any of the mouse buttons was pressed during the last update.
any_pressedWhether any of the mouse buttons is held down.
get_just_pressedThe mouse buttons which were pressed during the last update.
get_pressedThe mouse buttons which are held down.
newConstructs a new instance of the type from a table of its fields.

any_just_pressed

any_just_pressed(buttons: Vec<MouseButton>) -> bool

Whether any of the mouse buttons was pressed during the last update.

any_pressed

any_pressed(buttons: Vec<MouseButton>) -> bool

Whether any of the mouse buttons is held down.

get_just_pressed

get_just_pressed() -> Vec<MouseButton>

The mouse buttons which were pressed during the last update.

get_pressed

get_pressed() -> Vec<MouseButton>

The mouse buttons which are held down.

new

new(payload: Fields<MouseButton>) -> MouseButton

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
just_pressedWhether the mouse button was pressed during the last update.
just_releasedWhether the mouse button was released during the last update.
pressedWhether the mouse button is held down, false if the input resource is missing.

just_pressed

just_pressed(button: MouseButton) -> bool

Whether the mouse button was pressed during the last update.

just_released

just_released(button: MouseButton) -> bool

Whether the mouse button was released during the last update.

pressed

pressed(button: MouseButton) -> bool

Whether the mouse button is held down, false if the input resource is missing.

Variant Functions

Back.new

new(variant: EnumVariantRef, payload: Fields<MouseButton::Back>) -> MouseButton

Forward.new

new(variant: EnumVariantRef, payload: Fields<MouseButton::Forward>) -> MouseButton

Left.new

new(variant: EnumVariantRef, payload: Fields<MouseButton::Left>) -> MouseButton

Middle.new

new(variant: EnumVariantRef, payload: Fields<MouseButton::Middle>) -> MouseButton

Other.new

new(variant: EnumVariantRef, payload: Fields<MouseButton::Other>) -> MouseButton

Right.new

new(variant: EnumVariantRef, payload: Fields<MouseButton::Right>) -> MouseButton

NativeKeyCode

Contains the platform-native physical key identifier

The exact values vary from platform to platform (which is part of why this is a per-platform enum), but the values are primarily tied to the key’s physical location on the keyboard.

This enum is primarily used to store raw keycodes when Winit doesn’t map a given native physical key identifier to a meaningful KeyCode variant. In the presence of identifiers we haven’t mapped for you yet, this lets you use KeyCode to:

  • Correctly match key press and release events.
  • On non-web platforms, support assigning keybinds to virtually any key through a UI.

Variants

VariantFields
Unidentified
Android(u32)
MacOS(u16)
Windows(u16)
Xkb(u32)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<NativeKeyCode>) -> NativeKeyCode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Android.new

new(variant: EnumVariantRef, payload: Fields<NativeKeyCode::Android>) -> NativeKeyCode

MacOS.new

new(variant: EnumVariantRef, payload: Fields<NativeKeyCode::MacOS>) -> NativeKeyCode

Unidentified.new

new(variant: EnumVariantRef, payload: Fields<NativeKeyCode::Unidentified>) -> NativeKeyCode

Windows.new

new(variant: EnumVariantRef, payload: Fields<NativeKeyCode::Windows>) -> NativeKeyCode

Xkb.new

new(variant: EnumVariantRef, payload: Fields<NativeKeyCode::Xkb>) -> NativeKeyCode

input.InputFocusSystems

The types and functions in the input.InputFocusSystems namespace, as returned by import_namespace("input.InputFocusSystems").

Values

NameType
DispatchReflectSystemSet
FocusChangeEventsReflectSystemSet

math

The types and functions in the math namespace, as returned by import_namespace("math").

Types

TypeSummary
Aabb2dA 2D axis-aligned bounding box, or bounding rectangle
Aabb3dA 3D axis-aligned bounding box
Affine2
Affine3A
AnnulusA primitive shape formed by the region between two circles, also known as a ring.
Capsule2dA 2D capsule primitive, also known as a stadium or pill shape.
Capsule3dA 3D capsule primitive centered on the origin A three-dimensional capsule is defined as a surface at a distance…
CircleA circle primitive, representing the set of points some distance from the origin
CompassOctantA compass enum with 8 directions.
ConeA cone primitive centered on the midpoint between the tip of the cone and the center of its base.
CuboidA cuboid primitive, which is like a cube, except that the x, y, and z dimensions are not required to be the same.
CylinderA cylinder primitive centered on the origin
Dir2A normalized vector pointing in a direction in 2D space
Dir3A normalized vector pointing in a direction in 3D space
DVec2
DVec3
EaseFunctionCurve functions over the unit interval, commonly used for easing transitions.
EulerRot
IVec2
IVec3
JumpAtConfiguration options for the EaseFunction::Steps curves. This closely replicates the CSS step function specification.
Mat2
Mat3
Mat3A
Mat4
Plane3dA bounded plane in 3D space. It forms a surface starting from the origin with a defined height and width.
Quat
Ray2dAn infinite half-line starting at origin and going in direction in 2D space.
Ray3dAn infinite half-line starting at origin and going in direction in 3D space.
RectA rectangle defined by two opposite corners.
RectangleA rectangle primitive, which is like a square, except that the width and height can be different
RegularPolygonA polygon centered on the origin where all vertices lie on a circle, equally far apart.
Rot2A 2D rotation.
SphereA sphere primitive, representing the set of all points some distance from the origin
TorusA torus primitive, often representing a ring or donut shape The set of points some distance from a circle centered at…
Triangle2dA triangle in 2D space
URectA rectangle defined by two opposite corners.
UVec2
UVec3
Vec2
Vec3
Vec3A
Vec4

Aabb2d

A 2D axis-aligned bounding box, or bounding rectangle

Fields

FieldType
minVec2
maxVec2

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Aabb2d>) -> Aabb2d

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Aabb3d

A 3D axis-aligned bounding box

Fields

FieldType
minVec3A
maxVec3A

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Aabb3d>) -> Aabb3d

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Affine2

Fields

FieldType
matrix2Mat2
translationVec2

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Affine2>) -> Affine2

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Affine3A

Fields

FieldType
matrix3Mat3A
translationVec3A

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Affine3A>) -> Affine3A

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Annulus

A primitive shape formed by the region between two circles, also known as a ring.

Fields

FieldType
inner_circleCircle
outer_circleCircle

Functions

NameSummary
newA ring with the given inner and outer radii.

new

new(inner_radius: f32, outer_radius: f32) -> Annulus

A ring with the given inner and outer radii.

Capsule2d

A 2D capsule primitive, also known as a stadium or pill shape.

A two-dimensional capsule is defined as a neighborhood of points at a distance (radius) from a line

Fields

FieldType
radiusf32
half_lengthf32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Capsule2d>) -> Capsule2d

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Capsule3d

A 3D capsule primitive centered on the origin A three-dimensional capsule is defined as a surface at a distance (radius) from a line

Fields

FieldType
radiusf32
half_lengthf32

Functions

NameSummary
newA capsule with the given radius and length of its middle section.

new

new(radius: f32, length: f32) -> Capsule3d

A capsule with the given radius and length of its middle section.

Circle

A circle primitive, representing the set of points some distance from the origin

Fields

FieldType
radiusf32

Functions

NameSummary
newA circle with the given radius.

new

new(radius: f32) -> Circle

A circle with the given radius.

CompassOctant

A compass enum with 8 directions.

         N (North)
         ▲
    NW   │   NE
       ╲ │ ╱
W (West) ┼─────► E (East)
       ╱ │ ╲
    SW   │   SE
         ▼
         S (South)

Variants

Variant
North
NorthEast
East
SouthEast
South
SouthWest
West
NorthWest

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<CompassOctant>) -> CompassOctant

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

East.new

new(variant: EnumVariantRef, payload: Fields<CompassOctant::East>) -> CompassOctant

North.new

new(variant: EnumVariantRef, payload: Fields<CompassOctant::North>) -> CompassOctant

NorthEast.new

new(variant: EnumVariantRef, payload: Fields<CompassOctant::NorthEast>) -> CompassOctant

NorthWest.new

new(variant: EnumVariantRef, payload: Fields<CompassOctant::NorthWest>) -> CompassOctant

South.new

new(variant: EnumVariantRef, payload: Fields<CompassOctant::South>) -> CompassOctant

SouthEast.new

new(variant: EnumVariantRef, payload: Fields<CompassOctant::SouthEast>) -> CompassOctant

SouthWest.new

new(variant: EnumVariantRef, payload: Fields<CompassOctant::SouthWest>) -> CompassOctant

West.new

new(variant: EnumVariantRef, payload: Fields<CompassOctant::West>) -> CompassOctant

Cone

A cone primitive centered on the midpoint between the tip of the cone and the center of its base.

The cone is oriented with its tip pointing towards the Y axis.

Fields

FieldType
radiusf32
heightf32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Cone>) -> Cone

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Cuboid

A cuboid primitive, which is like a cube, except that the x, y, and z dimensions are not required to be the same.

Fields

FieldType
half_sizeVec3

Functions

NameSummary
from_sizeA box with the given size as a Vec3.
newA box with the given length along the x, y and z axes.

from_size

from_size(size: Vec3) -> Cuboid

A box with the given size as a Vec3.

new

new(x_length: f32, y_length: f32, z_length: f32) -> Cuboid

A box with the given length along the x, y and z axes.

Cylinder

A cylinder primitive centered on the origin

Fields

FieldType
radiusf32
half_heightf32

Functions

NameSummary
newA cylinder with the given radius and height.

new

new(radius: f32, height: f32) -> Cylinder

A cylinder with the given radius and height.

Dir2

A normalized vector pointing in a direction in 2D space

Fields

IndexType
0Vec2

Functions

NameSummary
neg_xThe direction along the negative x axis.
neg_yThe direction along the negative y axis.
newA unit direction pointing the same way as the vector, or nil if the vector is zero or not finite.
xThe direction along the positive x axis.
yThe direction along the positive y axis.

neg_x

neg_x() -> Dir2

The direction along the negative x axis.

neg_y

neg_y() -> Dir2

The direction along the negative y axis.

new

new(v: Vec2) -> Optional<Dir2>

A unit direction pointing the same way as the vector, or nil if the vector is zero or not finite.

x

x() -> Dir2

The direction along the positive x axis.

y

y() -> Dir2

The direction along the positive y axis.

Methods

NameSummary
as_vec2This direction as a unit Vec2.
slerpSpherically interpolates between this direction and other by t, from 0 to 1.

as_vec2

as_vec2(self: Dir2) -> Vec2

This direction as a unit Vec2.

slerp

slerp(self: Dir2, other: Dir2, t: f32) -> Dir2

Spherically interpolates between this direction and other by t, from 0 to 1.

Operators

NameSummary
eqWhether both directions have exactly the same components.
mulThis direction scaled by length, as a Vec2.
negThe opposite direction.

eq

eq(self: Dir2, other: Dir2) -> bool

Whether both directions have exactly the same components.

mul

mul(self: Dir2, length: f32) -> Vec2

This direction scaled by length, as a Vec2.

neg

neg(self: Dir2) -> Dir2

The opposite direction.

Dir3

A normalized vector pointing in a direction in 3D space

Fields

IndexType
0Vec3

Functions

NameSummary
neg_xThe direction along the negative x axis.
neg_yThe direction along the negative y axis.
neg_zThe direction along the negative z axis.
newA unit direction pointing the same way as the vector, or nil if the vector is zero or not finite.
xThe direction along the positive x axis.
yThe direction along the positive y axis.
zThe direction along the positive z axis.

neg_x

neg_x() -> Dir3

The direction along the negative x axis.

neg_y

neg_y() -> Dir3

The direction along the negative y axis.

neg_z

neg_z() -> Dir3

The direction along the negative z axis.

new

new(v: Vec3) -> Optional<Dir3>

A unit direction pointing the same way as the vector, or nil if the vector is zero or not finite.

x

x() -> Dir3

The direction along the positive x axis.

y

y() -> Dir3

The direction along the positive y axis.

z

z() -> Dir3

The direction along the positive z axis.

Methods

NameSummary
as_vec3This direction as a unit Vec3.
slerpSpherically interpolates between this direction and other by t, from 0 to 1.

as_vec3

as_vec3(self: Dir3) -> Vec3

This direction as a unit Vec3.

slerp

slerp(self: Dir3, other: Dir3, t: f32) -> Dir3

Spherically interpolates between this direction and other by t, from 0 to 1.

Operators

NameSummary
eqWhether both directions have exactly the same components.
mulThis direction scaled by length, as a Vec3.
negThe opposite direction.

eq

eq(self: Dir3, other: Dir3) -> bool

Whether both directions have exactly the same components.

mul

mul(self: Dir3, length: f32) -> Vec3

This direction scaled by length, as a Vec3.

neg

neg(self: Dir3) -> Dir3

The opposite direction.

DVec2

Fields

FieldType
xf64
yf64

Functions

NameSummary
newCreates a new double precision vector.

new

new(x: f64, y: f64) -> DVec2

Creates a new double precision vector.

Methods

NameSummary
as_vec2Converts to a single precision Vec2.

as_vec2

as_vec2(self: DVec2) -> Vec2

Converts to a single precision Vec2.

DVec3

Fields

FieldType
xf64
yf64
zf64

Functions

NameSummary
newCreates a new double precision vector.

new

new(x: f64, y: f64, z: f64) -> DVec3

Creates a new double precision vector.

Methods

NameSummary
as_vec3Converts to a single precision Vec3.

as_vec3

as_vec3(self: DVec3) -> Vec3

Converts to a single precision Vec3.

EaseFunction

Curve functions over the unit interval, commonly used for easing transitions.

EaseFunction can be used on its own to interpolate between 0.0 and 1.0. It can also be combined with EasingCurve to interpolate between other intervals and types, including vectors and rotations.

Example

sample the smoothstep function at various points. This will return None if the parameter is outside the unit interval.

let f = EaseFunction::SmoothStep;

assert_eq!(f.sample(-1.0), None);
assert_eq!(f.sample(0.0), Some(0.0));
assert_eq!(f.sample(0.5), Some(0.5));
assert_eq!(f.sample(1.0), Some(1.0));
assert_eq!(f.sample(2.0), None);

sample_clamped will clamp the parameter to the unit interval, so it always returns a value.

assert_eq!(f.sample_clamped(-1.0), 0.0);
assert_eq!(f.sample_clamped(0.0), 0.0);
assert_eq!(f.sample_clamped(0.5), 0.5);
assert_eq!(f.sample_clamped(1.0), 1.0);
assert_eq!(f.sample_clamped(2.0), 1.0);

Variants

VariantFields
Linear
QuadraticIn
QuadraticOut
QuadraticInOut
CubicIn
CubicOut
CubicInOut
QuarticIn
QuarticOut
QuarticInOut
QuinticIn
QuinticOut
QuinticInOut
SmoothStepIn
SmoothStepOut
SmoothStep
SmootherStepIn
SmootherStepOut
SmootherStep
SineIn
SineOut
SineInOut
CircularIn
CircularOut
CircularInOut
ExponentialIn
ExponentialOut
ExponentialInOut
ElasticIn
ElasticOut
ElasticInOut
BackIn
BackOut
BackInOut
BounceIn
BounceOut
BounceInOut
Steps(usize, JumpAt)
Elastic(f32)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<EaseFunction>) -> EaseFunction

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
sampleThe eased value at t, clamped to between 0 and 1.

sample

sample(self: EaseFunction, t: f32) -> f32

The eased value at t, clamped to between 0 and 1.

Variant Functions

BackIn.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::BackIn>) -> EaseFunction

BackInOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::BackInOut>) -> EaseFunction

BackOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::BackOut>) -> EaseFunction

BounceIn.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::BounceIn>) -> EaseFunction

BounceInOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::BounceInOut>) -> EaseFunction

BounceOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::BounceOut>) -> EaseFunction

CircularIn.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::CircularIn>) -> EaseFunction

CircularInOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::CircularInOut>) -> EaseFunction

CircularOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::CircularOut>) -> EaseFunction

CubicIn.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::CubicIn>) -> EaseFunction

CubicInOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::CubicInOut>) -> EaseFunction

CubicOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::CubicOut>) -> EaseFunction

Elastic.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::Elastic>) -> EaseFunction

ElasticIn.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::ElasticIn>) -> EaseFunction

ElasticInOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::ElasticInOut>) -> EaseFunction

ElasticOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::ElasticOut>) -> EaseFunction

ExponentialIn.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::ExponentialIn>) -> EaseFunction

ExponentialInOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::ExponentialInOut>) -> EaseFunction

ExponentialOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::ExponentialOut>) -> EaseFunction

Linear.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::Linear>) -> EaseFunction

QuadraticIn.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuadraticIn>) -> EaseFunction

QuadraticInOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuadraticInOut>) -> EaseFunction

QuadraticOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuadraticOut>) -> EaseFunction

QuarticIn.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuarticIn>) -> EaseFunction

QuarticInOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuarticInOut>) -> EaseFunction

QuarticOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuarticOut>) -> EaseFunction

QuinticIn.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuinticIn>) -> EaseFunction

QuinticInOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuinticInOut>) -> EaseFunction

QuinticOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuinticOut>) -> EaseFunction

SineIn.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::SineIn>) -> EaseFunction

SineInOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::SineInOut>) -> EaseFunction

SineOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::SineOut>) -> EaseFunction

SmoothStep.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::SmoothStep>) -> EaseFunction

SmoothStepIn.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::SmoothStepIn>) -> EaseFunction

SmoothStepOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::SmoothStepOut>) -> EaseFunction

SmootherStep.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::SmootherStep>) -> EaseFunction

SmootherStepIn.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::SmootherStepIn>) -> EaseFunction

SmootherStepOut.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::SmootherStepOut>) -> EaseFunction

Steps.new

new(variant: EnumVariantRef, payload: Fields<EaseFunction::Steps>) -> EaseFunction

EulerRot

Variants

Variant
ZYX
ZXY
YXZ
YZX
XYZ
XZY
ZYZ
ZXZ
YXY
YZY
XYX
XZX
ZYXEx
ZXYEx
YXZEx
YZXEx
XYZEx
XZYEx
ZYZEx
ZXZEx
YXYEx
YZYEx
XYXEx
XZXEx

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<EulerRot>) -> EulerRot

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

XYX.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::XYX>) -> EulerRot

XYXEx.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::XYXEx>) -> EulerRot

XYZ.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::XYZ>) -> EulerRot

XYZEx.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::XYZEx>) -> EulerRot

XZX.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::XZX>) -> EulerRot

XZXEx.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::XZXEx>) -> EulerRot

XZY.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::XZY>) -> EulerRot

XZYEx.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::XZYEx>) -> EulerRot

YXY.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::YXY>) -> EulerRot

YXYEx.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::YXYEx>) -> EulerRot

YXZ.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::YXZ>) -> EulerRot

YXZEx.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::YXZEx>) -> EulerRot

YZX.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::YZX>) -> EulerRot

YZXEx.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::YZXEx>) -> EulerRot

YZY.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::YZY>) -> EulerRot

YZYEx.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::YZYEx>) -> EulerRot

ZXY.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::ZXY>) -> EulerRot

ZXYEx.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::ZXYEx>) -> EulerRot

ZXZ.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::ZXZ>) -> EulerRot

ZXZEx.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::ZXZEx>) -> EulerRot

ZYX.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::ZYX>) -> EulerRot

ZYXEx.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::ZYXEx>) -> EulerRot

ZYZ.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::ZYZ>) -> EulerRot

ZYZEx.new

new(variant: EnumVariantRef, payload: Fields<EulerRot::ZYZEx>) -> EulerRot

IVec2

Fields

FieldType
xi32
yi32

Functions

NameSummary
newCreates a new vector.
oneA vector with all components set to 1.
splatA vector with all components set to v.
unit_xThe unit vector along the x axis.
unit_yThe unit vector along the y axis.
zeroA vector with all components set to 0.

new

new(x: i32, y: i32) -> IVec2

Creates a new vector.

one

one() -> IVec2

A vector with all components set to 1.

splat

splat(v: i32) -> IVec2

A vector with all components set to v.

unit_x

unit_x() -> IVec2

The unit vector along the x axis.

unit_y

unit_y() -> IVec2

The unit vector along the y axis.

zero

zero() -> IVec2

A vector with all components set to 0.

Methods

NameSummary
absThe absolute value of every component.
as_vec2Converts to a float vector.
clampClamps every component between the components of min and max.
dotThe dot product of two vectors.
length_squaredThe squared length of the vector.
maxThe larger of each pair of components.
max_elementThe largest component.
minThe smaller of each pair of components.
min_elementThe smallest component.
to_arrayThe components as a list.

abs

abs(self: IVec2) -> IVec2

The absolute value of every component.

as_vec2

as_vec2(self: IVec2) -> Vec2

Converts to a float vector.

clamp

clamp(self: IVec2, min: IVec2, max: IVec2) -> IVec2

Clamps every component between the components of min and max.

dot

dot(self: IVec2, other: IVec2) -> i32

The dot product of two vectors.

length_squared

length_squared(self: IVec2) -> i32

The squared length of the vector.

max

max(self: IVec2, other: IVec2) -> IVec2

The larger of each pair of components.

max_element

max_element(self: IVec2) -> i32

The largest component.

min

min(self: IVec2, other: IVec2) -> IVec2

The smaller of each pair of components.

min_element

min_element(self: IVec2) -> i32

The smallest component.

to_array

to_array(self: IVec2) -> Vec<i32>

The components as a list.

Operators

NameSummary
addAdds a vector or a number to every component.
divDivides component-wise by a vector, or by a number. Errors if any divisor component is 0.
eqWhether all components are equal.
mulMultiplies component-wise by a vector, or scales by a number.
negNegates every component.
remThe component-wise remainder of dividing by a vector, or by a number. Errors if any divisor component is 0.
subSubtracts a vector or a number from every component.

add

add(self: IVec2, rhs: IVec2 | i32) -> IVec2

Adds a vector or a number to every component.

div

div(self: IVec2, rhs: IVec2 | i32) -> IVec2

Divides component-wise by a vector, or by a number. Errors if any divisor component is 0.

eq

eq(self: IVec2, other: IVec2) -> bool

Whether all components are equal.

mul

mul(self: IVec2, rhs: IVec2 | i32) -> IVec2

Multiplies component-wise by a vector, or scales by a number.

neg

neg(self: IVec2) -> IVec2

Negates every component.

rem

rem(self: IVec2, rhs: IVec2 | i32) -> IVec2

The component-wise remainder of dividing by a vector, or by a number. Errors if any divisor component is 0.

sub

sub(self: IVec2, rhs: IVec2 | i32) -> IVec2

Subtracts a vector or a number from every component.

IVec3

Fields

FieldType
xi32
yi32
zi32

Functions

NameSummary
newCreates a new vector.
oneA vector with all components set to 1.
splatA vector with all components set to v.
unit_xThe unit vector along the x axis.
unit_yThe unit vector along the y axis.
unit_zThe unit vector along the z axis.
zeroA vector with all components set to 0.

new

new(x: i32, y: i32, z: i32) -> IVec3

Creates a new vector.

one

one() -> IVec3

A vector with all components set to 1.

splat

splat(v: i32) -> IVec3

A vector with all components set to v.

unit_x

unit_x() -> IVec3

The unit vector along the x axis.

unit_y

unit_y() -> IVec3

The unit vector along the y axis.

unit_z

unit_z() -> IVec3

The unit vector along the z axis.

zero

zero() -> IVec3

A vector with all components set to 0.

Methods

NameSummary
absThe absolute value of every component.
as_vec3Converts to a float vector.
clampClamps every component between the components of min and max.
dotThe dot product of two vectors.
length_squaredThe squared length of the vector.
maxThe larger of each pair of components.
max_elementThe largest component.
minThe smaller of each pair of components.
min_elementThe smallest component.
to_arrayThe components as a list.

abs

abs(self: IVec3) -> IVec3

The absolute value of every component.

as_vec3

as_vec3(self: IVec3) -> Vec3

Converts to a float vector.

clamp

clamp(self: IVec3, min: IVec3, max: IVec3) -> IVec3

Clamps every component between the components of min and max.

dot

dot(self: IVec3, other: IVec3) -> i32

The dot product of two vectors.

length_squared

length_squared(self: IVec3) -> i32

The squared length of the vector.

max

max(self: IVec3, other: IVec3) -> IVec3

The larger of each pair of components.

max_element

max_element(self: IVec3) -> i32

The largest component.

min

min(self: IVec3, other: IVec3) -> IVec3

The smaller of each pair of components.

min_element

min_element(self: IVec3) -> i32

The smallest component.

to_array

to_array(self: IVec3) -> Vec<i32>

The components as a list.

Operators

NameSummary
addAdds a vector or a number to every component.
divDivides component-wise by a vector, or by a number. Errors if any divisor component is 0.
eqWhether all components are equal.
mulMultiplies component-wise by a vector, or scales by a number.
negNegates every component.
remThe component-wise remainder of dividing by a vector, or by a number. Errors if any divisor component is 0.
subSubtracts a vector or a number from every component.

add

add(self: IVec3, rhs: IVec3 | i32) -> IVec3

Adds a vector or a number to every component.

div

div(self: IVec3, rhs: IVec3 | i32) -> IVec3

Divides component-wise by a vector, or by a number. Errors if any divisor component is 0.

eq

eq(self: IVec3, other: IVec3) -> bool

Whether all components are equal.

mul

mul(self: IVec3, rhs: IVec3 | i32) -> IVec3

Multiplies component-wise by a vector, or scales by a number.

neg

neg(self: IVec3) -> IVec3

Negates every component.

rem

rem(self: IVec3, rhs: IVec3 | i32) -> IVec3

The component-wise remainder of dividing by a vector, or by a number. Errors if any divisor component is 0.

sub

sub(self: IVec3, rhs: IVec3 | i32) -> IVec3

Subtracts a vector or a number from every component.

JumpAt

Configuration options for the EaseFunction::Steps curves. This closely replicates the CSS step function specification.

Variants

Variant
Start
End
None
Both

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<JumpAt>) -> JumpAt

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Both.new

new(variant: EnumVariantRef, payload: Fields<JumpAt::Both>) -> JumpAt

End.new

new(variant: EnumVariantRef, payload: Fields<JumpAt::End>) -> JumpAt

None.new

new(variant: EnumVariantRef, payload: Fields<JumpAt::None>) -> JumpAt

Start.new

new(variant: EnumVariantRef, payload: Fields<JumpAt::Start>) -> JumpAt

Mat2

Fields

FieldType
x_axisVec2
y_axisVec2

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Mat2>) -> Mat2

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Mat3

Fields

FieldType
x_axisVec3
y_axisVec3
z_axisVec3

Functions

NameSummary
from_colsA matrix with the given columns.
from_diagonalA matrix with the given diagonal and zeros elsewhere.
from_quatThe rotation matrix of a rotation.
from_rotation_xA rotation matrix of angle radians around the x axis.
from_rotation_yA rotation matrix of angle radians around the y axis.
from_rotation_zA rotation matrix of angle radians around the z axis.
identityThe identity matrix, which leaves vectors unchanged.
newConstructs a new instance of the type from a table of its fields.

from_cols

from_cols(x: Vec3, y: Vec3, z: Vec3) -> Mat3

A matrix with the given columns.

from_diagonal

from_diagonal(diagonal: Vec3) -> Mat3

A matrix with the given diagonal and zeros elsewhere.

from_quat

from_quat(q: Quat) -> Mat3

The rotation matrix of a rotation.

from_rotation_x

from_rotation_x(angle: f32) -> Mat3

A rotation matrix of angle radians around the x axis.

from_rotation_y

from_rotation_y(angle: f32) -> Mat3

A rotation matrix of angle radians around the y axis.

from_rotation_z

from_rotation_z(angle: f32) -> Mat3

A rotation matrix of angle radians around the z axis.

identity

identity() -> Mat3

The identity matrix, which leaves vectors unchanged.

new

new(payload: Fields<Mat3>) -> Mat3

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
colThe column at index, starting from 0. Errors if index is out of range.
determinantThe determinant of the matrix.
inverseThe matrix that undoes this one.
mul_vec3Transforms a Vec3 by this matrix.
rowThe row at index, starting from 0. Errors if index is out of range.
transform_point2Transforms a point in 2D, treating it as having a z of 1.
transform_vector2Transforms a direction in 2D, ignoring translation.
transposeThe matrix with rows and columns swapped.

col

col(self: Mat3, index: usize) -> Vec3

The column at index, starting from 0. Errors if index is out of range.

determinant

determinant(self: Mat3) -> f32

The determinant of the matrix.

inverse

inverse(self: Mat3) -> Mat3

The matrix that undoes this one.

mul_vec3

mul_vec3(self: Mat3, v: Vec3) -> Vec3

Transforms a Vec3 by this matrix.

row

row(self: Mat3, index: usize) -> Vec3

The row at index, starting from 0. Errors if index is out of range.

transform_point2

transform_point2(self: Mat3, point: Vec2) -> Vec2

Transforms a point in 2D, treating it as having a z of 1.

transform_vector2

transform_vector2(self: Mat3, vector: Vec2) -> Vec2

Transforms a direction in 2D, ignoring translation.

transpose

transpose(self: Mat3) -> Mat3

The matrix with rows and columns swapped.

Operators

NameSummary
addAdds two matrices component-wise.
divDivides every component by a number.
eqWhether both matrices have exactly the same components.
mulMultiplies by a matrix, or transforms a vector, or scales every component by a number.
subSubtracts two matrices component-wise.

add

add(self: Mat3, other: Mat3) -> Mat3

Adds two matrices component-wise.

div

div(self: Mat3, rhs: f32) -> Mat3

Divides every component by a number.

eq

eq(self: Mat3, other: Mat3) -> bool

Whether both matrices have exactly the same components.

mul

mul(self: Mat3, rhs: Mat3 | Vec3 | f32) -> Mat3 | Vec3

Multiplies by a matrix, or transforms a vector, or scales every component by a number.

sub

sub(self: Mat3, other: Mat3) -> Mat3

Subtracts two matrices component-wise.

Mat3A

Fields

FieldType
x_axisVec3A
y_axisVec3A
z_axisVec3A

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Mat3A>) -> Mat3A

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Mat4

Fields

FieldType
x_axisVec4
y_axisVec4
z_axisVec4
w_axisVec4

Functions

NameSummary
from_colsA matrix with the given columns.
from_quatThe rotation matrix of a rotation.
from_rotation_translationA matrix that rotates by rotation, then moves by translation.
from_scaleA matrix that scales every axis by the matching component of scale.
from_scale_rotation_translationA matrix that scales by scale, then rotates by rotation, then moves by translation.
from_translationA matrix that moves points by translation.
identityThe identity matrix, which leaves vectors unchanged.
newConstructs a new instance of the type from a table of its fields.

from_cols

from_cols(x: Vec4, y: Vec4, z: Vec4, w: Vec4) -> Mat4

A matrix with the given columns.

from_quat

from_quat(q: Quat) -> Mat4

The rotation matrix of a rotation.

from_rotation_translation

from_rotation_translation(rotation: Quat, translation: Vec3) -> Mat4

A matrix that rotates by rotation, then moves by translation.

from_scale

from_scale(scale: Vec3) -> Mat4

A matrix that scales every axis by the matching component of scale.

from_scale_rotation_translation

from_scale_rotation_translation(scale: Vec3, rotation: Quat, translation: Vec3) -> Mat4

A matrix that scales by scale, then rotates by rotation, then moves by translation.

from_translation

from_translation(translation: Vec3) -> Mat4

A matrix that moves points by translation.

identity

identity() -> Mat4

The identity matrix, which leaves vectors unchanged.

new

new(payload: Fields<Mat4>) -> Mat4

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
colThe column at index, starting from 0. Errors if index is out of range.
determinantThe determinant of the matrix.
inverseThe matrix that undoes this one.
project_point3Transforms a point in 3D by a projection matrix, including the perspective divide.
rowThe row at index, starting from 0. Errors if index is out of range.
transform_point3Transforms a point in 3D, including translation and the projection divide.
transform_vector3Transforms a direction in 3D, ignoring translation.
transposeThe matrix with rows and columns swapped.

col

col(self: Mat4, index: usize) -> Vec4

The column at index, starting from 0. Errors if index is out of range.

determinant

determinant(self: Mat4) -> f32

The determinant of the matrix.

inverse

inverse(self: Mat4) -> Mat4

The matrix that undoes this one.

project_point3

project_point3(self: Mat4, point: Vec3) -> Vec3

Transforms a point in 3D by a projection matrix, including the perspective divide.

row

row(self: Mat4, index: usize) -> Vec4

The row at index, starting from 0. Errors if index is out of range.

transform_point3

transform_point3(self: Mat4, point: Vec3) -> Vec3

Transforms a point in 3D, including translation and the projection divide.

transform_vector3

transform_vector3(self: Mat4, vector: Vec3) -> Vec3

Transforms a direction in 3D, ignoring translation.

transpose

transpose(self: Mat4) -> Mat4

The matrix with rows and columns swapped.

Operators

NameSummary
addAdds two matrices component-wise.
divDivides every component by a number.
eqWhether both matrices have exactly the same components.
mulMultiplies by a matrix, or transforms a vector, or scales every component by a number.
subSubtracts two matrices component-wise.

add

add(self: Mat4, other: Mat4) -> Mat4

Adds two matrices component-wise.

div

div(self: Mat4, rhs: f32) -> Mat4

Divides every component by a number.

eq

eq(self: Mat4, other: Mat4) -> bool

Whether both matrices have exactly the same components.

mul

mul(self: Mat4, rhs: Mat4 | Vec4 | f32) -> Mat4 | Vec4

Multiplies by a matrix, or transforms a vector, or scales every component by a number.

sub

sub(self: Mat4, other: Mat4) -> Mat4

Subtracts two matrices component-wise.

Plane3d

A bounded plane in 3D space. It forms a surface starting from the origin with a defined height and width.

Fields

FieldType
normalDir3
half_sizeVec2

Functions

NameSummary
newA plane facing normal with the given half size. Errors if the normal is zero or not finite.

new

new(normal: Vec3, half_size: Vec2) -> Plane3d

A plane facing normal with the given half size. Errors if the normal is zero or not finite.

Quat

Fields

FieldType
xf32
yf32
zf32
wf32

Functions

NameSummary
from_axis_angleA rotation of angle radians around axis. Errors if the axis is zero or not finite.
from_eulerA rotation from three angles in radians, applied in the given EulerRot order, i.e. EulerRot.YXZ.
from_mat3The rotation described by a 3x3 rotation matrix.
from_rotation_arcThe rotation that turns the direction from onto the direction to. Errors if either vector is zero or not finite.
from_rotation_xA rotation of angle radians around the x axis.
from_rotation_yA rotation of angle radians around the y axis.
from_rotation_zA rotation of angle radians around the z axis.
identityThe identity rotation, which leaves everything unchanged.
newConstructs a new instance of the type from a table of its fields.

from_axis_angle

from_axis_angle(axis: Vec3, angle: f32) -> Quat

A rotation of angle radians around axis. Errors if the axis is zero or not finite.

from_euler

from_euler(order: EulerRot, a: f32, b: f32, c: f32) -> Quat

A rotation from three angles in radians, applied in the given EulerRot order, i.e. EulerRot.YXZ.

from_mat3

from_mat3(m: Mat3) -> Quat

The rotation described by a 3x3 rotation matrix.

from_rotation_arc

from_rotation_arc(from: Vec3, to: Vec3) -> Quat

The rotation that turns the direction from onto the direction to. Errors if either vector is zero or not finite.

from_rotation_x

from_rotation_x(angle: f32) -> Quat

A rotation of angle radians around the x axis.

from_rotation_y

from_rotation_y(angle: f32) -> Quat

A rotation of angle radians around the y axis.

from_rotation_z

from_rotation_z(angle: f32) -> Quat

A rotation of angle radians around the z axis.

identity

identity() -> Quat

The identity rotation, which leaves everything unchanged.

new

new(payload: Fields<Quat>) -> Quat

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
angleThe angle in radians this rotation turns by around its axis.
angle_betweenThe angle in radians between two rotations.
axisThe axis this rotation turns around.
conjugateThe rotation with the vector part negated, which is the inverse for unit quaternions.
dotThe dot product of two rotations.
inverseThe rotation that undoes this one.
is_normalizedWhether the quaternion has a length of 1.
lengthThe length of the quaternion, which is 1 for a rotation.
lerpLinearly interpolates towards other, t = 0 gives this rotation and t = 1 gives other.
mul_vec3Rotates a Vec3.
normalizeThe rotation scaled to a length of 1.
slerpSpherically interpolates towards other, t = 0 gives this rotation and t = 1 gives other.
to_eulerThe three angles in radians of this rotation, in the given EulerRot order.
xyzThe vector part of the quaternion, i.e. the x, y and z components.

angle

angle(self: Quat) -> f32

The angle in radians this rotation turns by around its axis.

angle_between

angle_between(self: Quat, other: Quat) -> f32

The angle in radians between two rotations.

axis

axis(self: Quat) -> Vec3

The axis this rotation turns around.

conjugate

conjugate(self: Quat) -> Quat

The rotation with the vector part negated, which is the inverse for unit quaternions.

dot

dot(self: Quat, other: Quat) -> f32

The dot product of two rotations.

inverse

inverse(self: Quat) -> Quat

The rotation that undoes this one.

is_normalized

is_normalized(self: Quat) -> bool

Whether the quaternion has a length of 1.

length

length(self: Quat) -> f32

The length of the quaternion, which is 1 for a rotation.

lerp

lerp(self: Quat, other: Quat, t: f32) -> Quat

Linearly interpolates towards other, t = 0 gives this rotation and t = 1 gives other.

mul_vec3

mul_vec3(self: Quat, v: Vec3) -> Vec3

Rotates a Vec3.

normalize

normalize(self: Quat) -> Quat

The rotation scaled to a length of 1.

slerp

slerp(self: Quat, other: Quat, t: f32) -> Quat

Spherically interpolates towards other, t = 0 gives this rotation and t = 1 gives other.

to_euler

to_euler(self: Quat, order: EulerRot) -> Vec<f32>

The three angles in radians of this rotation, in the given EulerRot order.

xyz

xyz(self: Quat) -> Vec3

The vector part of the quaternion, i.e. the x, y and z components.

Operators

NameSummary
eqWhether both rotations have exactly the same components.
mulComposes two rotations when given a rotation, or rotates a vector when given a Vec3.
negThe opposite rotation, with every component negated.

eq

eq(self: Quat, other: Quat) -> bool

Whether both rotations have exactly the same components.

mul

mul(self: Quat, rhs: Quat | Vec3) -> Quat | Vec3

Composes two rotations when given a rotation, or rotates a vector when given a Vec3.

neg

neg(self: Quat) -> Quat

The opposite rotation, with every component negated.

Ray2d

An infinite half-line starting at origin and going in direction in 2D space.

Fields

FieldType
originVec2
directionDir2

Functions

NameSummary
newA ray from origin in the direction of direction. Errors if the direction is zero or not finite.

new

new(origin: Vec2, direction: Vec2) -> Ray2d

A ray from origin in the direction of direction. Errors if the direction is zero or not finite.

Methods

NameSummary
get_pointThe point at distance along the ray from its origin.
intersect_planeThe distance along the ray to the line through plane_origin with normal plane_normal, or nil if the ray never…

get_point

get_point(self: Ray2d, distance: f32) -> Vec2

The point at distance along the ray from its origin.

intersect_plane

intersect_plane(self: Ray2d, plane_origin: Vec2, plane_normal: Vec2) -> Optional<f32>

The distance along the ray to the line through plane_origin with normal plane_normal, or nil if the ray never reaches it. Errors if the normal is zero or not finite.

Ray3d

An infinite half-line starting at origin and going in direction in 3D space.

Fields

FieldType
originVec3
directionDir3

Functions

NameSummary
newA ray from origin in the direction of direction. Errors if the direction is zero or not finite.

new

new(origin: Vec3, direction: Vec3) -> Ray3d

A ray from origin in the direction of direction. Errors if the direction is zero or not finite.

Methods

NameSummary
get_pointThe point at distance along the ray from its origin.
intersect_planeThe distance along the ray to the plane through plane_origin with normal plane_normal, or nil if the ray never…

get_point

get_point(self: Ray3d, distance: f32) -> Vec3

The point at distance along the ray from its origin.

intersect_plane

intersect_plane(self: Ray3d, plane_origin: Vec3, plane_normal: Vec3) -> Optional<f32>

The distance along the ray to the plane through plane_origin with normal plane_normal, or nil if the ray never reaches it. Errors if the normal is zero or not finite.

Rect

A rectangle defined by two opposite corners.

The rectangle is axis aligned, and defined by its minimum and maximum coordinates, stored in Rect::min and Rect::max, respectively. The minimum/maximum invariant must be upheld by the user when directly assigning the fields, otherwise some methods produce invalid results. It is generally recommended to use one of the constructor methods instead, which will ensure this invariant is met, unless you already have the minimum and maximum corners.

Fields

FieldType
minVec2
maxVec2

Functions

NameSummary
from_center_half_sizeA rectangle with the given center and half of its full size.
from_center_sizeA rectangle with the given center and full size.
from_cornersA rectangle spanning the two given corners, in either order.
newA rectangle from its minimum corner (x0, y0) and maximum corner (x1, y1).

from_center_half_size

from_center_half_size(origin: Vec2, half_size: Vec2) -> Rect

A rectangle with the given center and half of its full size.

from_center_size

from_center_size(origin: Vec2, size: Vec2) -> Rect

A rectangle with the given center and full size.

from_corners

from_corners(p0: Vec2, p1: Vec2) -> Rect

A rectangle spanning the two given corners, in either order.

new

new(x0: f32, y0: f32, x1: f32, y1: f32) -> Rect

A rectangle from its minimum corner (x0, y0) and maximum corner (x1, y1).

Methods

NameSummary
centerThe center of the rectangle as a Vec2.
containsWhether the point lies inside the rectangle, including its edges.
half_sizeHalf of the full size of the rectangle as a Vec2.
heightThe height of the rectangle.
inflateThis rectangle grown by expansion on every side, or shrunk if it is negative.
intersectThe overlap of this rectangle and other, which is empty if they do not overlap.
is_emptyWhether the rectangle has no area.
sizeThe full size of the rectangle as a Vec2.
unionThe smallest rectangle that contains both this one and other.
widthThe width of the rectangle.

center

center(self: Rect) -> Vec2

The center of the rectangle as a Vec2.

contains

contains(self: Rect, point: Vec2) -> bool

Whether the point lies inside the rectangle, including its edges.

half_size

half_size(self: Rect) -> Vec2

Half of the full size of the rectangle as a Vec2.

height

height(self: Rect) -> f32

The height of the rectangle.

inflate

inflate(self: Rect, expansion: f32) -> Rect

This rectangle grown by expansion on every side, or shrunk if it is negative.

intersect

intersect(self: Rect, other: Rect) -> Rect

The overlap of this rectangle and other, which is empty if they do not overlap.

is_empty

is_empty(self: Rect) -> bool

Whether the rectangle has no area.

size

size(self: Rect) -> Vec2

The full size of the rectangle as a Vec2.

union

union(self: Rect, other: Rect) -> Rect

The smallest rectangle that contains both this one and other.

width

width(self: Rect) -> f32

The width of the rectangle.

Operators

NameSummary
eqWhether both rectangles have exactly the same corners.

eq

eq(self: Rect, other: Rect) -> bool

Whether both rectangles have exactly the same corners.

Rectangle

A rectangle primitive, which is like a square, except that the width and height can be different

Fields

FieldType
half_sizeVec2

Functions

NameSummary
from_sizeA rectangle with the given size as a Vec2.
newA rectangle with the given width and height.

from_size

from_size(size: Vec2) -> Rectangle

A rectangle with the given size as a Vec2.

new

new(width: f32, height: f32) -> Rectangle

A rectangle with the given width and height.

RegularPolygon

A polygon centered on the origin where all vertices lie on a circle, equally far apart.

Fields

FieldType
circumcircleCircle
sidesu32

Functions

NameSummary
newA regular polygon with the given number of sides, all corners at circumradius from the center.

new

new(circumradius: f32, sides: u32) -> RegularPolygon

A regular polygon with the given number of sides, all corners at circumradius from the center.

Rot2

A 2D rotation.

Example

use std::f32::consts::PI;

// Create rotations from counterclockwise angles in radians or degrees
let rotation1 = Rot2::radians(PI / 2.0);
let rotation2 = Rot2::degrees(45.0);

// Get the angle back as radians or degrees
assert_eq!(rotation1.as_degrees(), 90.0);
assert_eq!(rotation2.as_radians(), PI / 4.0);

// "Add" rotations together using `*`
#[cfg(feature = "approx")]
assert_relative_eq!(rotation1 * rotation2, Rot2::degrees(135.0));

// Rotate vectors
#[cfg(feature = "approx")]
assert_relative_eq!(rotation1 * Vec2::X, Vec2::Y);

Fields

FieldType
cosf32
sinf32

Functions

NameSummary
degreesA counterclockwise rotation of degrees degrees.
identityThe rotation that leaves everything unchanged.
newConstructs a new instance of the type from a table of its fields.
radiansA counterclockwise rotation of radians radians.
turn_fractionA counterclockwise rotation of fraction of a full turn, so 1.0 is a full turn.

degrees

degrees(degrees: f32) -> Rot2

A counterclockwise rotation of degrees degrees.

identity

identity() -> Rot2

The rotation that leaves everything unchanged.

new

new(payload: Fields<Rot2>) -> Rot2

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

radians

radians(radians: f32) -> Rot2

A counterclockwise rotation of radians radians.

turn_fraction

turn_fraction(fraction: f32) -> Rot2

A counterclockwise rotation of fraction of a full turn, so 1.0 is a full turn.

Methods

NameSummary
as_degreesThe angle of this rotation in degrees.
as_radiansThe angle of this rotation in radians.
inverseThe rotation that undoes this one.
nlerpLinearly interpolates between this rotation and other by t, from 0 to 1, then normalizes.
slerpSpherically interpolates between this rotation and other by t, from 0 to 1.

as_degrees

as_degrees(self: Rot2) -> f32

The angle of this rotation in degrees.

as_radians

as_radians(self: Rot2) -> f32

The angle of this rotation in radians.

inverse

inverse(self: Rot2) -> Rot2

The rotation that undoes this one.

nlerp

nlerp(self: Rot2, other: Rot2, t: f32) -> Rot2

Linearly interpolates between this rotation and other by t, from 0 to 1, then normalizes.

slerp

slerp(self: Rot2, other: Rot2, t: f32) -> Rot2

Spherically interpolates between this rotation and other by t, from 0 to 1.

Operators

NameSummary
eqWhether both rotations have exactly the same components.
mulComposes two rotations when given a rotation, or rotates a Vec2 when given a vector.

eq

eq(self: Rot2, other: Rot2) -> bool

Whether both rotations have exactly the same components.

mul

mul(self: Rot2, rhs: Rot2 | Vec2) -> Rot2 | Vec2

Composes two rotations when given a rotation, or rotates a Vec2 when given a vector.

Sphere

A sphere primitive, representing the set of all points some distance from the origin

Fields

FieldType
radiusf32

Functions

NameSummary
newA sphere with the given radius.

new

new(radius: f32) -> Sphere

A sphere with the given radius.

Torus

A torus primitive, often representing a ring or donut shape The set of points some distance from a circle centered at the origin

Fields

FieldType
minor_radiusf32
major_radiusf32

Functions

NameSummary
newA donut shape with the given inner and outer radii of its tube.

new

new(inner_radius: f32, outer_radius: f32) -> Torus

A donut shape with the given inner and outer radii of its tube.

Triangle2d

A triangle in 2D space

Fields

FieldType
vertices[Vec2; 3]

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Triangle2d>) -> Triangle2d

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

URect

A rectangle defined by two opposite corners.

The rectangle is axis aligned, and defined by its minimum and maximum coordinates, stored in URect::min and URect::max, respectively. The minimum/maximum invariant must be upheld by the user when directly assigning the fields, otherwise some methods produce invalid results. It is generally recommended to use one of the constructor methods instead, which will ensure this invariant is met, unless you already have the minimum and maximum corners.

Fields

FieldType
minUVec2
maxUVec2

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<URect>) -> URect

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

UVec2

Fields

FieldType
xu32
yu32

Functions

NameSummary
newCreates a new vector.
oneA vector with all components set to 1.
splatA vector with all components set to v.
unit_xThe unit vector along the x axis.
unit_yThe unit vector along the y axis.
zeroA vector with all components set to 0.

new

new(x: u32, y: u32) -> UVec2

Creates a new vector.

one

one() -> UVec2

A vector with all components set to 1.

splat

splat(v: u32) -> UVec2

A vector with all components set to v.

unit_x

unit_x() -> UVec2

The unit vector along the x axis.

unit_y

unit_y() -> UVec2

The unit vector along the y axis.

zero

zero() -> UVec2

A vector with all components set to 0.

Methods

NameSummary
as_vec2Converts to a float vector.
clampClamps every component between the components of min and max.
dotThe dot product of two vectors.
length_squaredThe squared length of the vector.
maxThe larger of each pair of components.
max_elementThe largest component.
minThe smaller of each pair of components.
min_elementThe smallest component.
to_arrayThe components as a list.

as_vec2

as_vec2(self: UVec2) -> Vec2

Converts to a float vector.

clamp

clamp(self: UVec2, min: UVec2, max: UVec2) -> UVec2

Clamps every component between the components of min and max.

dot

dot(self: UVec2, other: UVec2) -> u32

The dot product of two vectors.

length_squared

length_squared(self: UVec2) -> u32

The squared length of the vector.

max

max(self: UVec2, other: UVec2) -> UVec2

The larger of each pair of components.

max_element

max_element(self: UVec2) -> u32

The largest component.

min

min(self: UVec2, other: UVec2) -> UVec2

The smaller of each pair of components.

min_element

min_element(self: UVec2) -> u32

The smallest component.

to_array

to_array(self: UVec2) -> Vec<u32>

The components as a list.

Operators

NameSummary
addAdds a vector or a number to every component.
divDivides component-wise by a vector, or by a number. Errors if any divisor component is 0.
eqWhether all components are equal.
mulMultiplies component-wise by a vector, or scales by a number.
remThe component-wise remainder of dividing by a vector, or by a number. Errors if any divisor component is 0.
subSubtracts a vector or a number from every component.

add

add(self: UVec2, rhs: UVec2 | u32) -> UVec2

Adds a vector or a number to every component.

div

div(self: UVec2, rhs: UVec2 | u32) -> UVec2

Divides component-wise by a vector, or by a number. Errors if any divisor component is 0.

eq

eq(self: UVec2, other: UVec2) -> bool

Whether all components are equal.

mul

mul(self: UVec2, rhs: UVec2 | u32) -> UVec2

Multiplies component-wise by a vector, or scales by a number.

rem

rem(self: UVec2, rhs: UVec2 | u32) -> UVec2

The component-wise remainder of dividing by a vector, or by a number. Errors if any divisor component is 0.

sub

sub(self: UVec2, rhs: UVec2 | u32) -> UVec2

Subtracts a vector or a number from every component.

UVec3

Fields

FieldType
xu32
yu32
zu32

Functions

NameSummary
newCreates a new vector.
oneA vector with all components set to 1.
splatA vector with all components set to v.
unit_xThe unit vector along the x axis.
unit_yThe unit vector along the y axis.
unit_zThe unit vector along the z axis.
zeroA vector with all components set to 0.

new

new(x: u32, y: u32, z: u32) -> UVec3

Creates a new vector.

one

one() -> UVec3

A vector with all components set to 1.

splat

splat(v: u32) -> UVec3

A vector with all components set to v.

unit_x

unit_x() -> UVec3

The unit vector along the x axis.

unit_y

unit_y() -> UVec3

The unit vector along the y axis.

unit_z

unit_z() -> UVec3

The unit vector along the z axis.

zero

zero() -> UVec3

A vector with all components set to 0.

Methods

NameSummary
as_vec3Converts to a float vector.
clampClamps every component between the components of min and max.
dotThe dot product of two vectors.
length_squaredThe squared length of the vector.
maxThe larger of each pair of components.
max_elementThe largest component.
minThe smaller of each pair of components.
min_elementThe smallest component.
to_arrayThe components as a list.

as_vec3

as_vec3(self: UVec3) -> Vec3

Converts to a float vector.

clamp

clamp(self: UVec3, min: UVec3, max: UVec3) -> UVec3

Clamps every component between the components of min and max.

dot

dot(self: UVec3, other: UVec3) -> u32

The dot product of two vectors.

length_squared

length_squared(self: UVec3) -> u32

The squared length of the vector.

max

max(self: UVec3, other: UVec3) -> UVec3

The larger of each pair of components.

max_element

max_element(self: UVec3) -> u32

The largest component.

min

min(self: UVec3, other: UVec3) -> UVec3

The smaller of each pair of components.

min_element

min_element(self: UVec3) -> u32

The smallest component.

to_array

to_array(self: UVec3) -> Vec<u32>

The components as a list.

Operators

NameSummary
addAdds a vector or a number to every component.
divDivides component-wise by a vector, or by a number. Errors if any divisor component is 0.
eqWhether all components are equal.
mulMultiplies component-wise by a vector, or scales by a number.
remThe component-wise remainder of dividing by a vector, or by a number. Errors if any divisor component is 0.
subSubtracts a vector or a number from every component.

add

add(self: UVec3, rhs: UVec3 | u32) -> UVec3

Adds a vector or a number to every component.

div

div(self: UVec3, rhs: UVec3 | u32) -> UVec3

Divides component-wise by a vector, or by a number. Errors if any divisor component is 0.

eq

eq(self: UVec3, other: UVec3) -> bool

Whether all components are equal.

mul

mul(self: UVec3, rhs: UVec3 | u32) -> UVec3

Multiplies component-wise by a vector, or scales by a number.

rem

rem(self: UVec3, rhs: UVec3 | u32) -> UVec3

The component-wise remainder of dividing by a vector, or by a number. Errors if any divisor component is 0.

sub

sub(self: UVec3, rhs: UVec3 | u32) -> UVec3

Subtracts a vector or a number from every component.

Vec2

Fields

FieldType
xf32
yf32

Functions

NameSummary
from_angleThe unit vector of the given angle in radians, measured counterclockwise from the x axis.
newCreates a new vector.
oneA vector with all components set to 1.
splatA vector with all components set to v.
unit_xThe unit vector along the x axis.
unit_yThe unit vector along the y axis.
zeroA vector with all components set to 0.

from_angle

from_angle(angle: f32) -> Vec2

The unit vector of the given angle in radians, measured counterclockwise from the x axis.

new

new(x: f32, y: f32) -> Vec2

Creates a new vector.

local Vec2 = import_namespace("math").Vec2
local v = Vec2.new(3, 4)
assert(v:length() == 5)
let Vec2 = import_namespace("math").Vec2;
let v = Vec2.new(3.0, 4.0);
assert!(v.length() == 5.0);

one

one() -> Vec2

A vector with all components set to 1.

splat

splat(v: f32) -> Vec2

A vector with all components set to v.

unit_x

unit_x() -> Vec2

The unit vector along the x axis.

unit_y

unit_y() -> Vec2

The unit vector along the y axis.

zero

zero() -> Vec2

A vector with all components set to 0.

Methods

NameSummary
absThe absolute value of every component.
angle_toThe signed angle in radians to rotate this vector onto other.
as_dvec2Converts to a double precision vector.
as_ivec2Converts to an integer vector, rounding towards zero.
as_uvec2Converts to an unsigned integer vector, rounding towards zero, negative values become 0.
ceilRounds every component up.
clampClamps every component between the components of min and max.
clamp_lengthScales the vector so that its length is between min and max.
clamp_length_maxScales the vector down so that its length is at most max.
distanceThe distance between two points.
distance_squaredThe squared distance between two points.
dotThe dot product of two vectors.
extendA Vec3 with the given z.
floorRounds every component down.
fractThe fractional part of every component, i.e. x - floor(x).
lengthThe length of the vector.
length_squaredThe squared length of the vector, faster than length when comparing lengths.
lerpLinearly interpolates towards other, t = 0 gives this vector and t = 1 gives other.
maxThe larger of each pair of components.
max_elementThe largest component.
minThe smaller of each pair of components.
min_elementThe smallest component.
move_towardsMoves towards target by at most max_distance, without overshooting.
normalizeThe vector scaled to a length of 1. Errors if the vector is zero, or not finite.
normalize_or_zeroThe vector scaled to a length of 1, or zero if that’s not possible.
perpThe vector rotated by 90 degrees counterclockwise.
perp_dotThe 2D cross product, positive if other is counterclockwise from this vector.
project_ontoThe projection of this vector onto other.
rdivDivides a number by every component, for n / v.
reflectReflects this vector off a surface with the given normal, which must be of length 1.
reject_fromThe part of this vector perpendicular to other.
rotateRotates other by the angle of this vector, and scales it by its length.
roundRounds every component to the nearest integer.
rsubSubtracts every component from a number, for n - v.
signumThe sign of every component: 1, -1, or NaN.
to_angleThe angle of this vector in radians, measured counterclockwise from the x axis.
to_arrayThe components as a list.
try_normalizeThe vector scaled to a length of 1, or nil if that’s not possible.

abs

abs(self: Vec2) -> Vec2

The absolute value of every component.

angle_to

angle_to(self: Vec2, other: Vec2) -> f32

The signed angle in radians to rotate this vector onto other.

as_dvec2

as_dvec2(self: Vec2) -> DVec2

Converts to a double precision vector.

as_ivec2

as_ivec2(self: Vec2) -> IVec2

Converts to an integer vector, rounding towards zero.

as_uvec2

as_uvec2(self: Vec2) -> UVec2

Converts to an unsigned integer vector, rounding towards zero, negative values become 0.

ceil

ceil(self: Vec2) -> Vec2

Rounds every component up.

clamp

clamp(self: Vec2, min: Vec2, max: Vec2) -> Vec2

Clamps every component between the components of min and max.

clamp_length

clamp_length(self: Vec2, min: f32, max: f32) -> Vec2

Scales the vector so that its length is between min and max.

clamp_length_max

clamp_length_max(self: Vec2, max: f32) -> Vec2

Scales the vector down so that its length is at most max.

distance

distance(self: Vec2, other: Vec2) -> f32

The distance between two points.

distance_squared

distance_squared(self: Vec2, other: Vec2) -> f32

The squared distance between two points.

dot

dot(self: Vec2, other: Vec2) -> f32

The dot product of two vectors.

extend

extend(self: Vec2, z: f32) -> Vec3

A Vec3 with the given z.

floor

floor(self: Vec2) -> Vec2

Rounds every component down.

fract

fract(self: Vec2) -> Vec2

The fractional part of every component, i.e. x - floor(x).

length

length(self: Vec2) -> f32

The length of the vector.

length_squared

length_squared(self: Vec2) -> f32

The squared length of the vector, faster than length when comparing lengths.

lerp

lerp(self: Vec2, other: Vec2, t: f32) -> Vec2

Linearly interpolates towards other, t = 0 gives this vector and t = 1 gives other.

max

max(self: Vec2, other: Vec2) -> Vec2

The larger of each pair of components.

max_element

max_element(self: Vec2) -> f32

The largest component.

min

min(self: Vec2, other: Vec2) -> Vec2

The smaller of each pair of components.

min_element

min_element(self: Vec2) -> f32

The smallest component.

move_towards

move_towards(self: Vec2, target: Vec2, max_distance: f32) -> Vec2

Moves towards target by at most max_distance, without overshooting.

normalize

normalize(self: Vec2) -> Vec2

The vector scaled to a length of 1. Errors if the vector is zero, or not finite.

normalize_or_zero

normalize_or_zero(self: Vec2) -> Vec2

The vector scaled to a length of 1, or zero if that’s not possible.

perp

perp(self: Vec2) -> Vec2

The vector rotated by 90 degrees counterclockwise.

perp_dot

perp_dot(self: Vec2, other: Vec2) -> f32

The 2D cross product, positive if other is counterclockwise from this vector.

project_onto

project_onto(self: Vec2, other: Vec2) -> Vec2

The projection of this vector onto other.

rdiv

rdiv(self: Vec2, lhs: f32) -> Vec2

Divides a number by every component, for n / v.

reflect

reflect(self: Vec2, normal: Vec2) -> Vec2

Reflects this vector off a surface with the given normal, which must be of length 1.

reject_from

reject_from(self: Vec2, other: Vec2) -> Vec2

The part of this vector perpendicular to other.

rotate

rotate(self: Vec2, other: Vec2) -> Vec2

Rotates other by the angle of this vector, and scales it by its length.

round

round(self: Vec2) -> Vec2

Rounds every component to the nearest integer.

rsub

rsub(self: Vec2, lhs: f32) -> Vec2

Subtracts every component from a number, for n - v.

signum

signum(self: Vec2) -> Vec2

The sign of every component: 1, -1, or NaN.

to_angle

to_angle(self: Vec2) -> f32

The angle of this vector in radians, measured counterclockwise from the x axis.

to_array

to_array(self: Vec2) -> Vec<f32>

The components as a list.

try_normalize

try_normalize(self: Vec2) -> Optional<Vec2>

The vector scaled to a length of 1, or nil if that’s not possible.

Operators

NameSummary
addAdds a vector or a number to every component.
divDivides component-wise by a vector, or by a number.
eqWhether all components are equal.
mulMultiplies component-wise by a vector, or scales by a number.
negNegates every component.
remThe component-wise remainder of dividing by a vector, or by a number.
subSubtracts a vector or a number from every component.

add

add(self: Vec2, rhs: Vec2 | f32) -> Vec2

Adds a vector or a number to every component.

div

div(self: Vec2, rhs: Vec2 | f32) -> Vec2

Divides component-wise by a vector, or by a number.

eq

eq(self: Vec2, other: Vec2) -> bool

Whether all components are equal.

mul

mul(self: Vec2, rhs: Vec2 | f32) -> Vec2

Multiplies component-wise by a vector, or scales by a number.

neg

neg(self: Vec2) -> Vec2

Negates every component.

rem

rem(self: Vec2, rhs: Vec2 | f32) -> Vec2

The component-wise remainder of dividing by a vector, or by a number.

sub

sub(self: Vec2, rhs: Vec2 | f32) -> Vec2

Subtracts a vector or a number from every component.

Vec3

Fields

FieldType
xf32
yf32
zf32

Functions

NameSummary
newCreates a new vector.
oneA vector with all components set to 1.
splatA vector with all components set to v.
unit_xThe unit vector along the x axis.
unit_yThe unit vector along the y axis, which is up in bevy.
unit_zThe unit vector along the z axis.
zeroA vector with all components set to 0.

new

new(x: f32, y: f32, z: f32) -> Vec3

Creates a new vector.

local Vec3 = import_namespace("math").Vec3
local v = Vec3.new(1, 2, 3)
assert(v + v == Vec3.new(2, 4, 6))
let Vec3 = import_namespace("math").Vec3;
let v = Vec3.new(1.0, 2.0, 3.0);
assert!(v + v == Vec3.new(2.0, 4.0, 6.0));

one

one() -> Vec3

A vector with all components set to 1.

splat

splat(v: f32) -> Vec3

A vector with all components set to v.

unit_x

unit_x() -> Vec3

The unit vector along the x axis.

unit_y

unit_y() -> Vec3

The unit vector along the y axis, which is up in bevy.

unit_z

unit_z() -> Vec3

The unit vector along the z axis.

zero

zero() -> Vec3

A vector with all components set to 0.

Methods

NameSummary
absThe absolute value of every component.
angle_betweenThe angle in radians between two vectors, between 0 and pi.
any_orthogonal_vectorSome vector perpendicular to this one.
as_dvec3Converts to a double precision vector.
as_ivec3Converts to an integer vector, rounding towards zero.
as_uvec3Converts to an unsigned integer vector, rounding towards zero, negative values become 0.
ceilRounds every component up.
clampClamps every component between the components of min and max.
clamp_lengthScales the vector so that its length is between min and max.
clamp_length_maxScales the vector down so that its length is at most max.
crossThe cross product, perpendicular to both vectors.
distanceThe distance between two points.
distance_squaredThe squared distance between two points.
dotThe dot product of two vectors.
extendA Vec4 with the given w.
floorRounds every component down.
fractThe fractional part of every component, i.e. x - floor(x).
lengthThe length of the vector.
length_squaredThe squared length of the vector, faster than length when comparing lengths.
lerpLinearly interpolates towards other, t = 0 gives this vector and t = 1 gives other.
maxThe larger of each pair of components.
max_elementThe largest component.
minThe smaller of each pair of components.
min_elementThe smallest component.
move_towardsMoves towards target by at most max_distance, without overshooting.
normalizeThe vector scaled to a length of 1. Errors if the vector is zero, or not finite.
normalize_or_zeroThe vector scaled to a length of 1, or zero if that’s not possible.
project_ontoThe projection of this vector onto other.
rdivDivides a number by every component, for n / v.
reflectReflects this vector off a surface with the given normal, which must be of length 1.
reject_fromThe part of this vector perpendicular to other.
roundRounds every component to the nearest integer.
rsubSubtracts every component from a number, for n - v.
signumThe sign of every component: 1, -1, or NaN.
to_arrayThe components as a list.
to_vec3aConverts to a Vec3A, used by some bevy types such as bounding boxes.
truncateA Vec2 of the x and y components.
try_normalizeThe vector scaled to a length of 1, or nil if that’s not possible.

abs

abs(self: Vec3) -> Vec3

The absolute value of every component.

angle_between

angle_between(self: Vec3, other: Vec3) -> f32

The angle in radians between two vectors, between 0 and pi.

any_orthogonal_vector

any_orthogonal_vector(self: Vec3) -> Vec3

Some vector perpendicular to this one.

as_dvec3

as_dvec3(self: Vec3) -> DVec3

Converts to a double precision vector.

as_ivec3

as_ivec3(self: Vec3) -> IVec3

Converts to an integer vector, rounding towards zero.

as_uvec3

as_uvec3(self: Vec3) -> UVec3

Converts to an unsigned integer vector, rounding towards zero, negative values become 0.

ceil

ceil(self: Vec3) -> Vec3

Rounds every component up.

clamp

clamp(self: Vec3, min: Vec3, max: Vec3) -> Vec3

Clamps every component between the components of min and max.

clamp_length

clamp_length(self: Vec3, min: f32, max: f32) -> Vec3

Scales the vector so that its length is between min and max.

clamp_length_max

clamp_length_max(self: Vec3, max: f32) -> Vec3

Scales the vector down so that its length is at most max.

cross

cross(self: Vec3, other: Vec3) -> Vec3

The cross product, perpendicular to both vectors.

distance

distance(self: Vec3, other: Vec3) -> f32

The distance between two points.

distance_squared

distance_squared(self: Vec3, other: Vec3) -> f32

The squared distance between two points.

dot

dot(self: Vec3, other: Vec3) -> f32

The dot product of two vectors.

extend

extend(self: Vec3, w: f32) -> Vec4

A Vec4 with the given w.

floor

floor(self: Vec3) -> Vec3

Rounds every component down.

fract

fract(self: Vec3) -> Vec3

The fractional part of every component, i.e. x - floor(x).

length

length(self: Vec3) -> f32

The length of the vector.

length_squared

length_squared(self: Vec3) -> f32

The squared length of the vector, faster than length when comparing lengths.

lerp

lerp(self: Vec3, other: Vec3, t: f32) -> Vec3

Linearly interpolates towards other, t = 0 gives this vector and t = 1 gives other.

max

max(self: Vec3, other: Vec3) -> Vec3

The larger of each pair of components.

max_element

max_element(self: Vec3) -> f32

The largest component.

min

min(self: Vec3, other: Vec3) -> Vec3

The smaller of each pair of components.

min_element

min_element(self: Vec3) -> f32

The smallest component.

move_towards

move_towards(self: Vec3, target: Vec3, max_distance: f32) -> Vec3

Moves towards target by at most max_distance, without overshooting.

normalize

normalize(self: Vec3) -> Vec3

The vector scaled to a length of 1. Errors if the vector is zero, or not finite.

normalize_or_zero

normalize_or_zero(self: Vec3) -> Vec3

The vector scaled to a length of 1, or zero if that’s not possible.

project_onto

project_onto(self: Vec3, other: Vec3) -> Vec3

The projection of this vector onto other.

rdiv

rdiv(self: Vec3, lhs: f32) -> Vec3

Divides a number by every component, for n / v.

reflect

reflect(self: Vec3, normal: Vec3) -> Vec3

Reflects this vector off a surface with the given normal, which must be of length 1.

reject_from

reject_from(self: Vec3, other: Vec3) -> Vec3

The part of this vector perpendicular to other.

round

round(self: Vec3) -> Vec3

Rounds every component to the nearest integer.

rsub

rsub(self: Vec3, lhs: f32) -> Vec3

Subtracts every component from a number, for n - v.

signum

signum(self: Vec3) -> Vec3

The sign of every component: 1, -1, or NaN.

to_array

to_array(self: Vec3) -> Vec<f32>

The components as a list.

to_vec3a

to_vec3a(self: Vec3) -> Vec3A

Converts to a Vec3A, used by some bevy types such as bounding boxes.

truncate

truncate(self: Vec3) -> Vec2

A Vec2 of the x and y components.

try_normalize

try_normalize(self: Vec3) -> Optional<Vec3>

The vector scaled to a length of 1, or nil if that’s not possible.

Operators

NameSummary
addAdds a vector or a number to every component.
divDivides component-wise by a vector, or by a number.
eqWhether all components are equal.
mulMultiplies component-wise by a vector, or scales by a number.
negNegates every component.
remThe component-wise remainder of dividing by a vector, or by a number.
subSubtracts a vector or a number from every component.

add

add(self: Vec3, rhs: Vec3 | f32) -> Vec3

Adds a vector or a number to every component.

div

div(self: Vec3, rhs: Vec3 | f32) -> Vec3

Divides component-wise by a vector, or by a number.

eq

eq(self: Vec3, other: Vec3) -> bool

Whether all components are equal.

mul

mul(self: Vec3, rhs: Vec3 | f32) -> Vec3

Multiplies component-wise by a vector, or scales by a number.

neg

neg(self: Vec3) -> Vec3

Negates every component.

rem

rem(self: Vec3, rhs: Vec3 | f32) -> Vec3

The component-wise remainder of dividing by a vector, or by a number.

sub

sub(self: Vec3, rhs: Vec3 | f32) -> Vec3

Subtracts a vector or a number from every component.

Vec3A

Fields

FieldType
xf32
yf32
zf32

Functions

NameSummary
newCreates a new vector.

new

new(x: f32, y: f32, z: f32) -> Vec3A

Creates a new vector.

Methods

NameSummary
to_vec3Converts to a Vec3.

to_vec3

to_vec3(self: Vec3A) -> Vec3

Converts to a Vec3.

Vec4

Fields

FieldType
xf32
yf32
zf32
wf32

Functions

NameSummary
newCreates a new vector.
oneA vector with all components set to 1.
splatA vector with all components set to v.
zeroA vector with all components set to 0.

new

new(x: f32, y: f32, z: f32, w: f32) -> Vec4

Creates a new vector.

one

one() -> Vec4

A vector with all components set to 1.

splat

splat(v: f32) -> Vec4

A vector with all components set to v.

zero

zero() -> Vec4

A vector with all components set to 0.

Methods

NameSummary
absThe absolute value of every component.
ceilRounds every component up.
clampClamps every component between the components of min and max.
clamp_lengthScales the vector so that its length is between min and max.
clamp_length_maxScales the vector down so that its length is at most max.
distanceThe distance between two points.
distance_squaredThe squared distance between two points.
dotThe dot product of two vectors.
floorRounds every component down.
fractThe fractional part of every component, i.e. x - floor(x).
lengthThe length of the vector.
length_squaredThe squared length of the vector, faster than length when comparing lengths.
lerpLinearly interpolates towards other, t = 0 gives this vector and t = 1 gives other.
maxThe larger of each pair of components.
max_elementThe largest component.
minThe smaller of each pair of components.
min_elementThe smallest component.
move_towardsMoves towards target by at most max_distance, without overshooting.
normalizeThe vector scaled to a length of 1. Errors if the vector is zero, or not finite.
normalize_or_zeroThe vector scaled to a length of 1, or zero if that’s not possible.
project_ontoThe projection of this vector onto other.
rdivDivides a number by every component, for n / v.
reflectReflects this vector off a surface with the given normal, which must be of length 1.
reject_fromThe part of this vector perpendicular to other.
roundRounds every component to the nearest integer.
rsubSubtracts every component from a number, for n - v.
signumThe sign of every component: 1, -1, or NaN.
to_arrayThe components as a list.
truncateA Vec3 of the x, y and z components.
try_normalizeThe vector scaled to a length of 1, or nil if that’s not possible.

abs

abs(self: Vec4) -> Vec4

The absolute value of every component.

ceil

ceil(self: Vec4) -> Vec4

Rounds every component up.

clamp

clamp(self: Vec4, min: Vec4, max: Vec4) -> Vec4

Clamps every component between the components of min and max.

clamp_length

clamp_length(self: Vec4, min: f32, max: f32) -> Vec4

Scales the vector so that its length is between min and max.

clamp_length_max

clamp_length_max(self: Vec4, max: f32) -> Vec4

Scales the vector down so that its length is at most max.

distance

distance(self: Vec4, other: Vec4) -> f32

The distance between two points.

distance_squared

distance_squared(self: Vec4, other: Vec4) -> f32

The squared distance between two points.

dot

dot(self: Vec4, other: Vec4) -> f32

The dot product of two vectors.

floor

floor(self: Vec4) -> Vec4

Rounds every component down.

fract

fract(self: Vec4) -> Vec4

The fractional part of every component, i.e. x - floor(x).

length

length(self: Vec4) -> f32

The length of the vector.

length_squared

length_squared(self: Vec4) -> f32

The squared length of the vector, faster than length when comparing lengths.

lerp

lerp(self: Vec4, other: Vec4, t: f32) -> Vec4

Linearly interpolates towards other, t = 0 gives this vector and t = 1 gives other.

max

max(self: Vec4, other: Vec4) -> Vec4

The larger of each pair of components.

max_element

max_element(self: Vec4) -> f32

The largest component.

min

min(self: Vec4, other: Vec4) -> Vec4

The smaller of each pair of components.

min_element

min_element(self: Vec4) -> f32

The smallest component.

move_towards

move_towards(self: Vec4, target: Vec4, max_distance: f32) -> Vec4

Moves towards target by at most max_distance, without overshooting.

normalize

normalize(self: Vec4) -> Vec4

The vector scaled to a length of 1. Errors if the vector is zero, or not finite.

normalize_or_zero

normalize_or_zero(self: Vec4) -> Vec4

The vector scaled to a length of 1, or zero if that’s not possible.

project_onto

project_onto(self: Vec4, other: Vec4) -> Vec4

The projection of this vector onto other.

rdiv

rdiv(self: Vec4, lhs: f32) -> Vec4

Divides a number by every component, for n / v.

reflect

reflect(self: Vec4, normal: Vec4) -> Vec4

Reflects this vector off a surface with the given normal, which must be of length 1.

reject_from

reject_from(self: Vec4, other: Vec4) -> Vec4

The part of this vector perpendicular to other.

round

round(self: Vec4) -> Vec4

Rounds every component to the nearest integer.

rsub

rsub(self: Vec4, lhs: f32) -> Vec4

Subtracts every component from a number, for n - v.

signum

signum(self: Vec4) -> Vec4

The sign of every component: 1, -1, or NaN.

to_array

to_array(self: Vec4) -> Vec<f32>

The components as a list.

truncate

truncate(self: Vec4) -> Vec3

A Vec3 of the x, y and z components.

try_normalize

try_normalize(self: Vec4) -> Optional<Vec4>

The vector scaled to a length of 1, or nil if that’s not possible.

Operators

NameSummary
addAdds a vector or a number to every component.
divDivides component-wise by a vector, or by a number.
eqWhether all components are equal.
mulMultiplies component-wise by a vector, or scales by a number.
negNegates every component.
remThe component-wise remainder of dividing by a vector, or by a number.
subSubtracts a vector or a number from every component.

add

add(self: Vec4, rhs: Vec4 | f32) -> Vec4

Adds a vector or a number to every component.

div

div(self: Vec4, rhs: Vec4 | f32) -> Vec4

Divides component-wise by a vector, or by a number.

eq

eq(self: Vec4, other: Vec4) -> bool

Whether all components are equal.

mul

mul(self: Vec4, rhs: Vec4 | f32) -> Vec4

Multiplies component-wise by a vector, or scales by a number.

neg

neg(self: Vec4) -> Vec4

Negates every component.

rem

rem(self: Vec4, rhs: Vec4 | f32) -> Vec4

The component-wise remainder of dividing by a vector, or by a number.

sub

sub(self: Vec4, rhs: Vec4 | f32) -> Vec4

Subtracts a vector or a number from every component.

petgraph

The types and functions in the petgraph namespace, as returned by import_namespace("petgraph").

Types

DiGraph<Unknown, Unknown, u32>

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<DiGraph<Unknown, Unknown, u32>>) -> DiGraph<Unknown, Unknown, u32>

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

render

The types and functions in the render namespace, as returned by import_namespace("render").

Types

TypeSummary
AlphaModeSets how a material’s base color alpha channel is used for transparency.
ImageAn image, optimized for usage in rendering.
IndicesAn array of indices into the VertexAttributeValues for a mesh.
JointAabb
JointIndex
MeshA 3D object made out of vertices representing triangles, lines, or points, with “attribute” values for each vertex.
MeshAttributeCompressionFlagsIf the corresponding attribute compression is enabled: - Position will be Snorm16x4 relative to the mesh’s AABB.
MeshExtractableData<Indices>
MeshExtractableData<Unknown>
MeshExtractableData<Unknown>
MorphAttributesAttributes differences used for morph targets.
NoBackgroundMotionVectorsWhen added to a camera with MotionVectorPrepass, disables the automatic background motion vector prepass.
OpaqueRendererMethodRender method used for opaque materials.
ParallaxMappingMethodThe parallax mapping method to use to compute depth based on the material’s depth_map.
ReadbackOnceMarker component that pairs with a Readback to indicate the entity should be despawned after the first…
ScreenshotA component that signals to the renderer to capture a screenshot this frame.
ScreenshotCaptured
ShaderBufferA storage buffer that is prepared as a RenderAsset and uploaded to the GPU.
SkinnedMeshBoundsData that can be used to calculate the AABB of a skinned mesh.
SkinnedMeshInverseBindposesNot reflected: scripts can only pass values of it around.
StandardMaterialA material with “standard” properties used in PBR lighting.
TextureAtlasAn index into a TextureAtlasLayout, which corresponds to a specific section of a texture.
UvChannelAn enum to define which UV attribute to use for a texture.

AlphaMode

Sets how a material’s base color alpha channel is used for transparency.

Variants

VariantFields
Opaque
Mask(f32)
Blend
Premultiplied
AlphaToCoverage
Add
Multiply

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<AlphaMode>) -> AlphaMode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Add.new

new(variant: EnumVariantRef, payload: Fields<AlphaMode::Add>) -> AlphaMode

AlphaToCoverage.new

new(variant: EnumVariantRef, payload: Fields<AlphaMode::AlphaToCoverage>) -> AlphaMode

Blend.new

new(variant: EnumVariantRef, payload: Fields<AlphaMode::Blend>) -> AlphaMode

Mask.new

new(variant: EnumVariantRef, payload: Fields<AlphaMode::Mask>) -> AlphaMode

Multiply.new

new(variant: EnumVariantRef, payload: Fields<AlphaMode::Multiply>) -> AlphaMode

Opaque.new

new(variant: EnumVariantRef, payload: Fields<AlphaMode::Opaque>) -> AlphaMode

Premultiplied.new

new(variant: EnumVariantRef, payload: Fields<AlphaMode::Premultiplied>) -> AlphaMode

Image

Asset

An image, optimized for usage in rendering.

Remote Inspection

To transmit an Image between two running Bevy apps, e.g. through BRP, use SerializedImage, which requires the serialize feature. This type is only meant for short-term transmission between same versions and should not be stored anywhere.

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
add_assetAdds a value of this type as a new asset, returning a strong handle to it.
get_assetThe asset a handle points to, or nil if it isn’t loaded or added yet.
loadStarts loading an asset of this type from a path, returning a handle to it right away.
newConstructs a new instance of the type from a table of its fields.

add_asset

add_asset(value: Image) -> Handle<Image>

Adds a value of this type as a new asset, returning a strong handle to it.

Arguments

  • value: The asset value.

Returns: A handle to the new asset.

get_asset

get_asset(handle: Handle<Image>) -> Optional<Image>

The asset a handle points to, or nil if it isn’t loaded or added yet.

Changes to the returned value change the asset.

Arguments

  • handle: The handle to the asset.

Returns: The asset, or nil.

load

load(path: String) -> Handle<Image>

Starts loading an asset of this type from a path, returning a handle to it right away.

Arguments

  • path: The asset path, relative to the assets folder.

Returns: A handle to the asset, which is loaded in the background.

new

new(payload: Fields<Image>) -> Image

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
heightThe height of the image in pixels.
sizeThe size of the image in pixels.
size_f32The size of the image in pixels, as decimal numbers.
widthThe width of the image in pixels.

height

height(self: Image) -> u32

The height of the image in pixels.

size

size(self: Image) -> UVec2

The size of the image in pixels.

size_f32

size_f32(self: Image) -> Vec2

The size of the image in pixels, as decimal numbers.

width

width(self: Image) -> u32

The width of the image in pixels.

Indices

An array of indices into the VertexAttributeValues for a mesh.

It describes the order in which the vertex attributes should be joined into faces.

Variants

VariantFields
U16(Vec<u16>)
U32(Vec<u32>)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Indices>) -> Indices

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

NameSummary
U16.new
U32.new

U16.new

new(variant: EnumVariantRef, payload: Fields<Indices::U16>) -> Indices

U32.new

new(variant: EnumVariantRef, payload: Fields<Indices::U32>) -> Indices

JointAabb

Fields

FieldType
centerVec3
half_sizeVec3

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<JointAabb>) -> JointAabb

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

JointIndex

Fields

IndexType
0u16

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<JointIndex>) -> JointIndex

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Mesh

Asset

A 3D object made out of vertices representing triangles, lines, or points, with “attribute” values for each vertex.

Meshes can be automatically generated by a bevy AssetLoader (generally by loading a Gltf file), or by converting a primitive using into. It is also possible to create one manually. They can be edited after creation.

Meshes can be rendered with a Mesh2d and MeshMaterial2d or Mesh3d and MeshMaterial3d for 2D and 3D respectively.

A Mesh in Bevy is equivalent to a “primitive” in the glTF format, for a glTF Mesh representation, see GltfMesh.

Manual creation

The following function will construct a flat mesh, to be rendered with a StandardMaterial or ColorMaterial:

fn create_simple_parallelogram() -> Mesh {
    // Create a new mesh using a triangle list topology, where each set of 3 vertices composes a triangle.
    Mesh::new(PrimitiveTopology::TriangleList, RenderAssetUsages::default())
        // Add 4 vertices, each with its own position attribute (coordinate in
        // 3D space), for each of the corners of the parallelogram.
        .with_inserted_attribute(
            Mesh::ATTRIBUTE_POSITION,
            vec![[0.0, 0.0, 0.0], [1.0, 2.0, 0.0], [2.0, 2.0, 0.0], [1.0, 0.0, 0.0]]
        )
        // Assign a UV coordinate to each vertex.
        .with_inserted_attribute(
            Mesh::ATTRIBUTE_UV_0,
            vec![[0.0, 1.0], [0.5, 0.0], [1.0, 0.0], [0.5, 1.0]]
        )
        // Assign normals (everything points outwards)
        .with_inserted_attribute(
            Mesh::ATTRIBUTE_NORMAL,
            vec![[0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]]
        )
        // After defining all the vertices and their attributes, build each triangle using the
        // indices of the vertices that make it up in a counter-clockwise order.
        .with_inserted_indices(Indices::U32(vec![
            // First triangle
            0, 3, 1,
            // Second triangle
            1, 3, 2
        ]))
}

You can see how it looks like here, used in a Mesh3d with a square bevy logo texture, with added axis, points, lines and text for clarity.

Other examples

For further visualization, explanation, and examples, see the built-in Bevy examples, and the implementation of the built-in shapes. In particular, generate_custom_mesh teaches you to access and modify the attributes of a Mesh after creating it.

Common points of confusion

  • UV maps in Bevy start at the top-left, see ATTRIBUTE_UV_0, other APIs can have other conventions, OpenGL starts at bottom-left.
  • It is possible and sometimes useful for multiple vertices to have the same position attribute value, it’s a common technique in 3D modeling for complex UV mapping or other calculations.
  • Bevy performs frustum culling based on the Aabb of meshes, which is calculated and added automatically for new meshes only. If a mesh is modified, the entity’s Aabb needs to be updated manually or deleted so that it is re-calculated.

Use with StandardMaterial

To render correctly with StandardMaterial, a mesh needs to have properly defined:

  • UVs: Bevy needs to know how to map a texture onto the mesh (also true for ColorMaterial).
  • Normals: Bevy needs to know how light interacts with your mesh. 0.0, 0.0, 1.0 is very common for simple flat meshes on the XY plane, because simple meshes are smooth and they don’t require complex light calculations.
  • Vertex winding order: by default, StandardMaterial.cull_mode is Some(Face::Back), which means that Bevy would only render the “front” of each triangle, which is the side of the triangle from where the vertices appear in a counter-clockwise order.

Remote Inspection

To transmit a Mesh between two running Bevy apps, e.g. through BRP, use SerializedMesh. This type is only meant for short-term transmission between same versions and should not be stored anywhere.

Fields

FieldType
indicesMeshExtractableData<Indices>
morph_targetsMeshExtractableData<Unknown>
morph_target_namesMeshExtractableData<Unknown>
asset_usageRenderAssetUsages
enable_raytracingbool
attribute_compressionMeshAttributeCompressionFlags
final_aabbOptional<Aabb3d>
final_uv_ranges[Optional<Aabb2d>; 2]
skinned_mesh_boundsOptional<SkinnedMeshBounds>

Functions

NameSummary
add_assetAdds a value of this type as a new asset, returning a strong handle to it.
from_shapeA mesh for a shape such as a cuboid or a sphere. Errors if the value is not a shape.
get_assetThe asset a handle points to, or nil if it isn’t loaded or added yet.
loadStarts loading an asset of this type from a path, returning a handle to it right away.
newConstructs a new instance of the type from a table of its fields.

add_asset

add_asset(value: Mesh) -> Handle<Mesh>

Adds a value of this type as a new asset, returning a strong handle to it.

Arguments

  • value: The asset value.

Returns: A handle to the new asset.

from_shape

A mesh for a shape such as a cuboid or a sphere. Errors if the value is not a shape.

get_asset

get_asset(handle: Handle<Mesh>) -> Optional<Mesh>

The asset a handle points to, or nil if it isn’t loaded or added yet.

Changes to the returned value change the asset.

Arguments

  • handle: The handle to the asset.

Returns: The asset, or nil.

load

load(path: String) -> Handle<Mesh>

Starts loading an asset of this type from a path, returning a handle to it right away.

Arguments

  • path: The asset path, relative to the assets folder.

Returns: A handle to the asset, which is loaded in the background.

new

new(payload: Fields<Mesh>) -> Mesh

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
count_verticesThe number of vertices in the mesh.

count_vertices

count_vertices(self: Mesh) -> usize

The number of vertices in the mesh.

MeshAttributeCompressionFlags

If the corresponding attribute compression is enabled:

  • Position will be Snorm16x4 relative to the mesh’s AABB. The w component is unused.
  • Normal and tangent will be Snorm16x2 with octahedral encoding, using octahedral_encode_signed and octahedral_encode_tangent.
  • UV0 and UV1 will be Unorm16x2. UVs are remapped based on their min/max values so they can go beyond 0, 1, though a larger range will reduce precision.

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

MeshExtractableData<Indices>

Variants

VariantFields
Data(Indices)
NoData
ExtractedToRenderWorld

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<MeshExtractableData<Indices>>) -> MeshExtractableData<Indices>

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Data.new

new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Indices>::Data>) -> MeshExtractableData<Indices>

ExtractedToRenderWorld.new

new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Indices>::ExtractedToRenderWorld>) -> MeshExtractableData<Indices>

NoData.new

new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Indices>::NoData>) -> MeshExtractableData<Indices>

MeshExtractableData<Unknown>

Variants

VariantFields
Data(Vec<String>)
NoData
ExtractedToRenderWorld

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<MeshExtractableData<Unknown>>) -> MeshExtractableData<Unknown>

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Data.new

new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Unknown>::Data>) -> MeshExtractableData<Unknown>

ExtractedToRenderWorld.new

new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Unknown>::ExtractedToRenderWorld>) -> MeshExtractableData<Unknown>

NoData.new

new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Unknown>::NoData>) -> MeshExtractableData<Unknown>

MeshExtractableData<Unknown>

Variants

VariantFields
Data(Vec<MorphAttributes>)
NoData
ExtractedToRenderWorld

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<MeshExtractableData<Unknown>>) -> MeshExtractableData<Unknown>

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Data.new

new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Unknown>::Data>) -> MeshExtractableData<Unknown>

ExtractedToRenderWorld.new

new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Unknown>::ExtractedToRenderWorld>) -> MeshExtractableData<Unknown>

NoData.new

new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Unknown>::NoData>) -> MeshExtractableData<Unknown>

MorphAttributes

Attributes differences used for morph targets.

Fields

FieldType
positionVec3
pad_af32
normalVec3
pad_bf32
tangentVec3
pad_cf32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<MorphAttributes>) -> MorphAttributes

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

NoBackgroundMotionVectors

Component

When added to a camera with MotionVectorPrepass, disables the automatic background motion vector prepass.

By default, any camera with MotionVectorPrepass will automatically write camera-rotation motion vectors for background pixels (those with no geometry, i.e. depth == 0 in reversed-Z). Add this component to opt out, for example if you are writing custom background motion vectors for your own effect.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

OpaqueRendererMethod

Render method used for opaque materials.

The forward rendering main pass draws each mesh entity and shades it according to its corresponding material and the lights that affect it. Some render features like Screen Space Ambient Occlusion require running depth and normal prepasses, that are ‘deferred’-like prepasses over all mesh entities to populate depth and normal textures. This means that when using render features that require running prepasses, multiple passes over all visible geometry are required. This can be slow if there is a lot of geometry that cannot be batched into few draws.

Deferred rendering runs a prepass to gather not only geometric information like depth and normals, but also all the material properties like base color, emissive color, reflectance, metalness, etc, and writes them into a deferred ‘g-buffer’ texture. The deferred main pass is then a fullscreen pass that reads data from these textures and executes shading. This allows for one pass over geometry, but is at the cost of not being able to use MSAA, and has heavier bandwidth usage which can be unsuitable for low end mobile or other bandwidth-constrained devices.

If a material indicates OpaqueRendererMethod::Auto, DefaultOpaqueRendererMethod will be used.

Variants

Variant
Forward
Deferred
Auto

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<OpaqueRendererMethod>) -> OpaqueRendererMethod

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Auto.new

new(variant: EnumVariantRef, payload: Fields<OpaqueRendererMethod::Auto>) -> OpaqueRendererMethod

Deferred.new

new(variant: EnumVariantRef, payload: Fields<OpaqueRendererMethod::Deferred>) -> OpaqueRendererMethod

Forward.new

new(variant: EnumVariantRef, payload: Fields<OpaqueRendererMethod::Forward>) -> OpaqueRendererMethod

ParallaxMappingMethod

The parallax mapping method to use to compute depth based on the material’s depth_map.

Parallax Mapping uses a depth map texture to give the illusion of depth variation on a mesh surface that is geometrically flat.

See the parallax_mapping.wesl shader code for implementation details and explanation of the methods used.

Variants

VariantFields
Occlusion
Relief{ max_steps: u32 }

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ParallaxMappingMethod>) -> ParallaxMappingMethod

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Occlusion.new

new(variant: EnumVariantRef, payload: Fields<ParallaxMappingMethod::Occlusion>) -> ParallaxMappingMethod

Relief.new

new(variant: EnumVariantRef, payload: Fields<ParallaxMappingMethod::Relief>) -> ParallaxMappingMethod

ReadbackOnce

Marker component that pairs with a Readback to indicate the entity should be despawned after the first ReadbackComplete event fires for it.

commands.spawn(ReadbackOnce::buffer(handle));

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ReadbackOnce>) -> ReadbackOnce

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Screenshot

Component

A component that signals to the renderer to capture a screenshot this frame.

This component should be spawned on a new entity with an observer that will trigger with ScreenshotCaptured when the screenshot is ready.

Screenshots are captured asynchronously and may not be available immediately after the frame that the component is spawned on. The observer should be used to handle the screenshot when it is ready.

Note that the screenshot entity will be despawned after the screenshot is captured and the observer is triggered.

Usage


fn take_screenshot(mut commands: Commands) {
   commands.spawn(Screenshot::primary_window())
      .observe(save_to_disk("screenshot.png"));
}

Fields

IndexType
0RenderTarget

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Screenshot>) -> Screenshot

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ScreenshotCaptured

Fields

FieldType
entityEntity
imageImage

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ScreenshotCaptured>) -> ScreenshotCaptured

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ShaderBuffer

Asset

A storage buffer that is prepared as a RenderAsset and uploaded to the GPU.

This buffer primarily exists in order to be embedded into a material that implements the bevy_render_macros::AsBindGroup trait. Compared to embedding a raw Buffer, ShaderBuffer has the advantage that the buffer can be resized without regenerating the materials that embed it.

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
add_assetAdds a value of this type as a new asset, returning a strong handle to it.
get_assetThe asset a handle points to, or nil if it isn’t loaded or added yet.
loadStarts loading an asset of this type from a path, returning a handle to it right away.
newConstructs a new instance of the type from a table of its fields.

add_asset

add_asset(value: ShaderBuffer) -> Handle<ShaderBuffer>

Adds a value of this type as a new asset, returning a strong handle to it.

Arguments

  • value: The asset value.

Returns: A handle to the new asset.

get_asset

get_asset(handle: Handle<ShaderBuffer>) -> Optional<ShaderBuffer>

The asset a handle points to, or nil if it isn’t loaded or added yet.

Changes to the returned value change the asset.

Arguments

  • handle: The handle to the asset.

Returns: The asset, or nil.

load

load(path: String) -> Handle<ShaderBuffer>

Starts loading an asset of this type from a path, returning a handle to it right away.

Arguments

  • path: The asset path, relative to the assets folder.

Returns: A handle to the asset, which is loaded in the background.

new

new(payload: Fields<ShaderBuffer>) -> ShaderBuffer

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

SkinnedMeshBounds

Data that can be used to calculate the AABB of a skinned mesh.

Fields

FieldType
aabbsVec<JointAabb>
aabb_index_to_joint_indexVec<JointIndex>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<SkinnedMeshBounds>) -> SkinnedMeshBounds

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

SkinnedMeshInverseBindposes

Not reflected: scripts can only pass values of it around.

Opaque: scripts can't access its fields, only its functions.

StandardMaterial

A material with “standard” properties used in PBR lighting. Standard property values with pictures here: https://google.github.io/filament/notes/material_properties.html.

May be created directly from a Color or an Image.

The StandardMaterial can be extended with more data and custom shaders using ExtendedMaterial. Examples of how to do this can be found in the Bevy examples.

Fields

FieldType
base_colorColor
base_color_channelUvChannel
base_color_textureOptional<Handle<Image>>
emissiveLinearRgba
emissive_exposure_weightf32
emissive_channelUvChannel
emissive_textureOptional<Handle<Image>>
perceptual_roughnessf32
metallicf32
metallic_roughness_channelUvChannel
metallic_roughness_textureOptional<Handle<Image>>
reflectancef32
specular_tintColor
diffuse_transmissionf32
specular_transmissionf32
thicknessf32
iorf32
attenuation_distancef32
attenuation_colorColor
normal_map_channelUvChannel
normal_map_textureOptional<Handle<Image>>
flip_normal_map_ybool
occlusion_channelUvChannel
occlusion_textureOptional<Handle<Image>>
clearcoatf32
clearcoat_perceptual_roughnessf32
anisotropy_strengthf32
anisotropy_rotationf32
double_sidedbool
unlitbool
fog_enabledbool
alpha_modeAlphaMode
depth_biasf32
depth_mapOptional<Handle<Image>>
parallax_depth_scalef32
parallax_mapping_methodParallaxMappingMethod
max_parallax_layer_countf32
lightmap_exposuref32
opaque_render_methodOpaqueRendererMethod
deferred_lighting_pass_idu8
uv_transformAffine2

Functions

NameSummary
from_colorA material with the given color as its base color and default settings for everything else.
newConstructs a new instance of the type from a table of its fields.

from_color

from_color(color: Color) -> StandardMaterial

A material with the given color as its base color and default settings for everything else.

new

new(payload: Fields<StandardMaterial>) -> StandardMaterial

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

TextureAtlas

An index into a TextureAtlasLayout, which corresponds to a specific section of a texture.

It stores a handle to TextureAtlasLayout and the index of the current section of the atlas. The texture atlas contains various sections of a given texture, allowing users to have a single image file for either sprite animation or global mapping. You can change the texture index of the atlas to animate the sprite or display only a section of the texture for efficient rendering of related game objects.

Check the following examples for usage:

Fields

FieldType
layoutHandle<TextureAtlasLayout>
indexusize

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<TextureAtlas>) -> TextureAtlas

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

UvChannel

An enum to define which UV attribute to use for a texture.

It only supports two UV attributes, Mesh::ATTRIBUTE_UV_0 and Mesh::ATTRIBUTE_UV_1. The default is UvChannel::Uv0.

Variants

Variant
Uv0
Uv1

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<UvChannel>) -> UvChannel

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

NameSummary
Uv0.new
Uv1.new

Uv0.new

new(variant: EnumVariantRef, payload: Fields<UvChannel::Uv0>) -> UvChannel

Uv1.new

new(variant: EnumVariantRef, payload: Fields<UvChannel::Uv1>) -> UvChannel

smol_str

The types and functions in the smol_str namespace, as returned by import_namespace("smol_str").

Types

TypeSummary
SmolStr

SmolStr

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<SmolStr>) -> SmolStr

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

sprite

The types and functions in the sprite namespace, as returned by import_namespace("sprite").

Types

TypeSummary
AlphaMode2dSets how a 2d material’s base color alpha channel is used for transparency.
AnchorNormalized (relative to its size) offset of a 2d renderable entity from its Transform.
BorderRectDefines border insets that shrink a rectangle from its minimum and maximum corners.
ColorMaterialA 2d material that renders 2d meshes with a texture tinted by a uniform color
MeshMaterial2d<ColorMaterial>A material used for rendering a Mesh2d.
MeshMaterial2d<SpriteMeshMaterial>A material used for rendering a Mesh2d.
SliceScaleModeDefines how a texture slice scales when resized
SpriteDescribes a sprite to be rendered to a 2D camera
SpriteAlphaModeAn enum describing how a sprite’s alpha channel will be handled.
SpriteImageModeControls how the image is altered when scaled.
SpriteMeshMaterial
SpriteScalingModeRepresents various modes for proportional scaling of a texture.
TextureAtlasLayoutStores a map used to lookup the position of a texture in a TextureAtlas.
TextureSlicerSlices a texture using the 9-slicing technique.
TilemapChunkMaterialNot reflected: scripts can only pass values of it around.

AlphaMode2d

Sets how a 2d material’s base color alpha channel is used for transparency. Currently, this only works with Mesh2d. Sprites are always transparent.

This is very similar to AlphaMode but this only applies to 2d meshes. We use a separate type because 2d doesn’t support all the transparency modes that 3d does.

Variants

VariantFields
Opaque
Mask(f32)
Blend

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<AlphaMode2d>) -> AlphaMode2d

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Blend.new

new(variant: EnumVariantRef, payload: Fields<AlphaMode2d::Blend>) -> AlphaMode2d

Mask.new

new(variant: EnumVariantRef, payload: Fields<AlphaMode2d::Mask>) -> AlphaMode2d

Opaque.new

new(variant: EnumVariantRef, payload: Fields<AlphaMode2d::Opaque>) -> AlphaMode2d

Anchor

Component

Normalized (relative to its size) offset of a 2d renderable entity from its Transform.

Fields

IndexType
0Vec2

Functions

NameSummary
bottom_centerThe anchor in the middle of the bottom edge.
bottom_leftThe anchor in the bottom left corner.
bottom_rightThe anchor in the bottom right corner.
centerThe anchor in the middle of the sprite.
center_leftThe anchor in the middle of the left edge.
center_rightThe anchor in the middle of the right edge.
newConstructs a new instance of the type from a table of its fields.
top_centerThe anchor in the middle of the top edge.
top_leftThe anchor in the top left corner.
top_rightThe anchor in the top right corner.

bottom_center

bottom_center() -> Anchor

The anchor in the middle of the bottom edge.

bottom_left

bottom_left() -> Anchor

The anchor in the bottom left corner.

bottom_right

bottom_right() -> Anchor

The anchor in the bottom right corner.

center

center() -> Anchor

The anchor in the middle of the sprite.

center_left

center_left() -> Anchor

The anchor in the middle of the left edge.

center_right

center_right() -> Anchor

The anchor in the middle of the right edge.

new

new(payload: Fields<Anchor>) -> Anchor

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

top_center

top_center() -> Anchor

The anchor in the middle of the top edge.

top_left

top_left() -> Anchor

The anchor in the top left corner.

top_right

top_right() -> Anchor

The anchor in the top right corner.

Methods

NameSummary
as_vecThe offset of the anchor from the center, as a fraction of the sprite size.

as_vec

as_vec(self: Anchor) -> Vec2

The offset of the anchor from the center, as a fraction of the sprite size.

BorderRect

Defines border insets that shrink a rectangle from its minimum and maximum corners.

This struct is used to represent thickness or offsets from the four edges of a rectangle, with values increasing inwards.

Fields

FieldType
min_insetVec2
max_insetVec2

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<BorderRect>) -> BorderRect

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ColorMaterial

Asset

A 2d material that renders 2d meshes with a texture tinted by a uniform color

Fields

FieldType
colorColor
alpha_modeAlphaMode2d
uv_transformAffine2
textureOptional<Handle<Image>>

Functions

NameSummary
add_assetAdds a value of this type as a new asset, returning a strong handle to it.
get_assetThe asset a handle points to, or nil if it isn’t loaded or added yet.
loadStarts loading an asset of this type from a path, returning a handle to it right away.
newConstructs a new instance of the type from a table of its fields.

add_asset

add_asset(value: ColorMaterial) -> Handle<ColorMaterial>

Adds a value of this type as a new asset, returning a strong handle to it.

Arguments

  • value: The asset value.

Returns: A handle to the new asset.

get_asset

get_asset(handle: Handle<ColorMaterial>) -> Optional<ColorMaterial>

The asset a handle points to, or nil if it isn’t loaded or added yet.

Changes to the returned value change the asset.

Arguments

  • handle: The handle to the asset.

Returns: The asset, or nil.

load

load(path: String) -> Handle<ColorMaterial>

Starts loading an asset of this type from a path, returning a handle to it right away.

Arguments

  • path: The asset path, relative to the assets folder.

Returns: A handle to the asset, which is loaded in the background.

new

new(payload: Fields<ColorMaterial>) -> ColorMaterial

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

MeshMaterial2d<ColorMaterial>

Component

A material used for rendering a Mesh2d.

See Material2d for general information about 2D materials and how to implement your own materials.

Example

// Spawn an entity with a mesh using `ColorMaterial`.
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<ColorMaterial>>,
) {
    commands.spawn((
        Mesh2d(meshes.add(Circle::new(50.0))),
        MeshMaterial2d(materials.add(ColorMaterial::from_color(RED))),
    ));
}

Fields

IndexType
0Handle<ColorMaterial>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<MeshMaterial2d<ColorMaterial>>) -> MeshMaterial2d<ColorMaterial>

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

MeshMaterial2d<SpriteMeshMaterial>

Component

A material used for rendering a Mesh2d.

See Material2d for general information about 2D materials and how to implement your own materials.

Example

// Spawn an entity with a mesh using `ColorMaterial`.
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<ColorMaterial>>,
) {
    commands.spawn((
        Mesh2d(meshes.add(Circle::new(50.0))),
        MeshMaterial2d(materials.add(ColorMaterial::from_color(RED))),
    ));
}

Fields

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<MeshMaterial2d<SpriteMeshMaterial>>) -> MeshMaterial2d<SpriteMeshMaterial>

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

SliceScaleMode

Defines how a texture slice scales when resized

Variants

VariantFields
Stretch
Tile{ stretch_value: f32 }

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<SliceScaleMode>) -> SliceScaleMode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

NameSummary
Stretch.new
Tile.new

Stretch.new

new(variant: EnumVariantRef, payload: Fields<SliceScaleMode::Stretch>) -> SliceScaleMode

Tile.new

new(variant: EnumVariantRef, payload: Fields<SliceScaleMode::Tile>) -> SliceScaleMode

Sprite

Component

Describes a sprite to be rendered to a 2D camera

Fields

FieldType
imageHandle<Image>
texture_atlasOptional<TextureAtlas>
colorColor
flip_xbool
flip_ybool
custom_sizeOptional<Vec2>
rectOptional<Rect>
image_modeSpriteImageMode
alpha_modeSpriteAlphaMode

Functions

NameSummary
from_atlas_imageA sprite that shows a section of an image from a texture atlas.
from_colorA solid square of the given color and size.
from_imageA sprite that shows the whole image.
newConstructs a new instance of the type from a table of its fields.
sizedA sprite with no image that is drawn at the given size.

from_atlas_image

from_atlas_image(image: Handle<Image>, atlas: TextureAtlas) -> Sprite

A sprite that shows a section of an image from a texture atlas.

from_color

from_color(color: Color, size: Vec2) -> Sprite

A solid square of the given color and size.

from_image

from_image(image: Handle<Image>) -> Sprite

A sprite that shows the whole image.

new

new(payload: Fields<Sprite>) -> Sprite

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

sized

sized(size: Vec2) -> Sprite

A sprite with no image that is drawn at the given size.

SpriteAlphaMode

An enum describing how a sprite’s alpha channel will be handled. The base color being modified is that of the texture after tinting. The default is Blend.

Variants

VariantFields
Opaque
Mask(f32)
Blend

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<SpriteAlphaMode>) -> SpriteAlphaMode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Blend.new

new(variant: EnumVariantRef, payload: Fields<SpriteAlphaMode::Blend>) -> SpriteAlphaMode

Mask.new

new(variant: EnumVariantRef, payload: Fields<SpriteAlphaMode::Mask>) -> SpriteAlphaMode

Opaque.new

new(variant: EnumVariantRef, payload: Fields<SpriteAlphaMode::Opaque>) -> SpriteAlphaMode

SpriteImageMode

Controls how the image is altered when scaled.

Variants

VariantFields
Auto
Scale(SpriteScalingMode)
Sliced(TextureSlicer)
Tiled{ tile_x: bool, tile_y: bool, stretch_value: f32 }

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<SpriteImageMode>) -> SpriteImageMode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Auto.new

new(variant: EnumVariantRef, payload: Fields<SpriteImageMode::Auto>) -> SpriteImageMode

Scale.new

new(variant: EnumVariantRef, payload: Fields<SpriteImageMode::Scale>) -> SpriteImageMode

Sliced.new

new(variant: EnumVariantRef, payload: Fields<SpriteImageMode::Sliced>) -> SpriteImageMode

Tiled.new

new(variant: EnumVariantRef, payload: Fields<SpriteImageMode::Tiled>) -> SpriteImageMode

SpriteMeshMaterial

Asset

Fields

FieldType
imageHandle<Image>
texture_atlasOptional<TextureAtlas>
colorColor
flip_xbool
flip_ybool
custom_sizeOptional<Vec2>
rectOptional<Rect>
image_modeSpriteImageMode
alpha_modeAlphaMode2d
anchorVec2
texture_atlas_layoutOptional<TextureAtlasLayout>
texture_atlas_indexusize

Functions

NameSummary
add_assetAdds a value of this type as a new asset, returning a strong handle to it.
get_assetThe asset a handle points to, or nil if it isn’t loaded or added yet.
loadStarts loading an asset of this type from a path, returning a handle to it right away.
newConstructs a new instance of the type from a table of its fields.

add_asset

Adds a value of this type as a new asset, returning a strong handle to it.

Arguments

  • value: The asset value.

Returns: A handle to the new asset.

get_asset

get_asset(handle: Handle<SpriteMeshMaterial>) -> Optional<SpriteMeshMaterial>

The asset a handle points to, or nil if it isn’t loaded or added yet.

Changes to the returned value change the asset.

Arguments

  • handle: The handle to the asset.

Returns: The asset, or nil.

load

load(path: String) -> Handle<SpriteMeshMaterial>

Starts loading an asset of this type from a path, returning a handle to it right away.

Arguments

  • path: The asset path, relative to the assets folder.

Returns: A handle to the asset, which is loaded in the background.

new

new(payload: Fields<SpriteMeshMaterial>) -> SpriteMeshMaterial

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

SpriteScalingMode

Represents various modes for proportional scaling of a texture.

Can be used in SpriteImageMode::Scale.

Variants

Variant
FillCenter
FillStart
FillEnd
FitCenter
FitStart
FitEnd

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<SpriteScalingMode>) -> SpriteScalingMode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

FillCenter.new

new(variant: EnumVariantRef, payload: Fields<SpriteScalingMode::FillCenter>) -> SpriteScalingMode

FillEnd.new

new(variant: EnumVariantRef, payload: Fields<SpriteScalingMode::FillEnd>) -> SpriteScalingMode

FillStart.new

new(variant: EnumVariantRef, payload: Fields<SpriteScalingMode::FillStart>) -> SpriteScalingMode

FitCenter.new

new(variant: EnumVariantRef, payload: Fields<SpriteScalingMode::FitCenter>) -> SpriteScalingMode

FitEnd.new

new(variant: EnumVariantRef, payload: Fields<SpriteScalingMode::FitEnd>) -> SpriteScalingMode

FitStart.new

new(variant: EnumVariantRef, payload: Fields<SpriteScalingMode::FitStart>) -> SpriteScalingMode

TextureAtlasLayout

Asset

Stores a map used to lookup the position of a texture in a TextureAtlas. This can be used to either use and look up a specific section of a texture, or animate frame-by-frame as a sprite sheet.

Optionally it can store a mapping from sub texture handles to the related area index (see TextureAtlasBuilder).

Example usage animating sprite. Example usage animating sprite in response to an event. Example usage loading sprite sheet.

Fields

FieldType
sizeUVec2
texturesVec<URect>

Functions

NameSummary
add_assetAdds a value of this type as a new asset, returning a strong handle to it.
from_gridA layout of equal tiles in a grid, numbered left to right and then top to bottom.
get_assetThe asset a handle points to, or nil if it isn’t loaded or added yet.
loadStarts loading an asset of this type from a path, returning a handle to it right away.
newConstructs a new instance of the type from a table of its fields.

add_asset

Adds a value of this type as a new asset, returning a strong handle to it.

Arguments

  • value: The asset value.

Returns: A handle to the new asset.

from_grid

from_grid(tile_size: UVec2, columns: u32, rows: u32, padding: Optional<UVec2>, offset: Optional<UVec2>) -> TextureAtlasLayout

A layout of equal tiles in a grid, numbered left to right and then top to bottom. Padding and offset are in pixels, and default to none.

get_asset

get_asset(handle: Handle<TextureAtlasLayout>) -> Optional<TextureAtlasLayout>

The asset a handle points to, or nil if it isn’t loaded or added yet.

Changes to the returned value change the asset.

Arguments

  • handle: The handle to the asset.

Returns: The asset, or nil.

load

load(path: String) -> Handle<TextureAtlasLayout>

Starts loading an asset of this type from a path, returning a handle to it right away.

Arguments

  • path: The asset path, relative to the assets folder.

Returns: A handle to the asset, which is loaded in the background.

new

new(payload: Fields<TextureAtlasLayout>) -> TextureAtlasLayout

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Operators

NameSummary
lenThe number of tiles in the layout.

len

len(self: TextureAtlasLayout) -> usize

The number of tiles in the layout.

TextureSlicer

Slices a texture using the 9-slicing technique. This allows to reuse an image at various sizes without needing to prepare multiple assets. The associated texture will be split into nine portions, so that on resize the different portions scale or tile in different ways to keep the texture in proportion.

For example, when resizing a 9-sliced texture the corners will remain unscaled while the other sections will be scaled or tiled.

See 9-sliced textures.

Fields

FieldType
borderBorderRect
center_scale_modeSliceScaleMode
sides_scale_modeSliceScaleMode
max_corner_scalef32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<TextureSlicer>) -> TextureSlicer

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

TilemapChunkMaterial

Not reflected: scripts can only pass values of it around.

Opaque: scripts can't access its fields, only its functions.

text

The types and functions in the text namespace, as returned by import_namespace("text").

Types

TypeSummary
EmSizeThe font size, in logical pixels, used to resolve Val::Em values in a UI node.
FontNot reflected: scripts can only pass values of it around.
FontFeaturesOpenType features for .otf fonts that support them.
FontFeatureTagAn OpenType font feature tag.
FontSizeThe vertical height of rasterized glyphs in the font atlas in pixels.
FontSmoothingDetermines which antialiasing method to use when rendering text.
FontSourceDetermines how the font face for a text sections is selected.
FontStyleThe slant style of a font face: normal, italic, or oblique.
FontVariationsOpenType font variations for variable fonts that support them.
FontVariationTagAn OpenType font variation tag.
FontWeightHow thick or bold the strokes of a font appear.
FontWidthThe visual width of a font as a ratio of its normal width, typically 0.5 to 2.0.
GenericFontFamilyGeneric font families that are resolved through Parley’s font database.
JustifyDescribes the horizontal alignment of multiple lines of text relative to each other.
LineBreakDetermines how lines will be broken when preventing text from running out of bounds.
RemSizeThe root font size, in logical pixels.
TextThe top-level UI text component.
Text2dThe top-level 2D text component.
TextFontTextFont determines the style of a text span within a ComputedTextBlock, specifically the font face, the font size…
TextLayoutComponent with text format settings for a block of text.
TextSpanA span of text in a tree of spans.

Values

NameType
EditableTextSystemsReflectSystemSet
Text2dUpdateSystemsReflectSystemSet

EmSize

Component

The font size, in logical pixels, used to resolve Val::Em values in a UI node.

Em units are relative to the font size of the node they sit on, and this is that font size made concrete. Required by Node, so every UI node has one.

If the node has a TextFont, the EmSize is derived from it whenever the TextFont, RemSize or render-target info changes; until then any value you place on it persists. If it does not have a TextFont, the value is yours to set, for example by an app-level propagation system. EmSize defaults to DEFAULT_REM_SIZE_PX, which matches the default RemSize but does not track changes to it. Use Val::Rem instead for values that should follow the root font size.

Removing a TextFont leaves the last derived value in place.

Fields

IndexType
0f32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<EmSize>) -> EmSize

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Font

Not reflected: scripts can only pass values of it around.

Opaque: scripts can't access its fields, only its functions.

FontFeatures

OpenType features for .otf fonts that support them.

Examples features include ligatures, small-caps, and fractional number display. For the complete list of OpenType features, see the spec at <https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist>.

Usage:

use bevy_text::{FontFeatureTag, FontFeatures};

// Create using the builder
let font_features = FontFeatures::builder()
  .enable(FontFeatureTag::STANDARD_LIGATURES)
  .set(FontFeatureTag::WEIGHT, 300)
  .build();

// Create from a list
let more_font_features: FontFeatures = [
  FontFeatureTag::STANDARD_LIGATURES,
  FontFeatureTag::OLDSTYLE_FIGURES,
  FontFeatureTag::TABULAR_FIGURES
].into();

Fields

FieldType
featuresVec<(FontFeatureTag, u32)>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<FontFeatures>) -> FontFeatures

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

FontFeatureTag

An OpenType font feature tag.

Fields

IndexType
0[u8; 4]

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<FontFeatureTag>) -> FontFeatureTag

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

FontSize

The vertical height of rasterized glyphs in the font atlas in pixels.

This is multiplied by the scale factor, but not the text entity transform or camera projection.

The viewport variants are not supported by Text2d.

A new font atlas is generated for every combination of font handle and scaled font size which can have a strong performance impact.

Variants

VariantFields
Px(f32)
Vw(f32)
Vh(f32)
VMin(f32)
VMax(f32)
Rem(f32)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<FontSize>) -> FontSize

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Px.new

new(variant: EnumVariantRef, payload: Fields<FontSize::Px>) -> FontSize

Rem.new

new(variant: EnumVariantRef, payload: Fields<FontSize::Rem>) -> FontSize

VMax.new

new(variant: EnumVariantRef, payload: Fields<FontSize::VMax>) -> FontSize

VMin.new

new(variant: EnumVariantRef, payload: Fields<FontSize::VMin>) -> FontSize

Vh.new

new(variant: EnumVariantRef, payload: Fields<FontSize::Vh>) -> FontSize

Vw.new

new(variant: EnumVariantRef, payload: Fields<FontSize::Vw>) -> FontSize

FontSmoothing

Determines which antialiasing method to use when rendering text. By default, text is rendered with grayscale antialiasing, but this can be changed to achieve a pixelated look.

Note: Subpixel antialiasing is not currently supported.

Variants

Variant
None
AntiAliased

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<FontSmoothing>) -> FontSmoothing

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

AntiAliased.new

new(variant: EnumVariantRef, payload: Fields<FontSmoothing::AntiAliased>) -> FontSmoothing

None.new

new(variant: EnumVariantRef, payload: Fields<FontSmoothing::None>) -> FontSmoothing

FontSource

Determines how the font face for a text sections is selected.

A FontSource can be a handle to a font asset, a font family name, a CSS font-family list, an ordered family list, or a generic font category that is resolved using Parley’s font database.

Font family fallback (selection of a font when the requested font is not found) is automatically handled by parley::fontique. Be sure to enable the parley/system feature for automatic discovery of system fonts.

Generally speaking, these fallbacks are OS-specific, and do not require manual configuration.

You can check which font family is used for a given FontSource by calling FontCx::get_family.

Variants

VariantFields
Handle(Handle<Font>)
Family(SmolStr)
Families(SmolStr)
List(Vec<FontSource>)
Generic(GenericFontFamily)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<FontSource>) -> FontSource

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Families.new

new(variant: EnumVariantRef, payload: Fields<FontSource::Families>) -> FontSource

Family.new

new(variant: EnumVariantRef, payload: Fields<FontSource::Family>) -> FontSource

Generic.new

new(variant: EnumVariantRef, payload: Fields<FontSource::Generic>) -> FontSource

Handle.new

new(variant: EnumVariantRef, payload: Fields<FontSource::Handle>) -> FontSource

List.new

new(variant: EnumVariantRef, payload: Fields<FontSource::List>) -> FontSource

FontStyle

The slant style of a font face: normal, italic, or oblique.

Variants

VariantFields
Normal
Italic
Oblique(Optional<f32>)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<FontStyle>) -> FontStyle

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Italic.new

new(variant: EnumVariantRef, payload: Fields<FontStyle::Italic>) -> FontStyle

Normal.new

new(variant: EnumVariantRef, payload: Fields<FontStyle::Normal>) -> FontStyle

Oblique.new

new(variant: EnumVariantRef, payload: Fields<FontStyle::Oblique>) -> FontStyle

FontVariations

OpenType font variations for variable fonts that support them.

Variable fonts expose named axes (e.g. wght, FILL) that accept continuous f32 values. This is distinct from FontFeatures, which mainly controls on/off OpenType layout features.

Usage

use bevy_text::{FontVariationTag, FontVariations};

let variations = FontVariations::builder()
    .set(FontVariationTag::WEIGHT, 400.0)
    .build();

Fields

FieldType
variationsVec<(FontVariationTag, f32)>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<FontVariations>) -> FontVariations

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

FontVariationTag

An OpenType font variation tag.

Fields

IndexType
0[u8; 4]

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<FontVariationTag>) -> FontVariationTag

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

FontWeight

How thick or bold the strokes of a font appear.

Valid font weights range from 1 to 1000, inclusive. Weights above 1000 are clamped to 1000. A weight of 0 is treated as FontWeight::DEFAULT.

Legacy names from when most fonts weren’t variable fonts are included as const values, but are misleading if used in documentation and examples, as valid weights for variable fonts are all of the numbers from 1-1000, and not all fonts which are not variable fonts have those weights supplied. If you use a custom font that supplies only specific weights, that will be documented where you purchased the font.

<https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/font-weight>

Fields

IndexType
0u16

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<FontWeight>) -> FontWeight

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

FontWidth

The visual width of a font as a ratio of its normal width, typically 0.5 to 2.0. <https://docs.microsoft.com/en-us/typography/opentype/spec/os2#uswidthclass>

Fields

IndexType
0f32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<FontWidth>) -> FontWidth

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

GenericFontFamily

Generic font families that are resolved through Parley’s font database.

Variants

Variant
Serif
SansSerif
Cursive
Fantasy
Monospace
SystemUi
UiSerif
UiSansSerif
UiMonospace
UiRounded
Emoji
Math
FangSong

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<GenericFontFamily>) -> GenericFontFamily

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Cursive.new

new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::Cursive>) -> GenericFontFamily

Emoji.new

new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::Emoji>) -> GenericFontFamily

FangSong.new

new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::FangSong>) -> GenericFontFamily

Fantasy.new

new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::Fantasy>) -> GenericFontFamily

Math.new

new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::Math>) -> GenericFontFamily

Monospace.new

new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::Monospace>) -> GenericFontFamily

SansSerif.new

new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::SansSerif>) -> GenericFontFamily

Serif.new

new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::Serif>) -> GenericFontFamily

SystemUi.new

new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::SystemUi>) -> GenericFontFamily

UiMonospace.new

new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::UiMonospace>) -> GenericFontFamily

UiRounded.new

new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::UiRounded>) -> GenericFontFamily

UiSansSerif.new

new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::UiSansSerif>) -> GenericFontFamily

UiSerif.new

new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::UiSerif>) -> GenericFontFamily

Justify

Describes the horizontal alignment of multiple lines of text relative to each other.

This only affects the internal positioning of the lines of text within a text entity and does not affect the text entity’s position.

Has no affect on a single line text entity, unless used together with a TextBounds component with an explicit width value.

Variants

Variant
Left
Center
Right
Justified
Start
End

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Justify>) -> Justify

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Center.new

new(variant: EnumVariantRef, payload: Fields<Justify::Center>) -> Justify

End.new

new(variant: EnumVariantRef, payload: Fields<Justify::End>) -> Justify

Justified.new

new(variant: EnumVariantRef, payload: Fields<Justify::Justified>) -> Justify

Left.new

new(variant: EnumVariantRef, payload: Fields<Justify::Left>) -> Justify

Right.new

new(variant: EnumVariantRef, payload: Fields<Justify::Right>) -> Justify

Start.new

new(variant: EnumVariantRef, payload: Fields<Justify::Start>) -> Justify

LineBreak

Determines how lines will be broken when preventing text from running out of bounds.

Variants

Variant
WordBoundary
AnyCharacter
WordOrCharacter
NoWrap

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<LineBreak>) -> LineBreak

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

AnyCharacter.new

new(variant: EnumVariantRef, payload: Fields<LineBreak::AnyCharacter>) -> LineBreak

NoWrap.new

new(variant: EnumVariantRef, payload: Fields<LineBreak::NoWrap>) -> LineBreak

WordBoundary.new

new(variant: EnumVariantRef, payload: Fields<LineBreak::WordBoundary>) -> LineBreak

WordOrCharacter.new

new(variant: EnumVariantRef, payload: Fields<LineBreak::WordOrCharacter>) -> LineBreak

RemSize

The root font size, in logical pixels.

Rem units always resolve against this one global resource, including FontSize::Rem, LetterSpacing::Rem and Val::Rem.

Fields

IndexType
0f32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<RemSize>) -> RemSize

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Text

Component

The top-level UI text component.

Adding Text to an entity will pull in required components for setting up a UI text node.

The string in this component is the first ‘text span’ in a hierarchy of text spans that are collected into a ComputedTextBlock. See TextSpan for the component used by children of entities with Text.

// Basic usage.
world.spawn(Text::new("hello world!"));

// With non-default style.
world.spawn((
    Text::new("hello world!"),
    TextFont {
        font: font_handle.clone().into(),
        font_size: FontSize::Px(60.0),
        ..Default::default()
    },
    TextColor(BLUE.into()),
));

// With text justification.
world.spawn((
    Text::new("hello world\nand bevy!"),
    TextLayout::justify(Justify::Center)
));

// With spans
world.spawn(Text::new("hello ")).with_children(|parent| {
    parent.spawn(TextSpan::new("world"));
    parent.spawn((TextSpan::new("!"), TextColor(BLUE.into())));
});

Fields

IndexType
0String

Functions

NameSummary
newCreates a new text component holding text.

new

new(text: String) -> Text

Creates a new text component holding text.

local Text = import_namespace("text").Text
local text = Text.new("hi")
assert(text:as_str() == "hi")
let Text = import_namespace("text").Text;
let text = Text.new("hi");
assert!(text.as_str() == "hi");

Methods

NameSummary
as_strThe text as a string.
setReplaces the text.

as_str

as_str(self: Text) -> String

The text as a string.

set

set(self: Text, text: String)

Replaces the text.

Text2d

Component

The top-level 2D text component.

Adding Text2d to an entity will pull in required components for setting up 2d text. Example usage.

The string in this component is the first ‘text span’ in a hierarchy of text spans that are collected into a ComputedTextBlock. See TextSpan for the component used by children of entities with Text2d.

With Text2d the justify field of TextLayout only affects the internal alignment of a block of text and not its relative position, which is controlled by the Anchor component. This means that for a block of text consisting of only one line that doesn’t wrap, the justify field will have no effect.

// Basic usage.
world.spawn(Text2d::new("hello world!"));

// With non-default style.
world.spawn((
    Text2d::new("hello world!"),
    TextFont {
        font: font_handle.clone().into(),
        font_size: FontSize::Px(60.0),
        ..Default::default()
    },
    TextColor(BLUE.into()),
));

// With text justification.
world.spawn((
    Text2d::new("hello world\nand bevy!"),
    TextLayout::justify(Justify::Center)
));

// With spans
world.spawn(Text2d::new("hello ")).with_children(|parent| {
    parent.spawn(TextSpan::new("world"));
    parent.spawn((TextSpan::new("!"), TextColor(BLUE.into())));
});

Viewport-based FontSize variants for Text2d are resolved based on the primary window’s logical size.

Fields

IndexType
0String

Functions

NameSummary
newCreates a new 2d text component holding text.

new

new(text: String) -> Text2d

Creates a new 2d text component holding text.

Methods

NameSummary
as_strThe text as a string.
setReplaces the text.

as_str

as_str(self: Text2d) -> String

The text as a string.

set

set(self: Text2d, text: String)

Replaces the text.

TextFont

Component

TextFont determines the style of a text span within a ComputedTextBlock, specifically the font face, the font size, the line height, and the antialiasing method.

Fields

FieldType
fontFontSource
font_sizeFontSize
weightFontWeight
widthFontWidth
styleFontStyle
font_smoothingFontSmoothing
font_featuresFontFeatures
font_variationsFontVariations

Functions

NameSummary
from_font_sizeCreates a text font with the default font face and the given size in logical pixels.
newConstructs a new instance of the type from a table of its fields.

from_font_size

from_font_size(font_size: f32) -> TextFont

Creates a text font with the default font face and the given size in logical pixels.

local TextFont = import_namespace("text").TextFont
local font = TextFont.from_font_size(20.0)
assert(font:with_font_size(30.0) ~= nil)
let TextFont = import_namespace("text").TextFont;
let font = TextFont.from_font_size(20.0);
assert!(font.with_font_size(30.0) != ());

new

new(payload: Fields<TextFont>) -> TextFont

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
with_fontA copy of the text font that uses the font face font.
with_font_sizeA copy of the text font with its size set to font_size in logical pixels.

with_font

with_font(self: TextFont, font: Handle<Font>) -> TextFont

A copy of the text font that uses the font face font.

with_font_size

with_font_size(self: TextFont, font_size: f32) -> TextFont

A copy of the text font with its size set to font_size in logical pixels.

TextLayout

Component

Component with text format settings for a block of text.

A block of text is composed of text spans, which each have a separate string value and TextFont. Text spans associated with a text block are collected into ComputedTextBlock for layout, and then inserted to TextLayoutInfo for rendering.

See Text2d in bevy_sprite for the core component of 2d text, and Text in bevy_ui for UI text.

Fields

FieldType
justifyJustify
linebreakLineBreak

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.
new_with_justifyA text layout that aligns lines with the given justification and wraps at word boundaries.
new_with_no_wrapA text layout that never wraps soft line breaks, only explicit newlines start a new line.

new

new(payload: Fields<TextLayout>) -> TextLayout

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

new_with_justify

new_with_justify(justify: Justify) -> TextLayout

A text layout that aligns lines with the given justification and wraps at word boundaries.

new_with_no_wrap

new_with_no_wrap() -> TextLayout

A text layout that never wraps soft line breaks, only explicit newlines start a new line.

TextSpan

Component

A span of text in a tree of spans.

A TextSpan is only valid when it exists as a child of a parent that has either Text or Text2d. The parent’s Text / Text2d component contains the base text content. Any children with TextSpan extend this text by appending their content to the parent’s text in sequence to form a ComputedTextBlock. The parent’s TextLayout determines the layout of the block but each node has its own TextFont and TextColor.

Fields

IndexType
0String

Functions

NameSummary
newCreates a new text span holding text.

new

new(text: String) -> TextSpan

Creates a new text span holding text.

Methods

NameSummary
as_strThe text as a string.
setReplaces the text.

as_str

as_str(self: TextSpan) -> String

The text as a string.

set

set(self: TextSpan, text: String)

Replaces the text.

time

The types and functions in the time namespace, as returned by import_namespace("time").

Types

TypeSummary
Duration
FixedThe fixed timestep game clock following virtual time.
Instant
RealReal time clock representing elapsed wall clock time.
StopwatchA Stopwatch is a struct that tracks elapsed time when started.
Time<T>A clock, T is the kind of clock, i.e. Virtual or Fixed.
TimerTracks elapsed time. Enters the finished state once duration is reached.
TimerModeSpecifies Timer behavior.
VirtualThe virtual game clock representing game time.

Values

NameType
TimeSystemsReflectSystemSet

Duration

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
from_microsA duration of micros microseconds.
from_millisA duration of millis milliseconds.
from_nanosA duration of nanos nanoseconds.
from_secsA duration of secs seconds. Errors if secs is negative or not finite.
newConstructs a new instance of the type from a table of its fields.
zeroA duration of no time.

from_micros

from_micros(micros: u64) -> Duration

A duration of micros microseconds.

from_millis

from_millis(millis: u64) -> Duration

A duration of millis milliseconds.

from_nanos

from_nanos(nanos: u64) -> Duration

A duration of nanos nanoseconds.

from_secs

from_secs(secs: f32) -> Duration

A duration of secs seconds. Errors if secs is negative or not finite.

new

new(payload: Fields<Duration>) -> Duration

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

zero

zero() -> Duration

A duration of no time.

Methods

NameSummary
as_millisThe duration in whole milliseconds, rounded down.
as_secsThe duration in seconds.
as_secs_f64The duration in seconds, as a double precision number.
is_zeroWhether the duration is zero.

as_millis

as_millis(self: Duration) -> u64

The duration in whole milliseconds, rounded down.

as_secs

as_secs(self: Duration) -> f32

The duration in seconds.

as_secs_f64

as_secs_f64(self: Duration) -> f64

The duration in seconds, as a double precision number.

is_zero

is_zero(self: Duration) -> bool

Whether the duration is zero.

Operators

NameSummary
addThe sum of two durations, capped at the largest representable duration.
divThe duration divided by divisor. Errors if divisor is not positive.
eqWhether two durations are equal.
ltWhether this duration is shorter than other.
mulThe duration scaled by factor. Errors if factor is negative or not finite.
subThe difference of two durations, or zero if rhs is the longer one.

add

add(self: Duration, rhs: Duration) -> Duration

The sum of two durations, capped at the largest representable duration.

div

div(self: Duration, divisor: f32) -> Duration

The duration divided by divisor. Errors if divisor is not positive.

eq

eq(self: Duration, other: Duration) -> bool

Whether two durations are equal.

lt

lt(self: Duration, other: Duration) -> bool

Whether this duration is shorter than other.

mul

mul(self: Duration, factor: f32) -> Duration

The duration scaled by factor. Errors if factor is negative or not finite.

sub

sub(self: Duration, rhs: Duration) -> Duration

The difference of two durations, or zero if rhs is the longer one.

Fixed

The fixed timestep game clock following virtual time.

A specialization of the Time structure. For method documentation, see Time<Fixed>#impl-Time<Fixed>.

It is automatically inserted as a resource by TimePlugin and updated based on Time<Virtual>. The fixed clock is automatically set as the generic Time resource during FixedUpdate schedule processing.

The fixed timestep clock advances in fixed-size increments, which is extremely useful for writing logic (like physics) that should have consistent behavior, regardless of framerate.

The default timestep() is 64 hertz, or 15625 microseconds. This value was chosen because using 60 hertz has the potential for a pathological interaction with the monitor refresh rate where the game alternates between running two fixed timesteps and zero fixed timesteps per frame (for example when running two fixed timesteps takes longer than a frame). Additionally, the value is a power of two which losslessly converts into f32 and f64.

To run a system on a fixed timestep, add it to one of the FixedMain schedules, most commonly FixedUpdate.

This schedule is run a number of times between PreUpdate and Update according to the accumulated overstep() time divided by the timestep(). This means the schedule may run 0, 1 or more times during a single update (which typically corresponds to a rendered frame).

Time<Fixed> and the generic Time resource will report a delta() equal to timestep() and always grow elapsed() by one timestep() per iteration.

The fixed timestep clock follows the Time<Virtual> clock, which means it is affected by pause(), set_relative_speed() and set_max_delta() from virtual time. If the virtual clock is paused, the FixedUpdate schedule will not run. It is guaranteed that the elapsed() time in Time<Fixed> is always between the previous elapsed() and the current elapsed() value in Time<Virtual>, so the values are compatible.

Changing the timestep size while the game is running should not normally be done, as having a regular interval is the point of this schedule, but it may be necessary for effects like “bullet-time” if the normal granularity of the fixed timestep is too big for the slowed down time. In this case, set_timestep() and be called to set a new value. The new value will be used immediately for the next run of the FixedUpdate schedule, meaning that it will affect the delta() value for the very next FixedUpdate, even if it is still during the same frame. Any overstep() present in the accumulator will be processed according to the new timestep() value.

Fields

FieldType
timestepDuration
overstepDuration

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Fixed>) -> Fixed

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Instant

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Instant>) -> Instant

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
duration_sinceThe duration from earlier to this instant, or zero if earlier is later.
elapsedThe duration since this instant was taken.

duration_since

duration_since(self: Instant, earlier: Instant) -> Duration

The duration from earlier to this instant, or zero if earlier is later.

elapsed

elapsed(self: Instant) -> Duration

The duration since this instant was taken.

Real

Real time clock representing elapsed wall clock time.

A specialization of the Time structure. For method documentation, see Time<Real>#impl-Time<Real>.

It is automatically inserted as a resource by TimePlugin and updated with time instants according to TimeUpdateStrategy.^disclaimer

Note: Using TimeUpdateStrategy::ManualDuration allows for mocking the wall clock for testing purposes. Besides this use case, it is not recommended to do this, as it will no longer represent “wall clock” time as intended.

The delta() and elapsed() values of this clock should be used for anything which deals specifically with real time (wall clock time). It will not be affected by relative game speed adjustments, pausing or other adjustments.^disclaimer

The clock does not count time from startup() to first_update()) into elapsed, but instead will start counting time from the first update call. delta() and elapsed() will report zero on the first update as there is no previous update instant. This means that a delta() of zero must be handled without errors in application logic, as it may theoretically also happen at other times.

Instants for startup(), first_update() and last_update() are recorded and accessible.

[`Time<Real>#impl-Time<Real>`](./timet.md) is only a *mock* of wall clock time.

Fields

FieldType
startupInstant
first_updateOptional<Instant>
last_updateOptional<Instant>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Real>) -> Real

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Stopwatch

A Stopwatch is a struct that tracks elapsed time when started.

Note that in order to advance the stopwatch tick MUST be called.

Examples

use std::time::Duration;
let mut stopwatch = Stopwatch::new();
assert_eq!(stopwatch.elapsed_secs(), 0.0);

stopwatch.tick(Duration::from_secs_f32(1.0)); // tick one second
assert_eq!(stopwatch.elapsed_secs(), 1.0);

stopwatch.pause();
stopwatch.tick(Duration::from_secs_f32(1.0)); // paused stopwatches don't tick
assert_eq!(stopwatch.elapsed_secs(), 1.0);

stopwatch.reset(); // reset the stopwatch
assert!(stopwatch.is_paused());
assert_eq!(stopwatch.elapsed_secs(), 0.0);

Fields

FieldType
elapsedDuration
is_pausedbool

Functions

NameSummary
newA stopwatch at zero, which is running.

new

new() -> Stopwatch

A stopwatch at zero, which is running.

Methods

NameSummary
elapsedThe time the stopwatch has run for.
elapsed_secsThe time the stopwatch has run for, in seconds.
is_pausedWhether the stopwatch is paused.
pauseStops the stopwatch from advancing until it is unpaused.
resetSets the stopwatch back to zero elapsed time.
set_elapsedSets the time the stopwatch has run for.
tickAdvances the stopwatch by delta, given in seconds or as a duration. Errors if the time is negative.
unpauseResumes a paused stopwatch.

elapsed

elapsed(self: Stopwatch) -> Duration

The time the stopwatch has run for.

elapsed_secs

elapsed_secs(self: Stopwatch) -> f32

The time the stopwatch has run for, in seconds.

is_paused

is_paused(self: Stopwatch) -> bool

Whether the stopwatch is paused.

pause

pause(self: Stopwatch)

Stops the stopwatch from advancing until it is unpaused.

reset

reset(self: Stopwatch)

Sets the stopwatch back to zero elapsed time.

set_elapsed

set_elapsed(self: Stopwatch, elapsed: Duration)

Sets the time the stopwatch has run for.

tick

tick(self: Stopwatch, delta: f32 | Duration)

Advances the stopwatch by delta, given in seconds or as a duration. Errors if the time is negative.

unpause

unpause(self: Stopwatch)

Resumes a paused stopwatch.

Time<T>

Generic

A clock, T is the kind of clock, i.e. Virtual or Fixed.

Fields

FieldType
contextT
wrap_periodDuration
deltaDuration
delta_secsf32
delta_secs_f64f64
elapsedDuration
elapsed_secsf32
elapsed_secs_f64f64
elapsed_wrappedDuration
elapsed_secs_wrappedf32
elapsed_secs_wrapped_f64f64

Instantiations

Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

On Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>

new(payload: Fields<Time<Virtual>>) -> Time<Virtual>

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
deltaThe time that passed since the previous update.
delta_secsThe time that passed since the previous update, in seconds.
delta_secs_f64The time that passed since the previous update, in seconds as a double precision number.
elapsedThe total time that passed since the clock started.
elapsed_secsThe total time that passed since the clock started, in seconds.
elapsed_secs_f64The total time that passed since the clock started, in seconds as a double precision number.
elapsed_secs_wrappedThe total time that passed since the clock started, in seconds, wrapped to a period so it stays precise for long…
is_pausedWhether the clock is paused.
max_deltaThe largest time a single update can add to the clock, longer frames are cut short.
overstep_fractionHow far the clock is into the next fixed update step, from 0 to 1.
pauseStops the clock until it is unpaused, the time does not advance while paused.
relative_speedThe speed of the clock relative to real time, 1 is real time and 2 is twice as fast.
set_max_deltaSets the largest time a single update can add to the clock.
set_relative_speedSets the speed of the clock relative to real time. Errors if speed is negative or not finite.
set_timestep_secondsSets the length of one fixed update step, in seconds. Errors if seconds is not positive or not finite.
timestepThe length of one fixed update step.
unpauseResumes a paused clock.

delta

On Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>

delta(self: Time<Virtual>) -> Duration

The time that passed since the previous update.

delta_secs

On Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>

delta_secs(self: Time<Virtual>) -> f32

The time that passed since the previous update, in seconds.

delta_secs_f64

On Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>

delta_secs_f64(self: Time<Virtual>) -> f64

The time that passed since the previous update, in seconds as a double precision number.

elapsed

On Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>

elapsed(self: Time<Virtual>) -> Duration

The total time that passed since the clock started.

elapsed_secs

On Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>

elapsed_secs(self: Time<Virtual>) -> f32

The total time that passed since the clock started, in seconds.

elapsed_secs_f64

On Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>

elapsed_secs_f64(self: Time<Virtual>) -> f64

The total time that passed since the clock started, in seconds as a double precision number.

elapsed_secs_wrapped

On Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>

elapsed_secs_wrapped(self: Time<Virtual>) -> f32

The total time that passed since the clock started, in seconds, wrapped to a period so it stays precise for long running apps.

is_paused

On Time<Virtual>

is_paused(self: Time<Virtual>) -> bool

Whether the clock is paused.

max_delta

On Time<Virtual>

max_delta(self: Time<Virtual>) -> Duration

The largest time a single update can add to the clock, longer frames are cut short.

overstep_fraction

On Time<Fixed>

overstep_fraction(self: Time<Fixed>) -> f32

How far the clock is into the next fixed update step, from 0 to 1.

pause

On Time<Virtual>

pause(self: Time<Virtual>)

Stops the clock until it is unpaused, the time does not advance while paused.

relative_speed

On Time<Virtual>

relative_speed(self: Time<Virtual>) -> f32

The speed of the clock relative to real time, 1 is real time and 2 is twice as fast.

set_max_delta

On Time<Virtual>

set_max_delta(self: Time<Virtual>, max_delta: Duration)

Sets the largest time a single update can add to the clock.

set_relative_speed

On Time<Virtual>

set_relative_speed(self: Time<Virtual>, speed: f32)

Sets the speed of the clock relative to real time. Errors if speed is negative or not finite.

set_timestep_seconds

On Time<Fixed>

set_timestep_seconds(self: Time<Fixed>, seconds: f64)

Sets the length of one fixed update step, in seconds. Errors if seconds is not positive or not finite.

timestep

On Time<Fixed>

timestep(self: Time<Fixed>) -> Duration

The length of one fixed update step.

unpause

On Time<Virtual>

unpause(self: Time<Virtual>)

Resumes a paused clock.

Timer

Tracks elapsed time. Enters the finished state once duration is reached.

Note that in order to advance the timer tick MUST be called.

Timer modes

There are two timer modes (TimerMode):

  • Non repeating timers will stop tracking and stay in the finished state until reset.
  • Repeating timers will only be in the finished state on each tick duration is reached or exceeded, and can still be reset at any given point.

Pausing timers

You can pause a timer using Timer::pause. Paused timers will not have elapsed time increased.

Elapsing multiple times a frame

Repeating timers might elapse multiple times per frame if the time is advanced by more than the timer duration. You can check how many times a timer elapsed each tick with Timer::times_finished_this_tick. For non-repeating timers, this will always be 0 or 1.

Fields

FieldType
stopwatchStopwatch
durationDuration
modeTimerMode
finishedbool
times_finished_this_ticku32

Functions

NameSummary
from_secondsA timer which runs for secs seconds, in mode. Errors if secs is negative or not finite.
newA timer which runs for duration, in mode.

from_seconds

from_seconds(secs: f32, mode: TimerMode) -> Timer

A timer which runs for secs seconds, in mode. Errors if secs is negative or not finite.

local Timer = import_namespace("time").Timer
local TimerMode = import_namespace("time").TimerMode
local timer = Timer.from_seconds(2, TimerMode.Repeating)
timer:tick(1)
assert(not timer:finished())
timer:tick(1.5)
assert(timer:finished())
let Timer = import_namespace("time").Timer;
let TimerMode = import_namespace("time").TimerMode;
let timer = Timer.from_seconds(2.0, TimerMode.Repeating);
timer.tick(1.0);
assert!(!timer.finished());
timer.tick(1.5);
assert!(timer.finished());

new

new(duration: Duration, mode: TimerMode) -> Timer

A timer which runs for duration, in mode.

Methods

NameSummary
almost_finishMakes the timer finish on its next tick.
durationThe duration the timer runs for.
elapsedThe time the timer has run for.
elapsed_secsThe time the timer has run for, in seconds.
finishedWhether the timer has run for its full duration.
fractionHow much of the duration has passed, from 0 to 1.
fraction_remainingHow much of the duration is left, from 0 to 1.
just_finishedWhether the timer finished during the last tick.
modeWhether the timer runs once, or repeats.
pauseStops the timer from advancing until it is unpaused.
pausedWhether the timer is paused.
remainingThe time left until the timer finishes.
remaining_secsThe time left until the timer finishes, in seconds.
resetSets the timer back to zero elapsed time, keeping its duration and mode.
set_durationSets the duration the timer runs for.
set_elapsedSets the time the timer has run for.
set_modeSets whether the timer runs once, or repeats.
tickAdvances the timer by delta, given in seconds or as a duration. Errors if the time is negative.
times_finished_this_tickHow many times the timer finished during the last tick, which can be more than once for a short timer.
unpauseResumes a paused timer.

almost_finish

almost_finish(self: Timer)

Makes the timer finish on its next tick.

duration

duration(self: Timer) -> Duration

The duration the timer runs for.

elapsed

elapsed(self: Timer) -> Duration

The time the timer has run for.

elapsed_secs

elapsed_secs(self: Timer) -> f32

The time the timer has run for, in seconds.

finished

finished(self: Timer) -> bool

Whether the timer has run for its full duration.

fraction

fraction(self: Timer) -> f32

How much of the duration has passed, from 0 to 1.

fraction_remaining

fraction_remaining(self: Timer) -> f32

How much of the duration is left, from 0 to 1.

just_finished

just_finished(self: Timer) -> bool

Whether the timer finished during the last tick.

mode

mode(self: Timer) -> TimerMode

Whether the timer runs once, or repeats.

pause

pause(self: Timer)

Stops the timer from advancing until it is unpaused.

paused

paused(self: Timer) -> bool

Whether the timer is paused.

remaining

remaining(self: Timer) -> Duration

The time left until the timer finishes.

remaining_secs

remaining_secs(self: Timer) -> f32

The time left until the timer finishes, in seconds.

reset

reset(self: Timer)

Sets the timer back to zero elapsed time, keeping its duration and mode.

set_duration

set_duration(self: Timer, duration: Duration)

Sets the duration the timer runs for.

set_elapsed

set_elapsed(self: Timer, elapsed: Duration)

Sets the time the timer has run for.

set_mode

set_mode(self: Timer, mode: TimerMode)

Sets whether the timer runs once, or repeats.

tick

tick(self: Timer, delta: f32 | Duration)

Advances the timer by delta, given in seconds or as a duration. Errors if the time is negative.

times_finished_this_tick

times_finished_this_tick(self: Timer) -> u32

How many times the timer finished during the last tick, which can be more than once for a short timer.

unpause

unpause(self: Timer)

Resumes a paused timer.

TimerMode

Specifies Timer behavior.

Variants

Variant
Once
Repeating

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<TimerMode>) -> TimerMode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

NameSummary
Once.new
Repeating.new

Once.new

new(variant: EnumVariantRef, payload: Fields<TimerMode::Once>) -> TimerMode

Repeating.new

new(variant: EnumVariantRef, payload: Fields<TimerMode::Repeating>) -> TimerMode

Virtual

The virtual game clock representing game time.

A specialization of the Time structure. For method documentation, see Time<Virtual>#impl-Time<Virtual>.

Normally used as Time<Virtual>. It is automatically inserted as a resource by TimePlugin and updated based on Time<Real>. The virtual clock is automatically set as the default generic Time resource for the update.

The virtual clock differs from real time clock in that it can be paused, sped up and slowed down. It also limits how much it can advance in a single update in order to prevent unexpected behavior in cases where updates do not happen at regular intervals (e.g. coming back after the program was suspended a long time).

The virtual clock can be paused by calling pause(), unpaused by calling unpause(), or toggled by calling toggle(). When the game clock is paused delta() will be zero on each update, and elapsed() will not grow. effective_speed() will return 0.0. Calling pause() will not affect value the delta() value for the update currently being processed.

The speed of the virtual clock can be changed by calling set_relative_speed(). A value of 2.0 means that virtual clock should advance twice as fast as real time, meaning that delta() values will be double of what Time<Real>::delta() reports and elapsed() will go twice as fast as Time<Real>::elapsed(). Calling set_relative_speed() will not affect the delta() value for the update currently being processed.

The maximum amount of delta time that can be added by a single update can be set by set_max_delta(). This value serves a dual purpose in the virtual clock.

If the game temporarily freezes due to any reason, such as disk access, a blocking system call, or operating system level suspend, reporting the full elapsed delta time is likely to cause bugs in game logic. Usually if a laptop is suspended for an hour, it doesn’t make sense to try to simulate the game logic for the elapsed hour when resuming. Instead it is better to lose the extra time and pretend a shorter duration of time passed. Setting max_delta() to a relatively short time means that the impact on game logic will be minimal.

If the game lags for some reason, meaning that it will take a longer time to compute a frame than the real time that passes during the computation, then we would fall behind in processing virtual time. If this situation persists, and computing a frame takes longer depending on how much virtual time has passed, the game would enter a “death spiral” where computing each frame takes longer and longer and the game will appear to freeze. By limiting the maximum time that can be added at once, we also limit the amount of virtual time the game needs to compute for each frame. This means that the game will run slow, and it will run slower than real time, but it will not freeze and it will recover as soon as computation becomes fast again.

You should set max_delta() to a value that is approximately the minimum FPS your game should have even if heavily lagged for a moment. The actual FPS when lagged will be somewhat lower than this, depending on how much more time it takes to compute a frame compared to real time. You should also consider how stable your FPS is, as the limit will also dictate how big of an FPS drop you can accept without losing time and falling behind real time.

Fields

FieldType
max_deltaDuration
pausedbool
relative_speedf64
effective_speedf64

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Virtual>) -> Virtual

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

transform

The types and functions in the transform namespace, as returned by import_namespace("transform").

Types

TypeSummary
GlobalTransformGlobalTransform is an affine transformation from entity-local coordinates to worldspace coordinates.
TransformDescribe the position of an entity. If the entity has a parent, the position is relative to its parent position.

GlobalTransform

Component

GlobalTransform is an affine transformation from entity-local coordinates to worldspace coordinates.

You cannot directly mutate GlobalTransform; instead, you change an entity’s transform by manipulating its Transform, which indirectly causes Bevy to update its GlobalTransform.

Transform and GlobalTransform

Transform transforms an entity relative to its parent’s reference frame, or relative to world space coordinates, if it doesn’t have a ChildOf component.

GlobalTransform is managed by Bevy; it is computed by successively applying the Transform of each ancestor entity which has a Transform. This is done automatically by Bevy-internal systems in the TransformSystems::Propagate system set.

This system runs during PostUpdate. If you update the Transform of an entity in this schedule or after, you will notice a 1 frame lag before the GlobalTransform is updated.

Examples

  • transform

Fields

IndexType
0Affine3A

Functions

NameSummary
from_xyzA transform at the position x, y, z, with no rotation and a scale of 1.
identityThe identity transform, which maps every point to itself.
newConstructs a new instance of the type from a table of its fields.

from_xyz

from_xyz(x: f32, y: f32, z: f32) -> GlobalTransform

A transform at the position x, y, z, with no rotation and a scale of 1.

identity

identity() -> GlobalTransform

The identity transform, which maps every point to itself.

new

new(payload: Fields<GlobalTransform>) -> GlobalTransform

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
backThe direction opposite to forward, +z in local space.
compute_transformThe transform as a Transform, with the same position, rotation and scale.
downThe local down direction, -y.
forwardThe direction the transform faces, -z in local space.
leftThe direction to the local left, -x in local space.
reparented_toThe local Transform that gives this world transform when parented to parent.
rightThe direction to the local right, +x in local space.
rotationThe rotation in world space.
scaleThe scale in world space.
to_matrixThe matrix equivalent to this transform.
transform_pointApplies the transform to a point in local space, giving its world space position.
translationThe position in world space.
upThe local up direction, +y.

back

back(self: GlobalTransform) -> Vec3

The direction opposite to forward, +z in local space.

compute_transform

compute_transform(self: GlobalTransform) -> Transform

The transform as a Transform, with the same position, rotation and scale.

down

down(self: GlobalTransform) -> Vec3

The local down direction, -y.

forward

forward(self: GlobalTransform) -> Vec3

The direction the transform faces, -z in local space.

left

left(self: GlobalTransform) -> Vec3

The direction to the local left, -x in local space.

reparented_to

reparented_to(self: GlobalTransform, parent: GlobalTransform) -> Transform

The local Transform that gives this world transform when parented to parent.

right(self: GlobalTransform) -> Vec3

The direction to the local right, +x in local space.

rotation

rotation(self: GlobalTransform) -> Quat

The rotation in world space.

scale

scale(self: GlobalTransform) -> Vec3

The scale in world space.

to_matrix

to_matrix(self: GlobalTransform) -> Mat4

The matrix equivalent to this transform.

transform_point

transform_point(self: GlobalTransform, point: Vec3) -> Vec3

Applies the transform to a point in local space, giving its world space position.

translation

translation(self: GlobalTransform) -> Vec3

The position in world space.

up

up(self: GlobalTransform) -> Vec3

The local up direction, +y.

Operators

NameSummary
eqWhether both transforms have exactly the same components.
mulComposes two transforms when given a global transform, or applies a local transform to this one.

eq

eq(self: GlobalTransform, other: GlobalTransform) -> bool

Whether both transforms have exactly the same components.

mul

Composes two transforms when given a global transform, or applies a local transform to this one.

Transform

Component

Describe the position of an entity. If the entity has a parent, the position is relative to its parent position.

Transforms compose from right to left: if t1 and t2 are transforms, then t1 * t2 corresponds to applying t2 first, then applying t1.

Transform and GlobalTransform

Transform is the position of an entity relative to its parent position, or the reference frame if it doesn’t have a ChildOf component.

GlobalTransform is the position of an entity relative to the reference frame.

GlobalTransform is updated from Transform in the TransformSystems::Propagate system set.

This system runs during PostUpdate. If you update the Transform of an entity during this set or after, you will notice a 1 frame lag before the GlobalTransform is updated.

Examples

  • transform

Fields

FieldType
translationVec3
rotationQuat
scaleVec3

Functions

NameSummary
from_matrixThe transform described by a 4x4 matrix.
from_rotationA transform with the given rotation.
from_scaleA transform with the given scale.
from_translationA transform at the given position.
from_xyzA transform at the position x, y, z.
identityThe transform with no translation, no rotation and a scale of 1.
newConstructs a new instance of the type from a table of its fields.

from_matrix

from_matrix(matrix: Mat4) -> Transform

The transform described by a 4x4 matrix.

from_rotation

from_rotation(rotation: Quat) -> Transform

A transform with the given rotation.

from_scale

from_scale(scale: Vec3) -> Transform

A transform with the given scale.

from_translation

from_translation(translation: Vec3) -> Transform

A transform at the given position.

from_xyz

from_xyz(x: f32, y: f32, z: f32) -> Transform

A transform at the position x, y, z.

local Transform = import_namespace("transform").Transform
local t = Transform.from_xyz(1, 2, 3)
assert(t.translation.x == 1)
let Transform = import_namespace("transform").Transform;
let t = Transform.from_xyz(1.0, 2.0, 3.0);
assert!(t.translation.x == 1.0);

identity

identity() -> Transform

The transform with no translation, no rotation and a scale of 1.

new

new(payload: Fields<Transform>) -> Transform

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
backThe direction opposite to forward, +z in local space.
downThe local down direction, -y.
forwardThe direction the transform faces, -z in local space.
is_finiteWhether every component is a finite number.
leftThe direction to the local left, -x in local space.
local_xThe local x axis, as a direction.
local_yThe local y axis, as a direction.
local_zThe local z axis, as a direction.
look_atRotates this transform to face target, with up as the up direction. Errors if up is zero.
look_toRotates this transform to face along direction, with up as the up direction. Errors if either vector is zero.
looking_atA copy of this transform rotated to face target, with up as the up direction. Errors if up is zero.
looking_toA copy of this transform rotated to face along direction, with up as the up direction.
mul_transformComposes this transform with other, applying other first.
rightThe direction to the local right, +x in local space.
rotateRotates this transform by rotation, in the parent’s space.
rotate_aroundRotates this transform by rotation around point, moving it along the circle.
rotate_axisRotates this transform by angle radians around axis. Errors if the axis is zero.
rotate_localRotates this transform by rotation, in its own local space.
rotate_local_xRotates this transform by angle radians around its local x axis.
rotate_local_yRotates this transform by angle radians around its local y axis.
rotate_local_zRotates this transform by angle radians around its local z axis.
rotate_xRotates this transform by angle radians around the x axis.
rotate_yRotates this transform by angle radians around the y axis.
rotate_zRotates this transform by angle radians around the z axis.
to_matrixThe matrix equivalent to this transform.
transform_pointApplies the transform to a point: scales, rotates, then translates it.
translate_aroundMoves this transform around point by rotation, without changing its rotation.
upThe local up direction, +y.
with_rotationA copy of this transform with a new rotation.
with_scaleA copy of this transform with a new scale.
with_translationA copy of this transform with a new position.

back

back(self: Transform) -> Vec3

The direction opposite to forward, +z in local space.

down

down(self: Transform) -> Vec3

The local down direction, -y.

forward

forward(self: Transform) -> Vec3

The direction the transform faces, -z in local space.

is_finite

is_finite(self: Transform) -> bool

Whether every component is a finite number.

left

left(self: Transform) -> Vec3

The direction to the local left, -x in local space.

local_x

local_x(self: Transform) -> Vec3

The local x axis, as a direction.

local_y

local_y(self: Transform) -> Vec3

The local y axis, as a direction.

local_z

local_z(self: Transform) -> Vec3

The local z axis, as a direction.

look_at

look_at(self: Transform, target: Vec3, up: Vec3)

Rotates this transform to face target, with up as the up direction. Errors if up is zero.

look_to

look_to(self: Transform, direction: Vec3, up: Vec3)

Rotates this transform to face along direction, with up as the up direction. Errors if either vector is zero.

looking_at

looking_at(self: Transform, target: Vec3, up: Vec3) -> Transform

A copy of this transform rotated to face target, with up as the up direction. Errors if up is zero.

looking_to

looking_to(self: Transform, direction: Vec3, up: Vec3) -> Transform

A copy of this transform rotated to face along direction, with up as the up direction. Errors if either vector is zero.

mul_transform

mul_transform(self: Transform, other: Transform) -> Transform

Composes this transform with other, applying other first.

right

right(self: Transform) -> Vec3

The direction to the local right, +x in local space.

rotate

rotate(self: Transform, rotation: Quat)

Rotates this transform by rotation, in the parent’s space.

rotate_around

rotate_around(self: Transform, point: Vec3, rotation: Quat)

Rotates this transform by rotation around point, moving it along the circle.

rotate_axis

rotate_axis(self: Transform, axis: Vec3, angle: f32)

Rotates this transform by angle radians around axis. Errors if the axis is zero.

rotate_local

rotate_local(self: Transform, rotation: Quat)

Rotates this transform by rotation, in its own local space.

rotate_local_x

rotate_local_x(self: Transform, angle: f32)

Rotates this transform by angle radians around its local x axis.

rotate_local_y

rotate_local_y(self: Transform, angle: f32)

Rotates this transform by angle radians around its local y axis.

rotate_local_z

rotate_local_z(self: Transform, angle: f32)

Rotates this transform by angle radians around its local z axis.

rotate_x

rotate_x(self: Transform, angle: f32)

Rotates this transform by angle radians around the x axis.

rotate_y

rotate_y(self: Transform, angle: f32)

Rotates this transform by angle radians around the y axis.

rotate_z

rotate_z(self: Transform, angle: f32)

Rotates this transform by angle radians around the z axis.

to_matrix

to_matrix(self: Transform) -> Mat4

The matrix equivalent to this transform.

transform_point

transform_point(self: Transform, point: Vec3) -> Vec3

Applies the transform to a point: scales, rotates, then translates it.

translate_around

translate_around(self: Transform, point: Vec3, rotation: Quat)

Moves this transform around point by rotation, without changing its rotation.

up

up(self: Transform) -> Vec3

The local up direction, +y.

with_rotation

with_rotation(self: Transform, rotation: Quat) -> Transform

A copy of this transform with a new rotation.

with_scale

with_scale(self: Transform, scale: Vec3) -> Transform

A copy of this transform with a new scale.

with_translation

with_translation(self: Transform, translation: Vec3) -> Transform

A copy of this transform with a new position.

Operators

NameSummary
eqWhether both transforms have exactly the same components.
mulComposes two transforms when given a transform, or transforms a point when given a Vec3.

eq

eq(self: Transform, other: Transform) -> bool

Whether both transforms have exactly the same components.

mul

mul(self: Transform, rhs: Transform | Vec3) -> Transform | Vec3

Composes two transforms when given a transform, or transforms a point when given a Vec3.

transform.TransformSystems

The types and functions in the transform.TransformSystems namespace, as returned by import_namespace("transform.TransformSystems").

Values

NameType
PropagateReflectSystemSet

ui

The types and functions in the ui namespace, as returned by import_namespace("ui").

Types

TypeSummary
AlignContentUsed to control how items are distributed.
AlignItemsUsed to control how each individual item is aligned by default within the space they’re given.
AlignSelfUsed to control how the specified item is aligned within the space it’s given.
BackgroundColorThe background color of the node
BorderColorThe border color of the UI node.
BorderRadiusUsed to add rounded corners to a UI node.
BoxSizingWhich part of a Node’s box length styles like width and height control
ComputedNodeProvides the computed size and layout properties of a UI Node.
CornerRadiusThe horizontal and vertical radii of a rounded corner’s elliptical arc.
DisplayDefines the layout model used by this node.
FlexDirectionDefines how flexbox items are ordered within a flexbox
FlexWrapDefines if flexbox items appear on a single line or on multiple lines
GlobalZIndexGlobalZIndex allows a Node entity anywhere in the UI hierarchy to escape the implicit draw ordering of the UI’s…
GridAutoFlowControls whether grid items are placed row-wise or column-wise as well as whether the sparse or dense packing algorithm…
GridPlacementRepresents the position of a grid item in a single axis.
GridTrackA GridTrack is a Row or Column of a CSS Grid.
GridTrackRepetitionHow many times to repeat a repeated grid track
ImageNodeA UI Node that renders an image.
InlineDirectionSets the inline axis direction (LTR or RTL) used for layout.
JustifyContentUsed to control how items are distributed.
JustifyItemsUsed to control how each individual item is aligned by default within the space they’re given.
JustifySelfUsed to control how the specified item is aligned within the space it’s given.
MaxTrackSizingFunction
MinTrackSizingFunction
NodeThe base component for UI entities. It describes UI layout and style properties.
NodeImageModeControls how the image is altered to fit within the layout and how the layout algorithm determines the space in the…
OutlineThe Outline component adds an outline outside the edge of a UI node. Outlines do not take up space in the layout.
OverflowWhether to show or hide overflowing items
OverflowAxisWhether to show or hide overflowing items
OverflowClipMarginThe bounds of the visible area when a UI node is clipped.
PositionTypeThe strategy used to position this node
RepeatedGridTrackRepresents a possibly repeated GridTrack.
ResolvedBorderRadiusRepresents the resolved border radii values for a UI node.
UiRectA type which is commonly used to define margins, paddings and borders.
ValRepresents the possible value types for layout properties.
VisualBoxUsed to determine which region of a UI node is used for visual bounds.
ZIndexIndicates that this Node entity’s front-to-back ordering is not controlled solely by its location in the UI…

Values

NameType
AccessibilityUiSystemsReflectSystemSet

AlignContent

Used to control how items are distributed.

  • For Flexbox containers, controls alignment of lines if flex_wrap is set to FlexWrap::Wrap and there are multiple lines of items.
  • For CSS Grid containers, controls alignment of grid rows.

Safe alignments

Safe alignments will fall back to Self::Start if aligning the items would overflow the container, so the start of the content stays visible.

https://developer.mozilla.org/en-US/docs/Web/CSS/align-content

Variants

Variant
Default
Start
StartSafe
End
EndSafe
FlexStart
FlexStartSafe
FlexEnd
FlexEndSafe
Center
CenterSafe
Stretch
SpaceBetween
SpaceEvenly
SpaceAround

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<AlignContent>) -> AlignContent

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Center.new

new(variant: EnumVariantRef, payload: Fields<AlignContent::Center>) -> AlignContent

CenterSafe.new

new(variant: EnumVariantRef, payload: Fields<AlignContent::CenterSafe>) -> AlignContent

Default.new

new(variant: EnumVariantRef, payload: Fields<AlignContent::Default>) -> AlignContent

End.new

new(variant: EnumVariantRef, payload: Fields<AlignContent::End>) -> AlignContent

EndSafe.new

new(variant: EnumVariantRef, payload: Fields<AlignContent::EndSafe>) -> AlignContent

FlexEnd.new

new(variant: EnumVariantRef, payload: Fields<AlignContent::FlexEnd>) -> AlignContent

FlexEndSafe.new

new(variant: EnumVariantRef, payload: Fields<AlignContent::FlexEndSafe>) -> AlignContent

FlexStart.new

new(variant: EnumVariantRef, payload: Fields<AlignContent::FlexStart>) -> AlignContent

FlexStartSafe.new

new(variant: EnumVariantRef, payload: Fields<AlignContent::FlexStartSafe>) -> AlignContent

SpaceAround.new

new(variant: EnumVariantRef, payload: Fields<AlignContent::SpaceAround>) -> AlignContent

SpaceBetween.new

new(variant: EnumVariantRef, payload: Fields<AlignContent::SpaceBetween>) -> AlignContent

SpaceEvenly.new

new(variant: EnumVariantRef, payload: Fields<AlignContent::SpaceEvenly>) -> AlignContent

Start.new

new(variant: EnumVariantRef, payload: Fields<AlignContent::Start>) -> AlignContent

StartSafe.new

new(variant: EnumVariantRef, payload: Fields<AlignContent::StartSafe>) -> AlignContent

Stretch.new

new(variant: EnumVariantRef, payload: Fields<AlignContent::Stretch>) -> AlignContent

AlignItems

Used to control how each individual item is aligned by default within the space they’re given.

  • For Flexbox containers, sets default cross axis alignment of the child items.
  • For CSS Grid containers, controls block (vertical) axis alignment of children of this grid container within their grid areas.

Safe alignments

Safe alignments will fall back to Self::Start if aligning the items would overflow the container, so the start of the content stays visible.

https://developer.mozilla.org/en-US/docs/Web/CSS/align-items

Variants

Variant
Default
Start
StartSafe
End
EndSafe
FlexStart
FlexStartSafe
FlexEnd
FlexEndSafe
Center
CenterSafe
Baseline
Stretch

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<AlignItems>) -> AlignItems

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Baseline.new

new(variant: EnumVariantRef, payload: Fields<AlignItems::Baseline>) -> AlignItems

Center.new

new(variant: EnumVariantRef, payload: Fields<AlignItems::Center>) -> AlignItems

CenterSafe.new

new(variant: EnumVariantRef, payload: Fields<AlignItems::CenterSafe>) -> AlignItems

Default.new

new(variant: EnumVariantRef, payload: Fields<AlignItems::Default>) -> AlignItems

End.new

new(variant: EnumVariantRef, payload: Fields<AlignItems::End>) -> AlignItems

EndSafe.new

new(variant: EnumVariantRef, payload: Fields<AlignItems::EndSafe>) -> AlignItems

FlexEnd.new

new(variant: EnumVariantRef, payload: Fields<AlignItems::FlexEnd>) -> AlignItems

FlexEndSafe.new

new(variant: EnumVariantRef, payload: Fields<AlignItems::FlexEndSafe>) -> AlignItems

FlexStart.new

new(variant: EnumVariantRef, payload: Fields<AlignItems::FlexStart>) -> AlignItems

FlexStartSafe.new

new(variant: EnumVariantRef, payload: Fields<AlignItems::FlexStartSafe>) -> AlignItems

Start.new

new(variant: EnumVariantRef, payload: Fields<AlignItems::Start>) -> AlignItems

StartSafe.new

new(variant: EnumVariantRef, payload: Fields<AlignItems::StartSafe>) -> AlignItems

Stretch.new

new(variant: EnumVariantRef, payload: Fields<AlignItems::Stretch>) -> AlignItems

AlignSelf

Used to control how the specified item is aligned within the space it’s given.

  • For Flexbox items, controls cross axis alignment of the item.
  • For CSS Grid items, controls block (vertical) axis alignment of a grid item within its grid area.

Safe alignments

Safe alignments will fall back to Self::Start if aligning the items would overflow the container, so the start of the content stays visible.

https://developer.mozilla.org/en-US/docs/Web/CSS/align-self

Variants

Variant
Auto
Start
StartSafe
End
EndSafe
FlexStart
FlexStartSafe
FlexEnd
FlexEndSafe
Center
CenterSafe
Baseline
Stretch

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<AlignSelf>) -> AlignSelf

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Auto.new

new(variant: EnumVariantRef, payload: Fields<AlignSelf::Auto>) -> AlignSelf

Baseline.new

new(variant: EnumVariantRef, payload: Fields<AlignSelf::Baseline>) -> AlignSelf

Center.new

new(variant: EnumVariantRef, payload: Fields<AlignSelf::Center>) -> AlignSelf

CenterSafe.new

new(variant: EnumVariantRef, payload: Fields<AlignSelf::CenterSafe>) -> AlignSelf

End.new

new(variant: EnumVariantRef, payload: Fields<AlignSelf::End>) -> AlignSelf

EndSafe.new

new(variant: EnumVariantRef, payload: Fields<AlignSelf::EndSafe>) -> AlignSelf

FlexEnd.new

new(variant: EnumVariantRef, payload: Fields<AlignSelf::FlexEnd>) -> AlignSelf

FlexEndSafe.new

new(variant: EnumVariantRef, payload: Fields<AlignSelf::FlexEndSafe>) -> AlignSelf

FlexStart.new

new(variant: EnumVariantRef, payload: Fields<AlignSelf::FlexStart>) -> AlignSelf

FlexStartSafe.new

new(variant: EnumVariantRef, payload: Fields<AlignSelf::FlexStartSafe>) -> AlignSelf

Start.new

new(variant: EnumVariantRef, payload: Fields<AlignSelf::Start>) -> AlignSelf

StartSafe.new

new(variant: EnumVariantRef, payload: Fields<AlignSelf::StartSafe>) -> AlignSelf

Stretch.new

new(variant: EnumVariantRef, payload: Fields<AlignSelf::Stretch>) -> AlignSelf

BackgroundColor

Component

The background color of the node

This serves as the “fill” color.

Fields

IndexType
0Color

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<BackgroundColor>) -> BackgroundColor

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

BorderColor

Component

The border color of the UI node.

Fields

FieldType
topColor
rightColor
bottomColor
leftColor

Functions

NameSummary
allA border with the same color on all four sides.
newConstructs a new instance of the type from a table of its fields.

all

all(color: Color) -> BorderColor

A border with the same color on all four sides.

new

new(payload: Fields<BorderColor>) -> BorderColor

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

BorderRadius

Used to add rounded corners to a UI node. You can set a UI node to have uniformly rounded corners, elliptical corners, or specify a different radius for each corner. If a given radius exceeds half the length of the node’s height or width, the radius will be calculated as half the height or width.

Percentage horizontal and vertical values are based on the node’s width and height, respectively.

Example

fn setup_ui(mut commands: Commands) {
    commands.spawn((
        Node {
            width: Val::Px(100.),
            height: Val::Px(100.),
            border: UiRect::all(Val::Px(2.)),
            border_radius: BorderRadius {
                // rounded corners, x and y radii equal
                top_left: CornerRadius::circular(px(10.)),
                top_right: percent(20.).into(),
                // elliptical corner
                bottom_right: CornerRadius::new(px(30.), px(20.)),
                bottom_left: CornerRadius { x: px(10.), y: px(40.) },
            },
            ..Default::default()
        },
        BackgroundColor(BLUE.into()),
    ));
}

https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius

Fields

FieldType
top_leftCornerRadius
top_rightCornerRadius
bottom_rightCornerRadius
bottom_leftCornerRadius

Functions

NameSummary
allEvery corner rounded by the same length.
maxThe most rounding possible, which makes the node a capsule, or a circle if it is square.
newConstructs a new instance of the type from a table of its fields.
percentEach corner rounded by a percentage, in the order top left, top right, bottom right, bottom left.
pxEach corner rounded by a length in logical pixels, in the order top left, top right, bottom right, bottom left.
zeroNo rounding, so every corner is a right angle.

all

all(radius: Val) -> BorderRadius

Every corner rounded by the same length.

max

max() -> BorderRadius

The most rounding possible, which makes the node a capsule, or a circle if it is square.

new

new(payload: Fields<BorderRadius>) -> BorderRadius

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

percent

percent(top_left: f32, top_right: f32, bottom_right: f32, bottom_left: f32) -> BorderRadius

Each corner rounded by a percentage, in the order top left, top right, bottom right, bottom left.

px

px(top_left: f32, top_right: f32, bottom_right: f32, bottom_left: f32) -> BorderRadius

Each corner rounded by a length in logical pixels, in the order top left, top right, bottom right, bottom left.

zero

zero() -> BorderRadius

No rounding, so every corner is a right angle.

BoxSizing

Which part of a Node’s box length styles like width and height control

See: https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing

Variants

Variant
BorderBox
ContentBox

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<BoxSizing>) -> BoxSizing

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

BorderBox.new

new(variant: EnumVariantRef, payload: Fields<BoxSizing::BorderBox>) -> BoxSizing

ContentBox.new

new(variant: EnumVariantRef, payload: Fields<BoxSizing::ContentBox>) -> BoxSizing

ComputedNode

Component

Provides the computed size and layout properties of a UI Node.

All of the fields are automatically calculated by ui_layout_system during PostUpdate in the UiSystems::Layout set.

The fields are measured in physical pixels. You can multiply by the inverse_scale_factor field to convert back to logical pixels.

Fields in this struct are public but should only rarely be directly modified. For example, in a scrollbar you may want to derive the handle’s size from the proportion of scrollable content in-view. You can directly modify ComputedNode after layout to set the handle size without a frame delay.

Fields

FieldType
sizeVec2
content_sizeVec2
scrollbar_sizeVec2
scroll_positionVec2
outline_widthf32
outline_offsetf32
unrounded_sizeVec2
borderBorderRect
border_radiusResolvedBorderRadius
paddingBorderRect
inverse_scale_factorf32
em_sizeEmSize
rem_sizeRemSize

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ComputedNode>) -> ComputedNode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Methods

NameSummary
content_sizeThe width and height of the node’s content in physical pixels, as calculated by the last layout.
inverse_scale_factorThe factor that turns physical pixels into logical pixels for this node.
is_emptyWhether the node has no width or no height, so that nothing is drawn for it.
sizeThe width and height of the node in physical pixels, as calculated by the last layout.

content_size

content_size(self: ComputedNode) -> Vec2

The width and height of the node’s content in physical pixels, as calculated by the last layout.

inverse_scale_factor

inverse_scale_factor(self: ComputedNode) -> f32

The factor that turns physical pixels into logical pixels for this node.

is_empty

is_empty(self: ComputedNode) -> bool

Whether the node has no width or no height, so that nothing is drawn for it.

size

size(self: ComputedNode) -> Vec2

The width and height of the node in physical pixels, as calculated by the last layout.

CornerRadius

The horizontal and vertical radii of a rounded corner’s elliptical arc. If one field is auto, the resolved radius will be circular and clamped to half the length of the node’s shortest side. If either field is zero, or both are auto, the node will have square corners.

Example

let radius = Val::Px(10.0);
let size = Vec2::new(100.0, 50.0);
let viewport_size = Vec2::new(1920.0, 1080.0);
let em_size = EmSize(20.0);
let rem_size = RemSize(20.0);

let c1 = CornerRadius {
    x: radius,
    y: Val::ZERO,
};
let c2 = CornerRadius {
    x: Val::ZERO,
    y: radius,
};
let r = c1.resolve(1.0, size, viewport_size, em_size, rem_size);
assert_eq!(
    r,
    c2.resolve(1.0, size, viewport_size, em_size, rem_size).yx(),
);
assert_eq!(
    r,
    Vec2::new(10.0, 0.0),
);

Fields

FieldType
xVal
yVal

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<CornerRadius>) -> CornerRadius

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Display

Defines the layout model used by this node.

Part of the Node component.

Variants

Variant
Flex
Grid
Block
None

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Display>) -> Display

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Block.new

new(variant: EnumVariantRef, payload: Fields<Display::Block>) -> Display

Flex.new

new(variant: EnumVariantRef, payload: Fields<Display::Flex>) -> Display

Grid.new

new(variant: EnumVariantRef, payload: Fields<Display::Grid>) -> Display

None.new

new(variant: EnumVariantRef, payload: Fields<Display::None>) -> Display

FlexDirection

Defines how flexbox items are ordered within a flexbox

Variants

Variant
Row
Column
RowReverse
ColumnReverse

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<FlexDirection>) -> FlexDirection

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Column.new

new(variant: EnumVariantRef, payload: Fields<FlexDirection::Column>) -> FlexDirection

ColumnReverse.new

new(variant: EnumVariantRef, payload: Fields<FlexDirection::ColumnReverse>) -> FlexDirection

Row.new

new(variant: EnumVariantRef, payload: Fields<FlexDirection::Row>) -> FlexDirection

RowReverse.new

new(variant: EnumVariantRef, payload: Fields<FlexDirection::RowReverse>) -> FlexDirection

FlexWrap

Defines if flexbox items appear on a single line or on multiple lines

Variants

Variant
NoWrap
Wrap
WrapReverse

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<FlexWrap>) -> FlexWrap

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

NoWrap.new

new(variant: EnumVariantRef, payload: Fields<FlexWrap::NoWrap>) -> FlexWrap

Wrap.new

new(variant: EnumVariantRef, payload: Fields<FlexWrap::Wrap>) -> FlexWrap

WrapReverse.new

new(variant: EnumVariantRef, payload: Fields<FlexWrap::WrapReverse>) -> FlexWrap

GlobalZIndex

Component

GlobalZIndex allows a Node entity anywhere in the UI hierarchy to escape the implicit draw ordering of the UI’s layout tree and be rendered above or below other UI nodes. Root UI nodes without a GlobalZIndex component receive an implicit global z-index of 0. Nodes with a GlobalZIndex of greater than 0 will be drawn on top of nodes without a GlobalZIndex or nodes with a lower GlobalZIndex. Nodes with a GlobalZIndex of less than 0 will be drawn below nodes without a GlobalZIndex or nodes with a greater GlobalZIndex. The order of nodes with the same GlobalZIndex is stable between frames.

If two Nodes have the same GlobalZIndex, ties are decided in order by:

  • The node with the higher ZIndex.
  • The node that was newly added this frame.
  • The node with a changed GlobalZIndex or ZIndex.

Otherwise the order is preserved from the previous frame.

Fields

IndexType
0i32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<GlobalZIndex>) -> GlobalZIndex

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

GridAutoFlow

Controls whether grid items are placed row-wise or column-wise as well as whether the sparse or dense packing algorithm is used.

The “dense” packing algorithm attempts to fill in holes earlier in the grid, if smaller items come up later. This may cause items to appear out-of-order when doing so would fill in holes left by larger items.

Defaults to GridAutoFlow::Row.

https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow

Variants

Variant
Row
Column
RowDense
ColumnDense

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<GridAutoFlow>) -> GridAutoFlow

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Column.new

new(variant: EnumVariantRef, payload: Fields<GridAutoFlow::Column>) -> GridAutoFlow

ColumnDense.new

new(variant: EnumVariantRef, payload: Fields<GridAutoFlow::ColumnDense>) -> GridAutoFlow

Row.new

new(variant: EnumVariantRef, payload: Fields<GridAutoFlow::Row>) -> GridAutoFlow

RowDense.new

new(variant: EnumVariantRef, payload: Fields<GridAutoFlow::RowDense>) -> GridAutoFlow

GridPlacement

Represents the position of a grid item in a single axis.

There are 3 fields which may be set:

  • start: which grid line the item should start at
  • end: which grid line the item should end at
  • span: how many tracks the item should span

The default span is 1. If neither start or end is set then the item will be placed automatically.

Generally, at most two fields should be set. If all three fields are specified then span will be ignored. If end specifies an earlier grid line than start then end will be ignored and the item will have a span of 1.

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Line-based_Placement_with_CSS_Grid

Fields

FieldType
startOptional<NonZeroI16>
spanOptional<NonZeroU16>
endOptional<NonZeroI16>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<GridPlacement>) -> GridPlacement

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

GridTrack

A GridTrack is a Row or Column of a CSS Grid. This struct specifies what size the track should be. See below for the different “track sizing functions” you can specify.

Fields

FieldType
min_sizing_functionMinTrackSizingFunction
max_sizing_functionMaxTrackSizingFunction

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<GridTrack>) -> GridTrack

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

GridTrackRepetition

How many times to repeat a repeated grid track

https://developer.mozilla.org/en-US/docs/Web/CSS/repeat

Variants

VariantFields
Count(u16)
AutoFill
AutoFit

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<GridTrackRepetition>) -> GridTrackRepetition

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

AutoFill.new

new(variant: EnumVariantRef, payload: Fields<GridTrackRepetition::AutoFill>) -> GridTrackRepetition

AutoFit.new

new(variant: EnumVariantRef, payload: Fields<GridTrackRepetition::AutoFit>) -> GridTrackRepetition

Count.new

new(variant: EnumVariantRef, payload: Fields<GridTrackRepetition::Count>) -> GridTrackRepetition

ImageNode

Component

A UI Node that renders an image.

Fields

FieldType
colorColor
imageHandle<Image>
texture_atlasOptional<TextureAtlas>
flip_xbool
flip_ybool
rectOptional<Rect>
image_modeNodeImageMode
visual_boxVisualBox

Functions

NameSummary
newA node that draws the given Image, untinted.

new

new(image: Handle<Image>) -> ImageNode

A node that draws the given Image, untinted.

Methods

NameSummary
with_colorA copy of the node that tints its image with color.

with_color

with_color(self: ImageNode, color: Color) -> ImageNode

A copy of the node that tints its image with color.

InlineDirection

Sets the inline axis direction (LTR or RTL) used for layout.

Variants

Variant
Ltr
Rtl

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<InlineDirection>) -> InlineDirection

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

NameSummary
Ltr.new
Rtl.new

Ltr.new

new(variant: EnumVariantRef, payload: Fields<InlineDirection::Ltr>) -> InlineDirection

Rtl.new

new(variant: EnumVariantRef, payload: Fields<InlineDirection::Rtl>) -> InlineDirection

JustifyContent

Used to control how items are distributed.

  • For Flexbox containers, controls alignment of items in the main axis.
  • For CSS Grid containers, controls alignment of grid columns.

Safe alignments

Safe alignments will fall back to Self::Start if aligning the items would overflow the container, so the start of the content stays visible.

https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content

Variants

Variant
Default
Start
StartSafe
End
EndSafe
FlexStart
FlexStartSafe
FlexEnd
FlexEndSafe
Center
CenterSafe
Stretch
SpaceBetween
SpaceEvenly
SpaceAround

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<JustifyContent>) -> JustifyContent

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Center.new

new(variant: EnumVariantRef, payload: Fields<JustifyContent::Center>) -> JustifyContent

CenterSafe.new

new(variant: EnumVariantRef, payload: Fields<JustifyContent::CenterSafe>) -> JustifyContent

Default.new

new(variant: EnumVariantRef, payload: Fields<JustifyContent::Default>) -> JustifyContent

End.new

new(variant: EnumVariantRef, payload: Fields<JustifyContent::End>) -> JustifyContent

EndSafe.new

new(variant: EnumVariantRef, payload: Fields<JustifyContent::EndSafe>) -> JustifyContent

FlexEnd.new

new(variant: EnumVariantRef, payload: Fields<JustifyContent::FlexEnd>) -> JustifyContent

FlexEndSafe.new

new(variant: EnumVariantRef, payload: Fields<JustifyContent::FlexEndSafe>) -> JustifyContent

FlexStart.new

new(variant: EnumVariantRef, payload: Fields<JustifyContent::FlexStart>) -> JustifyContent

FlexStartSafe.new

new(variant: EnumVariantRef, payload: Fields<JustifyContent::FlexStartSafe>) -> JustifyContent

SpaceAround.new

new(variant: EnumVariantRef, payload: Fields<JustifyContent::SpaceAround>) -> JustifyContent

SpaceBetween.new

new(variant: EnumVariantRef, payload: Fields<JustifyContent::SpaceBetween>) -> JustifyContent

SpaceEvenly.new

new(variant: EnumVariantRef, payload: Fields<JustifyContent::SpaceEvenly>) -> JustifyContent

Start.new

new(variant: EnumVariantRef, payload: Fields<JustifyContent::Start>) -> JustifyContent

StartSafe.new

new(variant: EnumVariantRef, payload: Fields<JustifyContent::StartSafe>) -> JustifyContent

Stretch.new

new(variant: EnumVariantRef, payload: Fields<JustifyContent::Stretch>) -> JustifyContent

JustifyItems

Used to control how each individual item is aligned by default within the space they’re given.

  • For Flexbox containers, this property has no effect. See justify_content for main axis alignment of flex items.
  • For CSS Grid containers, sets default inline (horizontal) axis alignment of child items within their grid areas.

Safe alignments

Safe alignments will fall back to Self::Start if aligning the items would overflow the container, so the start of the content stays visible.

https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items

Variants

Variant
Default
Start
StartSafe
End
EndSafe
Center
CenterSafe
Baseline
Stretch

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<JustifyItems>) -> JustifyItems

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Baseline.new

new(variant: EnumVariantRef, payload: Fields<JustifyItems::Baseline>) -> JustifyItems

Center.new

new(variant: EnumVariantRef, payload: Fields<JustifyItems::Center>) -> JustifyItems

CenterSafe.new

new(variant: EnumVariantRef, payload: Fields<JustifyItems::CenterSafe>) -> JustifyItems

Default.new

new(variant: EnumVariantRef, payload: Fields<JustifyItems::Default>) -> JustifyItems

End.new

new(variant: EnumVariantRef, payload: Fields<JustifyItems::End>) -> JustifyItems

EndSafe.new

new(variant: EnumVariantRef, payload: Fields<JustifyItems::EndSafe>) -> JustifyItems

Start.new

new(variant: EnumVariantRef, payload: Fields<JustifyItems::Start>) -> JustifyItems

StartSafe.new

new(variant: EnumVariantRef, payload: Fields<JustifyItems::StartSafe>) -> JustifyItems

Stretch.new

new(variant: EnumVariantRef, payload: Fields<JustifyItems::Stretch>) -> JustifyItems

JustifySelf

Used to control how the specified item is aligned within the space it’s given.

  • For children of flex nodes, this property has no effect. See justify_content for main axis alignment of flex items.
  • For CSS Grid items, controls inline (horizontal) axis alignment of a grid item within its grid area.

Safe alignments

Safe alignments will fall back to Self::Start if aligning the items would overflow the container, so the start of the content stays visible.

https://developer.mozilla.org/en-US/docs/Web/CSS/justify-self

Variants

Variant
Auto
Start
StartSafe
End
EndSafe
Center
CenterSafe
Baseline
Stretch

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<JustifySelf>) -> JustifySelf

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Auto.new

new(variant: EnumVariantRef, payload: Fields<JustifySelf::Auto>) -> JustifySelf

Baseline.new

new(variant: EnumVariantRef, payload: Fields<JustifySelf::Baseline>) -> JustifySelf

Center.new

new(variant: EnumVariantRef, payload: Fields<JustifySelf::Center>) -> JustifySelf

CenterSafe.new

new(variant: EnumVariantRef, payload: Fields<JustifySelf::CenterSafe>) -> JustifySelf

End.new

new(variant: EnumVariantRef, payload: Fields<JustifySelf::End>) -> JustifySelf

EndSafe.new

new(variant: EnumVariantRef, payload: Fields<JustifySelf::EndSafe>) -> JustifySelf

Start.new

new(variant: EnumVariantRef, payload: Fields<JustifySelf::Start>) -> JustifySelf

StartSafe.new

new(variant: EnumVariantRef, payload: Fields<JustifySelf::StartSafe>) -> JustifySelf

Stretch.new

new(variant: EnumVariantRef, payload: Fields<JustifySelf::Stretch>) -> JustifySelf

MaxTrackSizingFunction

Variants

VariantFields
Px(f32)
Percent(f32)
Em(f32)
Rem(f32)
MinContent
MaxContent
FitContentPx(f32)
FitContentPercent(f32)
Auto
Fraction(f32)
VMin(f32)
VMax(f32)
Vh(f32)
Vw(f32)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Auto.new

new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::Auto>) -> MaxTrackSizingFunction

Em.new

new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::Em>) -> MaxTrackSizingFunction

FitContentPercent.new

new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::FitContentPercent>) -> MaxTrackSizingFunction

FitContentPx.new

new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::FitContentPx>) -> MaxTrackSizingFunction

Fraction.new

new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::Fraction>) -> MaxTrackSizingFunction

MaxContent.new

new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::MaxContent>) -> MaxTrackSizingFunction

MinContent.new

new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::MinContent>) -> MaxTrackSizingFunction

Percent.new

new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::Percent>) -> MaxTrackSizingFunction

Px.new

new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::Px>) -> MaxTrackSizingFunction

Rem.new

new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::Rem>) -> MaxTrackSizingFunction

VMax.new

new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::VMax>) -> MaxTrackSizingFunction

VMin.new

new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::VMin>) -> MaxTrackSizingFunction

Vh.new

new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::Vh>) -> MaxTrackSizingFunction

Vw.new

new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::Vw>) -> MaxTrackSizingFunction

MinTrackSizingFunction

Variants

VariantFields
Px(f32)
Percent(f32)
Em(f32)
Rem(f32)
MinContent
MaxContent
Auto
VMin(f32)
VMax(f32)
Vh(f32)
Vw(f32)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Auto.new

new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::Auto>) -> MinTrackSizingFunction

Em.new

new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::Em>) -> MinTrackSizingFunction

MaxContent.new

new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::MaxContent>) -> MinTrackSizingFunction

MinContent.new

new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::MinContent>) -> MinTrackSizingFunction

Percent.new

new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::Percent>) -> MinTrackSizingFunction

Px.new

new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::Px>) -> MinTrackSizingFunction

Rem.new

new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::Rem>) -> MinTrackSizingFunction

VMax.new

new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::VMax>) -> MinTrackSizingFunction

VMin.new

new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::VMin>) -> MinTrackSizingFunction

Vh.new

new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::Vh>) -> MinTrackSizingFunction

Vw.new

new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::Vw>) -> MinTrackSizingFunction

Node

Component

The base component for UI entities. It describes UI layout and style properties.

When defining new types of UI entities, require Node to make them behave like UI nodes.

Nodes can be laid out using either Flexbox or CSS Grid Layout.

See below for general learning resources and for documentation on the individual style properties.

Flexbox
CSS Grid

See also

  • RelativeCursorPosition to obtain the cursor position relative to this node

Fields

FieldType
displayDisplay
box_sizingBoxSizing
position_typePositionType
overflowOverflow
scrollbar_widthf32
overflow_clip_marginOverflowClipMargin
leftVal
rightVal
topVal
bottomVal
widthVal
heightVal
min_widthVal
min_heightVal
max_widthVal
max_heightVal
aspect_ratioOptional<f32>
align_itemsAlignItems
justify_itemsJustifyItems
align_selfAlignSelf
justify_selfJustifySelf
align_contentAlignContent
justify_contentJustifyContent
directionInlineDirection
marginUiRect
paddingUiRect
borderUiRect
border_radiusBorderRadius
flex_directionFlexDirection
flex_wrapFlexWrap
flex_growf32
flex_shrinkf32
flex_basisVal
row_gapVal
column_gapVal
grid_auto_flowGridAutoFlow
grid_template_rowsVec<RepeatedGridTrack>
grid_template_columnsVec<RepeatedGridTrack>
grid_auto_rowsVec<GridTrack>
grid_auto_columnsVec<GridTrack>
grid_rowGridPlacement
grid_columnGridPlacement

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Node>) -> Node

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

NodeImageMode

Controls how the image is altered to fit within the layout and how the layout algorithm determines the space in the layout for the image

Variants

VariantFields
Auto
Stretch
Sliced(TextureSlicer)
Tiled{ tile_x: bool, tile_y: bool, stretch_value: f32 }

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<NodeImageMode>) -> NodeImageMode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Auto.new

new(variant: EnumVariantRef, payload: Fields<NodeImageMode::Auto>) -> NodeImageMode

Sliced.new

new(variant: EnumVariantRef, payload: Fields<NodeImageMode::Sliced>) -> NodeImageMode

Stretch.new

new(variant: EnumVariantRef, payload: Fields<NodeImageMode::Stretch>) -> NodeImageMode

Tiled.new

new(variant: EnumVariantRef, payload: Fields<NodeImageMode::Tiled>) -> NodeImageMode

Outline

Component

The Outline component adds an outline outside the edge of a UI node. Outlines do not take up space in the layout.

To add an Outline to a UI node you can spawn a (Node, Outline) tuple bundle:

fn setup_ui(mut commands: Commands) {
    commands.spawn((
        Node {
            width: Val::Px(100.),
            height: Val::Px(100.),
            ..Default::default()
        },
        BackgroundColor(BLUE.into()),
        Outline::new(Val::Px(10.), Val::ZERO, RED.into())
    ));
}

Outline components can also be added later to existing UI nodes:

fn outline_hovered_button_system(
    mut commands: Commands,
    mut node_query: Query<(Entity, &Hovered, Option<&mut Outline>), Changed<Hovered>>,
) {
    for (entity, hovered, mut maybe_outline) in node_query.iter_mut() {
        let outline_color =
            if hovered.get() {
                Color::WHITE
            } else {
                Color::NONE
            };
        if let Some(mut outline) = maybe_outline {
            outline.color = outline_color;
        } else {
            commands.entity(entity).insert(Outline::new(Val::Px(10.), Val::ZERO, outline_color));
        }
    }
}

Inserting and removing an Outline component repeatedly will result in table moves, so it is generally preferable to set Outline::color to Color::NONE to hide an outline.

Fields

FieldType
widthVal
offsetVal
colorColor

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Outline>) -> Outline

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Overflow

Whether to show or hide overflowing items

Fields

Functions

NameSummary
clipContent that overflows the node is clipped on both axes.
clip_xContent that overflows the node is clipped on the horizontal axis only.
clip_yContent that overflows the node is clipped on the vertical axis only.
hiddenContent that overflows the node is hidden on both axes, with the layout making room for it to be cut off.
newConstructs a new instance of the type from a table of its fields.
scrollContent that overflows the node can be scrolled on both axes.
visibleContent that overflows the node is shown.

clip

clip() -> Overflow

Content that overflows the node is clipped on both axes.

clip_x

clip_x() -> Overflow

Content that overflows the node is clipped on the horizontal axis only.

clip_y

clip_y() -> Overflow

Content that overflows the node is clipped on the vertical axis only.

hidden

hidden() -> Overflow

Content that overflows the node is hidden on both axes, with the layout making room for it to be cut off.

new

new(payload: Fields<Overflow>) -> Overflow

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

scroll

scroll() -> Overflow

Content that overflows the node can be scrolled on both axes.

visible

visible() -> Overflow

Content that overflows the node is shown.

OverflowAxis

Whether to show or hide overflowing items

Variants

Variant
Visible
Clip
Hidden
Scroll

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<OverflowAxis>) -> OverflowAxis

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Clip.new

new(variant: EnumVariantRef, payload: Fields<OverflowAxis::Clip>) -> OverflowAxis

Hidden.new

new(variant: EnumVariantRef, payload: Fields<OverflowAxis::Hidden>) -> OverflowAxis

Scroll.new

new(variant: EnumVariantRef, payload: Fields<OverflowAxis::Scroll>) -> OverflowAxis

Visible.new

new(variant: EnumVariantRef, payload: Fields<OverflowAxis::Visible>) -> OverflowAxis

OverflowClipMargin

The bounds of the visible area when a UI node is clipped.

Fields

FieldType
visual_boxVisualBox
marginf32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<OverflowClipMargin>) -> OverflowClipMargin

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

PositionType

The strategy used to position this node

Variants

Variant
Relative
Absolute

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<PositionType>) -> PositionType

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Absolute.new

new(variant: EnumVariantRef, payload: Fields<PositionType::Absolute>) -> PositionType

Relative.new

new(variant: EnumVariantRef, payload: Fields<PositionType::Relative>) -> PositionType

RepeatedGridTrack

Represents a possibly repeated GridTrack.

The repetition parameter can either be:

  • The integer 1, in which case the track is non-repeated.
  • a u16 count to repeat the track N times.
  • A GridTrackRepetition::AutoFit or GridTrackRepetition::AutoFill.

Note: that in the common case you want a non-repeating track (repetition count 1), you may use the constructor methods on GridTrack to create a RepeatedGridTrack. i.e. GridTrack::px(10.0) is equivalent to RepeatedGridTrack::px(1, 10.0).

You may only use one auto-repetition per track list. And if your track list contains an auto repetition then all tracks (in and outside of the repetition) must be fixed size (px or percent). Integer repetitions are just shorthand for writing out N tracks longhand and are not subject to the same limitations.

Fields

FieldType
repetitionGridTrackRepetition
tracksVec<GridTrack>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<RepeatedGridTrack>) -> RepeatedGridTrack

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ResolvedBorderRadius

Represents the resolved border radii values for a UI node.

The values are in physical pixels.

Fields

FieldType
top_leftVec2
top_rightVec2
bottom_rightVec2
bottom_leftVec2

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ResolvedBorderRadius>) -> ResolvedBorderRadius

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

UiRect

A type which is commonly used to define margins, paddings and borders.

Examples

Margin

A margin is used to create space around UI elements, outside of any defined borders.

let margin = UiRect::all(Val::Auto); // Centers the UI element

Padding

A padding is used to create space around UI elements, inside of any defined borders.

let padding = UiRect {
    left: Val::Px(10.0),
    right: Val::Px(20.0),
    top: Val::Px(30.0),
    bottom: Val::Px(40.0),
};

Borders

A border is used to define the width of the border of a UI element.

let border = UiRect {
    left: Val::Px(10.0),
    right: Val::Px(20.0),
    top: Val::Px(30.0),
    bottom: Val::Px(40.0),
};

Fields

FieldType
leftVal
rightVal
topVal
bottomVal

Functions

NameSummary
allA rectangle with the same length on all four sides.
axesA rectangle with one length for the left and right sides and another for the top and bottom.
horizontalA rectangle with the length on its left and right sides only.
newA rectangle with a length for each of its left, right, top and bottom sides.
percentA rectangle with percentages of the parent for its left, right, top and bottom sides.
pxA rectangle with lengths in logical pixels for its left, right, top and bottom sides.
verticalA rectangle with the length on its top and bottom sides only.
zeroA rectangle with no space on any side.

all

all(value: Val) -> UiRect

A rectangle with the same length on all four sides.

axes

axes(horizontal: Val, vertical: Val) -> UiRect

A rectangle with one length for the left and right sides and another for the top and bottom.

horizontal

horizontal(value: Val) -> UiRect

A rectangle with the length on its left and right sides only.

new

new(left: Val, right: Val, top: Val, bottom: Val) -> UiRect

A rectangle with a length for each of its left, right, top and bottom sides.

percent

percent(left: f32, right: f32, top: f32, bottom: f32) -> UiRect

A rectangle with percentages of the parent for its left, right, top and bottom sides.

px

px(left: f32, right: f32, top: f32, bottom: f32) -> UiRect

A rectangle with lengths in logical pixels for its left, right, top and bottom sides.

vertical

vertical(value: Val) -> UiRect

A rectangle with the length on its top and bottom sides only.

zero

zero() -> UiRect

A rectangle with no space on any side.

Val

Represents the possible value types for layout properties.

This enum allows specifying values for various Node properties in different units, such as logical pixels, percentages, or automatically determined values.

Val also implements core::str::FromStr to allow parsing values from strings in the format #.#px. Whitespaces between the value and unit is allowed. The following units are supported:

  • px: logical pixels
  • %: percentage
  • vw: percentage of the viewport width
  • vh: percentage of the viewport height
  • vmin: percentage of the viewport’s smaller dimension
  • vmax: percentage of the viewport’s larger dimension

Additionally, auto will be parsed as Val::Auto.

Variants

VariantFields
Auto
Px(f32)
Percent(f32)
Vw(f32)
Vh(f32)
VMin(f32)
VMax(f32)
Em(f32)
Rem(f32)

Functions

NameSummary
autoA length that the layout works out from the node and its contents.
newConstructs a new instance of the type from a table of its fields.
percentA length as a percentage of the parent’s size along the axis it applies to.
pxA length in logical pixels, such as Val.px(100) for 100 pixels.
vhA length as a percentage of the viewport height.
vmaxA length as a percentage of the viewport’s larger dimension.
vminA length as a percentage of the viewport’s smaller dimension.
vwA length as a percentage of the viewport width.

auto

auto() -> Val

A length that the layout works out from the node and its contents.

new

new(payload: Fields<Val>) -> Val

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

percent

percent(value: f32) -> Val

A length as a percentage of the parent’s size along the axis it applies to.

px

px(value: f32) -> Val

A length in logical pixels, such as Val.px(100) for 100 pixels.

local Node = import_namespace("ui").Node
local Val = import_namespace("ui").Val
local node = Node.new({ width = Val.px(100) })
assert(node.width[1] == 100)
let Node = import_namespace("ui").Node;
let Val = import_namespace("ui").Val;
let node = Node.new(#{ width: Val.px(100.0) });
assert!(node.width[0] == 100.0);

vh

vh(value: f32) -> Val

A length as a percentage of the viewport height.

vmax

vmax(value: f32) -> Val

A length as a percentage of the viewport’s larger dimension.

vmin

vmin(value: f32) -> Val

A length as a percentage of the viewport’s smaller dimension.

vw

vw(value: f32) -> Val

A length as a percentage of the viewport width.

Variant Functions

Auto.new

new(variant: EnumVariantRef, payload: Fields<Val::Auto>) -> Val

Em.new

new(variant: EnumVariantRef, payload: Fields<Val::Em>) -> Val

Percent.new

new(variant: EnumVariantRef, payload: Fields<Val::Percent>) -> Val

Px.new

new(variant: EnumVariantRef, payload: Fields<Val::Px>) -> Val

Rem.new

new(variant: EnumVariantRef, payload: Fields<Val::Rem>) -> Val

VMax.new

new(variant: EnumVariantRef, payload: Fields<Val::VMax>) -> Val

VMin.new

new(variant: EnumVariantRef, payload: Fields<Val::VMin>) -> Val

Vh.new

new(variant: EnumVariantRef, payload: Fields<Val::Vh>) -> Val

Vw.new

new(variant: EnumVariantRef, payload: Fields<Val::Vw>) -> Val

VisualBox

Used to determine which region of a UI node is used for visual bounds.

Variants

Variant
ContentBox
PaddingBox
BorderBox

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<VisualBox>) -> VisualBox

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

BorderBox.new

new(variant: EnumVariantRef, payload: Fields<VisualBox::BorderBox>) -> VisualBox

ContentBox.new

new(variant: EnumVariantRef, payload: Fields<VisualBox::ContentBox>) -> VisualBox

PaddingBox.new

new(variant: EnumVariantRef, payload: Fields<VisualBox::PaddingBox>) -> VisualBox

ZIndex

Component

Indicates that this Node entity’s front-to-back ordering is not controlled solely by its location in the UI hierarchy. A node with a higher z-index will appear on top of sibling nodes with a lower z-index.

UI nodes that have the same z-index will appear according to the order in which they appear in the UI hierarchy. In such a case, the last node to be added to its parent will appear in front of its siblings.

Nodes without this component will be treated as if they had a value of ZIndex(0).

Use GlobalZIndex if you need to order separate UI hierarchies or nodes that are not siblings in a given UI hierarchy.

Fields

IndexType
0i32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ZIndex>) -> ZIndex

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

ui.UiSystems

The types and functions in the ui.UiSystems namespace, as returned by import_namespace("ui.UiSystems").

Values

uuid

The types and functions in the uuid namespace, as returned by import_namespace("uuid").

Types

TypeSummary
Uuid

Uuid

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<Uuid>) -> Uuid

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

wgpu_types

The types and functions in the wgpu_types namespace, as returned by import_namespace("wgpu_types").

Types

TypeSummary
BlendState

BlendState

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<BlendState>) -> BlendState

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

window

The types and functions in the window namespace, as returned by import_namespace("window").

Types

TypeSummary
CompositeAlphaModeSpecifies how the alpha channel of the textures should be handled during compositing, for a Window.
EnabledButtonsSpecifies which Window control buttons should be enabled.
InternalWindowStateStores internal Window state that isn’t directly accessible.
MonitorSelectionReferences a screen monitor.
PresentModePresentation mode for a Window.
ScreenEdgeThe edges of a screen. Corresponds to winit::platform::ios::ScreenEdge.
VideoModeRepresents a video mode that a monitor supports
VideoModeSelectionReferences an exclusive fullscreen video mode.
WindowThe defining Component for window entities, storing information about how it should appear and behave.
WindowLevelSpecifies where a Window should appear relative to other overlapping windows (on top or under) .
WindowModeDefines the way a Window is displayed.
WindowPositionDefines where a Window should be placed on the screen.
WindowRefReference to a Window, whether it be a direct link to a specific entity or a more vague defaulting choice.
WindowResizeConstraintsThe size limits on a Window.
WindowResolutionControls the size of a Window
WindowThemeThe Window theme variant to use.

Values

NameType
ExitSystemsReflectSystemSet

CompositeAlphaMode

Specifies how the alpha channel of the textures should be handled during compositing, for a Window.

Variants

Variant
Auto
Opaque
PreMultiplied
PostMultiplied
Inherit

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<CompositeAlphaMode>) -> CompositeAlphaMode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Auto.new

new(variant: EnumVariantRef, payload: Fields<CompositeAlphaMode::Auto>) -> CompositeAlphaMode

Inherit.new

new(variant: EnumVariantRef, payload: Fields<CompositeAlphaMode::Inherit>) -> CompositeAlphaMode

Opaque.new

new(variant: EnumVariantRef, payload: Fields<CompositeAlphaMode::Opaque>) -> CompositeAlphaMode

PostMultiplied.new

new(variant: EnumVariantRef, payload: Fields<CompositeAlphaMode::PostMultiplied>) -> CompositeAlphaMode

PreMultiplied.new

new(variant: EnumVariantRef, payload: Fields<CompositeAlphaMode::PreMultiplied>) -> CompositeAlphaMode

EnabledButtons

Specifies which Window control buttons should be enabled.

Platform-specific

iOS, Android, and the Web do not have window control buttons.

On some Linux environments these values have no effect.

Fields

FieldType
minimizebool
maximizebool
closebool

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<EnabledButtons>) -> EnabledButtons

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

InternalWindowState

Stores internal Window state that isn’t directly accessible.

Fields

FieldType
minimize_requestOptional<bool>
maximize_requestOptional<bool>
drag_move_requestbool
drag_resize_requestOptional<CompassOctant>
physical_cursor_positionOptional<DVec2>

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<InternalWindowState>) -> InternalWindowState

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

MonitorSelection

References a screen monitor.

Used when centering a Window on a monitor.

Variants

VariantFields
Current
Primary
Index(usize)
Entity(Entity)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<MonitorSelection>) -> MonitorSelection

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Current.new

new(variant: EnumVariantRef, payload: Fields<MonitorSelection::Current>) -> MonitorSelection

Entity.new

new(variant: EnumVariantRef, payload: Fields<MonitorSelection::Entity>) -> MonitorSelection

Index.new

new(variant: EnumVariantRef, payload: Fields<MonitorSelection::Index>) -> MonitorSelection

Primary.new

new(variant: EnumVariantRef, payload: Fields<MonitorSelection::Primary>) -> MonitorSelection

PresentMode

Presentation mode for a Window.

The presentation mode specifies when a frame is presented to the window. The Fifo option corresponds to a traditional VSync, where the framerate is capped by the display refresh rate. Both Immediate and Mailbox are low-latency and are not capped by the refresh rate, but may not be available on all platforms. Tearing may be observed with Immediate mode, but will not be observed with Mailbox or Fifo.

AutoVsync or AutoNoVsync will gracefully fallback to Fifo when unavailable.

Immediate or Mailbox will panic if not supported by the platform.

Variants

Variant
AutoVsync
AutoNoVsync
Fifo
FifoRelaxed
Immediate
Mailbox

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<PresentMode>) -> PresentMode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

AutoNoVsync.new

new(variant: EnumVariantRef, payload: Fields<PresentMode::AutoNoVsync>) -> PresentMode

AutoVsync.new

new(variant: EnumVariantRef, payload: Fields<PresentMode::AutoVsync>) -> PresentMode

Fifo.new

new(variant: EnumVariantRef, payload: Fields<PresentMode::Fifo>) -> PresentMode

FifoRelaxed.new

new(variant: EnumVariantRef, payload: Fields<PresentMode::FifoRelaxed>) -> PresentMode

Immediate.new

new(variant: EnumVariantRef, payload: Fields<PresentMode::Immediate>) -> PresentMode

Mailbox.new

new(variant: EnumVariantRef, payload: Fields<PresentMode::Mailbox>) -> PresentMode

ScreenEdge

The edges of a screen. Corresponds to winit::platform::ios::ScreenEdge.

Platform-specific

  • Only used on iOS.

Variants

Variant
None
Top
Left
Bottom
Right
All

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ScreenEdge>) -> ScreenEdge

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

All.new

new(variant: EnumVariantRef, payload: Fields<ScreenEdge::All>) -> ScreenEdge

Bottom.new

new(variant: EnumVariantRef, payload: Fields<ScreenEdge::Bottom>) -> ScreenEdge

Left.new

new(variant: EnumVariantRef, payload: Fields<ScreenEdge::Left>) -> ScreenEdge

None.new

new(variant: EnumVariantRef, payload: Fields<ScreenEdge::None>) -> ScreenEdge

Right.new

new(variant: EnumVariantRef, payload: Fields<ScreenEdge::Right>) -> ScreenEdge

Top.new

new(variant: EnumVariantRef, payload: Fields<ScreenEdge::Top>) -> ScreenEdge

VideoMode

Represents a video mode that a monitor supports

Fields

FieldType
physical_sizeUVec2
bit_depthu16
refresh_rate_millihertzu32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<VideoMode>) -> VideoMode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

VideoModeSelection

References an exclusive fullscreen video mode.

Used when setting WindowMode::Fullscreen on a window.

Variants

VariantFields
Current
Specific(VideoMode)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<VideoModeSelection>) -> VideoModeSelection

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

Current.new

new(variant: EnumVariantRef, payload: Fields<VideoModeSelection::Current>) -> VideoModeSelection

Specific.new

new(variant: EnumVariantRef, payload: Fields<VideoModeSelection::Specific>) -> VideoModeSelection

Window

Component

The defining Component for window entities, storing information about how it should appear and behave.

Each window corresponds to an entity, and is uniquely identified by the value of their Entity. When the Window component is added to an entity, a new window will be opened. When it is removed or the entity is despawned, the window will close.

The primary window entity (and the corresponding window) is spawned by default by WindowPlugin and is marked with the PrimaryWindow component.

This component is synchronized with winit through bevy_winit: it will reflect the current state of the window and can be modified to change this state.

Example

Because this component is synchronized with winit, it can be used to perform OS-integrated windowing operations. For example, here’s a simple system to change the window mode:

fn change_window_mode(mut windows: Query<&mut Window, With<PrimaryWindow>>) {
    // Query returns one window typically.
    for mut window in windows.iter_mut() {
        window.mode =
            WindowMode::Fullscreen(MonitorSelection::Current, VideoModeSelection::Current);
    }
}

Fields

FieldType
present_modePresentMode
modeWindowMode
positionWindowPosition
resolutionWindowResolution
titleString
nameOptional<String>
composite_alpha_modeCompositeAlphaMode
resize_constraintsWindowResizeConstraints
resizablebool
enabled_buttonsEnabledButtons
decorationsbool
transparentbool
focusedbool
window_levelWindowLevel
canvasOptional<String>
fit_canvas_to_parentbool
prevent_default_event_handlingbool
internalInternalWindowState
ime_enabledbool
ime_positionVec2
window_themeOptional<WindowTheme>
visiblebool
skip_taskbarbool
clip_childrenbool
desired_maximum_frame_latencyOptional<NonZeroU32>
recognize_pinch_gesturebool
recognize_rotation_gesturebool
recognize_doubletap_gesturebool
recognize_pan_gestureOptional<(u8, u8)>
movable_by_window_backgroundbool
fullsize_content_viewbool
has_shadowbool
titlebar_shownbool
titlebar_transparentbool
titlebar_show_titlebool
titlebar_show_buttonsbool
borderless_gamebool
prefers_home_indicator_hiddenbool
prefers_status_bar_hiddenbool
preferred_screen_edges_deferring_system_gesturesScreenEdge

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.
primaryThe primary window, or nil if there is none.
primary_entityThe entity of the primary window, or nil if there is none.

new

new(payload: Fields<Window>) -> Window

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

primary

primary() -> Optional<Window>

The primary window, or nil if there is none.

primary_entity

primary_entity() -> Optional<Entity>

The entity of the primary window, or nil if there is none.

Methods

NameSummary
cursor_positionThe position of the cursor in logical pixels from the top left, or nil if the cursor is outside the window.
heightThe height of the window in logical pixels.
physical_heightThe height of the window in physical pixels.
physical_widthThe width of the window in physical pixels.
scale_factorThe ratio of physical to logical pixels, for example 2 on a high density screen.
set_cursor_positionMoves the cursor to the position in logical pixels, or hides it outside the window when given nil.
sizeThe size of the window in logical pixels.
widthThe width of the window in logical pixels.

cursor_position

cursor_position(self: Window) -> Optional<Vec2>

The position of the cursor in logical pixels from the top left, or nil if the cursor is outside the window.

height

height(self: Window) -> f32

The height of the window in logical pixels.

physical_height

physical_height(self: Window) -> u32

The height of the window in physical pixels.

physical_width

physical_width(self: Window) -> u32

The width of the window in physical pixels.

scale_factor

scale_factor(self: Window) -> f32

The ratio of physical to logical pixels, for example 2 on a high density screen.

set_cursor_position

set_cursor_position(self: Window, position: Optional<Vec2>)

Moves the cursor to the position in logical pixels, or hides it outside the window when given nil.

size

size(self: Window) -> Vec2

The size of the window in logical pixels.

width

width(self: Window) -> f32

The width of the window in logical pixels.

WindowLevel

Specifies where a Window should appear relative to other overlapping windows (on top or under) .

Levels are groups of windows with respect to their z-position.

The relative ordering between windows in different window levels is fixed. The z-order of windows within the same window level may change dynamically on user interaction.

Platform-specific

  • iOS / Android / Web / Wayland: Unsupported.

Variants

Variant
AlwaysOnBottom
Normal
AlwaysOnTop

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<WindowLevel>) -> WindowLevel

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

AlwaysOnBottom.new

new(variant: EnumVariantRef, payload: Fields<WindowLevel::AlwaysOnBottom>) -> WindowLevel

AlwaysOnTop.new

new(variant: EnumVariantRef, payload: Fields<WindowLevel::AlwaysOnTop>) -> WindowLevel

Normal.new

new(variant: EnumVariantRef, payload: Fields<WindowLevel::Normal>) -> WindowLevel

WindowMode

Defines the way a Window is displayed.

Variants

VariantFields
Windowed
BorderlessFullscreen(MonitorSelection)
Fullscreen(MonitorSelection, VideoModeSelection)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<WindowMode>) -> WindowMode

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

BorderlessFullscreen.new

new(variant: EnumVariantRef, payload: Fields<WindowMode::BorderlessFullscreen>) -> WindowMode

Fullscreen.new

new(variant: EnumVariantRef, payload: Fields<WindowMode::Fullscreen>) -> WindowMode

Windowed.new

new(variant: EnumVariantRef, payload: Fields<WindowMode::Windowed>) -> WindowMode

WindowPosition

Defines where a Window should be placed on the screen.

Variants

VariantFields
Automatic
Centered(MonitorSelection)
At(IVec2)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<WindowPosition>) -> WindowPosition

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

At.new

new(variant: EnumVariantRef, payload: Fields<WindowPosition::At>) -> WindowPosition

Automatic.new

new(variant: EnumVariantRef, payload: Fields<WindowPosition::Automatic>) -> WindowPosition

Centered.new

new(variant: EnumVariantRef, payload: Fields<WindowPosition::Centered>) -> WindowPosition

WindowRef

Reference to a Window, whether it be a direct link to a specific entity or a more vague defaulting choice.

Variants

VariantFields
Primary
Entity(Entity)

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<WindowRef>) -> WindowRef

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

NameSummary
Entity.new
Primary.new

Entity.new

new(variant: EnumVariantRef, payload: Fields<WindowRef::Entity>) -> WindowRef

Primary.new

new(variant: EnumVariantRef, payload: Fields<WindowRef::Primary>) -> WindowRef

WindowResizeConstraints

The size limits on a Window.

These values are measured in logical pixels (see WindowResolution), so the user’s scale factor does affect the size limits on the window.

Please note that if the window is resizable, then when the window is maximized it may have a size outside of these limits. The functionality required to disable maximizing is not yet exposed by winit.

Fields

FieldType
min_widthf32
min_heightf32
max_widthf32
max_heightf32

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

WindowResolution

Controls the size of a Window

Physical, logical and requested sizes

There are three sizes associated with a window:

  • the physical size, which represents the actual height and width in physical pixels the window occupies on the monitor,
  • the logical size, which represents the size that should be used to scale elements inside the window, measured in logical pixels,
  • the requested size, measured in logical pixels, which is the value submitted to the API when creating the window, or requesting that it be resized.

Scale factor

The reason logical size and physical size are separated and can be different is to account for the cases where:

  • several monitors have different pixel densities,
  • the user has set up a pixel density preference in its operating system,
  • the Bevy App has specified a specific scale factor between both.

The factor between physical size and logical size can be retrieved with WindowResolution::scale_factor.

For the first two cases, a scale factor is set automatically by the operating system through the window backend. You can get it with WindowResolution::base_scale_factor.

For the third case, you can override this automatic scale factor with WindowResolution::set_scale_factor_override.

Requested and obtained sizes

The logical size should be equal to the requested size after creating/resizing, when possible. The reason the requested size and logical size might be different is because the corresponding physical size might exceed limits (either the size limits of the monitor, or limits defined in WindowResizeConstraints).

Note: The requested size is not kept in memory, for example requesting a size too big for the screen, making the logical size different from the requested size, and then setting a scale factor that makes the previous requested size within the limits of the screen will not get back that previous requested size.

Fields

FieldType
physical_widthu32
physical_heightu32
scale_factor_overrideOptional<f32>
scale_factorf32

Functions

NameSummary
newCreates a resolution from a size in physical pixels.

new

new(physical_width: u32, physical_height: u32) -> WindowResolution

Creates a resolution from a size in physical pixels.

local WindowResolution = import_namespace("window").WindowResolution
local resolution = WindowResolution.new(800, 600)
assert(resolution:width() == 800)
let WindowResolution = import_namespace("window").WindowResolution;
let resolution = WindowResolution.new(800, 600);
assert!(resolution.width() == 800.0);

Methods

NameSummary
heightThe height in logical pixels.
scale_factorThe ratio of physical to logical pixels.
setSets the size in logical pixels.
widthThe width in logical pixels.

height

height(self: WindowResolution) -> f32

The height in logical pixels.

scale_factor

scale_factor(self: WindowResolution) -> f32

The ratio of physical to logical pixels.

set

set(self: WindowResolution, width: f32, height: f32)

Sets the size in logical pixels.

width

width(self: WindowResolution) -> f32

The width in logical pixels.

WindowTheme

The Window theme variant to use.

Variants

Variant
Light
Dark

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<WindowTheme>) -> WindowTheme

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

Variant Functions

NameSummary
Dark.new
Light.new

Dark.new

new(variant: EnumVariantRef, payload: Fields<WindowTheme::Dark>) -> WindowTheme

Light.new

new(variant: EnumVariantRef, payload: Fields<WindowTheme::Light>) -> WindowTheme

window.CursorSystems

The types and functions in the window.CursorSystems namespace, as returned by import_namespace("window.CursorSystems").

Values

NameType
UpdateReflectSystemSet

root

The types without a crate, such as primitives.

Types

TypeSummary
boolA boolean value
charAn 8-bit character
DynamicFunctionA callable dynamic function
DynamicFunctionMutA stateful and callable dynamic function
f32
f64A 64-bit floating point number
FunctionCallContextFunction call context, if accepted by a function, means the function can access the world in arbitrary ways.
i128A signed 128-bit integer
i16A signed 16-bit integer
i32A signed 32-bit integer
i64A signed 64-bit integer
i8A signed 8-bit integer
isizeA signed pointer-sized integer
OsStringA heap allocated OS string
PathBufA heap allocated file path
ReflectReferenceA reference to a reflectable type
ScriptValueA value representing the union of all representable values
StaticTypeRefA type itself, used to reach its static members, i.e. Vec3 in Vec3.new{}. Functions on it are shared by all types
strA string slice
StringA heap allocated string
u128An unsigned 128-bit integer
u16An unsigned 16-bit integer
u32An unsigned 32-bit integer
u64An unsigned 64-bit integer
u8An unsigned 8-bit integer
usizeAn unsigned pointer-sized integer
WorldThe ECS world containing all Components, Resources and Systems. Main point of interaction with a Bevy App.

bool

A boolean value

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<bool>) -> bool

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

char

An 8-bit character

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<char>) -> char

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

DynamicFunction

A callable dynamic function

Opaque: scripts can't access its fields, only its functions.

DynamicFunctionMut

A stateful and callable dynamic function

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<DynamicFunctionMut>) -> DynamicFunctionMut

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

f32

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<f32>) -> f32

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

f64

A 64-bit floating point number

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<f64>) -> f64

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

FunctionCallContext

Function call context, if accepted by a function, means the function can access the world in arbitrary ways.

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<FunctionCallContext>) -> FunctionCallContext

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

i128

A signed 128-bit integer

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<i128>) -> i128

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

i16

A signed 16-bit integer

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<i16>) -> i16

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

i32

A signed 32-bit integer

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<i32>) -> i32

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

i64

A signed 64-bit integer

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<i64>) -> i64

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

i8

A signed 8-bit integer

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<i8>) -> i8

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

isize

A signed pointer-sized integer

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<isize>) -> isize

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

OsString

A heap allocated OS string

Opaque: scripts can't access its fields, only its functions.

PathBuf

A heap allocated file path

Opaque: scripts can't access its fields, only its functions.

ReflectReference

A reference to a reflectable type

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
clearClears the container, if the reference is an appropriate container type.
cloneCreates an independent copy of the value, so that changing one doesn’t change the other.
functionsLists the functions available on the reference.
insertInserts the value into the reference at the specified index, if the reference is an appropriate container type.
map_getGets and clones the value under the specified key if the underlying type is a map type.
newConstructs a new instance of the type from a table of its fields.
popPops the value from the reference, if the reference is an appropriate container type.
pushPushes the value into the reference, if the reference is an appropriate container type.
removeRemoves the value at the specified key from the reference, if the reference is an appropriate container type.
variantIf this is an enum, returns a reference to the variant it is currently in.
variant_nameIf this type is an enum, will return the name of the variant it represents on the type.

clear

clear(reference: ReflectReference)

Clears the container, if the reference is an appropriate container type.

Arguments

  • reference: The reference to clear.

Returns: Nothing if the reference was cleared

clone

clone(reference: ReflectReference) -> ScriptValue

Creates an independent copy of the value, so that changing one doesn’t change the other.

Arguments

  • reference: The value to copy.

Returns: The copy.

functions

functions(reference: ReflectReference) -> Vec<FunctionInfo>

Lists the functions available on the reference.

Arguments

  • reference: The reference to list the functions of.

Returns: The functions available on the reference.

insert

insert(reference: ReflectReference, key: ScriptValue, value: ScriptValue)

Inserts the value into the reference at the specified index, if the reference is an appropriate container type.

Arguments

  • reference: The reference to insert the value into.
  • key: The index to insert the value at.
  • value: The value to insert.

Returns: Nothing if the value was inserted successfully.

map_get

map_get(reference: ReflectReference, key: ScriptValue) -> Optional<ScriptValue>

Gets and clones the value under the specified key if the underlying type is a map type.

Arguments

  • reference: The reference to index into.
  • key: The key to index with.

Returns: The value at the key, if the reference is a map.

new

new(payload: Fields<ReflectReference>) -> ReflectReference

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

pop

pop(reference: ReflectReference) -> ScriptValue

Pops the value from the reference, if the reference is an appropriate container type.

Arguments

  • reference: The reference to pop the value from.

Returns: The value that was popped, if the reference supports popping.

push

push(reference: ReflectReference, value: ScriptValue)

Pushes the value into the reference, if the reference is an appropriate container type.

Arguments

  • reference: The reference to push the value into.
  • value: The value to push.

Returns: Nothing if the value was pushed successfully.

remove

remove(reference: ReflectReference, key: ScriptValue) -> ScriptValue

Removes the value at the specified key from the reference, if the reference is an appropriate container type.

Arguments

  • reference: The reference to remove the value from.
  • key: The key to remove the value at.

Returns: The removed value if any

variant

variant(reference: ReflectReference) -> Optional<EnumVariantRef>

If this is an enum, returns a reference to the variant it is currently in.

This can be compared to MyEnum.Variant to check which variant a value is in.

Arguments

  • reference: The reference to get the variant of.

Returns: The variant, if the reference is an enum.

variant_name

variant_name(reference: ReflectReference) -> Optional<String>

If this type is an enum, will return the name of the variant it represents on the type.

Arguments

  • reference: The reference to get the variant name of.

Returns: The name of the variant, if the reference is an enum.

Operators

NameSummary
debugDisplays a debug representation of this reference.
displayDisplays this reference and its contents if possible.
eqWhether two values are equal, compared through reflection.
iterIterates over the reference, if the reference is an appropriate container type.
lenRetrieves the length of the reference, if the reference is an appropriate container type.

debug

debug(reference: ReflectReference) -> String

Displays a debug representation of this reference.

This is useful for debugging and logging.

Arguments

  • reference: The reference to display.

Returns: The display string.

display

display(reference: ReflectReference) -> String

Displays this reference and its contents if possible.

This is useful for debugging and logging.

Arguments

  • reference: The reference to display.

Returns: The display string.

eq

eq(reference: ReflectReference, other: ScriptValue) -> bool

Whether two values are equal, compared through reflection.

This is what == uses for types which don’t define their own equality. Values of different types, and values which can’t be compared, are not equal. An enum value is equal to an enum variant, i.e. MyEnum.Variant, if it is in that variant.

Arguments

  • reference: The value to compare.
  • other: The value to compare with.

Returns: Whether the values are equal.

iter

iter(reference: ReflectReference) -> DynamicFunctionMut

Iterates over the reference, if the reference is an appropriate container type.

Returns an “next” iterator function.

The iterator function should be called until it returns nil to signal the end of the iteration.

Arguments

  • reference: The reference to iterate over.

Returns: The iterator function.

len

len(reference: ReflectReference) -> Optional<usize>

Retrieves the length of the reference, if the reference is an appropriate container type.

Arguments

  • reference: The reference to get the length of.

Returns: The length of the reference, if the reference is a container.

ScriptValue

A value representing the union of all representable values

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<ScriptValue>) -> ScriptValue

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

StaticTypeRef

A type itself, used to reach its static members, i.e. Vec3 in Vec3.new{}. Functions on it are shared by all types

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
add_assetAdds a value of this type as a new asset, returning a strong handle to it.
get_assetThe asset a handle points to, or nil if it isn’t loaded or added yet.
loadStarts loading an asset of this type from a path, returning a handle to it right away.
newConstructs a new instance of the type from a table of its fields.

add_asset

add_asset<A>(asset_type: Type<A>, value: A) -> Handle<A>

Generic over A, the type given as asset_type.

Adds a value of this type as a new asset, returning a strong handle to it.

Arguments

  • asset_type: The asset type, filled in automatically.
  • value: The asset value.

Returns: A handle to the new asset.

get_asset

get_asset<A>(asset_type: Type<A>, handle: Handle<A>) -> Optional<A>

Generic over A, the type given as asset_type.

The asset a handle points to, or nil if it isn’t loaded or added yet.

Changes to the returned value change the asset.

Arguments

  • asset_type: The asset type, filled in automatically.
  • handle: The handle to the asset.

Returns: The asset, or nil.

load

load<A>(asset_type: Type<A>, path: String) -> Handle<A>

Generic over A, the type given as asset_type.

Starts loading an asset of this type from a path, returning a handle to it right away.

Arguments

  • asset_type: The asset type, filled in automatically.
  • path: The asset path, relative to the assets folder.

Returns: A handle to the asset, which is loaded in the background.

new

new(type: StaticTypeRef, payload: HashMap<String, ScriptValue>) -> ReflectReference

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • type: The type to construct.
  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

str

A string slice

Opaque: scripts can't access its fields, only its functions.

String

A heap allocated string

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<String>) -> String

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

u128

An unsigned 128-bit integer

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<u128>) -> u128

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

u16

An unsigned 16-bit integer

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<u16>) -> u16

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

u32

An unsigned 32-bit integer

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<u32>) -> u32

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

u64

An unsigned 64-bit integer

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<u64>) -> u64

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

u8

An unsigned 8-bit integer

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<u8>) -> u8

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

usize

An unsigned pointer-sized integer

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
newConstructs a new instance of the type from a table of its fields.

new

new(payload: Fields<usize>) -> usize

Constructs a new instance of the type from a table of its fields. Missing fields are filled in from the type’s default, then from the defaults of the fields’ types. For enums use the variant key, or construct from a variant directly.

Arguments

  • payload: The fields of the type, keyed by name or index, or a list of the fields in order.

Returns: The constructed value.

World

The ECS world containing all Components, Resources and Systems. Main point of interaction with a Bevy App.

Opaque: scripts can't access its fields, only its functions.

Functions

NameSummary
add_assetAdds a value as a new asset of its type, returning a strong handle to it.
add_default_componentAdds the given resource to the world.
add_observerAdds an observer which runs the callback callback of the calling script whenever an event of the given type is…
add_systemAdds the given system to the world.
asset_pathThe path the asset was loaded from, or nil if the handle is invalid or the asset was not loaded from a path.
despawnDespawns the given entity.
despawn_descendantsDespawn the descendants of the given entity.
despawn_recursiveDespawns the entity and all its descendants.
exitQuits the program.
find_entity_by_nameThe first entity with the given Name, or nil if there is none.
fixed_timeThe clock of the fixed update step, which advances in steps of the fixed timestep.
gamepadsThe entities of the connected gamepads.
get_assetRetrieves an asset by its handle and asset type registration.
get_childrenRetrieves the children of the given entity.
get_componentTries to retrieve the given component type on an entity.
get_enum_variantRetrieves the variant of an enum by name.
get_parentRetrieves the parent of the given entity.
get_resourceRetrieves the resource with the given registration.
get_schedule_by_nameRetrieves the schedule with the given name, Also ensures the schedule is initialized before returning it.
get_stateThe current value of the state of the given type, or nil if the app has no such state.
get_system_set_by_nameRetrieves a system set by its full name, i.e.
get_type_by_nameReturns either a ScriptComponentRegistration, ScriptResourceRegistration or ScriptBundleRegistration depending on…
has_assetChecks if can get asset handle
has_componentChecks if the given entity has the given component.
has_entityChecks if the given entity exists.
has_resourceChecks if the world has the given resource.
insert_bundleInserts the given bundle value into the provided entity, all of its components at once.
insert_childrenInserts the given children entities into the provided parent entity.
insert_componentInserts the given component value into the provided entity
is_loadedWhether the asset and all of its dependencies are loaded.
load_assetStarts loading an asset of the given type from a path, returning a handle to it right away.
load_stateThe loading state of the asset: "NotLoaded", "Loading", "Loaded" or "Failed".
push_childrenPushes the given children entities into the provided parent entity.
queryCreates a new ScriptQueryBuilder which can be used to query the ECS.
real_timeThe clock of the real world, which always advances at the system’s pace.
register_new_componentRegisters a new component type with the world.
register_new_eventRegisters a new script event.
register_new_system_setRegisters a new system set, which script systems can be put in and ordered against.
remove_componentRemoves the given component from the entity.
remove_resourceRemoves the given resource from the world.
set_next_stateSets the state to change to in the next state transition, for the type of the given state value.
spawnSpawns a new entity and returns it
spawn_bundleSpawns a new entity with the given bundle value and returns it.
timeThe default clock: in Update it advances by the frame time, in FixedUpdate by the fixed timestep.
trigger_eventTriggers an observer-style event: either a Rust event type with #[reflect(Event)], or an event registered with…
virtual_timeThe clock which can be paused and slowed down, it is the one games usually move objects with.
write_messageWrites a buffered message. The message type must be registered and have #[reflect(Message)].

add_asset

add_asset<A>(value: A) -> Handle<A>

Generic over A.

Adds a value as a new asset of its type, returning a strong handle to it.

Arguments

  • value: The asset value, of a type registered for asset reflection.

Returns: A handle to the new asset.

add_default_component

add_default_component(entity: Entity, registration: ScriptComponentRegistration)

Adds the given resource to the world.

Arguments

  • registration: The resource to add.

Returns: Nothing if the resource was added successfully.

add_observer

add_observer(event: ScriptTypeRegistration | ScriptEventRegistration, callback: String, components: Optional<Vec<ScriptComponentRegistration>>, entities: Optional<Vec<Entity>>) -> Entity

Adds an observer which runs the callback callback of the calling script whenever an event of the given type is triggered.

The callback is a normal script callback: either a function registered with register_callback, or a top level function with that name. It receives a copy of the event (or the payload, for script events), and is run by the same machinery as other callbacks: right after the operation which triggered the event, unless the script’s context is busy running another callback (e.g. the one that triggered the event), in which case it runs as soon as that callback finishes. Observers never re-enter a running script. The order in which the observers of an event run is unspecified. Removed component data is no longer available inside the callback. Errors of the callback are reported like those of other callbacks.

The event type must have #[reflect(Event)]. The lifecycle events (AddEvent, InsertEvent, DiscardEvent, RemoveEvent, DespawnEvent, imported with import_namespace("bevy_ecs")) are supported out of the box, and run for the given components.

Arguments

  • event: The type of the event to observe, or an event registered with register_new_event.
  • callback: The label of the callback to run, receives the event.
  • components: The components the observer is interested in, for component lifecycle events. Ignored for script events.
  • entities: If given, the observer only runs for these entities. Ignored for script events.

Returns: The observer entity, despawn it to remove the observer.

add_system

add_system(schedule: ReflectSchedule, builder: ScriptSystemBuilder) -> ReflectSystem

Adds the given system to the world.

Arguments

  • schedule: The schedule to add the system to.
  • builder: The system builder specifying the system and its dependencies.

Returns: The system that was added.

asset_path

asset_path<A>(handle: Handle<A>) -> Optional<String>

Generic over A.

The path the asset was loaded from, or nil if the handle is invalid or the asset was not loaded from a path.

Arguments

  • handle: The handle to the asset.

Returns: The asset path, if known.

despawn

despawn(entity: Entity)

Despawns the given entity.

Arguments

  • entity: The entity to despawn.

despawn_descendants

despawn_descendants(entity: Entity)

Despawn the descendants of the given entity.

Arguments

  • entity: The entity to despawn the descendants of.

Returns: Nothing if the descendants were despawned successfully.

despawn_recursive

despawn_recursive(entity: Entity)

Despawns the entity and all its descendants.

Arguments

  • entity: The entity to despawn recursively.

Returns: Nothing if the entity and its descendants were despawned successfully.

exit

exit()

Quits the program.

Returns: Nothing if the program was exited successfully.

find_entity_by_name

find_entity_by_name(name: String) -> Optional<Entity>

The first entity with the given Name, or nil if there is none.

fixed_time

fixed_time() -> Time<Fixed>

The clock of the fixed update step, which advances in steps of the fixed timestep.

gamepads

gamepads() -> Vec<Entity>

The entities of the connected gamepads.

get_asset

get_asset<A>(handle_reference: Handle<A>, registration: Type<A>) -> Optional<A>

Generic over A, the type given as registration.

Retrieves an asset by its handle and asset type registration.

Arguments

  • handle_reference: The handle to the asset (as a reflect reference).
  • registration: The type registration of the asset type.

Returns: The asset reference, if the asset is loaded.

get_children

get_children(entity: Entity) -> Vec<Entity>

Retrieves the children of the given entity.

Arguments

  • entity: The entity to retrieve the children of.

Returns: The children of the entity.

get_component

get_component<A>(entity: Entity, registration: Type<A>) -> Optional<A>

Generic over A, the type given as registration.

Tries to retrieve the given component type on an entity.

Arguments

  • entity: The entity to retrieve the component from.
  • registration: The component to retrieve.

Returns: The component on the entity, if it exists.

get_enum_variant

Retrieves the variant of an enum by name.

This is the same as accessing MyEnum.Variant, but works for variants which share a name with a function.

Arguments

  • registration: The enum type.
  • variant_name: The name of the variant.

Returns: The variant, if the type is an enum with such a variant.

get_parent

get_parent(entity: Entity) -> Optional<Entity>

Retrieves the parent of the given entity.

Arguments

  • entity: The entity to retrieve the parent of.

Returns: The parent of the entity

get_resource

get_resource<A>(registration: Type<A>) -> Optional<A>

Generic over A, the type given as registration.

Retrieves the resource with the given registration.

Arguments

  • registration: The registration of the resource to retrieve.

Returns: The resource, if it exists.

get_schedule_by_name

get_schedule_by_name(name: String) -> Optional<ReflectSchedule>

Retrieves the schedule with the given name, Also ensures the schedule is initialized before returning it.

Schedules in bevy are “containers” for systems, each schedule runs separately and contains different systems.

By default among others bevy contains the following schedules:

  • Update: Runs every frame.
  • PostUpdate: Runs after the Update schedule.
  • FixedUpdate: Runs at a fixed rate.

Arguments

  • name: The name of the schedule to retrieve.

Returns: The schedule with the given name, if it exists

get_state

get_state<A>(state_type: Type<A>) -> Optional<A>

Generic over A, the type given as state_type.

The current value of the state of the given type, or nil if the app has no such state.

The state type is passed as its registration, see world.get_type_by_name.

get_system_set_by_name

get_system_set_by_name(name: String) -> Optional<ReflectSystemSet>

Retrieves a system set by its full name, i.e. transform.TransformSystems.Propagate for a set of the game, or script.my_game.ai for a set registered by a script.

The sets of the game are also members of their namespace, i.e. import_namespace("transform.TransformSystems").Propagate.

Arguments

  • name: The full name of the system set.

Returns: The system set with the given name, if it exists.

get_type_by_name

get_type_by_name<A>(type_name: Type<A>) -> Optional<Type<A>>

Generic over A, the type given as type_name.

Returns either a ScriptComponentRegistration, ScriptResourceRegistration or ScriptBundleRegistration depending on the type of the type requested. If the type is none of these returns a ScriptTypeRegistration.

Arguments

  • type_name: The full path of the type to retrieve, i.e. bevy_transform::components::transform::Transform or script.my_game.Enemy.

Returns: The registration of the type, if it exists.

has_asset

has_asset<A>(handle_reference: Handle<A>) -> bool

Generic over A.

Checks if can get asset handle

has_component

has_component(entity: Entity, registration: ScriptComponentRegistration) -> bool

Checks if the given entity has the given component.

Arguments

  • entity: The entity to check.
  • registration: The component to check for.

Returns: Whether the entity has the component.

has_entity

has_entity(e: Entity) -> bool

Checks if the given entity exists.

Returns: Whether the entity exists.

has_resource

has_resource(registration: ScriptResourceRegistration) -> bool

Checks if the world has the given resource.

Arguments

  • registration: The registration of the resource to check for.

Returns: Whether the world has the resource.

insert_bundle

insert_bundle(entity: Entity, registration: ScriptBundleRegistration, value: ReflectReference)

Inserts the given bundle value into the provided entity, all of its components at once.

The bundle type must be registered in rust with #[reflect(Bundle)].

Arguments

  • entity: The entity to insert the bundle into.
  • registration: The bundle registration of the bundle to insert.
  • value: The value of the bundle to insert. Can be constructed like any other value, i.e. using construct or the type’s new function.

Returns: Nothing if the bundle was inserted successfully.

insert_children

insert_children(entity: Entity, index: usize, children: Vec<Entity>)

Inserts the given children entities into the provided parent entity.

Arguments

  • entity: The parent entity to receive children
  • index: The index to insert the children at
  • children: The children entities to insert

Returns: Nothing if the children were inserted successfully.

insert_component

insert_component<A>(entity: Entity, registration: Type<A>, value: A)

Generic over A, the type given as registration.

Inserts the given component value into the provided entity

Arguments

  • entity: The entity to insert the component into.
  • registration: The component registration of the component to insert.
  • value: The value of the component to insert. Can be constructed using construct

Returns: Nothing if the component was inserted successfully.

is_loaded

is_loaded<A>(handle: Handle<A>) -> bool

Generic over A.

Whether the asset and all of its dependencies are loaded.

Arguments

  • handle: The handle to the asset.

Returns: Whether the asset and its dependencies are loaded.

load_asset

load_asset<A>(path: String, asset_type: Type<A>) -> Handle<A>

Generic over A, the type given as asset_type.

Starts loading an asset of the given type from a path, returning a handle to it right away.

Arguments

  • path: The asset path, relative to the assets folder.
  • asset_type: The type of the asset, i.e. bevy_mod_scripting_asset::script_asset::ScriptAsset.

Returns: A handle to the asset, which is loaded in the background.

load_state

load_state<A>(handle: Handle<A>) -> String

Generic over A.

The loading state of the asset: "NotLoaded", "Loading", "Loaded" or "Failed".

Arguments

  • handle: The handle to the asset.

Returns: The name of the loading state.

push_children

push_children(entity: Entity, children: Vec<Entity>)

Pushes the given children entities into the provided parent entity.

Arguments

  • entity: The parent entity to receive children
  • children: The children entities to push

Returns: Nothing if the children were pushed successfully.

query

query() -> ScriptQueryBuilder

Creates a new ScriptQueryBuilder which can be used to query the ECS.

Returns:

  • query: The new query builder.

real_time

real_time() -> Time<Real>

The clock of the real world, which always advances at the system’s pace.

register_new_component

register_new_component(namespace: String, name: String, allow_existing: Optional<bool>) -> ScriptComponentRegistration

Registers a new component type with the world.

The component will behave like any other native component for all intents and purposes. The type that will be instantiated to back this component will be DynamicComponent which contains just one field:

  • data

This field can be set to any value and modified freely.

Arguments

  • namespace: The script namespace to register the component in, it must start with script., i.e. script.my_game. Scripts cannot add to other namespaces.
  • name: The name of the component type, unique within the namespace. The component can later be found as import_namespace(namespace).name.
  • allow_existing: If true, returns the registration of the already registered component with this name instead of failing. Defaults to false.

Returns: The registration of the new component type if successful.

register_new_event

register_new_event(namespace: String, name: String, allow_existing: Optional<bool>) -> ScriptEventRegistration

Registers a new script event.

Script events carry an arbitrary payload, and can be observed with add_observer and triggered with trigger_event.

Arguments

  • namespace: The script namespace to register the event in, it must start with script., i.e. script.my_game.
  • name: The name of the event, unique within the namespace.
  • allow_existing: If true, returns the already registered event with this name instead of failing. Defaults to false.

Returns: The handle of the new event.

register_new_system_set

register_new_system_set(namespace: String, name: String, allow_existing: Optional<bool>) -> ReflectSystemSet

Registers a new system set, which script systems can be put in and ordered against.

The set is removed from its namespace when the script unloads, registering it again (i.e. after a reload) gives the same set.

Arguments

  • namespace: The script namespace to register the set in, it must start with script., i.e. script.my_game.
  • name: The name of the set, unique within the namespace. The set can later be found as import_namespace(namespace).name.
  • allow_existing: If true, returns the already registered set with this name instead of failing. Defaults to false.

Returns: The new system set.

remove_component

remove_component(entity: Entity, registration: ScriptComponentRegistration)

Removes the given component from the entity.

Arguments

  • entity: The entity to remove the component from.
  • registration: The component to remove.

Returns: Nothing if the component was removed successfully or didn’t exist in the first place.

remove_resource

remove_resource(registration: ScriptResourceRegistration)

Removes the given resource from the world.

Arguments

  • registration: The resource to remove.

Returns: Nothing if the resource was removed successfully or didn’t exist in the first place.

set_next_state

set_next_state(value: ReflectReference)

Sets the state to change to in the next state transition, for the type of the given state value.

Errors if the value is not of a state type that the app has.

spawn

spawn() -> Entity

Spawns a new entity and returns it

Returns: The newly spawned entity

spawn_bundle

spawn_bundle(registration: ScriptBundleRegistration, value: ReflectReference) -> Entity

Spawns a new entity with the given bundle value and returns it.

Arguments

  • registration: The bundle registration of the bundle to insert.
  • value: The value of the bundle to insert.

Returns: The newly spawned entity

time

time() -> Time<()>

The default clock: in Update it advances by the frame time, in FixedUpdate by the fixed timestep.

trigger_event

trigger_event(event: ScriptTypeRegistration | ScriptEventRegistration, value: Optional<ScriptValue>)

Triggers an observer-style event: either a Rust event type with #[reflect(Event)], or an event registered with register_new_event.

Observers run immediately, and the commands they queue are applied before this function returns.

Arguments

  • event: The type of the event, or the script event.
  • value: The event value, e.g. built with construct, for Rust events. Any value (or nothing) for script events, which is passed to the observers.

Returns: Nothing if the event was triggered successfully.

virtual_time

virtual_time() -> Time<Virtual>

The clock which can be paused and slowed down, it is the one games usually move objects with.

write_message

write_message(registration: ScriptTypeRegistration, message: ReflectReference)

Writes a buffered message. The message type must be registered and have #[reflect(Message)].

Arguments

  • registration: The type of the message.
  • message: The message value, e.g. built with construct.

Returns: Nothing if the message was written successfully.

Developing BMS

This section is for developers who want to contribute to the BMS project. It covers various topics necessary for understanding the project and contributing to it.

Contributing

Please see the code of conduct as well as the contributing guidelines first.

In this section

  • Setup: preparing a local development environment
  • Writing Bindings: adding bindings for Bevy crates
  • New Languages: what it takes to support another scripting language
  • RFCs: design proposals and their discussion

Setup

BMS uses an xtask setup, which sets up everything you need for local development:

cargo xtask init

It currently configures the following IDEs:

If you’d like to add support for another IDE, please feel free to open a PR!

Writing Bindings

The bevy bindings shipped with BMS are hand written, using the #[script_bindings] macro (see Controlling Script Bindings). They live in crates/bindings/bevy_mod_scripting_bevy_<category>_bindings, one crate per area of functionality (i.e. math, ecs, ui) rather than one per upstream bevy crate.

The aim is a small, well documented scripting surface, which reads naturally from a script and compiles quickly.

Namespaces

Scripts reach types through the namespace of their category, i.e. import_namespace("math").Vec3 (see Namespaces). So each bindings crate:

  • passes namespace = "<category>" to every #[script_bindings] attribute, except on impl World blocks and on functions shared by all types (impl StaticTypeRef), which would otherwise move those BMS types into the category
  • calls set_crate_script_namespaces from its plugin’s finish, with the bevy crates it covers, so their types without bindings land in the same namespace

Generic types

Declare the generic types of the crate from its plugin, in the namespace of the category (register_generic_type::<Time<A>>("time", ...)), and use the markers in generic function signatures, see Generics.

Only declare types whose parameter is part of what they are (Handle, Time, ButtonInput), not containers like Arc<T>. Undeclared instantiations get a class each, named after their arguments (render.MeshExtractableData.Indices).

What to bind

Every reflected type is already usable from scripts without any bindings:

  • fields are read and written through references, i.e. transform.translation.x = 2
  • every type can be constructed with Type.new({...}), see Constructing Arbitrary Types
  • enum variants are available as Type.Variant
  • containers support len, iter, push etc., and every value can be printed

So only bind what scripts can’t already do, or can’t do comfortably:

  • methods with behaviour, i.e. Vec3:normalize() or Transform:look_at(...)
  • constructors for types which are built often (vectors, colors), or whose fields are private (i.e. Name), or whose meaning isn’t obvious from their fields (i.e. Quat.from_rotation_y)
  • operators, by registering functions named add, sub, mul, div, rem, neg, pow, eq or lt. With a number on the left, i.e. 2 * v, add and mul are called with the operands swapped, the others call rsub, rdiv, rrem or rpow on the right operand, which you register where they make sense

Do not write getters or setters for public fields.

Performance

  • Take non primitive arguments as R<T> or M<T>. These are a downcast of the reference the script holds, while V<T> rebuilds the value through reflection. Clone natively if you need ownership.
  • Return a reference with an extended path when returning a part of the receiver; it costs nothing, and writes to it reach the original value. Returning V<T> allocates a new value.
  • There is one function per name: registering a name again replaces the function. For mixed operands accept a Union, i.e. rhs: Union<R<Vec3>, f32>.
  • Mutate in place by taking M<Self>; pure functions return new values.

Native types

Hot value types, i.e. Vec3, can be stored by the languages themselves instead of being referenced through the world. Functions read them without converting to ScriptValues:

// fields are read and written with typed accessors
script_native!(world, Vec3 { x: f32, y: f32, z: f32 });
// components (and resources) of native types are native handles: `get_component` returns one, `t.translation` is a
// handle to the field, `t.translation.x = 5` writes the component
script_native!(world, Transform { translation: Vec3, rotation: Quat, scale: Vec3 });

Values of types with fields of native types (Transform.from_xyz(..)) stay references, so writes to their fields aren’t lost on a copy. Handles claim access to their component for each call, and error once the entity or component is gone. Arguments which aren’t native, i.e. references, are converted as usual.

Documentation

Doc comments end up in the generated docs and in editor declaration files, and are read by script writers rather than Rust developers:

  • start with one short sentence, and only describe the arguments when they are not obvious
  • avoid Rust specific terms, i.e. say “or nil” rather than Option
  • link bevy types using their full Rust path, i.e. [`Vec3`](glam::Vec3), these will be resolved to the bevy docs

Examples

Keep examples short and only add them where they help. Write one block per language, one after the other, using the multi-lang-example code block attribute followed by the language:

```multi-lang-example,lua
local Vec3 = import_namespace("math").Vec3
local v = Vec3.new(1, 2, 3)
assert(v.x == 1)
```

```multi-lang-example,rune
let Vec3 = import_namespace("math").Vec3;
let v = Vec3.new(1, 2, 3);
assert!(v.x == 1.0);
```

which renders as a single block with a tab per language:

local Vec3 = import_namespace("math").Vec3
local v = Vec3.new(1, 2, 3)
assert(v.x == 1)
let Vec3 = import_namespace("math").Vec3;
let v = Vec3.new(1, 2, 3);
assert!(v.x == 1.0);

Examples are tests: they must run as written and check their own results with assert. Every multi-lang-example block in the doc comments under crates/ and in the book is run by the doc_example_tests test, with the scenario in assets/doc_examples/default.bmsscenario (the same app as the script tests):

cargo test --test doc_example_tests --features lua54,rune,bevy_math_bindings -- math

Examples of a bindings crate whose feature is disabled are ignored. If an example needs a different setup, i.e. a window, name a scenario with the scenario attribute, i.e. multi-lang-example,lua,scenario=window, which refers to assets/doc_examples/window.bmsscenario. Mark examples which can’t run in a test app with ignore, i.e. multi-lang-example,lua,ignore, and say what they need in the surrounding docs.

Tests

Each bindings crate has its script tests under assets/tests/bindings/<category>/, with a script per language per type or topic, i.e. assets/tests/bindings/math/vec.lua and assets/tests/bindings/math/vec.rn. Run them with:

cargo test --test script_tests --features lua54,rune -- bindings/math

Adding New Languages to BMS

If you are interested in adding a new language to BMS, please read this section first. Adding a new language is a non-trivial task depending on the language you want to add. It also requires a lot of effort and time to maintain a new language, so unless the language you want to add is widely used and has a large community, it might not be worth the effort.

Evaluating Feasibility

In order for a language to work well with BMS it’s necessary it supports the following features:

  • Interoperability with Rust. If you can’t call it from Rust easilly and there is no existing crate that can do it for you, it’s a no-go.
  • First class functions. Or at least the ability to call an arbitrary function with an arbitrary number of arguments from a script. Without this feature, you would need to separately generate code for the bevy bindings which is painful and goes against the grain of BMS.

First Classs Functions

They don’t necessarily have to be first class from the script POV, but they need to be first class from the POV of the host language. This means that the host language needs to be able to call a function with an arbitrary number of arguments.

Examples

Let’s say your language supports a Value type which can be returned to the script. And it has a Value::Function variant. The type on the Rust side would look something like this:

pub enum Value {
    Function(Arc<Fn(&[Value]) -> Value>),
    // other variants
}

This is fine, and can be integrated with BMS. Since an Fn function can be a closure capturing a DynamicScriptFunction. If there is no support for FnMut closures though, you might face issues in the implementation. Iterators in bevy_mod_scripting_functions for example use DynamicScriptFunctionMut which cannot work with Fn closures.

Now let’s imagine instead another language with a similar enum, supports this type instead:

#![allow(unused)]
fn main() {
pub enum Value {
    Function(Arc<dyn Function>),
    // other variants
}

pub trait Function {
    fn call(&self, args: Vec<Value>) -> Value;

    fn num_params() -> usize;
}
}

This implies that to call this function, you need to be able to know the amount of arguments it expects at COMPILE time. This is not compatibile with dynamic functions, and would require a lot of code generation to make work with BMS. Languages with no support for dynamic functions are not compatible with BMS.

Interoperability with Rust

Not all languages can easilly be called from Rust. Lua has a wonderful crate which works out the ffi and safety issues for us. But not all languages have this luxury. If you can’t call it from Rust easilly and there is no existing crate that can do it for you, integrating with BMS might not be the best idea.

Necessary Features

In order for a language to be called “implemented” in BMS, it needs to support the following features.

Values

Every ScriptValue variant needs a counterpart in the language, in both directions. Two of them are handles rather than data:

  • ScriptValue::Reference: a reference to a reflected value, usually a userdata/custom type wrapping ReflectReference.
  • ScriptValue::Type: a type itself, i.e. what scripts use to reach a type’s static members. It carries only a TypeId and never allocates.

Every context gets the builtins as globals, nothing else: bevy_mod_scripting_bindings::builtins::builtins() (import_namespace, export_namespace) plus the language’s own register_callback:

for (name, function) in builtins() {
    context.globals().set(name, LuaScriptValue::from(ScriptValue::Function(function)))?;
}

Script handlers, loaders etc. must be implemented such that the ThreadWorldContainer is set for every interaction with script contexts, or anywhere else it might be needed.

Typed calls and native values

A language calls every function with DynamicScriptFunction::call_with (see bevy_mod_scripting_bindings::native), passing:

  • an ArgSource over its own values: numbers, booleans, native values, and any argument converted to a ScriptValue (the slow path)
  • a ReturnSink, which receives numbers, booleans, new native values or ScriptValues

DynamicScriptFunctionMut converts into a DynamicScriptFunction (.into()), so both are called the same way.

Native values are stored by the language as NativeStorage ([NativeHeader][value]): in memory it owns which never moves (a Lua userdata), or in a NativeBox. The language reaches their fields through the NativeType’s accessors and their methods through the functions registered on the type; anything else goes through NativeStorage::to_script_value, a reference to a copy. A language can decline native values (ReturnSink::native returning false), which then come back as references.

Dispatching to Rust

All lookup rules live in bevy_mod_scripting_bindings::dispatch; a language maps its operators and metamethods onto it, and converts the values:

Script operationdispatch function
v.name, v[key]index, returns Member::Method or Member::Static
v.name = xset_index
Type.name on a ScriptValue::Typestatic_index
v + x, -, *, /, %, ^, ==, <binary with the matching ScriptOperatorNames (dispatches to add, sub, mul, div, rem, pow, eq, lt)
2 * v (value on the right)binary too, which calls the operator’s reflected function (mul, rsub, …)
-vunary with Negation (neg)
#vlen (lists directly, references through len)
iterationiter, returns a function to call until it returns ScriptValue::Unit
printingdisplay / debug

Receivers

index returns functions which are called on the indexed value as Member::Method, without the value bound to them. Delivering the receiver is the language’s job:

  • Lua passes it with its colon syntax, v:length(), so the function is returned as is.
  • Rune has method syntax, but resolves v.name by a table fixed when its context is built, so every identifier in the script is registered when it is compiled (and v["name"] always works), see bevy_mod_scripting_rune::types. The receiver is passed to the function as the first argument.

Static members

Type.name resolves, in order, to:

  1. functions registered on the type itself
  2. functions shared by all types (registered on StaticTypeRef, i.e. the new constructor), with the type bound as their first argument by DynamicScriptFunction::bind_to_type
  3. the type’s enum variants

Types reach scripts in two forms, which resolve static members the same way:

  • ScriptValue::Type, i.e. world (import_namespace("bms").world), indexed with dispatch::static_index
  • type registrations, i.e. the entries of import_namespace, which are references and are indexed with dispatch::index like any other value

Binding the type is done by BMS, so languages never handle StaticTypeRef arguments themselves.

RFCs

An RFC is a request for comments from contributors, users and various other stakeholders. When an RFC is created it is usually done with the intention of gathering opinions and knowledge around the topic.

For BMS the process looks as follows:

  • An RFC is created and modified via PRs to the RFC file under docs/src/RequestsForComments/XX-RFCTITLE/XX-RFCTITLE.md.
  • The creator of an RFC also starts an issue for discussion of the RFC on github linking to the file.
  • Once enough perspectives are gathered an RFC can be closed and the decision implemented.

Abandoning Codegen

Summary

Codegen has played a big role from the start for BMS, giving us great benefits, but mainly the ability to quickly ‘sync’ our scripting API with each new bevy release (instead of a manual review each time).

This was especially important before the introduction of a unified scripting function registry, which would have meant writing a version of each API per language.

However, I believe that as Bevy is maturing, the APIs that people rely on are likely to be more stable than ever, and I have a hypothesis that a large majority of the generated bindings are simply left unused.

The other side of the coin is that codegen is somewhat problematic due to:

  • Largely increased compilation times
  • The need to stay in sync with the rustc codebase (the compiler internals we use to plug into the compilation)

I believe it’s time to finally abandon this concept, and commit to hand writing a core scripting API over the important parts of bevy.

Status Quo

A little context for those who are not aware of how codegen works in our case.

Automatic Bindings

The code under /codegen contains crates which create a custom cargo executable (a driver and the entry point). This works with cargo to execute a custom rustc compilation, which on top of compiling and error checking the code, also runs our custom hooks.

In these hooks we scan through the available types and generate artifacts as we go (caches and lookups), which are then used to render code templates. All of the crates found under crates/bindings are fully rendered via this process.

These templates direct the generator to produce #[script_bindings] invocations, just as if they were handwritten, based on the functions available.

The process is slightly limited due to the presence of generics and other rust quirks which can’t be handled automatically, e.g. fn hello<A: ToString>(a: A) wouldn’t work, even though it’s somewhat trivial to deal with by hand.

At the end we are left with tonnes of bindings crates for all the important bevy crates.

An example can be seen in our book with the SRGBA struct:

Note that the docgen is not tied to codegen, the same documentation would be produced if you manually wrote the script bindings macro invocations yourself.

Existing Manual Bindings

Not all of our bindings are automatically generated like this however. The crate bevy_mod_scripting_functions contains a load of hand-written core types and functions, like World::get_type_by_name or World::get_component, and way more.

These already live happily alongside the generated bindings, and are the model for what this RFC proposes we do everywhere.

Motivation

With the above in mind, I form the following hypotheses:

  • Automatically generated bindings are okay at best, with many functions missing and docs mentioning rust constructs explicitly (since they come directly from docstrings)
  • Most of them are unused
  • The lack of functionality for generating bindings for 3rd party libraries means the codegen is not as useful as it could be
  • Bevy’s API is stabilizing, and upcoming work on enums and constructors will make many bindings unnecessary anyway

Proposal

Based on the above, I propose the following:

  • Handwriting binding crates with high quality multi language docstrings
  • Empowering the community to build their own bindings crates for their favourite libraries

In this new world we would focus on writing the most critical pieces of integration with bevy. Instead of putting in effort to maintain a bespoke rustc compiler plugin, we could provide github action templates to let people build out bindings quickly.

Migration

The codegen runs on our side, not on the consumer’s machine, and its output is committed. So no feature flag or default-on/off transition is needed:

  1. Remove the codegen project, keeping whatever it last generated as plain source.
  2. Iterate on and clean up those bindings, deleting ones that are no longer needed as the enum and constructor work lands.

This starts from a non-breaking state, and I’d like to begin as early as the 0.20 cycle rather than waiting for the editor.

Bindings for 3rd party libraries (e.g. bevy_hanabi, UI, physics) would not live in core, which would only keep Bevy-native bindings. Instead we’d make it easy to set up small community bindings crates that sync to the main test suite and publish easily.

Alternatives

We could also of course make our current codegen better, more flexible and generally stronger, however some of its core problems will always remain (like bad documentation at best, and long compilation times).

Benefits

  • Clean compilation times have potential to go down by as much as 10 minutes (on my machine), which also makes clean CI builds cheaper
  • Bevy bindings quality increases, and a smaller API surface is easier for beginners
  • Intermediate file sizes decrease (i.e. LAD files, LUA declaration files)

Drawbacks

  • Each bevy version upgrade might take longer, due to the need to identify API surface changes. However, this should be fairly well mitigated by our test suite and also thanks to AI tools nowadays
  • Potentially smaller (but hopefully higher quality) API surface immediately after the switch

Release Notes

This section contains migration guides and release notes relevant to the bevy_mod_scripting crate.

This used to live in the repository, so for older release notes or guides, refer to the GitHub repository

Migration Guide: 0.13 to 0.14-alpha or 0.14 to 0.15

The most important changes to be aware of in this release are:

  • BMS now uses Handle<ScriptAsset> as its principle means of referring to scripts as opposed to the ScriptId that was used previously.

  • BMS exposes many more choices for deciding how scripts are associated with the contexts in which they run.

  • script_id is replaced with script_asset which now has a type of Handle<ScriptAsset>.

Handles

The use of handles for scripts is perhaps the biggest user-facing change. It makes BMS asset usage follow Bevy’s conventions. It requires less configuration. It is more idiomatic.

ScriptComponent Change

In prior versions, ScriptComponent accepted a vector of ScriptIds, which was a type alias for Cow<'static, str>.

-pub struct ScriptComponent(pub Vec<Cow<'static, str>>);
+pub struct ScriptComponent(pub Vec<Handle<ScriptAsset>>);

Because ScriptComponent accepts handles, it is no longer necessary to store the handles somewhere to prevent the script from unloading. Nor is it necessary to configure an asset path to script id mapper.

ScriptComponent(vec![asset_server.load("foo.lua")])

It is still beneficial to retain script assets in memory, for certain features to work. For example, script_asset will not be able to retrieve the asset path of the script if it’s not retained.

ScriptId Change

The ScriptId has changed from being a string to being an asset ID.

-type ScriptId = Cow<'static, str>
+type ScriptId = AssetId<ScriptAsset>

No Evaluation on Load

In prior versions, BMS would immediately evaluate a ScriptAsset when it was loaded, and if multiple script assets were loaded, they would be evaluated in non-deterministic order. (See issue #426.) Script assets no longer evaluate immediately. Script assets are only evaluated when their handles are added to a ScriptComponent or they are added to StaticScripts.

In addition when a ScriptComponent loads its scripts, it loads them sequentially.

ScriptAssetSettings Removed

The ScriptAssetSettings has been removed. Let us address each of its fields in turn.

script_id_mapper

See AssetPathToScriptIdMapper section.

extension_to_language_map and supported_extensions

This is now represented by the LanguageExtensions resource, which can be configured directly during initialization

pub struct LanguageExtensions(HashMap<&'static str, Language>);

or by the ConfigureScriptAssetSettings trait:

app.add_supported_script_extensions(&["p8lua"], Language::Lua);

In addition one can configure the language of an asset when it is loaded:

asset_server.load_with_settings("hello.p8lua", |settings: &mut ScriptSettings| {
   settings.language = Some(Language::Lua);
});

or when it is created:

let content = String::from("x = 0");
let mut script = ScriptAsset::from(content);
script.language = Language::Lua;

ScriptMetadata and ScriptMetadataStore Removed

These were present to associate the previous ScriptId with the asset ID and language. That is no longer necessary as the ScriptAsset knows its own language.

pub struct ScriptAsset {
    /// The body of the script
    pub content: Box<[u8]>,
    /// The language of the script
    pub language: Language,
}

AssetPathToScriptIdMapper Removed

No mapper is necessary between a script and a script ID. If you have a script handle, you have its script ID

let handle: Handle<ScriptAsset> = ...;
let script_id: ScriptId = handle.id(); // ScriptId = AssetId<ScriptAsset>

and vice versa.

let script_id: ScriptId = ...;
let handle: Handle<ScriptAsset> = Handle::Weak(script_id);

Contexts

Choosing how scripts run is a big policy decision. Previously BMS had two options:

  • Each script ran in its own context.
  • All scripts ran in one context.

This was controlled by the enable_context_sharing() method on ConfigureScriptPlugin. That function is now deprecated. Instead use the set_context_policy method:

app.add_plugins(LuaScriptingPlugin::default().set_context_policy(
    ContextPolicy::shared(),
));

The reason for this change is there are many more choices than before, namely:

  • ContextPolicy::shared()
  • ContextPolicy::per_script()
  • ContextPolicy::per_entity()
  • ContextPolicy::per_entity_and_script()

See Contexts for more information.

ContextKey Added

Previously BMS used a ScriptId and sometimes an Entity to refer to a context. If there was no entity then Entity::from_raw(0) was used. Instead BMS now uses this ContextKey to look up contexts.

pub struct ContextKey {
    /// Entity if there is one.
    pub entity: Option<Entity>,
    /// Script ID if there is one.
    pub script_id: Option<Handle<ScriptAsset>>
}

This change affects the parameters for the context_pre_handling_initializers

- context_pre_handling_initializers: vec![|script_id, entity, context| {
+ context_pre_handling_initializers: vec![|context_key, context| {

and context_initializers:

- context_initializers: vec![|script_id, context| {
+ context_initializers: vec![|context_key, context| {

Recipients Changes

The Recipients enum now looks like this:

#[derive(Clone, Debug)]
pub enum Recipients {
    /// The event needs to be handled by all scripts, if multiple scripts share a context, the event will be sent once per script in the context.
    AllScripts,
    /// The event is to be handled by all unique contexts, i.e. if two scripts share the same context, the event will be sent only once per the context.
    AllContexts,
    /// The event is to be handled by a specific script-entity pair
    ScriptEntity(ScriptId, Entity),
    /// the event is to be handled by a specific static script
    StaticScript(ScriptId),
}

This aligns with how scripts are associated with contexts better.

ScriptCallbackEvent changes

The language for recipients is now controlled through the language field of the ScriptCallbackEvent. This allows for more flexibility in how callbacks are handled, especially when multiple languages are involved.

If no language is specified, the callback will apply to all languages.

#[derive(Clone, Event, Debug)]
#[non_exhaustive]
pub struct ScriptCallbackEvent {
    /// The label of the callback
    pub label: CallbackLabel,
    /// The recipients of the callback
    pub recipients: Recipients,
    /// The language of the callback, if unspecified will apply to all languages
+   pub language: Option<Language>
    /// The arguments to the callback
    pub args: Vec<ScriptValue>,
    /// Whether the callback should emit a response event
    pub trigger_response: bool,
}

Bindings Changes

ScriptId

script_id is replaced with script_asset which now has a type of Handle<ScriptAsset>. This means that you can no longer use a string to refer to a script, but rather you must use a handle.

Scripts can still access the asset path of the script using:

-- prints: "my_script.lua"
print(script_asset:asset_path())

ScriptAttachment

The concept of script attachments has been introduced to describe the idea of a script instance. Previously this was muddied due to the fact script ID’s were the primary way to refer to scripts. Now the instance of a script and its mapping to a context is clearer.

This is reflected in a brand new set of bindings:

-- will create backing ScriptAttachment instances, that can be used in other bindings.
local entity_script = ScriptAttachment.new_entity_script(entity, script_asset)
local static_script = ScriptAttachment.new_static_script(script_asset)

System Builder

the system builder no longer accepts script id’s as parameters. Instead it accepts script attachments

-system_builder("my_callback", "this_script_id.lua")
+system_builder("my_callback", ScriptAttachment.new_static_script(script_asset))

0.15.0 - Asset Handles and Context Policies

This release focuses on aligning bevy_mod_scripting with modern Bevy practices, most notably by switching to Handle<ScriptAsset> for script management. This change simplifies the API, removes boilerplate, and makes script handling more idiomatic.

Summary

Asset-First Workflow

Scripts are now treated as first-class Bevy assets. The old ScriptId (which was a string) has been replaced by AssetId<ScriptAsset>, and you’ll primarily interact with scripts via Handle<ScriptAsset>.

// New way
let handle: Handle<ScriptAsset> = asset_server.load("my_script.lua");
commands.spawn(ScriptComponent(vec![handle]));

Scripts are now only evaluated when they are attached to a ScriptComponent or added to StaticScripts, which means you have more control over when and how scripts are executed.

Flexible Context Policies

You now have much finer control over how script contexts (i.e., the environment a script runs in) are created. The old enable_context_sharing() has been replaced with set_context_policy() which accepts a ContextPolicy:

  • ContextPolicy::shared(): All scripts run in one global context
  • ContextPolicy::per_script(): Each script asset gets its own context (the old default.)
  • ContextPolicy::per_entity(): Each entity with scripts gets its own context.
  • ContextPolicy::per_entity_and_script(): A unique context for every script on every entity (the new default).

This means that each script is maximally isolated by default, but you can still opt for shared contexts if needed.

Other Changes

  • Recipients Enum: The Recipients enum for events has been redesigned to align with the new context policies, offering AllScripts and AllContexts variants, and removing some variants which don’t fit the new model. If you need the old behaviour, you can simply query the ECS first before sending events.
  • API Cleanup: Several types and traits were removed or simplified, including ScriptAssetSettings, AssetPathToScriptIdMapper, and ScriptMetadataStore, as they are no longer needed with the new asset-based approach.

Migration Guide

This release contains significant breaking changes. Please refer to the migration guide for detailed instructions on updating your project.

Migrating to 0.16.0

https://github.com/makspll/bevy_mod_scripting/pull/455

Replace all usages of CallbackSettings<P>.callback_handler with P::handler()(..) and P::handle(..)

https://github.com/makspll/bevy_mod_scripting/pull/456

Replace all usages of CallbackBuilder<P>.load and CallbackBuilder<P>.reload with P::load(..) and P::reload(..) or P::context_loader()(..) and P::context_reloader()(..)

https://github.com/makspll/bevy_mod_scripting/pull/463

If you were relying on BMS enabling some features in Bevy crates, your builds might be pulling in less features than you expect. Ensure you explicitly select all features you need from bevy. BMS will now only pull in strictly necessary features and crates from bevy

https://github.com/makspll/bevy_mod_scripting/pull/470

Switch all references of ContextLoadingSettings to P::readonly_config(world.id()).

https://github.com/makspll/bevy_mod_scripting/pull/471

RuntimeSettings and RuntimeContainer are removed, replace usages with P::readonly_settings(world.id()).runtime) access to initializers is no longer possible outside the plugin setup phase

https://github.com/makspll/bevy_mod_scripting/pull/472

if you implemented a scripting plugin you will need to correct your function signatures for the above aliases, and fetch the config yourself to access callbacks via Plugin::readonly_configuration(world_id) using the world id you will now receive.

https://github.com/makspll/bevy_mod_scripting/pull/473

references to StaticScripts should be replaced with appropriate resident calls on ScriptContext filtered by the attachment kind

https://github.com/makspll/bevy_mod_scripting/pull/474

  • ScriptContext Access: Use .read() and .write() to access ScriptContext (now wrapped in Arc<RwLock<>>); replace get() with get_context()
  • HandlerContext: Replace with direct ScriptContext access; remove any with_handler_system_state() calls
  • Script Callbacks: Use new call_context_dynamic() or call_context() methods from the CallContext trait
  • Custom Context Types: Implement the new GetPluginFor trait to provide mapping from context to plugin type
  • Lua Interaction: Replace mlua::Lua with LuaContext wrapper type in all Lua code on BMS side
  • Script Callback Running: Replace run_with_handler() calls with run_with_context() or run_with_contexts()

https://github.com/makspll/bevy_mod_scripting/pull/475

  • References previously resident in bevy_mod_scripting_core::asset/bevy_mod_scripting::core::asset will now need to come from bevy_mod_scripting_asset or bevy_mod_scripting::asset
  • Adding supported extensions will now need to be done via scripting_plugin.add_supported_extension("extension") rather than via the app directly
  • Plugin implementors will need to add the new crate as a dependency and should not directly rely on the top workspace crate

https://github.com/makspll/bevy_mod_scripting/pull/477

  • Update imports to new crates (bevy_mod_scripting_bindings, bevy_mod_scripting_display, bevy_mod_scripting_asset) where appropriate, if you rely on the workspace these will be re-exported under bindings, display and asset respectively
  • Replace DisplayWithWorld usage with DisplayWithTypeInfo / DebugWithTypeInfo and use WithTypeInfo::new(value) in format strings. Ensure that the WorldGuard is in scope when printing using these utilities, or you might see raw type id’s

0.16.0

Improved printing and error ergonomics

Printing has been extracted into its own bevy_mod_scripting_display crate, and brand new traits including the reflectable DisplayWithTypeInfo were written.

There are now Debug and Display equivalent traits which receive type information from semi-static thread local objects in order to print things like TypeId’s with full information.

You can now also register ReflectDisplayWithTypeInfo against your types in the reflect registry, to customize printing.

A great re-slicing

Bindings have been split out into individual crates, for example bevy_reflect has a corresponding bevy_reflect_bms_bindings crate which contain’s its bindings. This is possible thanks to a brand new tool which allows us to calculate crate dependencies across a workspace during codegen (see bevy_mod_scripting_codegen)

At the same time more bindings are now being generated after fixing some bugs in type discovery.

Other refactorings include bevy_mod_scripting_bindings, bevy_mod_scripting_display and bevy_mod_scripting_asset being pulled out into their own crates.

This has significantly improved compile times allowing us to pack more bindings!

Getting rid of HandlerCtxt

HandlerCtxt has been removed and all of its containing resources have been put in P::readonly_configuration, which is a semi-static, WorldId parameterised static.

At the same time ScriptContext<P> has been wrapped in an Arc allowing us to run callbacks within callbacks, as long as they don’t modify the same contexts!

The great bevy minification

BMS has historically pointed at the top level bevy crate, this was handy but fairly clunky as it brought way more dependencies than necessary.

From now on all BMS crates point at bevy subcrates directly, with default features disabled, this means we pull in the minimum amount of dependencies possible (in theory, as long as we didn’t miss a feature)

Brand new scripting pipeline

A shiny new overhauled loading/unloading script pipeline which:

  • Is much more customizable (want custom callbacks, or don’t like how we named our core callbacks? Just disable them and add your own!)
  • More scalable, allowing you to load thousands of scripts, without hogging your framerate (by abstracting loading into tickable state machines)

See the new docs section for details.

Pre-expanding generated code

Generated code is now expanded at generation time via cargo expand saving on compilation time for consumers.

Migrating from 0.16 to 0.17

TypedThrough Changes

PR 497

If you were relying on ladfiles or implementing TypedThrough manually, the interfaces will have changed. Some types have moved between crates.

Less types will appear in ladfiles

Changes to path reflection

PR 491

Replace accesses to tuple structs, and tuples containing underscores, i.e. instead of my_tuple._1 use my_tuple[1]

ScriptAttachment Moved to new crate

PR 490

A new crate bevy_mod_scripting_script was created, to decouple some concerns within the workspace. References will now need to use the bevy_mod_scripting::script namespace or a direct crate reference.

0.17.0 - Lua declaration files & Asset references

Lua declaration files!

On top of the ability to plug into mdbook docs, you can now generate Lua declaration files for use with the lua language server.

You can do this by simply adding the generation plugin to your app:

#![allow(unused)]
fn main() {
    // this example is used to drive the generated docs on the official BMS book
    app.add_plugins(BMSPlugin.set::<ScriptingFilesGenerationPlugin>(
        ScriptingFilesGenerationPlugin::new(
            true, // enabled, you can use a compilation feature to disable this here
            PathBuf::from("assets").join("definitions"),
            Some(PathBuf::from("bindings.lad.json")), // do also save the ladfile itself
            "Core BMS framework bindings",
            true,
            true,
        ),
    ));
}

The definitions will be generated on startup!

While the generated files are not currently perfect, and not everything is yet supported, they should already make development much smoother with basic type hints and inline docs.

Improved path reflection and dictionary/set direct access!

We have decided to drop using the native Bevy reflection paths, and switched them out with custom ReferencePath and ReferencePart structures.

This works around previous limitations of not being able to reflect and modify into dictionaries as well as reference into (but not modify sets, this one is due to limitations in the native rust type).

This should also give us some minor performance benefits.

Registered Callbacks

You can now register callbacks dynamically from your scripts like so:

function on_script_loaded()
    register_callback("on_test", dynamic_on_test)
end

function dynamic_on_test()
    register_callback("on_test_last", dynamic_on_test_last)
    return "on test: I am dynamically registered from a normal callback!"
end

This has many benefits, including allowing registering different callbacks from withing a shared global script context (where different functions are in scope depending on the last loaded script, but are predictable during loads), finally making those fully usable!

Expansion of reflection to include Asset References

The reflection system now supports a new base kind, i.e. ReflectBase::Asset

allowing us to create and send back asset references to scripts seamlessly, as well as use two new bindings (given an existing handle):

get_asset(handle_reference, registration) - Retrieves an asset by handle

has_asset(handle_reference) - Checks if an asset exists

Addition of ScriptPipelineState

A new utility has been added to allow you to check on the current batch of scripts being loaded easilly. Check it out in the new loading bar example

ScriptPath in FunctionCallContext

You can now access the last loaded script path in a script context via the FunctionCallContext::location method.

This is a lua only feature due to limitations in Rhai.

Migrating from 0.17 to 0.18

Migrate according to the official bevy migration guide. Scripts referencing native bevy bindings will also need updating accordingly.

For example in lua entity:index() will now be entity:index():index().

0.18.0 - Bevy 0.18 Support

This update only upgrades the supported version of bevy to 0.18

0.19.0

See notes for the 0.18.0 release.

Migrating from 0.19 to 0.19

Observer overhaul

TransitionListener has been deleted, use observers instead:

> app.add_observer(
>     |trigger: On<LoadingCompleted>| println!("do stuff"),
> );
< active_machines.push_listener::<ReloadingInitialized<P>>(OnLoadingCompleteListener);

This allows you to use more convenient system parameter syntax to access resources and queries, but you may not use exclusive systems anymore.

If you want observers to respect ordering between themselves, you should prefer to issue commands in these instead (see related bevy issue).

Renaming Reflection Rroxies

Val<T>, Ref<T> and Mut<T> have been renamed to prevent clashes with native bevy types, as well as save a few keystrokes.

You should use: V<T>, R<T> and M<T> instead

> V<T>
< Val<T>
> R<T>
< Ref<T>
> M<T>
< Mut<T>

ScriptValue::List changes

This variant now uses VecDeque instead of Vec

Refactor of WorldAccessGuard and related types

Many functions previously living directly in WorldAccessGuard impls, now need to be accessed via the WorldExtensions trait.

Functions previously known as with_exclusive_access etc, have been split into: with_world and with_world_mut, allowing read access to the world too in some circumstances.

ReflectAccessId was removed in favour of WorldAccessRange which can be created via Into from ComponentId’s.

0.20.0 - Ergonomics, Observer overhaul

Observer overhaul

The script loading pipeline became more idiomatic with the use of observers.

What you would do previously with TransitionListener implementations you can now do with observers registered against each machine state, for example, to react to fresh scripts being loaded you can do the following:

#![allow(unused)]
fn main() {
app.add_observer(
    |trigger: On<LoadingCompleted>| println!("do stuff"),
);
}

Callback command changes

Callback commands now accept a post_callback function pointer which can be set to execute some logic right after the callback runs, to make working with observers and callbacks easier in general.

Ironing out edge cases in the script lifecycle

Contexts are now stored in a Context enum which also contains the “state” of the context. Contexts which are being processed by the pipeline will be marked as loading/reloading or unloading, allowing us to have more information when trying to run callbakcs against these.

Callbacks which are loading or unloading for example, will not have callbacks issued to them generally.

Renaming Reflection Rroxies

Val<T>, Ref<T> and Mut<T> have been renamed to prevent clashes with native bevy types, as well as save a few keystrokes.

You should use: V<T>, R<T> and M<T> instead

Addition of logging bindings

Standard log_info, log_debug, log_trace, log_warn and log_error functions are now available in scripts by default

Variadic bindings & Support for multiple return values

The ArgMeta trait now includes: variadic() -> bool which if true, allows an argument in a binding to capture all remaining arguments from the call (effectively only usable as the last argument).

This is implemented by the brand new VariadicTuple type, which is an untyped wrapper for a variable amount of non-homogenous values.

New variants in the TypedThrough and LAD file format have ben added to represent variadics, and lua definition files generated from these will support them.

Two bindings have been added: pack_args and unpack_args to allow script code to directly create/unpack tuple variants if necessary. However for languages like Lua, supporting multiple return values, ScriptValue::Tuple variants (which is what we produce to represent variadic returns), are converted to many return values naturally.

New VecDeque impls

VecDeque now implements various BMS traits and can be used in bindings as a normal argument.

Improved domain boundaries - Extracted bevy_mod_scripting_world crate

The following types were extracted into their own crate:

  • ReflectAccessId now known as WorldAccessRange
  • ClaimOwner
  • AccessInstance
  • AccessMap
  • DynamicSystemMeta
  • WorldGuard & WorldAccessGuard

the CachedRegistry trait was introduced to store registries such as:

  • AppScriptComponentRegistry
  • AppReflectAllocator
  • AppScheduleRegistry
  • AppScriptFunctionRegistry

etc. in a type-erased way.

This allowed bevy_mod_scripting_display to directly rely on world types, and removed a lot of awkward bridging code.

More Derive Macros

The following macros derive macros are now available: ArgMeta,FromScript.

This means for types you want to clone into scripts you can make convenient wrappers like so:

#![allow(unused)]
fn main() {
#[derive(Clone, TypedThrough, GetTypeDependencies, ArgMeta, IntoScript, FromScript, Reflect)]
pub struct MyThing(usize);


#[script_bindings(remote)]
impl MyThing {
    // Can now be used directly without V<> wrapper, acts exactly like V<MyThing>
    pub fn test(thing: MyThing) -> MyThing {
        thing
    }
}
}

And overriding either the into or from implementations if you wish easilly.

Migrating from 0.22 to 0.23

Scripts

Script components need a namespace

register_new_component takes a script.* namespace first:

- local Enemy = world.register_new_component("Enemy")
+ local Enemy = world.register_new_component("script.my_game", "Enemy")

Registering a name twice is still an error. If you worked around that for scripts which run more than once, you can now pass allow_existing as the third argument to get the existing registration:

local Enemy = world.register_new_component("script.my_game", "Enemy", true)

In Bevy’s component registry, script components are now named by their full path, i.e. script.my_game.Enemy.

types is deprecated

Use import_namespace with the crate that defines the type:

- local Transform = types.Transform
+ local Transform = import_namespace("bevy_transform").Transform

Script components are not added to types after a context is created. Import them from their namespace instead.

construct is stricter

construct (and the new Type.new) rejects unknown fields instead of ignoring them, and fills in missing fields from defaults.

Re-entering a running script is an error

Running a callback in a script context which is already running a callback (e.g. from an observer or a command flushed during the callback) now returns an error instead of deadlocking. Use queue_script_callback to run it once the context is free.

Rust

Messages renamed

Buffered BMS types are Bevy messages, and their names now say so:

0.220.23
ScriptCallbackEventScriptCallbackMessage
ScriptCallbackResponseEventScriptCallbackResponseMessage
ScriptErrorEventScriptErrorMessage
ScriptAttachedEventScriptAttachedMessage
ScriptDetachedEventScriptDetachedMessage
ScriptAssetModifiedEventScriptAssetModifiedMessage

ScriptingHandler::handle locks the context itself

Pass the context’s Arc instead of locking it:

- let mut context = context.lock();
- P::handle(args, &attachment, &label, &mut context, callbacks, world)
+ P::handle(args, &attachment, &label, &context, callbacks, world)

Pipeline progress functions renamed

0.220.23
num_processing_scriptsprocessing_script_count
processing_batch_completedis_processing_completed
num_loaded_scriptsloaded_script_count
progressprogress_fraction

World guard cache

WorldAccessGuard::setup_cache_raw takes two new arguments, the AppScriptCallbackRunners and the AppScriptTypeCatalogue. Prefer setup_cache(world, attachment), which reads them from the world. Use CurrentScriptAttachment::empty() for guards not tied to a running script.

Other

  • ScriptingSystemSet has a new variant, RunQueuedCallbacks.
  • The script function world.trigger_event (and WorldExtensions::trigger_event) applies all pending world commands before it returns, not only those of its observers.
  • Recipients moved to bevy_mod_scripting_script, and is re-exported from core::event. Resolving recipients is the GetRecipients trait.
  • AnyTypeRegistration has a fourth case, bundles (ScriptBundleRegistration).
  • ScriptComponentRegistration has a new public field, script_namespace.
  • WorldExtensions::register_script_component takes (namespace, name, allow_existing).
  • LAD files have new fields: namespace on types, Fields payloads, variant function namespaces, and default metadata. Custom LAD backends may need to handle them.

0.23.0 - Scripts calling scripts, constructors, namespaces

See the migration guide for breaking changes.

Scripts calling scripts

Scripts can run each other’s callbacks, in any language:

  • run_script_callback runs a callback right away and returns its result.
  • queue_script_callback runs it as soon as the current callback finishes, or in Last when called from a non-exclusive script system (ScriptingSystemSet::RunQueuedCallbacks).

Nested callbacks are now safe: re-entering a context that is already running (a script calling itself, scripts sharing a context, or a loop A → B → A) returns an error instead of freezing the app, and nesting is capped at 64. This is built on AppScriptCallbackRunners, which lets language-agnostic code run callbacks in any scripting language.

Constructors and enum variants

Every reflected type gets a new constructor, and enum variants are values:

local v = Vec3.new{ x = 1, y = 2 }            -- z is filled in from the default
local all = Recipients.AllScripts:new{}       -- construct a variant
if event.recipients:variant() == Recipients.AllScripts then ... end

Missing fields are filled in from defaults, and unknown fields are an error. The global construct follows the same rules. The generated LAD files and Lua language server definitions describe constructor payloads and variants, so editors complete and check them. In Rhai, call Type.new_.call(...), since new is reserved.

Events, messages and observers

  • world.trigger_event(type, value) and world.write_message(type, value) send reflected Bevy events and messages. trigger_event applies all pending commands, including those its observers queued, before it returns.
  • world.add_observer(event, callback, components?, entities?) runs a script callback when an event is triggered. That includes the component lifecycle events (AddEvent, InsertEvent, RemoveEvent, …), for native and script components alike. Observer callbacks never re-enter a busy script: they wait until it is free. Their errors are reported like those of other callbacks.
  • world.register_new_event(namespace, name) lets scripts define their own events, triggered with the same world.trigger_event(event, payload).

See Events and Messages.

Namespaces and modules

Types now live in namespaces: the crate that defines them, or bms for BMS’ own types. Override this with ScriptNamespace type data or #[script_bindings(namespace = "...")].

  • import_namespace("bevy_transform") returns the types in a namespace. It replaces the types global, which is now deprecated.
  • Scripts register components and events into script.* namespaces, and other scripts import them from there.
  • export_namespace(namespace, name, callback) shares a script function with other scripts, in any language.
  • A script’s exports and observers are removed when it unloads or reloads.
  • LAD files record each type’s namespace, and the Lua language server types import_namespace per namespace.

Types are indexed once in a shared, lazily rebuilt type catalogue, instead of once per script context. See Namespaces.

Script components and bundles

  • Inserting a script component no longer leaks memory.
  • register_new_component and register_new_event take an allow_existing argument, which returns the existing registration instead of failing when the name is taken (useful for scripts which run again).
  • world.insert_bundle and world.spawn_bundle insert bundles registered with #[reflect(Bundle)], all at once.

Fixes

  • on_script_reloaded always runs after on_script_loaded.
  • Fixed a rare ordering bug when iterating Vec<T> from Lua.
  • A nested callback no longer invalidates the world of the callback that called it.

Migrating from 0.23 to 0.24

See the release notes for what’s new. Most important changes first.

Scripts

Rhai is removed

Port Rhai scripts to Lua, or to Rune (the rune feature).

Everything is imported

The only globals left are import_namespace, export_namespace and register_callback. Everything else, world and types included, is imported from a namespace, see Namespaces. Bevy types are grouped by category (math, ecs, transform, ui, …), BMS’ types and functions live in bms:

+ local bms = import_namespace("bms")
+ local world = bms.world
+ local Vec3 = import_namespace("math").Vec3
+ local Transform = import_namespace("transform").Transform
  local t = Transform.from_translation(Vec3.new(1, 2, 3))
- log_info("hi")
+ bms.log_info("hi")
- world.despawn(entity)
+ world.despawn(bms.current_entity())
- script_asset
+ bms.current_script()

construct, system_builder, run_script_callback, queue_script_callback, pack_args and unpack_args moved to bms the same way. The deprecated types table is removed.

Query results are lists

The entity followed by the components, in the order they were added to the query:

  for _, result in pairs(world.query():component(Transform):build()) do
-     local entity, transform = result:entity(), result:components()[1]
+     local entity, transform = result[1], result[2]
  end

Other changes

  • The bindings are hand-written: functions of Bevy types which were generated before may be missing or named differently, check the generated docs.
  • world.get_type_by_name only takes full paths, i.e. "bevy_transform::components::transform::Transform" or "script.my_game.Enemy".
  • Script systems: resource and query components are writes, systems writing the same data no longer run in parallel, use resource_read / component_read where you only read. Sets are values (world.register_new_system_set(namespace, name), world.get_system_set_by_name) instead of names.
  • Asset references can’t be used in non-exclusive script systems, nor together with a mutably borrowed component in the same call.
  • Lua’s math.random is seeded with 0 in new contexts, and callbacks reach scripts in attachment order, see Determinism.

Rust

Features and crates

  • The rhai feature and bevy_mod_scripting_rhai are removed.

  • The generated *_bms_bindings crates are replaced by bevy_mod_scripting_bevy_<category>_bindings. The binding features are now bevy_{animation, asset, audio, camera, color, ecs, gizmos, input, math, render, sprite, state, text, time, transform, ui, window}_bindings:

    0.23 feature0.24
    bevy_reflect_bindings, bevy_curve_bindings, bevy_shape_bindingsbevy_math_bindings
    bevy_image_bindings, bevy_mesh_bindings, bevy_pbr_bindingsbevy_render_bindings
    bevy_input_focus_bindingsbevy_input_bindings
    bevy_core_pipeline_bindings, bevy_gltf_bindings, bevy_light_bindings, bevy_picking_bindings, bevy_post_process_bindings, bevy_scene_bindings, bevy_sprite_render_bindings, bevy_ui_render_bindings, bevy_ui_widgets_bindingsremoved, reachable through reflection

    The default features are core_functions and the ecs, input, math, time, transform, color and window bindings.

  • mlua is bumped to 0.12, see its changelog if you use it directly.

Script globals are removed

AppScriptGlobalsRegistry, #[script_globals], register_static*, GlobalNamespace, FunctionScope::Global, DummyScriptFunctionRegistry and use_dummy_registry are gone. Put functions in a namespace instead:

#[script_bindings(remote, namespace = "my_game")]
impl NamespaceMembers {
    /// `import_namespace("my_game").spawn_enemy(5)` in scripts
    fn spawn_enemy(ctxt: FunctionCallContext, hp: usize) -> Result<(), InteropError> { .. }
}

Values go in AppScriptNamespaceMembers::register_value, made each time the namespace is imported. Types with bindings from the bevy crates are in category namespaces, move a type with app.override_script_namespace.

Borrowed arguments end with the call

FromScript::from_script takes a &CallScope instead of a WorldGuard, and R/M borrow from it, so they can’t be kept past the function call (M<'static, T> arguments no longer compile). Get the guard with scope.world(), and convert outside of script functions in guard.with_call_scope(|scope| ..), which replaces with_access_scope and releases the claims when it ends:

fn from_script<'s>(value: ScriptValue, scope: &'s CallScope<'_>) -> Result<Self::This<'s>, InteropError> {
    let world = scope.world();
    ..
}

The allocator is removed

Values allocated for scripts are owned by the references to them and freed with the last one. ReflectAllocator, AppReflectAllocator, WorldExtensions::allocator, AllocatorDiagnosticPlugin, ScriptingSystemSet::GarbageCollection and InteropError::GarbageCollectedAllocation are gone, drop the allocator argument:

- let reference = ReflectReference::new_allocated(value, &mut world.allocator().write());
+ let reference = ReflectReference::new_allocated(value);

new_allocated_boxed and new_allocated_boxed_partial_reflect (renamed from new_allocated_boxed_parial_reflect) change the same way.

Functions

  • Registering a function name twice replaces it, there are no overloads (overwrite*, iter_overloads, remove_all_overloads are removed). Take a Union or ScriptValue for arguments of different types.
  • ScriptFunctionRegistry is keyed by TypeId instead of a namespace: register(type_id, ..), get_function(type_id, name), iter_namespace → iter_type.
  • #[derive(ScriptType)] implements everything a type needs to be used directly in function signatures (FromScript, IntoScript, ArgMeta, GetTypeDependencies, TypedThrough). Use #[script_type(from = custom)] / (into = custom) for a hand written conversion.
  • Renames: Namespace → FunctionScope (IntoNamespace is removed, use FunctionScope::OnType(TypeId::of::<T>())), FromScriptRef/IntoScriptRef → FromScriptErased/IntoScriptErased, try_call_overloads → call_operator.
  • Functions on StaticTypeRef take StaticTypeRef instead of V<StaticTypeRef>.

Script pipeline

  • ScriptAttachedMessage(a) / ScriptDetachedMessage(a) are one message, ScriptLifecycleMessage::Attached(a) / ::Detached(a), processed in the order they were written. An attachment whose script is still loading holds back the ones after it.
  • LoadedWithHandles is ScriptLifecycleQueue, get_ready yields (event, Option<(StrongScriptHandle, Language)>). GetScriptHandle::get_script_handle returns an Option (None: the event doesn’t wait for its script to load).
  • ScriptLoadingPipeline::time_budget: Option<Duration> is replaced by tick_budget: Option<usize>, the maximum amount of pipeline steps per frame, unlimited by default. ActiveMachines::budget and RunProcessingPipelineOnce::new take the same step count.

Script systems

  • Systems are identified by attachment and callback label (adding one again replaces it) and are removed with their script. Their errors are sent as ScriptErrorMessages instead of being logged.
  • ScriptSystemBuilder no longer implements IntoSystem, use ScriptSystemBuilder::build. in_set, before_set and after_set take a SystemSet. ScriptSystemSet holds a recycled slot instead of the callback label.
  • Rust sets are exposed to scripts with app.register_script_system_set(namespace, name, set) (ScriptSystemSetAppExt, now in bevy_mod_scripting_bindings). ReflectSystemSet is opaque.
  • ScriptQueryBuilder::as_query_state takes a QueryAccess: Declared for queries reported to the scheduler, MatchOnly for queries only finding entities.
  • ScriptQueryResult converts to a list instead of a reference, and its components are a Vec<Option<ReflectReference>>, None for absent optional components.

World access

  • ReflectReference::new_component_ref_by_id / new_resource_ref_by_id, ScriptComponentRegistration::new and ScriptResourceRegistration::new are unsafe: the type must be the type of the component or resource id. ReflectBaseType::base_id is private, read it with base_id().
  • WorldAccessGuard::new_non_exclusive takes an Option<Arc<ArchetypeFilter>>, restricting component accesses to the given archetypes (None for no restriction).
  • WorldAccessRange::External holds the value itself (AccessOwner) instead of an id and is no longer Copy, build it from the value: (&allocation_id).into().
  • At most 63 accesses to the same value can be claimed at once, claims beyond fail (the count used to overflow).
  • Asset references claim global access, and reading an asset no longer marks it modified.
  • ThreadWorldContainer::try_get_context() is an associated function (was ThreadWorldContainer.try_get_context()), set_context is replaced by replace_context, which restores the previous context when its guard is dropped. set_cached_registry is replaced by replace_cached_registry.
  • Removed: DynamicSystemMeta and its with_scope / release_all_accesses (claims are released when their CallScope ends), WorldAccessGuard::release_all_accesses, with_world_access_and_then, as_unsafe_world_cell_readonly (use as_unsafe_world_cell).
  • ReflectReference::type_id_of and TypeIdSource are removed, use tail_type_id, element_type_id or key_type_id.
  • ReferencePath::set_is_one_indexed is removed: indexes are normalised when the path is created.

Language implementations

  • Dispatch every script operation through bevy_mod_scripting_bindings::dispatch (index, set_index, static_index, binary, unary, len, iter, display, debug), see Necessary Features. WorldExtensions::lookup_function, lookup_instance_function, lookup_type_function and lookup_reserved_function are private.
  • Convert the new ScriptValue::Type(TypeId), a type itself (what world and StaticTypeRef are).
  • Set bindings::builtins::builtins() (import_namespace, export_namespace) and your register_callback as globals, nothing else. Don’t set world, entity or script_asset anymore.
  • LuaStaticReflectReference is LuaTypeRef.

Documentation tooling

  • The Lua language server files are split per namespace (bindings.d.lua, bindings.<namespace>.d.lua): point workspace.library at the directory. Classes are named after their namespace (math.Vec3), and generic classes need LuaLS 3.17+.
  • cargo xtask docgen is replaced by cargo xtask docs (all binding features, --test-bindings for the script test functions). cargo xtask bless-lad updates the LAD test fixtures.
  • ThroughTypeInfo is flat (ThroughTypeInfo::Vec(..), ThroughTypeInfo::Ref(type_info), replacing TypedWrapper / UntypedWrapper), ThroughTypeInfo::TypeInfo is Opaque. #[derive(TypedThrough)] documents a type as opaque, #[typed_through(value)] as a value.
  • generate_lad_file takes the AppGenericTypes, see app.register_generic_type.
  • LAD format:
    • LadFieldOrVariableKind → LadTypeKind. Ref/Mut/Val hold a LadNamedType: a type id as before, or a generic type applied to arguments ({ "generic_type": "bevy_asset::handle::Handle", "args": [...] }).
    • globals is removed, builtin functions are LadFunctionNamespace::Global (the mdbook “Globals” and “Functions” pages are one “Builtins” page). Namespaces have values (add_instance* → add_namespace_value_of / add_namespace_instance).
    • Instantiations of declared generic types are recorded on the generic type (generic_types, LadGenericType::instantiations, LadFile::get_instantiation) instead of being types of the file. polymorphizied_types is removed.
    • LadFunctionMetadata::is_operator → operator. Arguments are always named and never include the call context.
    • ArgumentVisitor has an Output type and visit_* methods per kind (visit_generic, visit_type, visit_tuple_with_rest, …).

0.24.0 - Codegen removed, typed scripts, script systems, Rune

See the migration guide for breaking changes.

Codegen is gone: 4x faster builds

The codegen project, its pinned nightly toolchain and the cargo expanded binding crates are removed (see the RFC). The bindings went from 4.3MB of generated source to 0.23MB written by hand:

BMS crates, default features + lua540.230.24
cargo build209s51s-76%
cargo check19.1s9.0s-53%
slowest cratebevy_reflect_bms_bindings, 193sbevy_mod_scripting_bevy_math_bindings, 43s

Non-incremental dev builds of the workspace crates only (dependencies cached), mean of 2 runs, 16 threads. Changing a binding is an ordinary edit, with no nightly toolchain or regeneration step.

Hand-written Bevy bindings

The Bevy bindings are written, documented and tested by hand, one crate per category, designed for scripts rather than mirrored from Rust:

local Vec3 = import_namespace("math").Vec3
local Transform = import_namespace("transform").Transform
local KeyCode = import_namespace("input").KeyCode
local Color = import_namespace("color").Color
local ui = import_namespace("ui")

local t = Transform.from_translation(Vec3.new(1, 2, 3)):looking_at(Vec3.zero(), Vec3.unit_y())
t.translation = 2 * t.translation            -- numbers work on either side of operators

if KeyCode.just_pressed(KeyCode.Space) then  -- no `ButtonInput<KeyCode>` resource lookups
    local node = ui.Node.new({ width = ui.Val.px(100) })
    local red = Color.hex("#ff0000"):mix(Color.named("rebecca_purple"), 0.5)
end
  • Covers math, ecs, time, transform, color, input, window, asset, camera, render, sprite, text and ui, plus new bindings for gizmos (Gizmos.line(a, b, color)), animation players, audio playback settings and states (world.get_state, world.set_next_state).
  • Things which panic in Rust are errors or nil in scripts: normalize of a zero vector, integer division by zero, Entity.from_bits of an invalid id, Dir3.new of a zero vector.
  • No generic type paths: world.time(), world.virtual_time(), Window.primary(), world.find_entity_by_name(name).
  • Everything without a binding stays reachable through reflection: fields, Type.new{..}, variants.
  • The examples in the binding docs run as tests, in every language.

Everything is imported

Scripts get three globals: import_namespace, export_namespace and register_callback. Types live in short category namespaces (math, ecs, transform, ui, …) instead of globals which shadowed each other, and so does world:

local bms = import_namespace("bms")
local world = bms.world
bms.log_info("hi from " .. tostring(bms.current_entity()))

Exposing your own functions is one attribute, no globals registry:

#[script_bindings(remote, namespace = "my_game")]
impl NamespaceMembers {
    /// `import_namespace("my_game").spawn_enemy(5)` in scripts
    fn spawn_enemy(ctxt: FunctionCallContext, hp: usize) -> Result<(), InteropError> { .. }
}

Types, constructors and enums

A type is a value now (ScriptValue::Type), not an allocated StaticTypeRef reference. What you import from a namespace is the type: it is its registration wherever one is expected, and it carries the type’s static functions, the shared new constructor and its enum variants. Calling Vec3.new{} no longer allocates the type and clones it back out on every call.

local time = import_namespace("time")
local Timer, TimerMode = time.Timer, time.TimerMode

world.add_default_component(entity, Transform)        -- the type as a registration
local timer = Timer.from_seconds(2, TimerMode.Repeating)
local image = Image.load("player.png")                -- on every asset type, a typed `Handle<Image>`

if event.key_code == KeyCode.KeyA then end            -- values compare against variants directly
local eased = EaseFunction.Linear:sample(0.5)         -- variants have their enum's functions
  • Every reflected value has == (through reflect_partial_eq) and :clone(), and operators a type doesn’t define fall back to the ones shared by all references.
  • #v goes through the type’s len function, so types can override it.
  • Asset types get load(path), add_asset(value) and get_asset(handle), next to world.load_asset, world.add_asset, world.is_loaded, world.load_state and world.asset_path.
  • #[reflect(NoTypeFunctions)] hides the shared type functions (i.e. new) from a type.
  • One function per name, taking a Union for different operand types (Union<R<Vec3>, f32> borrows): overloads, and the failed attempts they cost on every call, are gone.
  • #[derive(ScriptType)] implements everything a type needs to be used directly in function signatures.

Scripts your editor understands

The Lua language server files describe what scripts actually get back. Functions are generic in the type they are given, and generic types are declared once in terms of their parameters:

local transform = world.get_component(entity, Transform) -- transform.Transform?
local image = world.load_asset("player.png", Image)       -- asset.Handle<render.Image>
local state = world.get_state(GameState)                  -- my_game.GameState?
local t = world.get_type_by_name("bevy_transform::components::transform::Transform") -- the Transform type
  • A file per namespace, classes named after their namespace (math.Vec3), no type globals.
  • Type tables and values are separate classes: Transform.from_xyz completes on the type, fields on the value, and passing a resource where a component is expected is flagged.
  • Enum variants extend their enum, so Timer.from_seconds(2, TimerMode.Repeating) type-checks, and MyEnum.Variant:new{..} checks its fields.
  • Container fields are typed as what reading them gives: integer[] | ReflectReference.
  • The Lua tests of BMS are type-checked against the generated files in CI, with zero diagnostics.

Declare your own generic types with app.register_generic_type::<Handle<A>>("asset", &["A"], docs), and generic functions with TypeOf<R, A> / ValueOf<A> in their signature:

fn get_component(
    ctxt: FunctionCallContext,
    entity: V<Entity>,
    registration: TypeOf<V<ScriptComponentRegistration>, A>,
) -> Result<Option<ValueOf<A>>, InteropError>

The mdbook pages got the same treatment, and a rework: generic types show their layout and functions once, generics no longer vanish as HTML tags, rustdoc links resolve, and summaries are readable.

Script systems

Script systems grew into something you can build a mod’s logic on.

Parameters and queries

Systems declare what they read and write, so Bevy runs them in parallel with everything they don’t conflict with:

bms.system_builder("steer_enemies", attachment)
    :query(world.query()
        :component(Transform)          -- read + write
        :component_read(game.Enemy)    -- read only, readers run in parallel
        :optional_read(game.Shield)    -- nil for entities without it
        :changed(game.Target))         -- only entities whose target changed since the last run
    :resource_read(game.Difficulty)
function steer_enemies(enemies, difficulty)
    for _, result in ipairs(enemies) do
        local entity, transform, enemy, shield = result[1], result[2], result[3], result[4]
    end
end
  • added / changed filters, relative to the system’s last run (or the last update in world.query()).
  • Queries of a system may share components if with / without make them disjoint, like in Rust.
  • Query results are plain lists instead of allocated values.

Ordering and sets

Order against systems, other scripts’ systems, and sets, including Rust sets:

local propagate = import_namespace("transform.TransformSystems").Propagate
local ai = world.register_new_system_set("script.my_mod", "ai") -- other scripts import it from `script.my_mod`

builder:in_set(ai)
       :before_set(propagate)
       :after_script_system("on_physics", other_attachment)

The bindings register the main Bevy sets, expose your own with:

app.register_script_system_set("my_game.GameSystems", "Combat", GameSystems::Combat);

Run conditions

Evaluated in Rust, without calling into the script:

local c = bms.conditions
builder:run_if(c.any_with_component(game.Enemy))
       :run_if(c.not_(c.resource_exists(game.Paused)))
       :run_if(c.on_timer(0.5))

resource_exists, resource_changed, resource_added, any_with_component, on_timer, run_once, and the combinators not_, and_, or_.

Lifecycle

  • A system is identified by its script and callback label: adding it again replaces it, and it is removed when its script unloads or reloads.
  • Systems can be added to schedules which are running (i.e. from on_script_loaded), the change is applied once the schedule finishes.
  • Errors are sent as ScriptErrorMessages like those of other callbacks, and invalid parameters are reported once instead of every frame.
  • A non-exclusive system can only touch what it declared, on the entities its queries match.

See Script Systems.

Determinism

Given the same inputs, scripts load in the same order and callbacks reach scripts in the same order, on every run and machine:

  • Script contexts and their residents are kept in insertion order instead of randomly seeded maps, so callback order, reload order and the “first” script of a shared context are stable.
  • Attachments and detachments are one ordered ScriptLifecycleMessage stream: removing and re-inserting a script component in the same frame no longer ends up unloaded, and a detachment waits for its attachment whose script is still loading.
  • The pipeline budget counts steps (tick_budget) rather than wall clock time.
  • Lua’s math.random is seeded with 0 in new contexts.
  • Broadcast callbacks are no longer delivered twice to loaded scripts while another script is loading.

See Determinism for what BMS can’t control.

Rune

Rune is the second supported language, behind the rune feature. It replaces Rhai, which is removed:

pub fn on_script_loaded() {
    let bms = import_namespace("bms");
    let world = bms.world;
    for result in world.query().component(life_state_type(world)).build() {
        let cells = result[1].cells;
        cells[0] += 255;
    }
}

Operators, indexing and member lookups go through one language agnostic dispatch module, so every language resolves v.x, v:method() and 2 * v by the same rules, and adding a language is mostly converting values, see Necessary Features.

Faster interop: method calls at less than half the cost

Method calls from Lua cost less than half of what they did (cargo bench, medians of 3 runs on the same machine):

0.230.24
v:length()1.45µs0.67µs-54%
v:normalize() (returns a value)2.49µs1.04µs-58%
a + b1.57µs1.02µs-35%
v.x554ns426ns-23%
v.x = 2484ns519ns+7%
calling an empty function309ns178ns-42%
  • Values returned to scripts are owned by the references to them and freed with the last one: the allocator, its lock and the garbage collection system are gone.
  • v:method reuses one Lua function per registered function, and call locations are only looked up for errors.
  • Claiming the whole world (every asset access, world.spawn, …) no longer scans every component’s claims.

Soundness

The world access machinery was reviewed and tightened:

  • Borrowed arguments (R<T>, M<T>) are tied to the function call, keeping them past it no longer compiles.
  • Claims are released when callbacks fail or panic, can’t overflow, and hold across guards for values reachable from several of them.
  • Script systems declare exactly what they access to Bevy: written components and resources used to be declared as reads, letting writers run in parallel.
  • Reading an asset no longer takes it mutably, or marks it modified (i.e. re-uploading an Image every frame).
  • Constructors which trust the caller with a type and component id pairing are unsafe, and registrations can’t be forged through reflection.
  • Converting -1 to a NonMaxU32 from a script was undefined behaviour, it is an error now.

Other changes

  • Cyclic Lua tables are an error instead of a stack overflow.
  • Lua functions called from Rust return all of their values intact.
  • Indexes are normalised when values are created, so values pass between 0 and 1 indexed languages correctly.
  • DynamicScriptFunctions compare equal to their clones.
  • The function registry is not locked while functions run, which could deadlock with a writer on another thread.
  • Android and iOS builds are checked, and the script tests run on an emulator, in CI.
  • mlua 0.12.
  • Only the top level CHANGELOG.md is maintained, it covers every crate.

Migrating from 0.24 to 0.25

See the release notes for what’s new. Most important changes first.

Rust

Documentation tooling

  • ThroughTypeInfo has new variants: Function { params, returns } (FunctionOf), Literal (ByName) and Data (a type deriving ScriptData, with a ScriptDataShape of Fields or Union). In the LAD file, structs are referred to by LadTypeKind::Fields and enums by LadTypeKind::Val.
  • LadFile::types holds LadTypes: LadType::Reference(Box<LadTypeDefinition>) for the types so far (serialized as before), and LadType::Data(LadDataType) for ScriptData types, whose LadDataShape is fields or a union of kinds. Use get_reference_type / reference_types where a LadTypeDefinition was expected.
  • New LadTypeKind::Function { params, returns } and LadTypeKind::Literal: implementations of ArgumentVisitor add visit_function and visit_literal.

Functions

  • Conversions moved from function to conversions: function::{from, into, from_ref, into_ref} are conversions::{from, into, from_ref, into_ref} (FromScript, IntoScript, V, R, M, Union, FromScriptErased, IntoScriptErased). The crate root re-exports are unchanged, i.e. bevy_mod_scripting_bindings::V.
  • ValueOf<M> is ValueOf<M, R = ReflectReference>: ValueOf<A> is unchanged, new and into_inner take and give the R.
  • GetFunctionInfo implementations provide function_info(name, namespace), which needs no value. get_function_info calls it.
  • Union<T1, T2> only tries the types which could convert the value, see FromScript::could_convert. When only T1 could, the error is T1’s rather than T2’s. Override could_convert in hand-written FromScript implementations to rule out the kinds of values they never convert.

0.25.0 - Typed arguments

See the migration guide for breaking changes.

Typed arguments

Functions taking callbacks, names or tables of options are documented as exactly what they take, so the Lua language server checks the calls:

/// Spawns an enemy
#[derive(ScriptData)]
#[script_data(namespace = "game")]
struct SpawnOptions {
    name: String,
    speed: Option<Speed>,
    on_death: Option<FunctionOf<fn(V<Entity>) -> ()>>,
}

#[derive(ScriptData)]
#[script_data(namespace = "game")]
enum Speed {
    Named(ByName<Pace>),     // "Slow" | "Fast"
    Exact(f32),              // 2.5
}
game.spawn({ name = "goblin", speed = "Fast", on_death = function(entity) end }) -- `entity` is an ecs.Entity
game.spawn({ name = "goblin", speed = "fast" })   -- not a Pace
game.spawn({ speed = 2 })                         -- missing `name`
game.spawn({ name = "goblin", sped = 2 })         -- no field `sped`
  • FunctionOf<fn(A) -> R>: a function, documented as fun(arg1: A): R, so the parameters of a callback written inline are typed.
  • ByName<E>: a unit variant of a reflected enum, passed by its name as in Rust and documented as the names, "Slow" | "Fast".
  • #[derive(ScriptData)]: plain data, copied to and from scripts rather than referenced.
    • A struct is a map of its fields (a table in Lua, an object in Rune). Each field converts by its own type, so it can be a callback, a name or a union. Unknown, missing and mistyped fields are errors naming the field.
    • An enum whose variants each hold one value is the value of any of them, and may hold itself.
    • Both are data types in the book and the LAD file (LadType::Data): a class of the fields or an alias of the union in Lua.
  • ValueOf<A, R> takes the conversion: ValueOf<A, ScriptValue> is any value, typed as whatever was passed, i.e. fn boxed(v: ValueOf<A, ScriptValue>) -> V<MyBox<A>> gives a MyBox<integer> for boxed(5).

See Typed arguments.

Native types

Vectors (Vec2, Vec3, Vec4, Vec3A, DVec2, DVec3, IVec2, IVec3, UVec2, UVec3) and Quat values made by functions are stored by Lua and Rune themselves, and functions read their arguments without converting them to ScriptValues. Transform components are native handles: world.get_component(e, Transform) reads and writes the component directly (t.translation.x = 5 included). Other types opt in with script_native!, see Writing Bindings. Scripts behave the same: native values are copies like the values functions return, and work wherever references to vectors do.

Other changes

  • Unions only try the types which could convert a value (FromScript::could_convert), instead of building an error for each type which can’t.
  • Nested unions are documented as one union, Union<A, Union<B, C>> is A | B | C.
  • In the Lua language server files, function types in unions and lists are parenthesized: fun(): a | b returns the union.