Manual
Manual
Rust in a game
Most games are written entirely in C#, but a game can also have Rust of its own: a crate in its rust folder whose plugins are ordinary Bevy plugins, linked into the same library as the engine. This page covers when that is worth it, how the crate is set up and built, how its components and systems fit beside the game's C#, and what it cannot do yet.
When to use Rust
C# systems in Abyss read Bevy's memory directly, with no copying and no garbage: in the engine's benchmark over half a million entities, a C# system runs as fast as the same system written in Rust. Reach for Rust when you need something C# cannot give you:
- A crate from Bevy's ecosystem, such as a plugin someone else wrote.
- A component that holds what C# cannot, such as an asset
Handle, aStringor an enum with data. - A hot loop that benefits from auto-vectorization. Rust's compiler widens simple loops into SIMD instructions on its own, and .NET's does not. That, not the language, is where Rust's speed advantage comes from.
The rust folder and its crate
A game's Rust is one crate in its rust folder. The Project panel hides that folder until it has a file in it. To make the crate, open the Project panel's + menu and pick Rust Crate. It writes rust/Cargo.toml and rust/src/lib.rs, named after the game: a game in Space.Rocks gets the crate space-rocks and the plugin SpaceRocksPlugin.
[package]
name = "space-rocks"
version = "0.1.0"
edition.workspace = true
publish = false
[dependencies]
abyss-ffi = { workspace = true }
bevy_app = { workspace = true }
bevy_ecs = { workspace = true }The crate names the engine and Bevy with workspace = true. When the game builds, the build writes a Cargo workspace at the game's root: a Cargo.toml that gives every crate the engine's own versions and features, so Bevy is compiled once for the engine and your code together, and a Cargo.lock that starts as the engine's. That Cargo.toml records where the engine is on your computer, so it belongs to the build and not to your repository; the templates' .gitignore leaves both files out. Add other Bevy crates the same way as you need them, for example bevy_reflect, bevy_transform, bevy_time or bevy_gizmos.
The build compiles the engine, your crate and the crates of any packages that have Rust into one native library. The editor and dotnet run load that library in place of the engine's own, and a built game links it into its executable.
You need Rust installed to build such a game: a build that finds no cargo stops before it starts and says where to get Rust. The first build compiles Bevy, which takes a while; later builds compile only what changed.
A package can have Rust too, in packages/<id>/rust. A package's crate is shipped as source and compiled on the machine that builds the game, because Rust has no binary format that one build of Bevy can safely load into another. Your crate can depend on a package's crate by its name, with workspace = true.
Plugins
The crate's lib.rs starts with one plugin:
use bevy_app::{App, Plugin, Update};
/// Installed into every world the engine makes, after its window, assets and renderer.
pub struct SpaceRocksPlugin;
impl Plugin for SpaceRocksPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Update, update);
}
}
abyss_ffi::plugin!(SpaceRocksPlugin);
/// Runs on each of Bevy's frames while the game plays.
fn update() {}abyss_ffi::plugin! names a plugin for the engine to install. There is nothing else to register: linking the crate in is enough. The engine installs your plugins after the window, the assets and the renderer, as a Bevy game adds its plugins after Bevy's defaults, so a plugin that checks whether one of Bevy's plugins is already present finds the engine's. Adding a Bevy plugin the engine has already added is refused, as Bevy refuses any plugin added twice: the log says so, and your plugin's installation stops there. Check first, as crates in Bevy's ecosystem usually do. Plugins named by separate plugin! calls are installed in no particular order, so name a tuple, plugin!((Physics, AfterPhysics)), when order matters.
While you edit the game, none of its Rust systems run. Whatever your plugins add to Bevy's schedules runs only while the game plays, and the startup schedules run again at every Play. A plugin named plugin!(#[execute_always] Placing) also runs while the game is edited, for things that should follow the Inspector as you type, like an object placed from numbers.
Components and resources
A Rust component is a Bevy component that derives Reflect. The engine reads its fields through Bevy's reflection, so the Inspector shows it, scenes save it, and Add Component offers it when it is marked #[reflect(Component, Default)]:
use abyss_ffi::{Range, Tooltip};
use bevy_ecs::prelude::*;
use bevy_reflect::prelude::*;
use bevy_transform::components::Transform;
/// Moves an entity round a circle in the ground plane.
#[derive(Component, Reflect, Debug, Clone, Copy, PartialEq)]
#[reflect(Component, Default)]
#[require(Transform)]
pub struct Orbit {
#[reflect(@Tooltip("How far from the center, in meters."))]
pub radius: f32,
#[reflect(@Range(0.0, 10.0))]
#[reflect(@Tooltip("How fast it goes round, in radians a second."))]
pub speed: f32,
pub angle: f32,
}
impl Default for Orbit {
fn default() -> Self {
Self { radius: 1.0, speed: 1.0, angle: 0.0 }
}
}#[require(Transform)] is one of Bevy's required components: adding an Orbit to an entity without a Transform brings one.
The field attributes have the same names as the C# attributes and work the same way, written as Bevy's custom reflection attributes: @Range, @Tooltip, @HideInInspector and @FormerlySerializedAs. A Rust field can carry only one @FormerlySerializedAs, since Bevy keeps one attribute of each kind. A Color field takes @ColorUsage(false, true) for no alpha and HDR, a u64 holding an entity's bits takes @EntitySlot to be shown as an entity slot, and a number inside an enum variant takes @VariantDefault(2.5) for the value it starts at when that variant is picked. #[reflect(Component, Default, SerializeAllFields)], with abyss_ffi::ReflectSerializeAllFields in scope, makes scenes write every field, as [SerializeAllFields] does in C#.
A resource is a Bevy resource that derives Reflect, added with init_resource or insert_resource. When you press Stop in the editor, the resources of types from your game's own crate go back to what they were at Play, as entities do.
Systems
A Rust system is an ordinary Bevy system, added to Bevy's schedules in your plugin's build. It reads Bevy's clock with Res<Time>, which starts at zero at Play and stands still while the game is paused.
Bevy runs the game's C# frame systems inside the engine's own Update, and your plugin's Update systems run straight after the engine's. So a Rust system in Update sees what the C# systems wrote that frame, and one in PostUpdate sees the world positions Bevy worked out from them. Systems in FixedUpdate step on the same fixed clock as the C# systems marked Fixed.
A system can draw for whoever edits the game with Bevy's Gizmos, and reads what the editor has selected from the EditorSelection resource, which is empty in a built game:
fn draw(mut gizmos: Gizmos, selection: Res<EditorSelection>, orbits: Query<(Entity, &Orbit, &GlobalTransform)>) {
for (entity, orbit, at) in &orbits {
let color = if selection.is_selected(entity) { PICKED } else { RESTING };
gizmos.circle(Isometry3d::new(at.translation(), Quat::from_rotation_x(FRAC_PI_2)), orbit.radius, color);
}
}Lines drawn this way appear in the Scene panel only, never in the Game panel or a built game. From a plugin named #[execute_always], they appear while the game is edited too.
A panic in one of your systems is reported in the Logs panel with where it was raised, and the rest of the frame goes on, as it does when a C# system throws.
How C# sees a Rust component
A Rust component needs nothing declared on the C# side. The engine finds it by name, Orbit, or by its full Rust type path where two types share a name. The Inspector, the Add Component list and scene files all reach it that way.
A C# system reaches it by name too. Because Rust is free to reorder a struct's fields, C# never assumes a layout: it asks the engine where each field is and reads it there.
ComponentLayout orbit = schedule.World.LayoutOf("Orbit");ComponentField radius = orbit["radius"];
schedule.Add("Shrink orbits", [orbit.Write()], context =>{ foreach (Chunk chunk in context.Chunks) { FieldView<float> radii = chunk.GetFieldView<float>(0, radius); for (int row = 0; row < radii.Length; row++) { radii[row] *= 0.99f; } }});The layout lists the fields that are plain numbers or booleans, with the fields of a nested struct flattened under dotted names, as translation.x is for a Transform. A field it cannot describe, such as a Handle, a String or an enum, is left out of the layout. Reading a field this way is a strided walk rather than a contiguous span, so it is slower than reading a component declared in C#. A C# system that writes a Rust component publishes Bevy's change ticks, so a Rust query with Changed<Orbit> sees the write.
It does not work the other way round. A component declared in C# has no Rust type, so a Rust system cannot name it in a Query. When both languages need the same data, declare it in Rust.
Limits
- Rust loads once per editor session. The editor process keeps the library it started with. When a build changes the game's Rust, or a package's, the editor asks whether to Restart, which asks about unsaved scene changes and reopens the game, or to restart Later. Changes to C# need no restart.
- Statics keep their values between Plays. Every Play reloads the game's C#, but not its Rust, so a Rust
static, aOnceLockor athread_local!holds what the last Play left in it. Keep state in resources, which Stop puts back, or reset it in your plugin'sbuild. - Ordering against the engine's systems has no effect. The game's schedules are separate from the engine's, so
.after(TransformSystems::Propagate)orders your system against nothing. YourPostUpdatealready runs after all of the engine's. - A schedule your plugin runs itself is not held back. One you insert into Bevy's main schedule order runs while the game is edited, too.
- Some panics still end the game's loop, such as one in a schedule your plugin runs itself, or in the render world.
For the C# side of a game, see C# in a game. For how entities, components and systems fit together in both languages, see Entities, components and systems.
In the Scripting API
- ComponentLayout and FieldView<T>: a Rust component read from C#, a field at a time.
