Unofficial Bevy Cheat Book
This is a reference-style book for the Bevy game engine (GitHub).
It aims to teach Bevy concepts in a concise way, help you be productive, and discover the knowledge you need.
This book aggregates a lot of community wisdom that is often not covered by official documentation, saving you the need to struggle with issues that others have figured out already!
While it aims to be exhaustive, documenting an entire game engine is a monumental task. I focus my time on whatever I believe the community needs most.
Therefore, there are still a lot of omissions, both for basics and advanced topics. Nevertheless, I am confident this book will prove to be a valuable resource to you!
Welcome! May this book serve you well!
(don't forget to Star the book's GitHub repository, and consider donating 🙂)
How to use this book
The pages in this book are not designed to be read in order. Each page covers a standalone topic. Feel free to jump to whatever interests you.
If you have a specific topic in mind that you would like to learn about, you can find it from the table-of-contents (sidebar) or using the search function (in the top bar).
The Chapter Overview page will give you a general idea of how the book is structured.
The text on each page will link to other pages, where you can learn about other things mentioned in the text. This helps you jump around the book.
If you are new to Bevy, or would like a more guided experience, try the Guided Tour tutorial. It will help you navigate the book in an order that makes sense for learning, from beginner to advanced topics.
The Bevy Builtins page is a concise cheatsheet of useful information about types and features provided by Bevy.
Recommended Additional Resources
Bevy has a rich collection of official code examples.
Check out bevy-assets, for community-made resources.
Our community is very friendly and helpful. Feel welcome to join the Bevy Discord to chat, ask questions, or get involved in the project!
If you want to see some games made with Bevy, see itch.io or Bevy Assets.
Support Me
If you like this book, please consider sponsoring me. Thank you! ❤️
I'd like to keep improving and maintaining this book, to provide a high-quality independent learning resource for the Bevy community.
Support Bevy
If you like the Bevy Game Engine, you should consider donating to the project.
Maintenance Policy
To ease the maintenance burden, the policy of the project is that the book may contain a content for different versions of Bevy. However, mixing Bevy versions on the same page is not allowed.
Every page in the book must clearly state what version of Bevy it was last updated for, at the top of the page, above the main heading. All content on that page must be relevant for the stated Bevy version.
Current Bevy Version
The current Bevy release is 0.11.
The aim is to try to maintain the book up to date with the current latest release of Bevy. New content should be written for this version.
Old Bevy Version
Content for old releases of Bevy is only allowed in the book if it already exists from before and has not been updated yet. Outdated pages will be updated on a best-effort basis.
Unreleased (Bevy's git main branch)
Pages that cover new yet-unreleased features of Bevy are allowed. If there is an exciting new feature, and I want to document it, I will write a page, without waiting for the next release of Bevy to come out. :)
License
Copyright © 2021-2023 Ida (IyesGames)
All code in the book is provided under the MIT-0 License. At your option, you may also use it under the regular MIT License.
The text of the book is provided under the CC BY-NC-SA 4.0.
Exception: If used for the purpose of contribution to the "Official Bevy Project", the entire content of the book may be used under the MIT-0 License.
"Official Bevy Project" is defined as:
- Contents of the Git repository hosted at https://github.com/bevyengine/bevy
- Contents of the Git repository hosted at https://github.com/bevyengine/bevy-website
- Anything publicly visible on the bevyengine.org website
The MIT-0 license applies as soon as your contribution has been accepted upstream.
GitHub Forks and Pull Requests created for the purposes of contributing to the Official Bevy Project are given the following license exception: the Attribution requirements of CC BY-NC-SA 4.0 are waived for as long as the work is pending upstream review (Pull Request Open). If upstream rejects your contribution, you are given a period of 1 month to comply with the full terms of the CC BY-NC-SA 4.0 license or delete your work. If upstream accepts your contribution, the MIT-0 license applies.
Contributions
Development of this book is hosted on GitHub.
Please file GitHub Issues for any wrong/confusing/misleading information, as well as suggestions for new content you'd like to be added to the book.
Contributions are accepted, with some limitations.
See the Contributing section for all the details.
Stability Warning
Bevy is still a new and experimental game engine! It has only been public since August 2020!
While improvements have been happening at an incredible pace, and development is active, Bevy simply hasn't yet had the time to mature.
There are no stability guarantees and breaking changes happen often!
Usually, it not hard to adapt to changes with new releases, but you have been warned!
Bevy Version: | (any) |
---|
Chapter Overview
This book is organized into a number of different chapters, covering different aspects of working with Bevy. The is designed to be useful as a reference and learning tool, so you can jump to what interests you and learn about it.
If you would like a more guided tutorial-like experience, or to browse the book by relative difficulty (from beginner to advanced), try the guided tutorial page. It recommends topics in a logical order for learning.
The Bevy Builtins page is a concise cheatsheet of useful information about types and features provided by Bevy.
The book has the following general chapters:
- Bevy Tutorials: complete tutorials that you can follow to help you learn
- Bevy Setup Tips: project setup advice, recommendations for tools and plugins
- Common Pitfalls: solutions for common issues encountered by the community
- Bevy Cookbook: various code examples beyond the ones in Bevy official repos
- Bevy on Different Platforms: information about working with specific plaforms / OSs
- Appendix: General Concepts: various general gamedev knowledge, not specific to Bevy
To learn how to program in Bevy, see these chapters:
- Bevy Programming Framework: the ECS+App frameworks, the foundation of everything
- Programming Patterns: opinionated advice, patterns, idioms
- Bevy Render (GPU) Framework: working with the GPU and Bevy's rendering
The following chapters cover various Bevy feature areas:
- General Game Engine Features: general features that don't belong in any other chapter
- Asset Management: working with data assets
- Input Handling: working with different input devices
- Window Management: working with the OS window
- Working with 2D: Bevy's features for 2D games
- Working with 3D: Bevy's features for 3D games
Bevy Version: | 0.11 | (current) |
---|
List of Bevy Builtins
This page is a quick condensed listing of all the important things provided by Bevy.
- SystemParams
- Assets
- File Formats
- GLTF Asset Labels
- Shader Imports
wgpu
Backends- Schedules
- Run Conditions
- Plugins
- Bundles
- Resources (Configuration)
- Resources (Engine User)
- Resources (Input)
- Events (Input)
- Events (Engine)
- Events (System/Control)
- Components
SystemParams
These are all the special types that can be used as system parameters.
In regular systems:
Commands
: Manipulate the ECS using commandsQuery<T, F = ()>
(can contain tuples of up to 15 types): Access to entities and componentsRes<T>
: Shared access to a resourceResMut<T>
: Exclusive (mutable) access to a resourceOption<Res<T>>
: Shared access to a resource that may not existOption<ResMut<T>>
: Exclusive (mutable) access to a resource that may not existLocal<T>
: Data local to the systemEventReader<T>
: Receive eventsEventWriter<T>
: Send events&World
: Read-only direct access to the ECS WorldParamSet<...>
(with up to 8 params): Resolve conflicts between incompatible system parametersDeferred<T>
: Custom "deferred mutation", similar toCommands
, but for your own thingsRemovedComponents<T>
: Removal detectionGizmos
: A way to draw lines and shapes on the screen for debugging and dev purposesDiagnostics
: A way to report measurements/debug data to Bevy for tracking and visualizationSystemName
: The name (string) of the system, may be useful for debuggingParallelCommands
: Abstraction to help useCommands
when you will do your own parallelismWorldId
: The World ID of the world the system is running onComponentIdFor<T>
: Get theComponentId
of a given component typeEntities
: Low-level ECS metadata: All entitiesComponents
: Low-level ECS metadata: All componentsBundles
: Low-level ECS metadata: All bundlesArchetypes
: Low-level ECS metadata: All archetypesSystemChangeTick
: Low-level ECS metadata: Tick used for change detectionNonSend<T>
: Shared access to Non-Send
(main thread only) dataNonSendMut<T>
: Exclusive access to Non-Send
(main thread only) dataOption<NonSend<T>>
: Shared access to Non-Send
(main thread only) data that may not existOption<NonSendMut<T>>
: Exclusive access to Non-Send
(main thread only) data that may not existStaticSystemParam
: Helper for generic system abstractions, to avoid lifetime annotations- tuples containing any of these types, with up to 16 members
&mut World
: Full direct access to the ECS WorldLocal<T>
: Data local to the systemSystemState<P>
: Emulates a regular system, allowing you to easily access data from the World.P
are the system parameters.QueryState<Q, F = ()>
: Allows you to perform queries on the World, similar to aQuery
in regular systems.
Your function can have a maximum of 16 total parameters. If you need more, group them into tuples to work around the limit. Tuples can contain up to 16 members, but can be nested indefinitely.
Systems running during the Extract schedule can also use
Extract<T>
, to access data from the Main World instead of the
Render World. T
can be any read-only system parameter type.
Assets
(more info about working with assets)
These are the Asset types registered by Bevy by default.
Image
: Pixel data, used as a texture for 2D and 3D rendering; also contains theSamplerDescriptor
for texture filtering settingsTextureAtlas
: 2D "Sprite Sheet" defining sub-images within a single larger imageMesh
: 3D Mesh (geometry data), contains vertex attributes (like position, UVs, normals)Shader
: GPU shader code, in one of the supported languages (WGSL/SPIR-V/GLSL)ColorMaterial
: Basic "2D material": contains color, optionally an imageStandardMaterial
: "3D material" with support for Physically-Based RenderingAnimationClip
: Data for a single animation sequence, can be used withAnimationPlayer
Font
: Font data used for text renderingScene
: Scene composed of literal ECS entities to instantiateDynamicScene
: Scene composed with dynamic typing and reflectionGltf
: GLTF Master Asset: index of the entire contents of a GLTF fileGltfNode
: Logical GLTF object in a sceneGltfMesh
: Logical GLTF 3D model, consisting of multipleGltfPrimitive
sGltfPrimitive
: Single unit to be rendered, contains the Mesh and Material to useAudioSource
: Audio data forbevy_audio
FontAtlasSet
: (internal use for text rendering)SkinnedMeshInverseBindposes
: (internal use for skeletal animation)
File Formats
These are the asset file formats (asset loaders) supported by Bevy. Support for each one can be enabled/disabled using cargo features. Some are enabled by default, many are not.
Image formats (loaded as Image
assets):
Format | Cargo feature | Default? | Filename extensions |
---|---|---|---|
PNG | "png" | Yes | .png |
HDR | "hdr" | Yes | .hdr |
KTX2 | "ktx2" | Yes | .ktx2 |
KTX2+zstd | "ktx2", "zstd" | Yes | .ktx2 |
JPEG | "jpeg" | No | .jpg , .jpeg |
WebP | "webp" | No | .webp |
OpenEXR | "exr" | No | .exr |
TGA | "tga" | No | .tga |
PNM | "pnm" | No | .pam , .pbm , .pgm , .ppm |
BMP | "bmp" | No | .bmp |
DDS | "dds" | No | .dds |
KTX2+zlib | "ktx2", "zlib" | No | .ktx2 |
Basis | "basis-universal" | No | .basis |
Audio formats (loaded as AudioSource
assets):
Format | Cargo feature | Default? | Filename extensions |
---|---|---|---|
OGG Vorbis | "vorbis" | Yes | .ogg , .oga , .spx |
FLAC | "flac" | No | .flac |
WAV | "wav" | No | .wav |
MP3 | "mp3" | No | .mp3 |
3D asset (model or scene) formats:
Format | Cargo feature | Default? | Filename extensions |
---|---|---|---|
GLTF | "bevy_gltf" | Yes | .gltf , .glb |
Shader formats (loaded as Shader
assets):
Format | Cargo feature | Default? | Filename extensions |
---|---|---|---|
WGSL | n/a | Yes | .wgsl |
GLSL | "shader_format_glsl" | No | .vert , .frag , .comp |
SPIR-V | "shader_format_spirv" | No | .spv |
Font formats (loaded as Font
assets):
Format | Cargo feature | Default? | Filename extensions |
---|---|---|---|
TrueType | n/a | Yes | .ttf |
OpenType | n/a | Yes | .otf |
Bevy Scenes:
Format | Filename extensions |
---|---|
RON-serialized scene | .scn ,.scn.ron |
There are unofficial plugins available for adding support for even more file formats.
GLTF Asset Labels
Asset path labels to refer to GLTF sub-assets.
The following asset labels are supported ({}
is the numerical index):
Scene{}
: GLTF Scene as BevyScene
Node{}
: GLTF Node asGltfNode
Mesh{}
: GLTF Mesh asGltfMesh
Mesh{}/Primitive{}
: GLTF Primitive as BevyMesh
Mesh{}/Primitive{}/MorphTargets
: Morph target animation data for a GLTF PrimitiveTexture{}
: GLTF Texture as BevyImage
Material{}
: GLTF Material as BevyStandardMaterial
DefaultMaterial
: as above, if the GLTF file contains a default material with no indexAnimation{}
: GLTF Animation as BevyAnimationClip
Skin{}
: GLTF mesh skin as BevySkinnedMeshInverseBindposes
Shader Imports
TODO
wgpu
Backends
wgpu
(and hence Bevy) supports the following backends:
Platform | Backends (in order of priority) |
---|---|
Linux | Vulkan, GLES3 |
Windows | DirectX 12, Vulkan, GLES3 |
macOS | Metal |
iOS | Metal |
Android | Vulkan, GLES3 |
Web | WebGPU, WebGL2 |
On GLES3 and WebGL2, some renderer features are unsupported and performance is worse.
WebGPU is experimental and few browsers support it.
Schedules
Internally, Bevy has these built-in schedules:
Main
: runs every frame update cycle, to perform general app logicExtractSchedule
: runs afterMain
, to copy data from the Main World into the Render WorldRender
: runs afterExtractSchedule
, to perform all rendering/graphics, in parallel with the nextMain
run
The Main
schedule simply runs a sequence of other schedules:
On the first run (first frame update of the app):
On every run (controlled via the MainScheduleOrder
resource):
First
: any initialization that must be done at the start of every framePreUpdate
: for engine-internal systems intended to run before user logicStateTransition
: perform any pending state transitionsRunFixedUpdateLoop
: runs theFixedUpdate
schedule as many times as neededUpdate
: for all user logic (your systems) that should run every framePostUpdate
: for engine-internal systems intended to run after user logicLast
: any final cleanup that must be done at the end of every frame
FixedUpdate
is for all user logic (your systems) that should run at a fixed timestep.
StateTransition
runs the
OnEnter(...)
/OnTransition(...)
/OnExit(...)
schedules for your states, when you want to change state.
The Render
schedule is organized using sets (RenderSet
):
ExtractCommands
: apply deferred buffers from systems that ran inExtractSchedule
Prepare
/PrepareFlush
: set up data on the GPU (buffers, textures, etc.)Queue
/QueueFlush
: generate the render jobs to be run (usually phase items)PhaseSort
/PhaseSortFlush
: sort and batch phase items for efficient renderingRender
/RenderFlush
: execute the render graph to actually trigger the GPU to do workCleanup
/CleanupFlush
: clear any data from the render World that should not persist to the next frame
The *Flush
variants are just to apply any deferred buffers after every step, if needed.
Run Conditions
TODO
Plugins
TODO
Bundles
Bevy's built-in bundle types, for spawning different common kinds of entities.
Any tuples of up to 15 Component
types are valid bundles.
General:
SpatialBundle
: Contains the required transform and visibility components that must be included on all entities that need rendering or hierarchyTransformBundle
: Contains only the transform types, subset ofSpatialBundle
VisibilityBundle
: Contains only the visibility types, subset ofSpatialBundle
Scenes:
SceneBundle
: Used for spawning scenesDynamicSceneBundle
: Used for spawning dynamic scenes
Audio:
AudioBundle
: Play audio from anAudioSource
assetSpatialAudioBundle
: Play positional audio from anAudioSource
assetAudioSourceBundle
: Play audio from a custom data source/streamSpatialAudioSourceBundle
: Play positional audio from a custom data source/stream
Bevy 3D:
Camera3dBundle
: 3D camera, can use perspective (default) or orthographic projectionTemporalAntiAliasBundle
: Add this to a 3D camera to enable TAAScreenSpaceAmbientOcclusionBundle
: Add this to a 3D camera to enable SSAOMaterialMeshBundle
: 3D Object/Primitive: a Mesh and a custom Material to draw it withPbrBundle
:MaterialMeshBundle
with the default Physically-Based Material (StandardMaterial
)DirectionalLightBundle
: 3D directional light (like the sun)PointLightBundle
: 3D point light (like a lamp or candle)SpotLightBundle
: 3D spot light (like a projector or flashlight)
Bevy 2D:
Camera2dBundle
: 2D camera, uses orthographic projection + other special configuration for 2DSpriteBundle
: 2D sprite (Image
asset type)SpriteSheetBundle
: 2D sprite (TextureAtlas
asset type)MaterialMesh2dBundle
: 2D shape, with custom Mesh and Material (similar to 3D objects)Text2dBundle
: Text to be drawn in the 2D world (not the UI)
Bevy UI:
NodeBundle
: Empty node element (like HTML<div>
)ButtonBundle
: Button elementImageBundle
: Image element (Image
asset type)AtlasImageBundle
: Image element (TextureAtlas
asset type)TextBundle
: Text element
Resources
(more info about working with resources)
Configuration Resources
These resources allow you to change the settings for how various parts of Bevy work.
These may be inserted at the start, but should also be fine to change at runtime (from a system):
ClearColor
: Global renderer background color to clear the window at the start of each frameGlobalVolume
: The overall volume for playing audioAmbientLight
: Global renderer "fake lighting", so that shadows don't look too dark / blackMsaa
: Global renderer setting for Multi-Sample Anti-Aliasing (some platforms might only support the values 1 and 4)UiScale
: Global scale value to make all UIs bigger/smallerGizmoConfig
: Controls how gizmos are renderedWireframeConfig
: Global toggle to make everything be rendered as wireframeGamepadSettings
: Gamepad input device settings, like joystick deadzones and button sensitivitiesWinitSettings
: Settings for the OS Windowing backend, including update loop / power-management settingsTimeUpdateStrategy
: Used to control how theTime
is updatedSchedules
: Stores all schedules, letting you register additional functionality at runtimeMainScheduleOrder
: The sequence of schedules that will run every frame update
Settings that are not modifiable at runtime are not represented using resources. Instead, they are configured via the respective plugins.
Engine Resources
These resources provide access to different features of the game engine at runtime.
Access them from your systems, if you need their state, or to control the respective parts of Bevy. These resources are in the Main World. See here for the resources in the Render World.
Time
: Global time-related information (current frame delta time, time since startup, etc.)FixedTime
: Tracks remaining time until the next fixed updateAssetServer
: Control the asset system: Load assets, check load status, etc.Assets<T>
: Contains the actual data of the loaded assets of a given typeState<T>
: The current value of a states typeNextState<T>
: Used to queue a transition to another stateGamepads
: Tracks the IDs for all currently-detected (connected) gamepad devicesSceneSpawner
: Direct control over spawning Scenes into the main app WorldFrameCount
: The total number of framesScreenshotManager
: Used to request a screenshot of a window to be taken/savedAppTypeRegistry
: Access to the Reflection Type RegistryAsyncComputeTaskPool
: Task pool for running background CPU tasksComputeTaskPool
: Task pool where the main app schedule (all the systems) runsIoTaskPool
: Task pool where background i/o tasks run (like asset loading)WinitWindows
(non-send): Raw state of thewinit
backend for each windowNonSendMarker
: Dummy resource to ensure a system always runs on the main thread
Render World Resources
These resources are present in the Render World. They can be accessed from rendering systems (that run during render stages).
MainWorld
: (extract schedule only!) access data from the Main WorldRenderGraph
: The Bevy Render GraphPipelineCache
: Bevy's manager of render pipelines. Used to store render pipelines used by the app, to avoid recreating them more than once.TextureCache
: Bevy's manager of temporary textures. Useful when you need textures to use internally during rendering.DrawFunctions<P>
: Stores draw functions for a given phase item typeRenderAssets<T>
: Contains handles to the GPU representations of currently loaded asset dataDefaultImageSampler
: The default sampler forImage
asset texturesFallbackImage
: Dummy 1x1 pixel white texture. Useful for shaders that normally need a texture, when you don't have one available.
There are many other resources in the Render World, which are not mentioned here, either because they are internal to Bevy's rendering algorithms, or because they are just extracted copies of the equivalent resources in the Main World.
Low-Level wgpu
Resources
Using these resources, you can have direct access to the wgpu
APIs for controlling the GPU.
These are available in both the Main World and the Render World.
RenderDevice
: The GPU device, used for creating hardware resources for rendering/computeRenderQueue
: The GPU queue for submitting work to the hardwareRenderAdapter
: Handle to the physical GPU hardwareRenderAdapterInfo
: Information about the GPU hardware that Bevy is running on
Input Handling Resources
These resources represent the current state of different input devices. Read them from your systems to handle user input.
Input<KeyCode>
: Keyboard key state, as a binary Input valueInput<MouseButton>
: Mouse button state, as a binary Input valueInput<GamepadButton>
: Gamepad buttons, as a binary Input valueAxis<GamepadAxis>
: Analog Axis gamepad inputs (joysticks and triggers)Axis<GamepadButton>
: Gamepad buttons, represented as an analog Axis valueTouches
: The state of all fingers currently touching the touchscreenGamepads
: Registry of all the connectedGamepad
IDs
Events
(more info about working with events)
Input Events
These events fire on activity with input devices. Read them to [handle user input][cb::input].
MouseButtonInput
: Changes in the state of mouse buttonsMouseWheel
: Scrolling by a number of pixels or lines (MouseScrollUnit
)MouseMotion
: Relative movement of the mouse (pixels from previous frame), regardless of the OS pointer/cursorCursorMoved
: New position of the OS mouse pointer/cursorKeyboardInput
: Changes in the state of keyboard keys (keypresses, not text)ReceivedCharacter
: Unicode text input from the OS (correct handling of the user's language and layout)Ime
: Unicode text input from IME (support for advanced text input in different scripts)TouchInput
: Change in the state of a finger touching the touchscreenGamepadEvent
: Changes in the state of a gamepad or any of its buttons or axesGamepadRumbleRequest
: Send these events to control gamepad rumbleTouchpadMagnify
: Pinch-to-zoom gesture on laptop touchpad (macOS)TouchpadRotate
: Two-finger rotate gesture on laptop touchpad (macOS)
Engine Events
Events related to various internal things happening during the normal runtime of a Bevy app.
AssetEvent<T>
: Sent by Bevy when asset data has been added/modified/removed; can be used to detect changes to assetsHierarchyEvent
: Sent by Bevy when entity parents/children changeAppExit
: Tell Bevy to shut down
System and Control Events
Events from the OS / windowing system, or to control Bevy.
RequestRedraw
: In an app that does not refresh continuously, request one more update before going to sleepFileDragAndDrop
: The user drag-and-dropped a file into our appCursorEntered
: OS mouse pointer/cursor entered one of our windowsCursorLeft
: OS mouse pointer/cursor exited one of our windowsWindowCloseRequested
: OS wants to close one of our windowsWindowCreated
: New application window openedWindowClosed
: Bevy window closedWindowDestroyed
: OS window freed/dropped after window closeWindowFocused
: One of our windows is now focusedWindowMoved
: OS/user moved one of our windowsWindowResized
: OS/user resized one of our windowsWindowScaleFactorChanged
: One of our windows has changed its DPI scaling factorWindowBackendScaleFactorChanged
: OS reports change in DPI scaling factor for a window
Components
The complete list of individual component types is too specific to be useful to list here.
See: (List in API Docs)
Bevy Version: | (any) |
---|
Bevy Tutorials
This chapter of the book contains tutorials. Tutorials teach you things in a logical order from start to finish. If you are looking for something to guide you through learning Bevy, maybe some of them will be useful to you.
The rest of this book is designed to be used as a reference, so you can jump around to specific topics you want to learn about.
The first tutorial in this chapter, Guided Tour, simply organizes all the topics in this book in an order suggested for learning, from the basics to advanced concepts. You can use it as an alternative to the main table of contents (the left side bar), if you are just learning Bevy and don't know how to progress. If you are new to Bevy, you can start here to find your way around.
The other tutorials are more specialized. They cover specific workflows or advanced use cases.
You should also look at Bevy's official collection of examples. There is something for almost every area of the engine, though they usually only show the usage of the APIs without much explanation.
Bevy Version: | 0.11 | (current) |
---|
New to Bevy? Guided Tutorial!
Welcome to Bevy! :) We are glad to have you in our community!
This page will guide you through this book, to help you gain comprehensive knowledge of how to work with Bevy. The topics are structured in an order that makes sense for learning: from basics to advanced.
It is just a suggestion to help you navigate. Feel free to jump around the book and read whatever interests you. The main table-of-contents (the left sidebar) was designed to be a reference for Bevy users of any skill level.
Make sure to also look at the official Bevy examples. If you need help, use GitHub Discussions, or feel welcome to join us to chat and ask for help in Discord.
If you run into issues, be sure to check the Common Pitfalls chapter, to see if this book has something to help you. Solutions to some of the most common issues that Bevy community members have encountered are documented there.
Basics
These are the absolute essentials of using Bevy. Every Bevy project, even a simple one, would require you to be familiar with these concepts.
You could conceivably make something like a simple game-jam game or prototype, using just this knowledge. Though, as your project grows, you will likely quickly need to learn more.
- Bevy Setup Tips: Configuring your development tools and environment
- Bevy Programming Framework: How to write Bevy code, structure your data and logic
- General Game Engine Features: Basic features of Bevy, needed for making any game
- Bevy Asset Management: How to work with assets
- Input Handling: Using various input devices
- Window Management: Setting up the OS Window (or fullscreen) for your game
Next Steps
You will likely need to learn most of these topics to make a non-trivial Bevy project. After you are confident with the basics, you should learn these.
- Bevy Programming Framework
- General Game Engine Features:
- Input Handling:
- Bevy Asset Management:
- Bevy Setup Tips
Intermediate
These are more specialized topics. You may need some of them, depending on your project.
- Bevy Programming Framework
- General Game Engine Features:
- Input Handling:
- Programming Patterns
- Window Management:
Advanced
These topics are for niche technical situations. You can learn them, if you want to know more about how Bevy works internally, extend the engine with custom functionality, or do other advanced things with Bevy.
Bevy Version: | (any) |
---|
Bevy Setup Tips
This chapter is a collection of additional tips for configuring your project or development tools, collected from the Bevy community, beyond what is covered in Bevy's official setup documentation.
Feel free to suggest things to add under this chapter.
Also see the following other relevant content from this book:
Bevy Version: | 0.11 | (current) |
---|
Getting Started
This page covers the basic setup needed for Bevy development.
For the most part, Bevy is just like any other Rust library. You need to install Rust and setup your dev environment just like for any other Rust project. You can install Rust using Rustup. See Rust's official setup page.
On Linux, you need the development files for some system libraries. See the official Bevy Linux dependencies page.
Also see the Setup page in the official Bevy Book and the official Bevy Readme.
Creating a New Project
You can simply create a new Rust project, either from your IDE/editor, or the commandline:
cargo new --bin my_game
(creates a project called my_game
)
The Cargo.toml
file contains all the configuration of your project.
Add the latest version of bevy
as a dependency. Your file should now
look something like this:
[package]
name = "my_game"
version = "0.1.0"
edition = "2021"
[dependencies]
bevy = "0.11"
The src/main.rs
file is your main source code file. This is where you
start writing your Rust code. For a minimal Bevy app, you need
at least the following:
use bevy::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.run();
}
You can now compile and run your project. The first time, this will take a while, as it needs to build the whole Bevy engine and dependencies. Subsequent runs should be fast. You can do this from your IDE/editor, or the commandline:
cargo run
Documentation
You can generate your own docs (like what is on docs.rs), for offline use, including everything from your own project and all dependencies, in one place.
cargo doc --open
This will build all the HTML docs and open them in your web browser.
It does not require an internet connection, and gives you an easy way to search the API docs for all crates in your dependency tree all at once. It is more useful than the online version of the docs.
Optional Extra Setup
You will likely quickly run into unusably slow performance with the default Rust unoptimized dev builds. See here how to fix.
Iterative recompilation speed is important to keep you productive, so you don't have to wait long for the Rust compiler to rebuild your project every time you want to test your game. Bevy's getting started page has advice about how to speed up compile times.
Also have a look in the Dev Tools and Editors page for suggestions about additional external dev tools that may be helpful.
What's Next?
Have a look at the guided tutorial page of this book, and Bevy's official examples.
Check out the Bevy Assets Website to find other tutorials and learning resources from the community, and plugins to use in your project.
Join the community on Discord to chat with us!
Running into Issues?
If something is not working, be sure to check the Common Pitfalls chapter, to see if this book has something to help you. Solutions to some of the most common issues that Bevy community members have encountered are documented there.
If you need help, use GitHub Discussions, or feel welcome to come chat and ask for help in Discord.
GPU Drivers
To work at its best, Bevy needs DirectX 12 (Windows) or Vulkan (Linux, Android, Windows). macOS/iOS should just work, without any special driver setup, using Metal.
OpenGL (GLES3) can be used as a fallback, but will likely have issues (some bugs, unsupported features, worse performance).
Make sure you have compatible hardware and drivers installed on your system. Your users will also need to satisfy this requirement.
If Bevy is not working, install the latest drivers for your OS, or check with your Linux distribution whether Vulkan needs additional packages to be installed.
Web games are supported and should work in any modern browser, using WebGL2. Performance is limited and some Bevy features will not work. The new experimental high-performance WebGPU API is also supported, but browser adoption is still limited.
Bevy Version: | main | (development) |
---|
Using bleeding-edge Bevy (bevy main)
Bevy development moves very fast, and there are often exciting new things that are yet unreleased. This page will give you advice about using development versions of bevy.
Quick Start
If you are not using any 3rd-party plugins and just want to use the bevy main development branch:
[dependencies]
bevy = { git = "https://github.com/bevyengine/bevy" }
However, if you are working with external plugins, you should read the rest of this page. You will likely need to do more to make everything compatible.
Should you use bleeding-edge Bevy?
Currently, Bevy does not make patch releases (with rare exceptions for critical bugs), only major releases. The latest release is often missing the freshest bug fixes, usability improvements, and features. It may be compelling to join in on the action!
If you are new to Bevy, this might not be for you. You might be more comfortable using the released version. It will have the best compatibility with community plugins and documentation.
The in-development version of Bevy has frequent breaking changes. Therefore, it can be very annoying to use for any more serious projects, and 3rd-party plugin authors often don't bother to stay compatible. You will face breakage often and probably have to fix it yourself.
It is only recommended to do this for more experimental or toy projects. Most Bevy users should use the released version.
Though, there are ways you can manage the breakage and make it less of a problem. Thanks to cargo, you can update bevy at your convenience, whenever you feel ready to handle any possible breaking changes.
You may want to consider forking the repositories of Bevy and any plugins you
use. Using your own forks allows you to easily apply fixes if needed, or edit
their Cargo.toml
for any special configuration to make your project work.
If you choose to use Bevy main, you are highly encouraged to interact with the Bevy community on Discord and GitHub, so you can keep track of what's going on, get help, or participate in discussions.
Common pitfall: mysterious compile errors
When changing between different versions of Bevy (say, transitioning an existing project from the released version to the git version), you might get lots of strange unexpected build errors.
You can typically fix them by removing Cargo.lock
and the target
directory:
rm -rf Cargo.lock target
See this page for more info.
If you are still getting errors, it is probably because cargo is trying to use multiple different versions of bevy in your dependency tree simultaneously. This can happen if some of the plugins you use have specified a different Bevy version/commit from your project.
If you are using any 3rd-party plugins, please consider forking them, so you can
edit their Cargo.toml
and have control over how everything is configured.
Cargo Patches
In some cases, you might be able to use "cargo patches" to locally override
dependencies. For example, you might be able to point plugins to use your
fork of bevy, without forking and editing the plugin's Cargo.toml
, by
doing something like this:
# replace the bevy git URL source with ours
[patch."https://github.com/bevyengine/bevy"]
# if we have our own fork
bevy = { git = "https://github.com/me/bevy" }
# if we want to use a local path
bevy = { path = "../bevy" }
# some plugins might depend on individual bevy crates,
# instead of all of bevy, which means we need to patch
# every individual bevy crate specifically:
bevy_ecs = { path = "../bevy/crates/bevy_ecs" }
bevy_app = { path = "../bevy/crates/bevy_app" }
# ...
# replace released versions of crates (crates.io source) with ours
[patch.crates-io]
bevy_some_plugin = { git = "https://github.com/me/bevy_some_plugin", branch = "bevy_main" }
Updating Bevy
It is recommended that you specify a known-good Bevy commit in your
Cargo.toml
, so that you can be sure that you only update it when you
actually want to do so, avoiding unwanted breakage.
bevy = { git = "https://github.com/bevyengine/bevy", rev = "7a1bd34e" }
When you change anything, be sure to run:
cargo update
(or delete Cargo.lock
)
Otherwise you risk errors from cargo not resolving dependencies correctly.
Advice for plugin authors
If you are publishing a plugin crate, here are some recommendations:
- Have a separate branch in your repository, to keep support for bevy main separate from your main version for the released version of bevy
- Put information in your README to tell people how to find it
- Set up CI to notify you if your plugin is broken by new changes in bevy
Feel free to follow all the advice from this page, including cargo patches
as needed. Cargo patches only apply when you build your project directly,
not as a dependency, so they do not affect your users and can be safely kept
in your Cargo.toml
.
CI Setup
Here is an example for GitHub Actions. This will run at 8:00 AM (UTC) every day to verify that your code still compiles. GitHub will notify you when it fails.
name: check if code still compiles
on:
schedule:
- cron: '0 8 * * *'
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install Dependencies
run: sudo apt-get update && sudo apt-get install --no-install-recommends pkg-config libx11-dev libasound2-dev libudev-dev
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Check code
run: cargo update && cargo check --lib --examples
Bevy Version: | 0.11 | (current) |
---|
Text Editor / IDE
This sub-chapter contains tips for different text editors and IDEs.
Bevy is, for the most part, like any other Rust project. If your editor/IDE is set up for Rust, that might be all you need. This page contains additional information that may be useful for Bevy specifically.
If you have any tips/advice/configurations for your editor of choice, that you'd like to share with the community, please create a GitHub Issue, so we can add it to the book. If your editor is not in the list, I will add it.
Bevy Version: | 0.11 | (current) |
---|
Visual Studio Code
If you are a VSCode user and you'd like something to be added to this page, please file a GitHub Issue.
Rust Language Support
For good Rust support, install the Rust Analyzer plugin. Bevy uses a lot of procedural macros, so be sure to enable proc-macro support in the RA settings (it is not enabled by default).
CARGO_MANIFEST_DIR
When running your app/game, Bevy will search for the assets
folder in the path
specified in the BEVY_ASSET_ROOT
or CARGO_MANIFEST_DIR
environment variable.
This allows cargo run
to work correctly from the terminal.
If you want to run your project from VSCode in a non-standard way (say, inside a debugger), you have to be sure to set that correctly.
If this is not set, Bevy will search for assets
alongside the executable
binary, in the same folder where it is located. This makes things easy for
distribution. However, during development, since your executable is located
in the target
directory where cargo
placed it, Bevy will be unable to
find the assets
.
Here is a snippet showing how to create a run configuration for debugging Bevy
(with lldb
):
(this is for development on Bevy itself, and testing with the breakout
example)
(adapt to your needs if using for your project)
{
"type": "lldb",
"request": "launch",
"name": "Debug example 'breakout'",
"cargo": {
"args": [
"build",
"--example=breakout",
"--package=bevy"
],
"filter": {
"name": "breakout",
"kind": "example"
}
},
"args": [],
"cwd": "${workspaceFolder}",
"env": {
"CARGO_MANIFEST_DIR": "${workspaceFolder}",
}
}
Bevy Version: | 0.11 | (current) |
---|
JetBrains (IntelliJ, CLion)
If you are a JetBrains user and you'd like something to be added to this page, please file a GitHub Issue.
Rust Language Support
When using queries, type information gets lost due to Bevy relying on procedural macros. You can fix this by enabling procedural macro support in the IDE.
- type
Experimental feature
in the dialog of theHelp | Find Action
action - enable the features
org.rust.cargo.evaluate.build.scripts
andorg.rust.macros.proc
Bevy Version: | 0.11 | (current) |
---|
Kakoune
If you are a Kakoune user and you'd like something to be added to this page, please file a GitHub Issue.
Rust Language Support
You can use kak-lsp
with rust-analyzer
.
You want to install just the RA server, without the official VSCode plugin.
You can manage it via rustup
:
rustup component add rust-analyzer
Or you can build/install it yourself from git:
git clone https://github.com/rust-lang/rust-analyzer
cd rust-analyzer
git checkout release # use the `release` branch instead of `main`
cargo xtask install --server
The easiest way to set up kak-lsp
is using plug.kak
.
If you don't have plug.kak
, put the following in ~/.config/kak/kakrc
:
evaluate-commands %sh{
plugins="$kak_config/plugins"
mkdir -p "$plugins"
[ ! -e "$plugins/plug.kak" ] && \
git clone -q https://github.com/andreyorst/plug.kak.git "$plugins/plug.kak"
printf "%s\n" "source '$plugins/plug.kak/rc/plug.kak'"
}
plug "andreyorst/plug.kak" noload
And then to set up kak-lsp
with Rust support:
plug "kak-lsp/kak-lsp" do %{
cargo install --force --path .
} config %{
set global lsp_cmd "kak-lsp -s %val{session}"
# create a command to let you restart LSP if anything goes wrong / gets glitched
define-command lsp-restart -docstring 'restart lsp server' %{ lsp-stop; lsp-start }
# helper command to enable LSP
define-command -hidden lsp-init %{
lsp-enable-window
# preferences:
set window lsp_auto_highlight_references true
lsp-auto-signature-help-enable
# keybind: use "," to get a menu of available LSP commands
map global normal "," ": enter-user-mode lsp<ret>" -docstring "LSP mode"
}
hook global KakEnd .* lsp-exit
# autoenable LSP when opening Rust files
hook global WinSetOption filetype=rust %{
lsp-init
}
}
# formatting settings for Rust files
hook global BufSetOption filetype=rust %{
set buffer tabstop 4
set buffer indentwidth 4
set buffer formatcmd 'rustfmt'
set buffer autowrap_column 100
expandtab
}
Put the following in ~/.config/kak-lsp/kak-lsp.toml
to use rust-analyzer
:
[server]
# Shut down the `rust-analyzer` process after a period of inactivity
timeout = 900
[language.rust]
filetypes = ["rust"]
roots = ["Cargo.toml"]
command = "rust-analyzer"
settings_section = "rust-analyzer"
[language.rust.settings.rust-analyzer]
# Proc Macro support is important for Bevy projects
procMacro.enable = true
# disable hover actions, can be laggy on complex projects like Bevy
hoverActions.enable = false
# use the data generated by `cargo check`
cargo.loadOutDirsFromCheck = true
Bevy Version: | 0.11 | (current) |
---|
Vim
If you are a Vim user and you'd like something to be added to this page, please file a GitHub Issue.
Bevy Version: | 0.11 | (current) |
---|
Emacs
If you are an Emacs user and you'd like something to be added to this page, please file a GitHub Issue.
Bevy Version: | 0.11 | (current) |
---|
Configuring Bevy
Bevy is very modular and configurable. It is implemented as many separate cargo crates, allowing you to remove the parts you don't need. Higher-level functionality is built on top of lower-level foundational crates, and can be disabled or replaced with alternatives.
The lower-level core crates (like the Bevy ECS) can also be used completely standalone, or integrated into otherwise non-Bevy projects.
Bevy Cargo Features
In Bevy projects, you can enable/disable various parts of Bevy using cargo features.
Many common features are enabled by default. If you want to disable some of them, you need to disable all of them and re-enable the ones you need. Unfortunately, Cargo does not let you just disable individual default features.
Here is how you might configure your Bevy:
[dependencies.bevy]
version = "0.11"
# Disable the default features if there are any that you do not want
default-features = false
features = [
# These are the default features:
# (re-enable whichever you like)
# Bevy functionality:
"multi-threaded", # Run with multithreading
"bevy_asset", # Assets management
"bevy_audio", # Builtin audio
"bevy_gilrs", # Gamepad input support
"bevy_scene", # Scenes management
"bevy_winit", # Window management
"bevy_render", # Rendering framework core
"bevy_core_pipeline", # Common rendering abstractions
"bevy_gizmos", # Support drawing debug lines and shapes
"bevy_sprite", # 2D (sprites) rendering
"bevy_pbr", # 3D (physically-based) rendering
"bevy_gltf", # GLTF 3D assets format support
"bevy_text", # Text/font rendering
"bevy_ui", # UI toolkit
"animation", # Animation support
"tonemapping_luts", # Support different camera Tonemapping modes (embeds extra data)
"filesystem_watcher", # Asset hot-reloading
"default_font", # Embed a minimal default font for text/UI
# File formats:
"png", # PNG image format for simple 2D images
"hdr", # HDR images
"ktx2", # Preferred format for GPU textures
"zstd", # ZSTD compression support in KTX2 files
"vorbis", # Audio: OGG Vorbis
# Platform-specific:
"x11", # Linux: Support X11 windowing system
"android_shared_stdcxx", # Android: use shared C++ library
"webgl2", # Web: use WebGL2 instead of WebGPU
# These are other features that may be of interest:
# (add any of these that you need)
# Bevy functionality:
"subpixel_glyph_atlas", # Subpixel antialiasing for text/fonts
"serialize", # Support for `serde` Serialize/Deserialize
# File formats:
"dds", # Alternative DirectX format for GPU textures, instead of KTX2
"jpeg", # JPEG lossy format for 2D photos
"webp", # WebP image format
"bmp", # Uncompressed BMP image format
"tga", # Truevision Targa image format
"exr", # OpenEXR advanced image format
"pnm", # PNM (pam, pbm, pgm, ppm) image format
"basis-universal", # Basis Universal GPU texture compression format
"zlib", # zlib compression support in KTX2 files
"flac", # Audio: FLAC lossless format
"mp3", # Audio: MP3 format (not recommended)
"wav", # Audio: Uncompressed WAV
"symphonia-all", # All Audio formats supported by the Symphonia library
"shader_format_glsl", # GLSL shader support
"shader_format_spirv", # SPIR-V shader support
# Platform-specific:
"wayland", # (Linux) Support Wayland windowing system
"accesskit_unix", # (Unix-like) AccessKit integration for UI Accessibility
"bevy_dynamic_plugin", # (Desktop) support for loading of `DynamicPlugin`s
# Development/Debug features:
"dynamic_linking", # Dynamic linking for faster compile-times
"trace", # Enable tracing for performance measurement
"detailed_trace", # Make traces more verbose
"trace_tracy", # Tracing using `tracy`
"trace_tracy_memory", # + memory profiling
"trace_chrome", # Tracing using the Chrome format
"wgpu_trace", # WGPU/rendering tracing
]
(See here for a full list of Bevy's cargo features.)
Graphics / Rendering
For a graphical application or game (most Bevy projects), you can include
bevy_winit
and your selection of Rendering features. For
Linux support, you need at least one of x11
or wayland
.
bevy_render
and bevy_core_pipeline
are required for any application using
Bevy rendering.
If you only need 2D and no 3D, add bevy_sprite
.
If you only need 3D and no 2D, add bevy_pbr
. If you are loading 3D models
from GLTF files, add bevy_gltf
.
If you are using Bevy UI, you need bevy_text
and bevy_ui
.
If you want to draw debug lines and shapes on-screen, add bevy_gizmos
.
If you don't need any graphics (like for a dedicated game server, scientific simulation, etc.), you may remove all of these features.
File Formats
You can use the relevant cargo features to enable/disable support for loading assets with various different file formats.
See here for more information.
Input Devices
If you do not care about gamepad (controller/joystick)
support, you can disable bevy_gilrs
.
Linux Windowing Backend
On Linux, you can choose to support X11, Wayland,
or both. Only x11
is enabled by default, as it is the legacy system
that should be compatible with most/all distributions, to make your builds
smaller and compile faster. You might want to additionally enable wayland
,
to fully and natively support modern Linux environments. This will add a few
extra transitive dependencies to your project.
Development Features
While you are developing your project, these features might be useful:
Asset hot-reloading
The filesystem_watcher
feature controls support for hot-reloading of
assets, supported on desktop platforms.
Dynamic Linking
dynamic_linking
causes Bevy to be built and linked as a shared/dynamic
library. This will make incremental builds much faster.
This is only supported on desktop platforms. Known to work very well on Linux. Windows and macOS are also supported, but are less tested and have had issues in the past.
Do not enable this for release builds you intend to publish to other people, unless you have a very good special reason to and you know what you are doing. It introduces unneeded complexity (you need to bundle extra files) and potential for things to not work correctly. Use this only during development.
For this reason, it may be convenient to specify the feature as a commandline
option to cargo
, instead of putting it in your Cargo.toml
. Simply run your
project like this:
cargo run --features bevy/dynamic_linking
You could also add this to your IDE/editor configuration.
Tracing
The features trace
and wgpu_trace
may be useful for profiling and
diagnosing performance issues.
trace_chrome
and trace_tracy
choose the backend you want to use to
visualize the traces.
See Bevy's official docs on profiling to learn more.
Bevy Version: | (any) |
---|
Community Plugins Ecosystem
There is a growing ecosystem of unofficial community-made plugins for Bevy. They provide a lot of functionality that is not officially included with the engine. You might greatly benefit from using some of these in your projects.
To find such plugins, you should search the Bevy Assets page on the official Bevy website. This is the official registry of known community-made things for Bevy. If you publish your own plugins for Bevy, you should contribute a link to be added to that page.
Beware that some 3rd-party plugins may use unusual licenses! Be sure to check the license before using a plugin in your project.
Other pages in this book with valuable information when using 3rd-party plugins:
- Some plugins may require you to configure Bevy in some specific way.
- If you are using bleeding-edge unreleased Bevy (main), you may encounter difficulties with plugin compatibility.
Bevy Version: | 0.11 | (current) |
---|
Dev Tools and Editors for Bevy
Bevy does not yet have an official editor or other such tools. An official editor is planned as a long-term future goal. In the meantime, here are some community-made tools to help you.
Editor
bevy_inspector_egui
gives you a simple
editor-like property inspector window in-game. It lets you modify the values of
your components and resources in real-time as the game is running.
bevy_editor_pls
is an editor-like interface that
you can embed into your game. It has even more features, like switching app
states, fly camera, performance diagnostics, and inspector panels.
Diagnostics
bevy_mod_debugdump
is a tool to help visualize
your App Schedules (all of the registered
systems with their ordering
dependencies), and the Bevy Render Graph.
If you are getting confusing/cryptic compiler error messages (like
these) and you cannot figure them out,
bevycheck
is a tool you could use to help diagnose them.
It tries to provide more user-friendly Bevy-specific error messages.
Bevy Version: | (any) |
---|
Common Pitfalls
This chapter covers some common issues or surprises that you might be likely to encounter when working with Bevy, with specific advice about how to address them.
Bevy Version: | 0.11 | (current) |
---|
Strange Build Errors
Sometimes, you can get strange and confusing build errors when trying to compile your project.
Update your Rust
First, make sure your Rust is up-to-date. When using Bevy, you must use at least the latest stable version of Rust (or nightly).
If you are using rustup
to manage your Rust installation, you
can run:
rustup update
Clear the cargo state
Many kinds of build errors can often be fixed by forcing cargo
to regenerate
its internal state (recompute dependencies, etc.). You can do this by deleting
the Cargo.lock
file and the target
directory.
rm -rf target Cargo.lock
Try building your project again after doing this. It is likely that the mysterious errors will go away.
This trick often fixes the broken build, but if it doesn't help you, your issue might require further investigation. Reach out to the Bevy community via GitHub or Discord, and ask for help.
If you are using bleeding-edge Bevy ("main"), and the above does not solve the problem, your errors might be caused by 3rd-party plugins. See this page for solutions.
New Cargo Resolver
Cargo recently added a new dependency resolver algorithm, that is incompatible with the old one. Bevy requires the new resolver.
If you are just creating a new blank Cargo project, don't worry. This should
already be setup correctly by cargo new
.
If you are getting weird compiler errors from Bevy dependencies, read on. Make sure you have the correct configuration, and then clear the cargo state.
Single-Crate Projects
In a single-crate project (if you only have one Cargo.toml
file in your project),
if you are using the latest Rust2021 Edition, the new resolver is automatically
enabled.
So, you need either one of these settings in your Cargo.toml
:
[package]
edition = "2021"
or
[package]
resolver = "2"
Multi-Crate Workspaces
In a multi-crate Cargo workspace, the resolver is a global setting for the whole workspace. It will not be enabled by default.
This can bite you if you are transitioning a single-crate project into a workspace.
You must add it manually to the top-level Cargo.toml
for your Cargo Workspace:
[workspace]
resolver = "2"
Bevy Version: | (any) |
---|
Performance
Unoptimized debug builds
You can partially enable compiler optimizations in debug/dev mode!
You can enable higher optimizations for dependencies (incl. Bevy), but not your own code, to keep recompilations fast!
In Cargo.toml
or .cargo/config.toml
:
# Enable max optimizations for dependencies, but not for our code:
[profile.dev.package."*"]
opt-level = 3
The above is enough to make Bevy run fast. It will only slow down clean builds, without affecting recompilation times for your project.
If your own code does CPU-intensive work, you might want to also enable some optimization for it. However, this might greatly affect compile times in some projects (similar to a full release build), so it is not generally recommended.
# Enable only a small amount of optimization in debug mode
[profile.dev]
opt-level = 1
Warning! If you are using a debugger (like gdb
or lldb
) to step through
your code, any amount of compiler optimization can mess with the experience.
Your breakpoints might be skipped, and the code flow might jump around in
unexpected ways. If you want to debug / step through your code, you might want
opt-level = 0
.
Why is this necessary?
Rust without compiler optimizations is very slow. With Bevy in particular, the default cargo build debug settings will lead to awful runtime performance. Assets are slow to load and FPS is low.
Common symptoms:
- Loading high-res 3D models with a lot of large textures, from GLTF files, can take minutes! This can trick you into thinking that your code is not working, because you will not see anything on the screen until it is ready.
- After spawning even a few 2D sprites or 3D models, framerate may drop to unplayable levels.
Why not use --release
?
You may have heard the advice: just run with --release
! However, this is
bad advice. Don't do it.
Release mode also disables "debug assertions": extra checks useful during development. Many libraries also include additional stuff under that setting. In Bevy and WGPU that includes validation for shaders and GPU API usage. Release mode disables these checks, causing less-informative crashes, issues with hot-reloading, or potentially buggy/invalid logic going unnoticed.
Release mode also makes incremental recompilation slow. That negates Bevy's fast compile times, and can be very annoying while you develop.
With the advice at the top of this page, you don't need to build with
--release
, just to test your game with adequate performance. You can use
it for actual release builds that you send to your users.
If you want, you can also enable LTO (Link-Time-Optimization) for the actual release builds, to squeeze out even more performance at the cost of very slow compile times:
[profile.release]
lto = "thin"
Bevy Version: | 0.11 | (current) |
---|
Obscure Rust compiler errors
You can get confusing compiler errors when you try to add systems to your Bevy app.
Common beginner mistakes
- Using
commands: &mut Commands
instead ofmut commands: Commands
. - Using
Query<MyStuff>
instead ofQuery<&MyStuff>
orQuery<&mut MyStuff>
. - Using
Query<&ComponentA, &ComponentB>
instead ofQuery<(&ComponentA, &ComponentB)>
(forgetting the tuple) - Using your resource types directly without
Res
orResMut
. - Using your component types directly without putting them in a
Query
. - Using a bundle type in a query. You want individual components.
- Using other arbitrary types in your function.
Note that Query<Entity>
is correct, because the Entity ID is special;
it is not a component.
Error adding function as system
The errors can look like this:
error[E0277]: the trait bound `for<'a, 'b, 'c> fn(...) {system}: IntoSystem<(), (), _>` is not satisfied
--> src/main.rs:5:21
|
5 | .add_system(my_system)
| ---------- ^^^^^^^^^ the trait `IntoSystem<(), (), _>` is not implemented for fn item `for<'a, 'b, 'c> fn(...) {system}`
| |
| required by a bound introduced by this call
|
= help: the following other types implement trait `IntoSystemConfigs<Marker>`:
= ...
The error (confusingly) points to the place in your code where you try to add the system,
but in reality, the problem is actually in the fn
function definition!
This is caused by your function having invalid parameters. Bevy can only accept special types as system parameters!
Error on malformed queries
You might also errors that look like this:
error[E0277]: the trait bound `Transform: WorldQuery` is not satisfied
--> src/main.rs:10:12
|
10 | query: Query<Transform>,
| ^^^^^^^^^^^^^^^ the trait `WorldQuery` is not implemented for `Transform`
|
= help: the following other types implement trait `WorldQuery`:
&'__w mut T
&T
()
(F0, F1)
(F0, F1, F2)
(F0, F1, F2, F3)
(F0, F1, F2, F3, F4)
(F0, F1, F2, F3, F4, F5)
and 54 others
note: required by a bound in `bevy::prelude::Query`
--> ~/.cargo/registry/src/index.crates.io-6f17d22bba15001f/bevy_ecs-0.10.0/src/system/query.rs:276:37
|
276 | pub struct Query<'world, 'state, Q: WorldQuery, F: ReadOnlyWorldQuery = ()> {
| ^^^^^^^^^^ required by this bound in `Query`
To access your components, you need to use reference syntax (&
or &mut
).
error[E0107]: struct takes at most 2 generic arguments but 3 generic arguments were supplied
--> src/main.rs:10:12
|
10 | query: Query<&Transform, &Camera, &GlobalTransform>,
| ^^^^^ ---------------- help: remove this generic argument
| |
| expected at most 2 generic arguments
|
note: struct defined here, with at most 2 generic parameters: `Q`, `F`
--> ~/.cargo/registry/src/index.crates.io-6f17d22bba15001f/bevy_ecs-0.10.0/src/system/query.rs:276:12
|
276 | pub struct Query<'world, 'state, Q: WorldQuery, F: ReadOnlyWorldQuery = ()> {
| ^^^^^ - --------------------------
When you want to query for multiple components, you need to put them in a tuple:
(&Transform, &Camera, &GlobalTransform)
.
Bevy Version: | 0.11 | (current) |
---|
3D objects not displaying
This page will list some common issues that you may encounter, if you are trying to spawn a 3D object, but cannot see it on the screen.
Missing visibility components on parent
If your entity is in a hierarchy, all its parents need to have visibility components. It is required even if those parent entities are not supposed to render anything.
Fix it by inserting a VisibilityBundle
:
#![allow(unused)] fn main() { commands.entity(parent) .insert(VisibilityBundle::default()); }
Or better, make sure to spawn the parent entities correctly in the first place.
You can use a VisibilityBundle
or
SpatialBundle
(with transforms) if you
are not using a bundle that already includes these components.
Too far from camera
If something is further away than a certain distance from the camera, it will be
culled (not rendered). The default value is 1000.0
units.
You can control this using the far
field of
PerspectiveProjection
:
#![allow(unused)] fn main() { commands.spawn(Camera3dBundle { projection: Projection::Perspective(PerspectiveProjection { far: 10000.0, // change the maximum render distance ..default() }), ..default() }); }
Missing Vertex Attributes
Make sure your Mesh
includes all vertex attributes required
by your shader/material.
Bevy's default PBR StandardMaterial
requires all meshes to have:
- Positions
- Normals
Some others that may be required:
- UVs (if using textures in the material)
- Tangents (only if using normal maps, otherwise not required)
If you are generating your own mesh data, make sure to provide everything you need.
If you are loading meshes from asset files, make sure they include everything that is needed (check your export settings).
If you need Tangents for normal maps, it is recommended that you include them in your GLTF files. This avoids Bevy having to autogenerate them at runtime. Many 3D editors (like Blender) do not enable this option by default.
Incorrect usage of Bevy GLTF assets
Refer to the GLTF page to learn how to correctly use GLTF with Bevy.
GLTF files are complex. They contain many sub-assets, represented by different Bevy types. Make sure you are using the correct thing.
Make sure you are spawning a GLTF Scene, or using the correct
Mesh
and StandardMaterial
associated with the correct GLTF Primitive.
If you are using an asset path, be sure to include a label for the sub-asset you want:
let handle_scene: Handle<Scene> = asset_server.load("my.gltf#Scene0");
If you are spawning the top-level Gltf
master asset, it won't work.
If you are spawning a GLTF Mesh, it won't work.
Unsupported GLTF
Bevy does not fully support all features of the GLTF format and has some specific requirements about the data. Not all GLTF files can be loaded and rendered in Bevy. Unfortunately, in many of these cases, you will not get any error or diagnostic message.
Commonly-encountered limitations:
- Textures embedded in ascii (
*.gltf
) files (base64 encoding) cannot be loaded. Put your textures in external files, or use the binary (*.glb
) format. - Mipmaps are only supported if the texture files (in KTX2 or DDS format) contain them. The GLTF spec requires missing mipmap data to be generated by the game engine, but Bevy does not support this yet. If your assets are missing mipmaps, textures will look grainy/noisy.
This list is not exhaustive. There may be other unsupported scenarios that I did not know of or forgot to include here. :)
Vertex Order and Culling
By default, the Bevy renderer assumes Counter-Clockwise vertex order and has back-face culling enabled.
If you are generating your Mesh
from code, make sure your
vertices are in the correct order.
Unoptimized / Debug builds
Maybe your asset just takes a while to load? Bevy is very slow without compiler optimizations. It's actually possible that complex GLTF files with big textures can take over a minute to load and show up on the screen. It would be almost instant in optimized builds. See here.
Bevy Version: | (any) |
---|
Borrow multiple fields from struct
When you have a component or resource, that is larger struct with multiple fields, sometimes you want to borrow several of the fields at the same time, possibly mutably.
struct MyThing {
a: Foo,
b: Bar,
}
fn my_system(mut q: Query<&mut MyThing>) {
for thing in q.iter_mut() {
helper_func(&thing.a, &mut thing.b); // ERROR!
}
}
fn helper_func(foo: &Foo, bar: &mut Bar) {
// do something
}
This can result in a compiler error about conflicting borrows:
error[E0502]: cannot borrow `thing` as mutable because it is also borrowed as immutable
|
| helper_func(&thing.a, &mut thing.b); // ERROR!
| ----------- ----- ^^^^^ mutable borrow occurs here
| | |
| | immutable borrow occurs here
| immutable borrow later used by call
The solution is to use the "reborrow" idiom, a common but non-obvious trick in Rust programming:
// add this at the start of the for loop, before using `thing`:
let thing = &mut *thing;
// or, alternatively, Bevy provides a method, which does the same:
let thing = thing.into_inner();
Note that this line triggers change detection. Even if you don't modify the data afterwards, the component gets marked as changed.
Explanation
Bevy typically gives you access to your data via special wrapper types (like
[Res<T>
][bevy::Res], [ResMut<T>
][bevy::ResMut], and [Mut<T>
][bevy::Mut]
(when querying for components mutably)). This lets Bevy track
access to the data.
These are "smart pointer" types that use the Rust Deref
trait to dereference to your data. They usually work seamlessly and you
don't even notice them.
However, in a sense, they are opaque to the compiler. The Rust language allows fields of a struct to be borrowed individually, when you have direct access to the struct, but this does not work when it is wrapped in another type.
The "reborrow" trick shown above, effectively converts the wrapper
into a regular Rust reference. *thing
dereferences the wrapper via
DerefMut
, and then &mut
borrows it mutably. You now have
&mut MyStuff
instead of Mut<MyStuff>
.
Bevy Version: | 0.11 | (current) |
---|
Bevy Time vs. Rust/OS time
Do not use std::time::Instant::now()
to get the
current time. Get your timing information from Bevy, using
Res<Time>
.
Rust (and the OS) give you the precise time of the moment you call that function. However, that's not what you want.
Your game systems are run by Bevy's parallel scheduler, which means that they could be called at vastly different instants every frame! This will result in inconsistent / jittery timings and make your game misbehave or look stuttery.
Bevy's Time
gives you timing information that is consistent
throughout the frame update cycle. It is intended to be used for game logic.
This is not Bevy-specific, but applies to game development in general. Always get your time from your game engine, not from your programming language or operating system.
Bevy Version: | 0.11 | (current) |
---|
UV coordinates in Bevy
In Bevy, the vertical axis for the pixels of textures / images, and when sampling textures in a shader, points downwards, from top to bottom. The origin is at the top left.
This is inconsistent with the World-coordinate system used everywhere else in Bevy, where the Y axis points up.
It is, however, consistent with how most image file formats store pixel data, and with how most graphics APIs work (including DirectX, Vulkan, Metal, WebGPU, but not OpenGL).
OpenGL (and frameworks based on it) is different. If your prior experience is with that, you may find that your textures appear flipped vertically.
If you are using a mesh, make sure it has the correct UV values. If it was created with other software, be sure to select the correct settings.
If you are writing a custom shader, make sure your UV arithmetic is correct.
Sprites
If the images of your 2D sprites are flipped (for whatever reason), you can correct that using Bevy's sprite-flipping feature:
commands.spawn(SpriteBundle {
sprite: Sprite {
flip_y: true,
flip_x: false,
..Default::default()
},
..Default::default()
});
Quads
If you want to display an image (or custom shader) on a Quad
mesh, you can flip it vertically as follows:
let size = Vec2::new(2.0, 3.0);
let my_quad = shape::Quad::flipped(-size);
(this workaround is necessary, because the flipped
feature of Bevy's
Quad
primitive only does a horizonal flip, but we want a vertical flip)
Bevy Version: | (any) |
---|
Bevy Programming Framework
This chapter presents the features of the Bevy core programming framework. This covers the ECS (Entity Component System), App and Scheduling.
All the knowledge of this chapter is useful even if you want to use Bevy as something other than a game engine. For example: using just the ECS for a scientific simulation.
Hence, this chapter does not cover the game-engine parts of Bevy. Those features are covered in other chapters of the book, like the General Game Engine Features chapter.
Includes concise explanations of each core concept, with code snippets to show how it might be used. Care is taken to point out any important considerations for using each feature and to recommend known good practices.
For additional of programming patterns and idioms, see the Programming Patterns chapter.
Bevy Version: | 0.11 | (current) |
---|
ECS Programming Introduction
This page will try to teach you the general ECS mindset/paradigm.
Relevant official examples:
ecs_guide
.
Also check out the complete game examples:
alien_cake_addict
,
breakout
.
ECS is a programming paradigm that separates data and behavior. Bevy will store all of your data and manage all of your individual pieces of functionality for you. The code will run when appropriate. Your code can get access to whatever data it needs to do its thing.
This makes it easy to write game logic (Systems) in a way that is flexible and reusable. For example, you can implement:
- health and damage that works the same way for anything in the game, regardless of whether that's the player, an NPC, or a monster, or a vehicle
- gravity and collisions for anything that should have physics
- an animation or sound effect for all buttons in your UI
Of course, when you need specialized behavior only for specific entities (say, player movement, which only applies to the player), that is naturally easy to express, too.
Read more about how to represent your data.
Read more about how to represent your functionality.
Bevy Version: | 0.11 | (current) |
---|
Intro: Your Data
This page is an overview, to give you an idea of the big picture of how Bevy works. Click on the various links to be taken to dedicated pages where you can learn more about each concept.
As mentioned in the ECS Intro, Bevy stores all your data for you and allows you easy and flexible access to whatever you need, wherever you need it.
The ECS's data structure is called the World
. That is what
stores and manages all of the data. For advanced scenarios, is possible to have
multiple worlds, and then each one will behave as its own
separate ECS. However, normally, you just work with the main World that Bevy
sets up for your App.
You can represent your data in two different ways: Entities/Components, and Resources.
Entities / Components
Conceptually, you can think of it by analogy with tables, like in a database or
spreadsheet. Your different data types (Components) are like
the "columns" of a table, and there can be arbitrarily many "rows"
(Entities) containing values / instances of various components.
The Entity
ID is like the row number. It's an integer index
that lets you find specific component values.
Component types that are empty struct
s (contain no data) are called marker
components. They are useful as "tags" to identify
specific entities, or enable certain behaviors. For example, you could use them
to identify the player entity, to mark enemies that are currently chasing the
player, to select entities to be despawned at the end of the level, etc.
Here is an illustration to help you visualize the logical structure. The checkmarks show what component types are present on each entity. Empty cells mean that the component is not present. In this example, we have a player, a camera, and several enemies.
Entity (ID) | Transform | Player | Enemy | Camera | Health | ... |
---|---|---|---|---|---|---|
... | ||||||
107 | ✓ <translation> <rotation> <scale> | ✓ | ✓ 50.0 | |||
108 | ✓ <translation> <rotation> <scale> | ✓ | ✓ 25.0 | |||
109 | ✓ <translation> <rotation> <scale> | ✓ <camera data> | ||||
110 | ✓ <translation> <rotation> <scale> | ✓ | ✓ 10.0 | |||
111 | ✓ <translation> <rotation> <scale> | ✓ | ✓ 25.0 | |||
... |
Representing things this way gives you flexibility. For example, you could
create a Health
component for your game. You could then have many entities
representing different things in your game, such as the player, NPCs, or
monsters, all of which can have a Health
value (as well as other relevant
components).
The typical and obvious pattern is to use entities to represent "objects in the game/scene", such as the camera, the player, enemies, lights, props, UI elements, and other things. However, you are not limited to that. The ECS is a general-purpose data structure. You can create entities and components to store any data. For example, you could create an entity to store a bunch of settings or configuration parameters, or other abstract things.
Data stored using Entities and Components is accessed using queries.
For example, if you want to implement a game mechanic, write a system,
specify what component types you want to access, and do your thing. You can either
iterate through all entities that match your specification, or access specific
ones (if you know their Entity
ID).
Bevy can automatically keep track of what data your systems have access to and run them in parallel on multiple CPU cores. This way, you get multithreading with no extra effort from you!
If you want to modify the data structure itself (as opposed to just accessing existing data), such as to create or remove entities and components, that requires special consideration. Bevy cannot change the memory layout while other systems might be running. These operations can be buffered/deferred using Commands, to be applied later when it is safe to do so. You can also get direct World access using exclusive systems, if you want to perform such operations immediately (but without multithreading).
Comparison with Object-Oriented Programming
Object-Oriented programming teaches you to think of everything as "objects", where each object is an instance of a "class". The class specifies the data and functionality for all objects of that type, in one place. Every object of that class has the same data (with different values) and the same associated functionality.
This is the opposite of the ECS mentality. In ECS, any entity can have any data (any combination of components). The purpose of entities is to identify that data. Your systems are loose pieces of functionality that can operate on any data. They can easily find what they are looking for, and implement the desired behavior.
If you are an object-oriented programmer, you might be tempted to define a big
monolithic struct Player
containing all the fields / properties of the player.
In Bevy, this is considered bad practice, because doing it that way can make it
more difficult to work with your data and limit performance. Instead, you should
make things granular, when different pieces of data may be accessed independently.
For example, represent the player in your game as an entity, composed
of separate component types (separate struct
s) for things like the
health, XP, or whatever is relevant to your game. You can also attach
standard Bevy components like Transform
(transforms
explained) to it.
Then, each piece of functionality (each system) can just query for the data it needs. Common functionality (like a health/damage system) can be applied to any entity with the matching components, regardless of whether that's the player or something else in the game.
However, if some data always makes sense to be accessed together, then you
should put it in a single struct
. For example, Bevy's
Transform
or Color
. With these types, the
fields are not likely to be useful independently.
Additional Internal Details
The set / combination of components that a given entity has, is called the entity's Archetype. Bevy keeps track of that internally, to organize the data in RAM. Entities of the same Archetype have their data stored together, which allows the CPU to access and cache it efficiently.
If you add/remove component types on existing entities, you are changing the Archetype, which may require Bevy to copy the data to a different location.
Learn more about Bevy's component storage.
Resources
If there is only one global instance (singleton) of something, and it is standalone (not associated with other data), create a Resource.
For example, you could create a resource to store your game's graphics settings, or the data for the currently active game mode or session.
This is a simple way of storing data, when you know you don't need the flexibility of Entities/Components.
Bevy Version: | 0.11 | (current) |
---|
Intro: Your Code
This page is an overview, to give you an idea of the big picture of how Bevy works. Click on the various links to be taken to dedicated pages where you can learn more about each concept.
As mentioned in the ECS Intro, Bevy manages all of your functionality/behaviors for you, running them when appropriate and giving them access to whatever parts of your data they need.
Individual pieces of functionality are called systems. Each system
is a Rust function (fn
) you write, which accepts special parameter
types to indicate what data it needs to
access. Think of the function signature as a "specification" for what to fetch
from the ECS World
.
Here is what a system might look like. Note how, just by looking at the function parameters, we know exactly what data can be accessed.
fn enemy_detect_player(
// access data from resources
mut ai_settings: ResMut<EnemyAiSettings>,
gamemode: Res<GameModeData>,
// access data from entities/components
query_player: Query<&Transform, With<Player>>,
query_enemies: Query<&mut Transform, (With<Enemy>, Without<Player>)>,
// in case we want to spawn/despawn entities, etc.
mut commands: Commands,
) {
// ... implement your behavior here ...
}
(learn more about: systems, queries, commands, resources, entities, components)
Parallel Systems
Based on the parameter types of the systems you write, Bevy knows what data each system can access and whether it conflicts with any other systems. Systems that do not conflict (don't access any of the same data mutably) will be automatically run in parallel on different CPU threads. This way, you get multithreading, utilizing modern multi-core CPU hardware effectively, with no extra effort from you!
For best parallelism performance, it is recommended that you keep your
functionality and your data granular. Create many small
systems, each one with a narrowly-scoped purpose and accessing only the data it
needs. This gives Bevy more opportunities for parallelism. Putting too much
functionality in one system, or too much data in a single
component or resource struct
, limits parallelism.
Bevy's parallelism is non-deterministic by default. Your systems might run in a different and unpredictable order relative to one another, unless you add ordering dependencies to constrain it.
Exclusive Systems
Exclusive systems provide you with a way to get full direct
access to the ECS World
. They cannot run in parallel
with other systems, because they can access anything and do anything. Sometimes,
you might need this additonal power.
Schedules
Bevy stores systems inside of schedules
(Schedule
). The schedule contains the systems and all
relevant metadata to organize them, telling Bevy when and how to run them. Bevy
Apps typically contain many schedules. Each one is a collection of
systems to be invoked in different scenarios (every frame update, fixed
timestep update, at app startup, on state
transitions, etc.).
The metadata stored in schedules allows you to control how systems run:
- Add run conditions to control if systems should run during an invocation of the schedule. You can disable systems if you only need them to run sometimes.
- Add ordering constraints, if one system depends on another system completing before it.
Within schedules, systems can be grouped into sets. Sets allow multiple systems to share common configuration/metadata. Systems inherit configuration from all sets they belong to. Sets can also inherit configuration from other sets.
Here is an illustration to help you visualize the logical structure of a schedule. Let's look at how a hypothetical "Update" (run every frame) schedule of a game might be organized.
List of systems:
System name | Sets it belongs to | Run conditions | Ordering constraints |
---|---|---|---|
footstep_sound | AudioSet GameplaySet | after(player_movement) after(enemy_movement) | |
player_movement | GameplaySet | player_alive not(cutscene) | after(InputSet) |
camera_movement | GameplaySet | after(InputSet) | |
enemy_movement | EnemyAiSet | ||
enemy_spawn | EnemyAiSet | ||
enemy_despawn | EnemyAiSet | before(enemy_spawn) | |
mouse_input | InputSet | mouse_enabled | |
controller_input | InputSet | gamepad_enabled | |
background_music | AudioSet | ||
ui_button_animate | |||
menu_logo_animate | MainMenuSet | ||
menu_button_sound | MainMenuSet AudioSet | ||
... |
List of sets:
Set name | Parent Sets | Run conditions | Ordering constraints |
---|---|---|---|
MainMenuSet | in_state(MainMenu) | ||
GameplaySet | in_state(InGame) | ||
InputSet | GameplaySet | ||
EnemyAiSet | GameplaySet | not(cutscene) | after(player_movement) |
AudioSet | not(audio_muted) |
Note that it doesn't matter in what order systems are listed in the schedule. Their order of execution is determined by the metadata. Bevy will respect those constraints, but otherwise run systems in parallel as much as it can, depending on what CPU threads are available.
Also note how our hypothetical game is implemented using many individually-small
systems. For example, instead of playing audio inside of the player_movement
system, we made a separate play_footstep_sounds
system. These two pieces of
functionality probably need to access different data, so
putting them in separate systems allows Bevy more opportunities for parallelism.
By being separate systems, they can also have different configuration. The
play_footstep_sounds
system can be added to an AudioSet
set, from which it inherits a not(audio_muted)
run
condition.
Similarly, we put mouse and controller input in separate systems. The InputSet
set allows systems like player_movement
to share an ordering dependency
on all of them at once.
You can see how Bevy's scheduling APIs give you a lot of flexibility to organize all the functionality in your game. What will you do with all this power? ;)
Here is how schedule that was illustrated above could be created in code:
// Set configuration is per-schedule. Here we do it for `Update`
app.configure_set(Update, MainMenuSet
.run_if(in_state(MainMenu))
);
app.configure_set(Update, GameplaySet
.run_if(in_state(InGame))
);
app.configure_set(Update, InputSet
.in_set(GameplaySet)
);
app.configure_set(Update, EnemyAiSet
.in_set(GameplaySet)
.run_if(not(cutscene))
.after(player_movement)
);
app.configure_set(Update, AudioSet
.run_if(audio_muted)
);
app.add_systems(Update, (
(
ui_button_animate,
menu_logo_animate.in_set(MainMenuSet),
),
(
enemy_movement,
enemy_spawn,
enemy_despawn.before(enemy_spawn),
).in_set(EnemyAiSet),
(
mouse_input.run_if(mouse_enabled),
controller_input.run_if(gamepad_enabled),
).in_set(InputSet),
(
footstep_sound.in_set(GameplaySet),
menu_button_sound.in_set(MainMenuSet),
background_music,
).in_set(AudioSet),
(
player_movement
.run_if(player_alive)
.run_if(not(cutscene)),
camera_movement,
).in_set(GameplaySet).after(InputSet),
));
(learn more about: schedules, system sets, states, run conditions, system ordering)
Bevy Version: | 0.11 | (current) |
---|
The App
Relevant official examples: All of them ;)
In particular, check out the complete game examples:
alien_cake_addict
,
breakout
.
To enter the bevy runtime, you need to configure an App
. The app
is how you define the structure of all the things that make up your project:
plugins, systems (and their configuration/metadata),
event types, states, schedules…
Technically, the App
is what brings the whole ECS together. It
contains the World
(s) (where all the data
is stored), the Schedule(s) (where all the functionality is
stored and configured), and the "runner", which is the code that is responsible
for running everything.
You typically create your App
in your project's main
function.
However, you don't have to add everything from there. If you want to add things
to your app from multiple places (like other Rust files or crates), use
plugins. As your project grows, you will need to do that to keep
everything organized.
fn main() {
App::new()
// Bevy itself:
.add_plugins(DefaultPlugins)
// events:
.add_event::<LevelUpEvent>()
// systems to run once at startup:
.add_systems(Startup, spawn_things)
// systems to run each frame:
.add_systems(Update, (
player_level_up,
debug_levelups,
debug_stats_change,
))
// ...
// launch the app!
.run();
}
Note: add_systems
and add_plugins
allow you to add multiple things at once,
using tuple syntax.
Local resources do not need to be registered. They are part of their respective systems.
Component types do not need to be registered.
Schedules cannot (yet) be modified at runtime; all
systems you want to run must be added/configured in the
App
ahead of time. You can control individual systems using run
conditions. You can also dynamically enable/disable entire
schedules using the
MainScheduleOrder
resource.
Builtin Bevy Functionality
The Bevy game engine's own functionality is represented as a plugin group. Every typical Bevy app must first add it, using either:
DefaultPlugins
if you are making a full game/appMinimalPlugins
for something like a headless server.
Setting up data
Normally, you can set up your data from systems. Use Commands from regular systems, or use exclusive systems to get full World access.
Add your setup systems as startup systems for things you want to initialize at launch, or use state enter/exit systems to do things when transitioning between menus, game modes, levels, etc.
However, you can also initialize data directly from the app builder. This is common for resources, if they need to be present at all times. You can also get direct World access.
// Create (or overwrite) resource with specific value
app.insert_resource(StartingLevel(3));
// Ensure resource exists; if not, create it
// (using `Default` or `FromWorld`)
app.init_resource::<MyFancyResource>();
// We can also access/manipulate the World directly
// (in this example, to spawn an entity, but you can do anything)
app.world.spawn(SomeBundle::default());
Quitting the App
To cleanly shut down bevy, send an AppExit
event from any system:
use bevy::app::AppExit;
fn exit_system(mut exit: EventWriter<AppExit>) {
exit.send(AppExit);
}
For prototyping, Bevy provides a convenient system you can add, to close the
focused window on pressing the Esc
key. When all windows are closed, Bevy will
quit automatically.
app.add_systems(Update, bevy::window::close_on_esc);
Bevy Version: | 0.11 | (current) |
---|
Systems
Relevant official examples:
ecs_guide
,
startup_system
,
system_param
.
Systems are pieces of functionality, which are run by Bevy. They are typically implemented using regular Rust functions.
This is how you implement all your game logic. Each system specifies what data it needs to access to do its thing, and Bevy will run them in parallel when possible. You can add configuration/metadata to control how your systems should be run, using the app builder.
These functions can only take special parameter types, to specify what data you need access to. If you use unsupported parameter types in your function, you will get confusing compiler errors!
Some of the possibilities are:
- accessing resources using
Res
/ResMut
- accessing components of entities using queries (
Query
) - creating/destroying entities, components, and resources using Commands (
Commands
) - sending/receiving events using
EventWriter
/EventReader
fn debug_start(
// access resource
start: Res<StartingLevel>
) {
eprintln!("Starting on level {:?}", *start);
}
System parameters can be grouped into tuples (which can be nested). This is useful for organization.
fn complex_system(
(a, mut b): (Res<ResourceA>, ResMut<ResourceB>),
// this resource might not exist, so wrap it in an Option
mut c: Option<ResMut<ResourceC>>,
) {
if let Some(mut c) = c {
// do something
}
}
Your function can have a maximum of 16 total parameters. If you need more, group them into tuples to work around the limit. Tuples can contain up to 16 members, but can be nested indefinitely.
There is also a different kind of systems: exclusive systems. They have full direct access to the ECS World, so you can access any data you want and do anything, but cannot run in parallel. For most use cases, you should use regular parallel systems.
Runtime
To run your systems, you need to add them to Bevy via the app builder:
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// run these only once at launch
.add_systems(Startup, (setup_camera, debug_start))
// run these every frame update
.add_systems(Update, (move_player, enemies_ai))
// ...
.run();
}
Be careful: writing a new system fn
and forgetting to add it to your app is a
common mistake! If you run your project and your new code doesn't seem to be
running, make sure you added the system!
The above is enough for simple projects.
Systems are contained schedules. Update
is the
schedule where you typically add any systems you want to run every frame.
Startup
is where you typically add systems that should run
only once on app startup. There are also other possibilities.
As your project grows more complex, you might want to enhance your app builder with some of the powerful tools that Bevy offers for managing when/how your systems run, such as: explicit ordering, system sets, states, run conditions.
Bevy Version: | 0.11 | (current) |
---|
Resources
Relevant official examples:
ecs_guide
.
Resources allow you to store a single global instance of some data type, independently of entities.
Use them for data that is truly global for your app, such as configuration / settings. Resources make it easy for you to access such data from anywhere.
To create a new resource type, simply define a Rust struct
or enum
, and
derive the Resource
trait, similar to
components and events.
#[derive(Resource)]
struct GoalsReached {
main_goal: bool,
bonus: u32,
}
Types must be unique; there can only be at most one instance of a given type. If you might need multiple, consider using entities and components instead.
Bevy uses resources for many things. You can use these builtin resources to access various features of the engine. They work just like your own custom types.
Accessing Resources
To access the value of a resource from systems, use Res
/ResMut
:
fn my_system(
// these will panic if the resources don't exist
mut goals: ResMut<GoalsReached>,
other: Res<MyOtherResource>,
// use Option if a resource might not exist
mut fancy: Option<ResMut<MyFancyResource>>,
) {
if let Some(fancy) = &mut fancy {
// TODO: do things with `fancy`
}
// TODO: do things with `goals` and `other`
}
Managing Resources
If you need to create/remove resources at runtime, you can do so using
commands (Commands
):
fn my_setup(mut commands: Commands, /* ... */) {
// add (or overwrite) resource, using the provided data
commands.insert_resource(GoalsReached { main_goal: false, bonus: 100 });
// ensure resource exists (creating if necessary)
commands.init_resource::<MyFancyResource>();
// remove a resource (if it exists)
commands.remove_resource::<MyOtherResource>();
}
Alternatively, using direct World access from an exclusive system:
fn my_setup2(world: &mut World) {
// The same methods as with Commands are also available here,
// but we can also do fancier things:
// Check if resource exists
if !world.contains_resource::<MyFancyResource>() {
// Get access to a resource, inserting a custom value if unavailable
let _bonus = world.get_resource_or_insert_with(
|| GoalsReached { main_goal: false, bonus: 100 }
).bonus;
}
}
Resources can also be set up from the app builder. Do this for resources that are meant to always exist from the start.
App::new()
.add_plugins(DefaultPlugins)
.insert_resource(StartingLevel(3))
.init_resource::<MyFancyResource>()
// ...
Resource Initialization
Implement Default
for simple resources:
// simple derive, to set all fields to their defaults
#[derive(Resource, Default)]
struct GameProgress {
game_completed: bool,
secrets_unlocked: u32,
}
#[derive(Resource)]
struct StartingLevel(usize);
// custom implementation for unusual values
impl Default for StartingLevel {
fn default() -> Self {
StartingLevel(1)
}
}
// on enums, you can specify the default variant
#[derive(Resource, Default)]
enum GameMode {
Tutorial,
#[default]
Singleplayer,
Multiplayer,
}
For resources that need complex initialization, implement FromWorld
:
#[derive(Resource)]
struct MyFancyResource { /* stuff */ }
impl FromWorld for MyFancyResource {
fn from_world(world: &mut World) -> Self {
// You have full access to anything in the ECS World from here.
// For example, you can access (and mutate!) other resources:
let mut x = world.resource_mut::<MyOtherResource>();
x.do_mut_stuff();
MyFancyResource { /* stuff */ }
}
}
Beware: it can be easy to get yourself into a mess of unmaintainable code
if you overuse FromWorld
to do complex things.
Usage Advice
The choice of when to use entities/components vs. resources is typically about how you want to access the data: globally from anywhere (resources), or using ECS patterns (entities/components).
Even if there is only one of a certain thing in your game (such as the player in a single-player game), it can be a good fit to use an entity instead of resources, because entities are composed of multiple components, some of which can be common with other entities. This can make your game logic more flexible. For example, you could have a "health/damage system" that works with both the player and enemies.
Settings
One common usage of resources is for storing settings and configuration.
However, if it is something that cannot be changed at runtime and only used when
initializing a plugin, consider putting that inside the plugin's
struct
, instead of a resource.
Bevy Version: | 0.9 | (outdated!) |
---|
Relevant official examples:
ecs_guide
.
Entities
Entities are just a simple integer ID, that identifies a particular set of component values.
To create ("spawn") new entities, use Commands
.
Components
Components are the data associated with entities.
To create a new component type, simply define a Rust struct
or enum
, and
derive the Component
trait.
#[derive(Component)]
struct Health {
hp: f32,
extra: f32,
}
Types must be unique -- an entity can only have one component per Rust type.
Use wrapper (newtype) structs to make unique components out of simpler types:
#[derive(Component)]
struct PlayerXp(u32);
#[derive(Component)]
struct PlayerName(String);
You can use empty structs to help you identify specific entities. These are known as "marker components". Useful with query filters.
/// Add this to all menu ui entities to help identify them
#[derive(Component)]
struct MainMenuUI;
/// Marker for hostile game units
#[derive(Component)]
struct Enemy;
/// This will be used to identify the main player entity
#[derive(Component)]
struct Player;
/// Tag all creatures that are currently friendly towards the player
#[derive(Component)]
struct Friendly;
Components can be accessed from systems, using queries.
You can add/remove components on existing entities, using Commands
.
Component Bundles
Bundles are like "templates", to make it easy to create entities with a common set of components.
#[derive(Bundle)]
struct PlayerBundle {
xp: PlayerXp,
name: PlayerName,
health: Health,
_p: Player,
// We can nest/include another bundle.
// Add the components for a standard Bevy Sprite:
#[bundle]
sprite: SpriteSheetBundle,
}
Bevy also considers arbitrary tuples of components as bundles:
(ComponentA, ComponentB, ComponentC)
Note that you cannot query for a whole bundle. Bundles are just a convenience when creating the entities. Query for the individual component types that your system needs to access.
Bevy Version: | 0.9 | (outdated!) |
---|
Queries
Relevant official examples:
ecs_guide
.
Queries let you access components of entities.
Use the Query
system parameter, where you can
specify the data you want to access, and optionally additional
filters for selecting entities.
Think of the types you put in your Query
as a "specification" for selecting
what entities you want to access. Queries will match only those entities in the
ECS World that fit your specification. You are then able to access the relevant
data from individual such entities (using an Entity
ID), or
iterate to access all entities that qualify.
The first type parameter for a query is the data you want to access. Use &
for
shared/readonly access and &mut
for exclusive/mutable access. Use Option
if
the component is not required (you want to find entities with or without that
component. If you want multiple components, put them in a tuple.
fn check_zero_health(
// access entities that have `Health` and `Transform` components
// get read-only access to `Health` and mutable access to `Transform`
// optional component: get access to `Player` if it exists
mut query: Query<(&Health, &mut Transform, Option<&Player>)>,
) {
// get all matching entities
for (health, mut transform, player) in query.iter_mut() {
eprintln!("Entity at {} has {} HP.", transform.translation, health.hp);
// center if hp is zero
if health.hp <= 0.0 {
transform.translation = Vec3::ZERO;
}
if let Some(player) = player {
// the current entity is the player!
// do something special!
}
}
}
The above example used iteration to access all entities that the query could find.
To access the components from specific entity only:
if let Ok((health, mut transform)) = query.get_mut(entity) {
// do something with the components
} else {
// the entity does not have the components from the query
}
If you want to know the entity IDs of the entities you are accessing, you can
put the special Entity
type in your query. This is useful
together with iteration, so you can identify the entities that the query found:
// add `Entity` to `Query` to get Entity IDs
fn query_entities(q: Query<(Entity, /* ... */)>) {
for (e, /* ... */) in q.iter() {
// `e` is the Entity ID of the entity we are accessing
}
}
If you know that the query is expected to only ever match a single entity, you
can use single
/single_mut
(panic on error) or get_single
/get_single_mut
(return Result
). These methods ensure that there exists exactly
one candidate entity that can match your query, and will produce an error
otherwise.
fn query_player(mut q: Query<(&Player, &mut Transform)>) {
let (player, mut transform) = q.single_mut();
// do something with the player and its transform
}
Bundles
Queries work with individual components. If you created an entity using a bundle, you need to query for the specific components from that bundle that you care about.
A common beginner mistake is to query for the bundle type!
Query Filters
Add query filters to narrow down the entities you get from the query.
This is done using the second (optional) generic type parameter of the
Query
type.
Note the syntax of the query: first you specify the data you want to access (using a tuple to access multiple things), and then you add any additional filters (can also be a tuple, to add multiple).
Use With
/Without
to only get entities
that have specific components.
fn debug_player_hp(
// access the health (and optionally the PlayerName, if present), only for friendly players
query: Query<(&Health, Option<&PlayerName>), (With<Player>, Without<Enemy>)>,
) {
// get all matching entities
for (health, name) in query.iter() {
if let Some(name) = name {
eprintln!("Player {} has {} HP.", name.0, health.hp);
} else {
eprintln!("Unknown player has {} HP.", health.hp);
}
}
}
This is useful if you don't actually care about the data stored inside these components, but you want to make sure that your query only looks for entities that have (or not have) them. If you want the data, then put the component in the first part of the query (as shown previously), instead of using a filter.
Multiple filters can be combined:
- in a tuple to apply all of them (AND logic)
- using the
Or<(…)>
wrapper to detect any of them (OR logic).- (note the tuple inside)
Bevy Version: | 0.9 | (outdated!) |
---|
Commands
Relevant official examples:
ecs_guide
.
Use Commands
to spawn/despawn entities, add/remove
components on existing entities, manage resources.
These actions do not take effect immediately; they are queued to be performed later when it is safe to do so. See: stages.
(if you are not using stages, that means your other systems will see them on the next frame update)
fn spawn_things(
mut commands: Commands,
) {
// manage resources
commands.insert_resource(MyResource);
commands.remove_resource::<MyResource>();
// create a new entity using `spawn`,
// providing the data for the components it should have
// (typically using a Bundle)
commands.spawn(PlayerBundle {
name: PlayerName("Henry".into()),
xp: PlayerXp(1000),
health: Health {
hp: 100.0, extra: 20.0
},
_p: Player,
sprite: Default::default(),
});
// you can use a tuple if you need additional components or bundles
// (tuples of component and bundle types are considered bundles)
// (note the extra parentheses)
let my_entity_id = commands.spawn((
// add some components
ComponentA,
ComponentB::default(),
// add some bundles
MyBundle::default(),
TransformBundle::default(),
)).id(); // get the Entity (id) by calling `.id()` at the end
// add/remove components of an existing entity
commands.entity(my_entity_id)
.insert(ComponentC::default())
.remove::<ComponentA>()
.remove::<(ComponentB, MyBundle)>();
}
fn make_all_players_hostile(
mut commands: Commands,
// we need the Entity id, to perform commands on specific entities
query: Query<Entity, With<Player>>,
) {
for entity in query.iter() {
commands.entity(entity)
// add an `Enemy` component to the entity
.insert(Enemy)
// remove the `Friendly` component
.remove::<Friendly>();
}
}
fn despawn_all_enemies(
mut commands: Commands,
query: Query<Entity, With<Enemy>>,
) {
for entity in query.iter() {
commands.entity(entity).despawn();
}
}
Bevy Version: | 0.11 | (current) |
---|
Events
Relevant official examples:
event
.
Send data between systems! Let your systems communicate with each other!
Like resources or components, events are
simple Rust struct
s or enum
s. When creating a new event type, derive
the Event
trait.
Then, any system can send (broadcast) values of that type, and any system can receive those events.
- To send events, use an
EventWriter<T>
. - To receive events, use an
EventReader<T>
.
Every reader tracks the events it has read independently, so you can handle the same events from multiple systems.
#[derive(Event)]
struct LevelUpEvent(Entity);
fn player_level_up(
mut ev_levelup: EventWriter<LevelUpEvent>,
query: Query<(Entity, &PlayerXp)>,
) {
for (entity, xp) in query.iter() {
if xp.0 > 1000 {
ev_levelup.send(LevelUpEvent(entity));
}
}
}
fn debug_levelups(
mut ev_levelup: EventReader<LevelUpEvent>,
) {
for ev in ev_levelup.iter() {
eprintln!("Entity {:?} leveled up!", ev.0);
}
}
You need to register your custom event types via the app builder:
app.add_event::<LevelUpEvent>();
Usage Advice
Events should be your go-to data flow tool. As events can be sent from any system and received by multiple systems, they are extremely versatile.
Events can be a very useful layer of abstraction. They allow you to decouple things, so you can separate different functionality and more easily reason about which system is responsible for what.
You can imagine how, even in the simple "player level up" example shown above,
using events would allow us to easily extend our hypothetical game with more
functionality. If we wanted to display a fancy level-up effect or animation,
update UI, or anything else, we can just add more systems that read the events
and do their respective things. If the player_level_up
system had simply
checked the player XP and managed the player level directly, without going via
events, it would be unwieldy for future development of the game.
How it all works
When you register an event type, Bevy will create an Events<T>
resource, which acts as the backing storage for the event queue. Bevy
also adds an "event maintenance" system to clear events every
frame, preventing them from accumulating and using up memory.
The events storage is double-buffered, meaning that events stay for one extra frame after the frame when they were sent. This gives your systems a chance to read the events on the next frame, if they did not get a chance during the current frame.
If you don't like this, you can have manual control over when events are cleared (at the risk of leaking / wasting memory if you forget to clear them).
The EventWriter<T>
system parameter is just syntax sugar
for mutably accessing the Events<T>
resource to
add events to the queue. The EventReader<T>
is a little
more complex: it accesses the events storage immutably, but also stores an
integer counter to keep track of how many events you have read. This is why it
also needs the mut
keyword.
Possible Pitfalls
Beware of frame delay / 1-frame-lag. This can occur if Bevy runs the receiving system before the sending system. The receiving system will only get a chance to receive the events on the next frame update. If you need to ensure that events are handled immediately / during the same frame, you can use explicit system ordering.
Beware of lost events if you do not read events every frame, or at least once every other frame update. A common situation where this can occur is when using a fixed timestep or run conditions.
If you want events to persist for longer than two frames, you can implement a custom cleanup/management strategy. However, you can only do this for your own event types. There is no solution for Bevy's built-in types.
Bevy Version: | 0.9 | (outdated!) |
---|
Local Resources
Relevant official examples:
ecs_guide
.
Local resources allow you to have per-system data. This data is not stored in the ECS World, but rather together with your system.
Local<T>
is a system parameter similar to
ResMut<T>
, which gives you full mutable access to an
instance of some data type, that is independent from entities and components.
Res<T>
/ResMut<T>
refer to a single global
instance of the type, shared between all systems. On the other hand, every
Local<T>
parameter is a separate instance, exclusively for
that system.
#[derive(Default)]
struct MyState;
fn my_system1(mut local: Local<MyState>) {
// you can do anything you want with the local here
}
fn my_system2(mut local: Local<MyState>) {
// the local in this system is a different instance
}
The type must implement Default
or
FromWorld
. It is automatically initialized.
A system can have multiple Local
s of the same type.
Specify an initial value
Local<T>
is always automatically initialized using the
default value for the type.
If you need specific data, you can use a closure instead. Rust closures that take system parameters are valid Bevy systems, just like standalone functions. Using a closure allows you to "move data into the function".
This example shows how to initialize some data to configure a system,
without using Local<T>
:
#[derive(Default)]
struct MyConfig {
magic: usize,
}
fn my_system(
mut cmd: Commands,
my_res: Res<MyStuff>,
// note this isn't a valid system parameter
config: &MyConfig,
) {
// TODO: do stuff
}
fn main() {
let config = MyConfig {
magic: 420,
};
App::new()
.add_plugins(DefaultPlugins)
// create a "move closure", so we can use the `config`
// variable that we created above
.add_system(move |cmd: Commands, res: Res<MyStuff>| {
// call our function from inside the closure
my_system(cmd, res, &config);
})
.run();
}
Another way to accomplish the same thing is to "return" the system from "constructor" helper, that creates it:
#[derive(Default)]
struct MyConfig {
magic: usize,
}
fn main() {
// create a "constructor" closure, which can initialize
// our data and move it into a closure that bevy can run as a system
let constructor = || {
// create the `MyConfig`
let config = MyConfig {
magic: 420,
};
// this is the actual system that bevy will run
move |mut commands: Commands, res: Res<MyStuff>| {
// we can use `config` here, the value from above will be "moved in"
// we can also use our system params: `commands`, `res`
}
};
App::new()
.add_plugins(DefaultPlugins)
// note the parentheses `()`
// we are calling the "constructor" we made above,
// which will return the actual system that gets added to bevy
.add_system(constructor())
.run();
}
Bevy Version: | 0.9 | (outdated!) |
---|
Exclusive Systems
Exclusive systems are systems that Bevy will not run in parallel
with any other system. They can have full unrestricted access
to the whole ECS World
, by taking a &mut World
parameter.
Inside of an exclusive system, you have full control over all data stored in the ECS. You can do whatever you want.
Note that exclusive systems can limit performance, as they prevent multi-threading (nothing else runs at the same time).
Some example situations where exclusive systems are useful:
- Dump various entities and components to a file, to implement things like saving and loading of game save files, or scene export from an editor
- Directly spawn/despawn entities, or create/remove resources,
immediately with no delay (unlike when using
Commands
from a regular system) - Run arbitrary systems with your own scheduling algorithm
- …
See the direct World access page to learn more about how to do such things.
fn do_crazy_things(world: &mut World) {
// we can do anything with any data in the Bevy ECS here!
}
You need to add exclusive systems to the App, just like
regular systems, but you must call .exclusive_system()
on them.
They cannot be ordered in-between regular parallel systems. Exclusive systems always run at one of the following places:
.at_start()
: at the beginning of a stage.at_end()
: at the end of a stage, after commands from regular systems have been applied.before_commands()
: after all the regular systems in a stage, but before commands are applied
(if you don't specify anything, the default is assumed .at_start()
)
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// this will run at the start of CoreStage::Update (the default stage)
.add_system(do_crazy_things)
// this will run at the end of CoreStage::PostUpdate
.add_system_to_stage(
CoreStage::PostUpdate,
some_more_things
.at_end()
)
.run();
}
Bevy Version: | 0.9 | (outdated!) |
---|
Direct World Access
The World
is where Bevy ECS stores all data and
associated metadata. It keeps track of resources, entities and
components.
Typically, the App
's schedule runner will run all
stages (which, in turn, run their systems)
on the main world. Regular systems are limited in
what data they can access from the world, by their system parameter
types. Operations that manipulate the world itself
are only done indirectly using Commands
. This is how most
typical Bevy user code behaves.
However, there are also ways you can get full direct access to the world, which gives you full control and freedom to do anything with any data stored in the Bevy ECS:
- Exclusive systems
FromWorld
impls- Via the
App
builder - Manually created
World
s for purposes like tests or scenes - Custom Commands
- Custom
Stage
impls (not recommended, prefer exclusive systems)
Direct world access lets you do things like:
- Freely spawn/despawn entities, insert/remove resources, etc., taking effect immediately
(no delay like when using
Commands
from a regular system) - Access any component, entities, and resources you want
- Manually run arbitrary systems or stages
This is especially useful if you want to do things that do not fit within Bevy's typical execution model/flow of just running systems once every frame (organized with stages and labels).
With direct world access, you can implement custom control flow, like looping some systems multiple times, selecting different systems to run in different circumstances, exporting/importing data from files like scenes or game saves, …
Working with the World
Here are some ways that you can make use of the direct world access APIs.
SystemState
The easiest way to do things is using a SystemState
.
This is a type that "imitates a system", behaving the same way as a
system with various parameters would. All the same behaviors
like queries, change detection, and
even Commands
are available. You can use any system
params.
It also tracks any persistent state, used for things like change
detection or caching to improve performance. Therefore,
if you plan on reusing the same SystemState
multiple
times, you should store it somewhere, rather than creating a new one every
time. Every time you call .get(world)
, it behaves like another "run"
of a system.
If you are using Commands
, you can choose when you
want to apply them to the world. You need to manually call .apply(world)
on the SystemState
, to apply them.
// TODO: write code example
Running a Stage
If you want to run some systems (a common use-case is
testing), the easiest way is to construct an impromptu
SystemStage
(stages). This way you reuse
all the scheduling logic that Bevy normally does when running systems.
// TODO: write code example
Navigating by Metadata
The world contains a lot of metadata that allows navigating all the data efficiently, such as information about all the stored components, entities, archeypes.
// TODO: write code example
Bevy Version: | 0.9 | (outdated!) |
---|
Stages
All systems to be run by Bevy are contained in stages. Every frame update, Bevy executes each stage, in order. Within each stage, Bevy's scheduling algorithm can run many systems in parallel, using multiple CPU cores for good performance.
The boundaries between stages are effectively hard synchronization points. They ensure that all systems of the previous stage have completed before any systems of the next stage begin, and that there is a moment in time when no systems are in-progress.
This makes it possible/safe to apply Commands. Any operations
performed by systems using Commands
are applied at the
end of that stage.
By default, when you add your systems, they are added to
CoreStage::Update
. Startup systems are added to
StartupStage::Startup
.
Bevy's internal systems are in the other stages, to ensure they are ordered correctly relative to your game logic.
If you want to add your own systems to any of Bevy's internal stages, you need to beware of potential unexpected interactions with Bevy's own internal systems. Remember: Bevy's internals are implemented using ordinary systems and ECS, just like your own stuff!
You can add your own additional stages. For example, if we want our debug systems to run after our game logic:
fn main() {
// label for our debug stage
static DEBUG: &str = "debug";
App::new()
.add_plugins(DefaultPlugins)
// add DEBUG stage after Bevy's Update
// also make it single-threaded
.add_stage_after(CoreStage::Update, DEBUG, SystemStage::single_threaded())
// systems are added to the `CoreStage::Update` stage by default
.add_system(player_gather_xp)
.add_system(player_take_damage)
// add our debug systems
.add_system_to_stage(DEBUG, debug_player_hp)
.add_system_to_stage(DEBUG, debug_stats_change)
.add_system_to_stage(DEBUG, debug_new_hostiles)
.run();
}
If you need to manage when your systems run, relative to one another, it is generally preferable to avoid using stages, and to use explicit system ordering instead. Stages limit parallel execution and the performance of your game.
However, stages can make it easier to organize things, when you really want to be sure that all previous systems have completed. Stages are also the only way to apply Commands.
If you have systems that need to rely on the actions that other systems have performed by using Commands, and need to do so during the same frame, placing those systems into separate stages is the only way to accomplish that.
Bevy Version: | 0.9 | (outdated!) |
---|
System Order of Execution
Bevy's scheduling algorithm is designed to deliver maximum performance by running as many systems as possible in parallel across the available CPU threads.
This is possible when the systems do not conflict over the data they need to access. However, when a system needs to have mutable (exclusive) access to a piece of data, other systems that need to access the same data cannot be run at the same time. Bevy determines all of this information from the system's function signature (the types of the parameters it takes).
In such situations, the order is nondeterministic by default. Bevy takes no regard for when each system will run, and the order could even change every frame!
Does it even matter?
In many cases, you don't need to worry about this.
However, sometimes you need to rely on specific systems to run in a particular order. For example:
- Maybe the logic you wrote in one of your systems needs any modifications done to that data by another system to always happen first?
- One system needs to receive events sent by another system.
- You are using change detection.
In such situations, systems running in the wrong order typically causes their behavior to be delayed until the next frame. In rare cases, depending on your game logic, it may even result in more serious logic bugs!
It is up to you to decide if this is important.
With many things in typical games, such as juicy visual effects, it probably doesn't matter if they get delayed by a frame. It might not be worthwhile to bother with it. If you don't care, leaving the order ambiguous may also result in better performance.
On the other hand, for things like handling the player input controls, this would result in annoying lag, so you should probably fix it.
Explicit System Ordering
If a specific system must always run before or after some other systems, you can add ordering constraints:
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// order doesn't matter for these systems:
.add_system(particle_effects)
.add_system(npc_behaviors)
.add_system(enemy_movement)
.add_system(input_handling)
.add_system(
player_movement
// `player_movement` must always run before `enemy_movement`
.before(enemy_movement)
// `player_movement` must always run after `input_handling`
.after(input_handling)
)
.run();
}
.before
/.after
may be used as many times as you need on one system.
Labels
For more advanced use cases, you can use labels. Labels can
either be strings, or custom types (like enum
s) that derive SystemLabel
.
This allows you to affect multiple systems at once, with the same constraints. You can place multiple labels on one system. You can also use the same label on multiple systems.
Each label is a reference point that other systems can be ordered around.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[derive(SystemLabel)]
enum MyLabel {
/// everything that handles input
Input,
/// everything that updates player state
Player,
/// everything that moves things (works with transforms)
Movement,
/// systems that update the world map
Map,
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// use labels, because we want to have multiple affected systems
.add_system(input_joystick.label(MyLabel::Input))
.add_system(input_keyboard.label(MyLabel::Input))
.add_system(input_touch.label(MyLabel::Input))
.add_system(input_parameters.before(MyLabel::Input))
.add_system(
player_movement
.before(MyLabel::Map)
.after(MyLabel::Input)
// we can have multiple labels on this system
.label(MyLabel::Player)
.label(MyLabel::Movement)
// can also use loose strings as labels
.label("player_movement")
)
// … and so on …
.run();
}
When you have multiple systems with common labels or ordering, it may be convenient to use system sets.
Circular Dependencies
If you have multiple systems mutually depending on each other, then it is clearly impossible to resolve the situation completely like that.
You should try to redesign your game to avoid such situations, or just accept the consequences. You can at least make it behave predictably, using explicit ordering to specify the order you prefer.
Bevy Version: | 0.9 | (outdated!) |
---|
Run Criteria
Run Criteria are a mechanism for controlling if Bevy should run specific systems, at runtime. This is how you can make functionality that only runs under certain conditions.
Run Criteria can be applied to individual systems, system sets, and stages.
Run Criteria are Bevy systems that return a value of type enum ShouldRun
. They can accept any system
parameters, like a normal system.
This example shows how run criteria might be used to implement different multiplayer modes:
use bevy::ecs::schedule::ShouldRun;
#[derive(Debug, PartialEq, Eq)]
#[derive(Resource)]
enum MultiplayerKind {
Client,
Host,
Local,
}
fn run_if_connected(
mode: Res<MultiplayerKind>,
session: Res<MyNetworkSession>,
) -> ShouldRun
{
if *mode == MultiplayerKind::Client && session.is_connected() {
ShouldRun::Yes
} else {
ShouldRun::No
}
}
fn run_if_host(
mode: Res<MultiplayerKind>,
) -> ShouldRun
{
if *mode == MultiplayerKind::Host || *mode == MultiplayerKind::Local {
ShouldRun::Yes
} else {
ShouldRun::No
}
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// if we are currently connected to a server,
// activate our client systems
.add_system_set(
SystemSet::new()
.with_run_criteria(run_if_connected)
.before("input")
.with_system(server_session)
.with_system(fetch_server_updates)
)
// if we are hosting the game,
// activate our game hosting systems
.add_system_set(
SystemSet::new()
.with_run_criteria(run_if_host)
.before("input")
.with_system(host_session)
.with_system(host_player_movement)
.with_system(host_enemy_ai)
)
// other systems in our game
.add_system(smoke_particles)
.add_system(water_animation)
.add_system_set(
SystemSet::new()
.label("input")
.with_system(keyboard_input)
.with_system(gamepad_input)
)
.run();
}
Known Pitfalls
Combining Multiple Run Criteria
It is not possible to make a system that is conditional on multiple run
criteria. Bevy has a .pipe
method that allows you to "chain" run criteria,
which could let you modify the output of a run criteria, but this is very
limiting in practice.
Consider using iyes_loopless
. It allows you to
use any number of run conditions to control your systems, and does not prevent
you from using states or fixed timestep.
Events
When receiving events in systems that don't run every frame, you will miss any events that are sent during the frames when the receiving systems are not running!
To mitigate this, you could implement a custom cleanup strategy, to manually manage the lifetime of the relevant event types.
Bevy Version: | 0.9 | (outdated!) |
---|
System Sets
System Sets allow you to easily apply common properties to multiple systems, for purposes such as labeling, ordering, run criteria, and states.
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// group our input handling systems into a set
.add_system_set(
SystemSet::new()
.label("input")
.with_system(keyboard_input)
.with_system(gamepad_input)
)
// our "net" systems should run before "input"
.add_system_set(
SystemSet::new()
.label("net")
.before("input")
// individual systems can still have
// their own labels (and ordering)
.with_system(server_session.label("session"))
.with_system(server_updates.after("session"))
)
// some ungrouped systems
.add_system(player_movement.after("input"))
.add_system(session_ui.after("session"))
.add_system(smoke_particles)
.run();
}
Bevy Version: | 0.9 | (outdated!) |
---|
States
Relevant official examples:
state
.
States allow you to structure the runtime "flow" of your app.
This is how you can implement things like:
- A menu screen or a loading screen
- Pausing / unpausing the game
- Different game modes
- …
In every state, you can have different systems running. You can also add one-shot setup and cleanup systems to run when entering or exiting a state.
To use states, define an enum type and add system sets to your app builder:
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
enum AppState {
MainMenu,
InGame,
Paused,
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// add the app state type
.add_state(AppState::MainMenu)
// add systems to run regardless of state, as usual
.add_system(play_music)
// systems to run only in the main menu
.add_system_set(
SystemSet::on_update(AppState::MainMenu)
.with_system(handle_ui_buttons)
)
// setup when entering the state
.add_system_set(
SystemSet::on_enter(AppState::MainMenu)
.with_system(setup_menu)
)
// cleanup when exiting the state
.add_system_set(
SystemSet::on_exit(AppState::MainMenu)
.with_system(close_menu)
)
.run();
}
It is OK to have multiple system sets for the same state.
This is useful when you want to place labels and use explicit system ordering.
This can also be useful with Plugins. Each plugin can add its own set of systems to the same state.
States are implemented using run criteria under the hood. These special system set constructors are really just helpers to automatically add the state management run criteria.
Controlling States
Inside of systems, you can check and control the state using the
State<T>
resource:
fn play_music(
app_state: Res<State<AppState>>,
// ...
) {
match app_state.current() {
AppState::MainMenu => {
// TODO: play menu music
}
AppState::InGame => {
// TODO: play game music
}
AppState::Paused => {
// TODO: play pause screen music
}
}
}
To change to another state:
fn enter_game(mut app_state: ResMut<State<AppState>>) {
app_state.set(AppState::InGame).unwrap();
// ^ this can fail if we are already in the target state
// or if another state change is already queued
}
After the systems of the current state complete, Bevy will transition to the next state you set.
You can do arbitrarily many state transitions in a single frame update. Bevy will handle all of them and execute all the relevant systems (before moving on to the next stage).
State Stack
Instead of completely transitioning from one state to another, you can also overlay states, forming a stack.
This is how you can implement things like a "game paused" screen, or an overlay menu, with the game world still visible / running in the background.
You can have some systems that are still running even when the state is "inactive" (that is, in the background, with other states running on top). You can also add one-shot systems to run when "pausing" or "resuming" the state.
In your app builder:
// player movement only when actively playing
.add_system_set(
SystemSet::on_update(AppState::InGame)
.with_system(player_movement)
)
// player idle animation while paused
.add_system_set(
SystemSet::on_inactive_update(AppState::InGame)
.with_system(player_idle)
)
// animations both while paused and while active
.add_system_set(
SystemSet::on_in_stack_update(AppState::InGame)
.with_system(animate_trees)
.with_system(animate_water)
)
// things to do when becoming inactive
.add_system_set(
SystemSet::on_pause(AppState::InGame)
.with_system(hide_enemies)
)
// things to do when becoming active again
.add_system_set(
SystemSet::on_resume(AppState::InGame)
.with_system(reset_player)
)
// setup when first entering the game
.add_system_set(
SystemSet::on_enter(AppState::InGame)
.with_system(setup_player)
.with_system(setup_map)
)
// cleanup when finally exiting the game
.add_system_set(
SystemSet::on_exit(AppState::InGame)
.with_system(despawn_player)
.with_system(despawn_map)
)
To manage states like this, use push
/pop
:
// to go into the pause screen
app_state.push(AppState::Paused).unwrap();
// to go back into the game
app_state.pop().unwrap();
(using .set
as shown before replaces the active state at the top of the stack)
Known Pitfalls and Limitations
Combining with Other Run Criteria
Because states are implemented using run criteria, they cannot be combined with other uses of run criteria, such as fixed timestep.
If you try to add another run criteria to your system set, it would replace Bevy's state-management run criteria! This would make the system set no longer constrained to run as part of a state!
Consider using iyes_loopless
, which does not
have such limitations.
Multiple Stages
Bevy states cannot work across multiple stages. Workarounds are available, but they are broken and buggy.
This is a huge limitation in practice, as it greatly limits how you can use commands. Not being able to use Commands is a big deal, as you cannot do things like spawn entities and operate on them during the same frame, among other important use cases.
Consider using iyes_loopless
, which does not
have such limitations.
With Input
If you want to use Input<T>
to trigger state transitions using
a button/key press, you need to clear the input manually by calling .reset
:
fn esc_to_menu(
mut keys: ResMut<Input<KeyCode>>,
mut app_state: ResMut<State<AppState>>,
) {
if keys.just_pressed(KeyCode::Escape) {
app_state.set(AppState::MainMenu).unwrap();
keys.reset(KeyCode::Escape);
}
}
(note that this requires ResMut
)
Not doing this can cause issues.
iyes_loopless
does not have this issue.
Events
When receiving events in systems that don't run all the time, such as during a pause state, you will miss any events that are sent during the frames when the receiving systems are not running!
To mitigate this, you could implement a custom cleanup strategy, to manually manage the lifetime of the relevant event types.
Bevy Version: | 0.9 | (outdated!) |
---|
Plugins
Relevant official examples:
plugin
,
plugin_group
.
As your project grows, it can be useful to make it more modular. You can split it into "plugins".
Plugins are simply collections of things to be added to the App Builder. Think of this as a way to add things to the app from multiple places, like different Rust files/modules or crates.
struct MyPlugin;
impl Plugin for MyPlugin {
fn build(&self, app: &mut App) {
app
.init_resource::<MyOtherResource>()
.add_event::<MyEvent>()
.add_startup_system(plugin_init)
.add_system(my_system);
}
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugin(MyPlugin)
.run();
}
Note how you get &mut
access to the App
, so you can
add whatever you want to it, just like you can do from your fn main
.
For internal organization in your own project, the main value of plugins
comes from not having to declare all your Rust types and functions as
pub
, just so they can be accessible from fn main
to be added to the
app builder. Plugins let you add things to your app from multiple
different places, like separate Rust files / modules.
You can decide how plugins fit into the architecture of your game.
Some suggestions:
- Create plugins for different states.
- Create plugins for various sub-systems, like physics or input handling.
Plugin groups
Plugin groups register multiple plugins at once.
Bevy's DefaultPlugins
and
MinimalPlugins
are examples of this.
To create your own plugin group:
struct MyPluginGroup;
impl PluginGroup for MyPluginGroup {
fn build(self) -> PluginGroupBuilder {
PluginGroupBuilder::start::<Self>()
.add(FooPlugin)
.add(BarPlugin)
}
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(MyPluginGroup)
.run();
}
When adding a plugin group to the app, you can disable some plugins while keeping the rest.
For example, if you want to manually set up logging (with your own tracing
subscriber), you can disable Bevy's LogPlugin
:
App::new()
.add_plugins(
DefaultPlugins.build()
.disable::<LogPlugin>()
)
.run();
Note that this simply disables the functionality, but it cannot actually remove the code to avoid binary bloat. The disabled plugins still have to be compiled into your program.
If you want to slim down your build, you should look at disabling Bevy's default cargo features, or depending on the various Bevy sub-crates individually.
Plugin Configuration
Plugins are also a convenient place to store settings/configuration that are used during initialization/startup. For settings that can be changed at runtime, it is recommended that you put them in resources instead.
struct MyGameplayPlugin {
/// Should we enable dev hacks?
enable_dev_hacks: bool,
}
impl Plugin for MyGameplayPlugin {
fn build(&self, app: &mut App) {
// add our gameplay systems
app.add_system(health_system);
app.add_system(movement_system);
// ...
// if "dev mode" is enabled, add some hacks
if self.enable_dev_hacks {
app.add_system(player_invincibility);
app.add_system(free_camera);
}
}
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugin(MyGameplayPlugin {
enable_dev_hacks: false, // change to true for dev testing builds
})
.run();
}
Plugins that are added using Plugin Groups can also be
configured. Many of Bevy's DefaultPlugins
work
this way.
App::new()
.add_plugins(DefaultPlugins.set(
// here we configure the main window
WindowPlugin {
window: WindowDescriptor {
width: 800.0,
height: 600.0,
// ...
..Default::default()
},
..Default::default()
}
))
.run();
Publishing Crates
Plugins give you a nice way to publish Bevy-based libraries for other people to easily include into their projects.
If you intend to publish plugins as crates for public use, you should read the official guidelines for plugin authors.
Don't forget to submit an entry to Bevy Assets on the official website, so that people can find your plugin more easily. You can do this by making a PR in the Github repo.
If you are interested in supporting bleeding-edge Bevy (main), see here for advice.
Bevy Version: | 0.9 | (outdated!) |
---|
Change Detection
Relevant official examples:
component_change_detection
.
Bevy allows you to easily detect when data is changed. You can use this to perform actions in response to changes.
One of the main use cases is optimization – avoiding unnecessary work by only doing it if the relevant data has changed. Another use case is triggering special actions to occur on changes, like configuring something or sending the data somewhere.
Components
Filtering
You can make a query that only yields entities if specific components on them have been modified.
Use query filters:
Added<T>
: detect new component instances- if the component was added to an existing entity
- if a new entity with the component was spawned
Changed<T>
: detect component instances that have been changed- triggers when the component is accessed mutably
- also triggers if the component is newly-added (as per
Added
)
(If you want to react to removals, see the page on removal detection. It works differently and is much trickier to use.)
/// Print the stats of friendly players when they change
fn debug_stats_change(
query: Query<
// components
(&Health, &PlayerXp),
// filters
(Without<Enemy>, Or<(Changed<Health>, Changed<PlayerXp>)>),
>,
) {
for (health, xp) in query.iter() {
eprintln!(
"hp: {}+{}, xp: {}",
health.hp, health.extra, xp.0
);
}
}
/// detect new enemies and print their health
fn debug_new_hostiles(
query: Query<(Entity, &Health), Added<Enemy>>,
) {
for (entity, health) in query.iter() {
eprintln!("Entity {:?} is now an enemy! HP: {}", entity, health.hp);
}
}
Checking
If you want to access all the entities, as normal, regardless of if they have
been modified, but you just want to check the status, you can use the special
ChangeTrackers<T>
query parameter.
/// Make sprites flash red on frames when the Health changes
fn debug_damage(
mut query: Query<(&mut Sprite, ChangeTrackers<Health>)>,
) {
for (mut sprite, tracker) in query.iter_mut() {
// detect if the Health changed this frame
if tracker.is_changed() {
sprite.color = Color::RED;
} else {
// extra check so we don't mutate on every frame without changes
if sprite.color != Color::WHITE {
sprite.color = Color::WHITE;
}
}
}
}
This is useful for processing all entities, but doing different things depending on if they have been modified.
Resources
For resources, change detection is provided via methods on the
Res
/ResMut
system parameters.
fn check_res_changed(
my_res: Res<MyResource>,
) {
if my_res.is_changed() {
// do something
}
}
fn check_res_added(
// use Option, not to panic if the resource doesn't exist yet
my_res: Option<Res<MyResource>>,
) {
if let Some(my_res) = my_res {
// the resource exists
if my_res.is_added() {
// it was just added
// do something
}
}
}
Note that change detection cannot currently be used to detect
states changes (via the State
resource) (bug).
What gets detected?
Changed
detection is triggered by
DerefMut
. Simply accessing components via a mutable query,
without actually performing a &mut
access, will not trigger it.
This makes change detection quite accurate. You can rely on it to optimize your game's performance, or to otherwise trigger things to happen.
Also note that when you mutate a component, Bevy does not track if the new value is actually different from the old value. It will always trigger the change detection. If you want to avoid that, simply check it yourself:
fn update_player_xp(
mut query: Query<&mut PlayerXp>,
) {
for mut xp in query.iter_mut() {
let new_xp = maybe_lvl_up(&xp);
// avoid triggering change detection if the value is the same
if new_xp != *xp {
*xp = new_xp;
}
}
}
Change detection works on a per-system granularity, and is reliable. A system will not detect changes that it made itself, only those done by other systems, and only if it has not seen them before (the changes happened since the last time it ran). If your system only runs sometimes (such as with states or run criteria), you do not have to worry about missing changes.
Possible Pitfalls
Beware of frame delay / 1-frame-lag. This can occur if Bevy runs the detecting system before the changing system. The detecting system will see the change the next time it runs, typically on the next frame update.
If you need to ensure that changes are handled immediately / during the same frame, you can use explicit system ordering.
However, when detecting component additions with Added<T>
(which are typically done using Commands
), this is not
enough; you need stages.
Removal Detection
Relevant official examples:
removal_detection
.
Removal detection is special. This is because, unlike with change detection, the data does not exist in the ECS anymore (obviously), so Bevy cannot keep tracking metadata for it.
Nevertheless, being able to respond to removals is important for some applications, so Bevy offers a limited form of it.
Components
You can check for components that have been removed during the current frame. The data is cleared at the end of every frame update. Note that this makes this feature tricky to use, and requires you to use multiple stages.
When you remove a component (using Commands
(Commands
)), the operation is applied at the end of the
stage. The system that checks for the removal
must run in a later stage during the same frame update. Otherwise, it will
not detect the removal.
Use the RemovedComponents<T>
special system
parameter type, to get an iterator for the Entity
IDs of
all the entities that had a component of type T
that was removed earlier
this frame.
/// Some component type for the sake of this example.
#[derive(Component)]
struct Seen;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// we could add our system to Bevy's `PreUpdate` stage
// (alternatively, you could create your own stage)
.add_system_to_stage(CoreStage::PreUpdate, remove_components)
// our detection system runs in a later stage
// (in this case: Bevy's default `Update` stage)
.add_system(detect_removals)
.run();
}
fn remove_components(
mut commands: Commands,
q: Query<(Entity, &Transform), With<Seen>>,
) {
for (e, transform) in q.iter() {
if transform.translation.y < -10.0 {
// remove the `Seen` component from the entity
commands.entity(e)
.remove::<Seen>();
}
}
}
fn detect_removals(
removals: RemovedComponents<Seen>,
// ... (maybe Commands or a Query ?) ...
) {
for entity in removals.iter() {
// do something with the entity
}
}
(To do things with these entities, you can just use the Entity
IDs with
Commands::entity()
or Query::get()
.)
Resources
Bevy does not provide any API for detecting when resources are removed.
You can work around this using Option
and a separate
Local
system parameter, effectively implementing your own
detection.
fn detect_removed_res(
my_res: Option<Res<MyResource>>,
mut my_res_existed: Local<bool>,
) {
if let Some(my_res) = my_res {
// the resource exists!
// remember that!
*my_res_existed = true;
// (... you can do something with the resource here if you want ...)
} else if *my_res_existed {
// the resource does not exist, but we remember it existed!
// (it was removed)
// forget about it!
*my_res_existed = false;
// ... do something now that it is gone ...
}
}
Note that, since this detection is local to your system, it does not have to happen during the same frame update.
Bevy Version: | 0.9 | (outdated!) |
---|
System Piping
Relevant official examples:
system_piping
.
You can compose a single Bevy system from multiple Rust functions.
You can make functions that can take an input and produce an output, and be connected together to run as a single larger system. This is called "system piping".
You can think of it as creating "modular" systems made up of multiple building blocks. This way, you can reuse some common code/logic in multiple systems.
Note that system piping is not a way of communicating between systems. If you want to pass data between systems, you should use Events instead.
Example: Handling Result
s
One useful application of system piping is to be able to return errors (allowing
the use of Rust's ?
operator) and then have a separate function for handling
them:
fn net_receive(mut netcode: ResMut<MyNetProto>) -> std::io::Result<()> {
netcode.receive_updates()?;
Ok(())
}
fn handle_io_errors(In(result): In<std::io::Result<()>>) {
if let Err(e) = result {
eprintln!("I/O error occurred: {}", e);
}
}
Such functions cannot be registered individually as systems (Bevy doesn't know what to do with the input/output). By "piping" them together, we create a valid system that we can add:
fn main() {
App::new()
// ...
.add_system(net_receive.pipe(handle_io_errors))
// ...
.run();
}
Performance Warning
Beware that Bevy treats the whole chain as if it was a single big system, with all the combined system parameters and their respective data access requirements. This implies that parallelism could be limited, affecting performance.
If you create multiple "piped systems" that all contain a common function which contains any mutable access, that prevents all of them from running in parallel!
Bevy Version: | 0.9 | (outdated!) |
---|
Param Sets
For safety reasons, a system cannot have multiple parameters whose data access might have a chance of mutability conflicts over the same data.
Some examples:
- Multiple incompatible queries.
- Using
&World
while also having other system parameters to access specific data. - …
Bevy provides a solution: wrap them in a ParamSet
:
fn reset_health(
// access the health of enemies and the health of players
// (note: some entities could be both!)
mut set: ParamSet<(
Query<&mut Health, With<Enemy>>,
Query<&mut Health, With<Player>>,
// also access the whole world ... why not
&World,
)>,
) {
// set health of enemies (use the 1st param in the set)
for mut health in set.p0().iter_mut() {
health.hp = 50.0;
}
// set health of players (use the 2nd param in the set))
for mut health in set.p1().iter_mut() {
health.hp = 100.0;
}
// read some data from the world (use the 3rd param in the set)
let my_resource = set.p2().resource::<MyResource>();
// since we only used the conflicting system params one at a time,
// everything is safe and our code can compile; ParamSet guarantees this
}
This ensures only one of the conflicting parameters can be used at the same time.
The maximum number of parameters in a param set is 8.
Bevy Version: | 0.9 | (outdated!) |
---|
Non-Send Resources
"Non-send" refers to data types that must only be accessed from the "main
thread" of the application. Such data is marked by Rust as !Send
(lacking
the Send
trait).
Some (often system) libraries have interfaces that cannot be safely used from other threads. A common example of this are various low-level OS interfaces for things like windowing, graphics, or audio. If you are doing advanced things like creating a Bevy plugin for interfacing with such things, you may encounter the need for this.
Normally, Bevy works by running all your systems on a thread-pool, making use of many CPU cores. However, you might need to ensure that some code always runs on the "main thread", or access data that is not safe to access in a multithreaded way.
Non-Send Systems and Data Access
To do this, you can use a NonSend<T>
/
NonSendMut<T>
system parameter. This behaves just like
Res<T>
/ ResMut<T>
, letting you access an
ECS resource (single global instance of some data), except that
the presence of such a parameter forces the Bevy scheduler to always run the
system on the main thread. This ensures that data never has
to be sent between threads or accessed from different threads.
One example of such a resource is WinitWindows
in Bevy. This is the low-level version of Windows
that
gives you more direct access to OS window management functionality.
fn setup_raw_window(mut windows: NonSend<WinitWindows>) {
let raw_window = windows.get_window(WindowId::primary()).unwrap();
// do some special things
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// just add it as a normal system;
// Bevy will notice the NonSend parameter
// and ensure it runs on the main thread
.add_startup_system(setup_raw_window)
.run();
}
Custom Non-Send Resources
Normally, to insert resources, their types must be
Send
.
Bevy tracks non-Send resources separately, to ensure that they
can only be accessed using NonSend<T>
/
NonSendMut<T>
.
It is not possible to insert non-send resources using
Commands
, only using direct World access.
This means that you have to initialize them in an exclusive
system, FromWorld
impl,
or custom stage.
fn setup_platform_audio(world: &mut World) {
// assuming `OSAudioMagic` is some primitive that is not thread-safe
let instance = OSAudioMagic::init();
world.insert_non_send_resource(instance);
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_startup_system(setup_platform_audio)
.run();
}
Bevy Version: | (any) |
---|
General Game Engine Features
This chapter covers various general features of Bevy, important to using it as a game engine.
You are expected to be familiar with Bevy programming in general. For that, see the Bevy Programming Framework chapter.
The topics covered in this chapter are applicable to a wide variety of projects.
Complex topics that deserve more extensive coverage have their own chapters in the book:
Bevy Version: | 0.11 | (current) |
---|
Coordinate System
2D and 3D scenes and cameras
Bevy uses a right-handed Y-up coordinate system for the game world. The coordinate system is the same for 3D and 2D, for consistency.
It is easiest to explain in terms of 2D:
- The X axis goes from left to right (+X points right).
- The Y axis goes from bottom to top (+Y points up).
- The Z axis goes from far to near (+Z points towards you, out of the screen).
- For 2D, the origin (X=0.0; Y=0.0) is at the center of the screen by default.
When you are working with 2D sprites, you can put the background on Z=0.0, and place other sprites at increasing positive Z coordinates to layer them on top.
In 3D, the axes are oriented the same way:
- Y points up
- The forward direction is -Z
This is a right-handed coordinate system. You can use the fingers of your right hand to visualize the 3 axes: thumb=X, index=Y, middle=Z.
It is the same as Godot, Maya, and OpenGL. Compared to Unity, the Z axis is inverted.
(graphic modifed and used with permission; original by @FreyaHolmer)
UI
For UI, Bevy follows the same convention as most other UI toolkits, the Web, etc.
- The origin is at the top left corner of the screen
- The Y axis points downwards
- X goes from 0.0 (left screen edge) to the number of screen pixels (right screen edge)
- Y goes from 0.0 (top screen edge) to the number of screen pixels (bottom screen edge)
The units represent logical (compensated for DPI scaling) screen pixels.
UI layout flows from top to bottom, similar to a web page.
Cursor and Screen
The cursor position and any other window (screen-space) coordinates follow the same conventions as UI, as described above.
Bevy Version: | 0.9 | (outdated!) |
---|
Transforms
Relevant official examples:
transform
,
translation
,
rotation
,
3d_rotation
,
scale
,
move_sprite
,
parenting
,
anything that spawns 2D or 3D objects.
First, a quick definition, if you are new to game development:
a Transform is what allows you to place an object in the game world. It is a combination of the object's "translation" (position/coordinates), "rotation", and "scale" (size adjustment).
You move objects around by modifying the translation, rotate them by modifying the rotation, and make them larger or smaller by modifying the scale.
// To simply position something at specific coordinates
let xf_pos567 = Transform::from_xyz(5.0, 6.0, 7.0);
// To scale an object, making it twice as big in all dimensions
let xf_scale = Transform::from_scale(Vec3::splat(2.0));
// To rotate an object in 2D (Z-axis rotation) by 30°
// (angles are in radians! must convert from degrees!)
let xf_rot2d = Transform::from_rotation(Quat::from_rotation_z((30.0_f32).to_radians()));
// 3D rotations can be complicated; explore the methods available on `Quat`
// Simple 3D rotation by Euler-angles (X, Y, Z)
let xf_rot2d = Transform::from_rotation(Quat::from_euler(
EulerRot::XYZ,
(20.0_f32).to_radians(),
(10.0_f32).to_radians(),
(30.0_f32).to_radians(),
));
// Everything:
let xf = Transform::from_xyz(1.0, 2.0, 3.0)
.with_scale(Vec3::new(0.5, 0.5, 1.0))
.with_rotation(Quat::from_rotation_y(0.125 * std::f32::consts::PI));
Transform Components
In Bevy, transforms are represented by two components:
Transform
and GlobalTransform
.
Any Entity that represents an object in the game world needs to have both. All of Bevy's built-in bundle types include them.
If you are creating a custom entity without using those bundles, you can use one of the following to ensure you don't miss them:
SpatialBundle
for transforms + visibilityTransformBundle
for just the transforms
fn spawn_special_entity(
mut commands: Commands,
) {
// create an entity that does not use one of the common Bevy bundles,
// but still needs transforms and visibility
commands.spawn((
ComponentA,
ComponentB,
SpatialBundle {
transform: Transform::from_scale(Vec3::splat(3.0)),
visibility: Visibility {
is_visible: false,
},
..Default::default()
},
));
}
Transform
Transform
is what you typically work with. It is
a struct
containing the translation, rotation, and scale. To read or
manipulate these values, access it from your systems using a
query.
If the entity has a parent, the Transform
component is relative to the parent. This means that the child object will
move/rotate/scale along with the parent.
fn inflate_balloons(
mut query: Query<&mut Transform, With<Balloon>>,
keyboard: Res<Input<KeyCode>>,
) {
// every time the Spacebar is pressed,
// make all the balloons in the game bigger by 25%
if keyboard.just_pressed(KeyCode::Space) {
for mut transform in query.iter_mut() {
transform.scale *= 1.25;
}
}
}
GlobalTransform
GlobalTransform
represents the absolute global
position in the world.
If the entity does not have a parent, then this will have
the same value as the Transform
.
The value of GlobalTransform
is calculated/managed
internally by Bevy. See below.
Transform Propagation
Beware: The two components are synchronized by a bevy-internal
system (the "transform propagation system"), which runs in the
PostUpdate
stage.
When you mutate the Transform
, the
GlobalTransform
is not updated immediately. They
will be out-of-sync until the transform propagation system runs.
If you need to work with GlobalTransform
directly,
you should add your system to the PostUpdate
stage and order it after the
TransformSystem::TransformPropagate
label.
/// Print the up-to-date global coordinates of the player as of **this frame**.
fn debug_globaltransform(
query: Query<&GlobalTransform, With<Player>>,
) {
let gxf = query.single();
debug!("Player at: {:?}", gxf.translation());
}
fn main() {
// the label to use for ordering
use bevy::transform::TransformSystem;
App::new()
.add_plugins(DefaultPlugins)
.add_system_to_stage(
CoreStage::PostUpdate,
debug_globaltransform
.after(TransformSystem::TransformPropagate)
)
.run();
}
Bevy Version: | 0.9 | (outdated!) |
---|
Visibility
Relevant official examples:
parenting
.
Visibility is used to control if something is to be rendered or not. If you want an entity to exist in the world, just not be displayed, you can hide it.
/// Prepare the game map, but do not display it until later
fn setup_map_hidden(
mut commands: Commands,
) {
commands.spawn((
GameMapEntity,
SceneBundle {
scene: todo!(),
visibility: Visibility {
is_visible: false,
},
..Default::default()
},
));
}
/// When everything is ready, un-hide the game map
fn reveal_map(
mut query: Query<&mut Visibility, With<GameMapEntity>>,
) {
let mut vis_map = query.single_mut();
vis_map.is_visible = true;
}
Visibility Components
In Bevy, visibility is represented by two components:
Visibility
and ComputedVisibility
.
Any Entity that represents an object in the game world needs to have both. All of Bevy's built-in bundle types include them.
If you are creating a custom entity without using those bundles, you can use one of the following to ensure you don't miss them:
SpatialBundle
for transforms + visibilityVisibilityBundle
for just visibility
fn spawn_special_entity(
mut commands: Commands,
) {
// create an entity that does not use one of the common Bevy bundles,
// but still needs transforms and visibility
commands.spawn((
ComponentA,
ComponentB,
SpatialBundle {
transform: Transform::from_scale(Vec3::splat(3.0)),
visibility: Visibility {
is_visible: false,
},
..Default::default()
},
));
}
Visibility
Visibility
is the "user-facing toggle". This is where
you specify if you want this entity to be visible or not.
If you hide an entity that has children, they will also be
hidden, regardless of what their individual Visibility
value is set to.
ComputedVisibility
ComputedVisibility
represents the actual final
decision made by Bevy about whether this entity needs to be displayed.
The value of ComputedVisibility
is read-only. It
is managed internally by Bevy.
It can be affected by the visibility of parent entities, if any.
It is also affected by "culling" systems. If the entity is not in the range of any Camera or Light, it does not need to be rendered, so Bevy will hide it.
Checking Actual Visibility
You can use ComputedVisibility
to check if
the entity is actually visible.
Bevy's internal visibility computations are done in the
PostUpdate
stage. To get the up-to-date
values for the current frame, your system must be ordered
after these bevy-internal systems. You can use the
VisibilitySystems
labels.
/// Check if the Player was hidden manually
fn debug_player_visibility(
query: Query<&ComputedVisibility, With<Player>>,
) {
let vis = query.single();
// check if it was manually hidden via Visibility
// (incl. by any parent entity)
debug!("Player visible due to hierachy: {:?}", vis.is_visible_in_hierarchy());
}
/// Check if balloons are seen by any Camera, Light, etc… (not culled)
fn debug_balloon_visibility(
query: Query<&ComputedVisibility, With<Balloon>>,
) {
for vis in query.iter() {
debug!("Balloon is in view: {:?}", vis.is_visible_in_view());
// check overall final actual visibility
// (combines visible-in-hierarchy and visible-in-view)
debug!("Balloon is visible: {:?}", vis.is_visible());
}
}
fn main() {
// the labels to use for ordering
use bevy::render::view::VisibilitySystems;
App::new()
.add_plugins(DefaultPlugins)
.add_system_to_stage(
CoreStage::PostUpdate,
debug_balloon_visibility
// in-view visibility (culling) is done here:
.after(VisibilitySystems::CheckVisibility)
)
.add_system_to_stage(
CoreStage::PostUpdate,
debug_player_visibility
// hierarchy propagation is done here:
.after(VisibilitySystems::VisibilityPropagate)
)
.run();
}
Bevy Version: | 0.9 | (outdated!) |
---|
Cameras
Cameras drive all rendering in Bevy. They are responsible for configuring what to draw, how to draw it, and where to draw it.
You must have at least one camera entity, in order for anything to be displayed at all! If you forget to spawn a camera, you will get an empty black screen.
In the simplest case, you can create a camera with the default settings. Just
spawn an entity using Camera2dBundle
or
Camera3dBundle
. It will simply draw all renderable
entities that are visible.
This page gives a general overview of cameras in Bevy. Also see the dedicated pages for 2D cameras and 3D cameras.
Practical advice: always create marker components for your camera entities, so that you can query your cameras easily!
#[derive(Component)]
struct MyGameCamera;
fn setup(mut commands: Commands) {
commands.spawn((
Camera3dBundle::default(),
MyGameCamera,
));
}
The Camera Transform
Cameras have transforms, which can be used to position or rotate the camera. This is how you move the camera around.
For examples, see these cookbook pages:
- 3D pan-orbit camera, like in 3D editor apps
If you are making a game, you should implement your own custom camera controls that feel appropriate to your game's genre and gameplay.
Zooming the camera
Do not use the transform scale to "zoom" a camera! It just stretches the image, which is not "zooming". It might also cause other issues and incompatibilities. Use the projection to zoom.
For orthographic projections, change the projection's scale. This way you can be confident about how exactly coordinate/units map to the screen. This also helps avoid scaling artifacts with 2D assets.
fn zoom_2d(
mut q: Query<&mut OrthographicProjection, With<MyGameCamera>>,
) {
let mut projection = q.single_mut();
// example: zoom in
projection.scale *= 1.25;
// example: zoom out
projection.scale *= 0.75;
// always ensure you end up with sane values
// (pick an upper and lower bound for your application)
projection.scale = projection.scale.clamp(0.5, 5.0);
}
For 3D perspective projections, change the FOV. This achieves the desired 3D effect of zooming with a lens, while keeping the camera at the same distance from what it is looking at. Decrease the FOV to "zoom in" (make objects appear closer). Increase the FOV to "zoom out" (make objects appear further away, increase the stretching due to the perspective effect).
fn zoom_3d(
mut q: Query<&mut PerspectiveProjection, With<MyGameCamera>>,
) {
let mut projection = q.single_mut();
// example: zoom in
projection.fov *= 1.25;
// example: zoom out
projection.fov *= 0.75;
// always ensure you end up with sane values
// (pick an upper and lower bound for your application)
projection.fov = projection.fov.clamp(30.0f32.to_radians(), 90.0f32.to_radians());
}
In some applications (like 3D editors), "zooming" might mean moving the camera closer or farther away, instead of changing the FOV.
Projection
The camera projection is responsible for mapping the coordinate system to the viewport. This effectively determines the "coordinate space" you are working in.
Bevy provides two kinds of projections:
OrthographicProjection
and
PerspectiveProjection
. They are configurable,
to be able to serve a variety of different use cases. See the dedicated pages
for 2D cameras and 3D cameras to learn more
about what you can do with them.
It is possible to implement your own custom camera projections. This can give you full control over the coordinate system. However, beware that things might behave in unexpected ways if you violate Bevy's coordinate system conventions!
Note that Bevy uses a an infinite reversed Z configuration for 3D.
HDR and Tonemapping
Render Target
The render target of a camera determines where the GPU will draw things to. It
could be a window (for outputting directly to the screen) or an
Image
asset (render-to-texture).
By default, cameras output to the primary window.
use bevy::render::camera::RenderTarget;
fn debug_render_targets(
q: Query<&Camera>,
) {
for camera in &q {
match &camera.target {
RenderTarget::Window(wid) => {
eprintln!("Camera renders to window with id: {:?}", wid);
}
RenderTarget::Image(handle) => {
eprintln!("Camera renders to image asset with id: {:?}", handle);
}
}
}
}
Viewport
The viewport is an (optional) way to restrict a camera to a sub-area of its render target, defined as a rectangle. That rectangle is effectively treated as the "window" to draw in.
An obvious use-case are split-screen games, where you want a camera to only draw to one half of the screen.
use bevy::render::camera::Viewport;
fn setup_minimap(mut commands: Commands) {
commands.spawn((
Camera2dBundle {
camera: Camera {
// renders after / on top of other cameras
priority: 2,
// set the viewport to a 256x256 square in the top left corner
viewport: Some(Viewport {
physical_position: UVec2::new(0, 0),
physical_size: UVec2::new(256, 256),
..default()
}),
..default()
},
..default()
},
MyMinimapCamera,
));
}
If you need to find out the area a camera renders to (the viewport, if configured, or the entire window, if not):
fn debug_viewports(
q: Query<&Camera, With<MyExtraCamera>>,
) {
let camera = q.single();
// the size of the area being rendered to
let view_dimensions = camera.logical_viewport_size().unwrap();
// the top-left and bottom-right coordinates
let (corner1, corner2) = camera.logical_viewport_rect().unwrap();
}
Coordinate Conversion
Camera
provides methods to help with coordinate conversion
between on-screen coordinates and world-space coordinates. For an example, see
the "cursor to world" cookbook page.
Clear Color
This is the "background color" that the whole viewport will be cleared to, before a camera renders anything.
You can also disable clearing on a camera, if you want to preserve all the pixels as they were before.
Render Layers
RenderLayers
is a way to filter what entities should be
drawn by what cameras. Insert this component onto your entities
to place them in specific "layers". The layers are integers from 0 to 31 (32
total available).
Inserting this component onto a camera entity selects what layers that camera should render. Inserting this component onto renderable entities selects what cameras should render those entities. An entity will be rendered if there is any overlap between the camera's layers and the entity's layers (they have at least one layer in common).
If an entity does not have the RenderLayers
component,
it is assumed to belong to layer 0 (only).
use bevy::render::view::visibility::RenderLayers;
// This camera renders everything in layers 0, 1
commands.spawn((
Camera2dBundle::default(),
RenderLayers::from_layers(&[0, 1])
));
// This camera renders everything in layers 1, 2
commands.spawn((
Camera2dBundle::default(),
RenderLayers::from_layers(&[1, 2])
));
// This sprite will only be seen by the first camera
commands.spawn((
SpriteBundle::default(),
RenderLayers::layer(0),
));
// This sprite will be seen by both cameras
commands.spawn((
SpriteBundle::default(),
RenderLayers::layer(1),
));
// This sprite will only be seen by the second camera
commands.spawn((
SpriteBundle::default(),
RenderLayers::layer(2),
));
// This sprite will also be seen by both cameras
commands.spawn((
SpriteBundle::default(),
RenderLayers::from_layers(&[0, 2]),
));
You can also modify the render layers of entities after they are spawned.
Camera Ordering
A camera's priority is a simple integer value that controls the order relative to any other cameras with the same render target.
For example, if you have multiple cameras that all render to the primary window, they will behave as multiple "layers". Cameras with higher priority will render "on top of" cameras with lower priority.
use bevy::core_pipeline::clear_color::ClearColorConfig;
commands.spawn((
Camera2dBundle {
camera_2d: Camera2d {
// no "background color", we need to see the main camera's output
clear_color: ClearColorConfig::None,
..default()
},
camera: Camera {
// renders after / on top of the main camera
priority: 1,
..default()
},
..default()
},
MyOverlayCamera,
));
UI Rendering
Bevy UI rendering is integrated into the cameras! Every camera will, by default, also draw UI.
However, if you are working with multiple cameras, you probably only want your UI to be drawn once (probably by the main camera). You can disable UI rendering on your other cameras.
Also, UI on multiple cameras is currently broken in Bevy. Even if you want multiple UI cameras (say, to display UI in an app with multiple windows), it does not work correctly.
commands.spawn((
Camera3dBundle::default(),
// UI config is a separate component
UiCameraConfig {
show_ui: false,
},
MyExtraCamera,
));
Disabling Cameras
You can deactivate a camera without despawning it. This is useful when you want to preserve the camera entity and all the configuration it carries, so you can easily re-enable it later.
Some example use cases: toggling an overlay, switching between a 2D and 3D view.
fn toggle_overlay(
mut q: Query<&mut Camera, With<MyOverlayCamera>>,
) {
let mut camera = q.single_mut();
camera.is_active = !camera.is_active;
}
Multiple Cameras
This is an overview of different scenarios where you would need more than one camera entity.
Multiple Windows
Official example: multiple_windows
.
If you want to create a Bevy app with multiple windows, you need to spawn multiple cameras, one for each window, and set their render targets respectively. Then, you can use your cameras to control what to display in each window.
Split-Screen
Official example: split_screen
.
You can set the camera viewport to only render to a part of the render target. This way, a camera can be made to render one half of the screen (or any other area). Use a separate camera for each view in a split-screen game.
Overlays
Official example: two_passes
.
You might want to render multiple "layers" (passes) to the same render target. An example of this might be an overlay/HUD to be displayed as an overlay on top of the main game.
The overlay camera could be completely different from the main camera. For example, the main camera might draw a 3D scene, and the overlay camera might draw 2D shapes. Such use cases are possible!
Use a separate camera to create the overlay. Set the priority higher, to tell Bevy to render it after (on top of) the main camera. Make sure to disable clearing!
Think about which camera you want to be responsible for rendering the UI. Use the overlay camera if you want it to be unaffected, or use the main camera if you want the overlay to be on top of the UI. Disable it on the other camera.
Use Render Layers to control what entities should be rendered by each camera.
Render to Image
(aka Render to Texture)
Official example: render_to_texture
.
If you want to generate an image in memory, you can output to an Image
asset.
This is useful for intermediate steps in games, such as rendering a minimap or the gun in a shooter game. You can then use that image as part of the final scene to render to the screen. Item previews are a similar use case.
Another use case is window-less applications that want to generate image files. For example, you could use Bevy to render something, and then export it to a PNG file.
Bevy Version: | 0.9 | (outdated!) |
---|
HDR, Tonemapping, Bloom
HDR (High Dynamic Range) refers to the ability of the game engine to handle very
bright lights or colors. Bevy's rendering is HDR. This means you can have
objects with colors that go above 1.0
, very bright lights, or bright emissive
materials. All of this is supported for both 3D and 2D.
This is not to be confused with HDR display output, which is the ability to produce a HDR image to be displayed by a modern monitor or TV with HDR capabilities. Bevy has no support for this yet.
Camera HDR configuration
There is a per-camera toggle that lets you decide whether you want Bevy to preserve the HDR data internally during rendering.
commands.spawn((
Camera3dBundle {
camera: Camera {
hdr: true,
..default()
},
..default()
},
));
If it is enabled, Bevy's intermediate textures will be in HDR format. The shaders output HDR values and Bevy will store them, so they can be used in later rendering passes. This allows you to enable post-processing effects like Bloom, that make use of the HDR data. Tonemapping will happen as a post-processing step.
If it is disabled, the shaders are expected to output standard RGB colors in the 0.0 to 1.0 range. Tonemapping happens in the shader. The HDR information is not preserved. Effects that require HDR data, like Bloom, will not work.
It is disabled by default. If enabling it, make sure to also have tonemapping enabled, ideally with deband dithering.
If you have both HDR and MSAA enabled, it is possible you might encounter issues. There might be visual artifacts in some cases. It is also unsupported on Web/WASM, crashing at runtime. Disable MSAA if you experience any such issues.
Bloom
The "Bloom" effect creates a glow around bright lights. It is not a physically-accurate effect, but it does a good job of helping the perception of very bright light, especially when outputting HDR to the display hardware is not supported.
use bevy::core_pipeline::bloom::BloomSettings;
commands.spawn((
Camera3dBundle {
camera: Camera {
hdr: true,
..default()
},
..default()
},
BloomSettings {
intensity: 0.25, // the default is 0.3
..default()
},
));
Tonemapping
Tonemapping is the step of the rendering process where the colors of pixels are converted from their in-engine intermediate repesentation into the final values as they should be displayed on-screen.
This is very important with HDR applications, as in that case the image can contain very bright pixels (above 1.0) which need to be remapped into a range that can be displayed.
Tonemapping is enabled by default. Bevy gives you a simple toggle
(Tonemapping
) to disable it, per-camera. This is not
recommended, unless you know you only have very simple graphics that don't need
it. It can make your graphics look incorrect.
use bevy::core_pipeline::tonemapping::Tonemapping;
commands.spawn((
Camera3dBundle {
tonemapping: Tonemapping::Disabled,
..default()
},
));
commands.spawn((
Camera3dBundle {
// this is the default:
tonemapping: Tonemapping::Enabled {
deband_dither: true, // dithering
},
..default()
},
));
Bevy does not currently offer any way to customize the tonemapping operation, only a simple toggle. The tonemapping operation is Luminance-weighted Reinhard.
Deband Dithering
Deband dithering helps color gradients or other areas with subtle changes in color to appear higher-quality, without a "color banding" effect.
It is enabled by default, and can be disabled per-camera.
Here is an example image without dithering (top) and with dithering (bottom). Pay attention to the quality/smoothness of the green color gradient on the ground plane. In games with photorealistic graphics, similar situations can arise in the sky, in dark rooms, or lights glowing with a bloom effect.
Bevy Version: | 0.9 | (outdated!) |
---|
Time and Timers
Relevant official examples:
timers
,
move_sprite
.
Time
The Time
resource is your main global source
of timing information, that you can access from any system
that does anything that needs time. You should derive all timings from
it.
Bevy updates these values at the beginning of every frame.
Delta Time
The most common use case is "delta time" – how much time passed between the previous frame update and the current one. This tells you how fast the game is running, so you can scale things like movement and animations. This way everything can happen smoothly and run at the same speed, regardless of the game's frame rate.
fn asteroids_fly(
time: Res<Time>,
mut q: Query<&mut Transform, With<Asteroid>>,
) {
for mut transform in q.iter_mut() {
// move our asteroids along the X axis
// at a speed of 10.0 units per second
transform.translation.x += 10.0 * time.delta_seconds();
}
}
Ongoing Time
Time
can also give you the total running time since startup.
Use this if you need a cumulative, increasing, measurement of time.
use std::time::Instant;
/// Say, for whatever reason, we want to keep track
/// of when exactly some specific entities were spawned.
#[derive(Component)]
struct SpawnedTime(Instant);
fn spawn_my_stuff(
mut commands: Commands,
time: Res<Time>,
) {
commands.spawn((/* ... */))
// we can use startup time and elapsed duration
.insert(SpawnedTime(time.startup() + time.elapsed()))
// or just the time of last update
.insert(SpawnedTime(time.last_update().unwrap()));
}
Timers and Stopwatches
There are also facilities to help you track specific intervals or timings:
Timer
and Stopwatch
. You can create
many instances of these, to track whatever you want. You can use them in
your own component or resource types.
Timers and Stopwatches need to be ticked. You need to have some system
calling .tick(delta)
, for it to make progress, or it will be inactive.
The delta should come from the Time
resource.
Timer
Timer
allows you to detect when a certain interval of time
has elapsed. Timers have a set duration. They can be "repeating" or
"non-repeating".
Both kinds can be manually "reset" (start counting the time interval from the beginning) and "paused" (they will not progress even if you keep ticking them).
Repeating timers will automatically reset themselves after they reach their set duration.
Use .finished()
to detect when a timer has reached its set duration. Use
.just_finished()
, if you need to detect only on the exact tick when the
duration was reached.
use std::time::Duration;
#[derive(Component)]
struct FuseTime {
/// track when the bomb should explode (non-repeating timer)
timer: Timer,
}
fn explode_bombs(
mut commands: Commands,
mut q: Query<(Entity, &mut FuseTime)>,
time: Res<Time>,
) {
for (entity, mut fuse_timer) in q.iter_mut() {
// timers gotta be ticked, to work
fuse_timer.timer.tick(time.delta());
// if it finished, despawn the bomb
if fuse_timer.timer.finished() {
commands.entity(entity).despawn();
}
}
}
#[derive(Resource)]
struct BombsSpawnConfig {
/// How often to spawn a new bomb? (repeating timer)
timer: Timer,
}
/// Spawn a new bomb in set intervals of time
fn spawn_bombs(
mut commands: Commands,
time: Res<Time>,
mut config: ResMut<BombsSpawnConfig>,
) {
// tick the timer
config.timer.tick(time.delta());
if config.timer.finished() {
commands.spawn((
FuseTime {
// create the non-repeating fuse timer
timer: Timer::new(Duration::from_secs(5), TimerMode::Once),
},
// ... other components ...
));
}
}
/// Configure our bomb spawning algorithm
fn setup_bomb_spawning(
mut commands: Commands,
) {
commands.insert_resource(BombsSpawnConfig {
// create the repeating timer
timer: Timer::new(Duration::from_secs(10), TimerMode::Repeating),
})
}
Note that Bevy's timers do not work like typical real-life timers (which count downwards toward zero). Bevy's timers start from zero and count up towards their set duration. They are basically like stopwatches with extra features: a maximum duration and optional auto-reset.
Stopwatch
Stopwatch
allow you to track how much time has passed
since a certain point.
It will just keep accumulating time, which you can check with
.elapsed()
/.elapsed_secs()
. You can manually reset it at any time.
use bevy::time::Stopwatch;
#[derive(Component)]
struct JumpDuration {
time: Stopwatch,
}
fn jump_duration(
time: Res<Time>,
mut q_player: Query<&mut JumpDuration, With<Player>>,
kbd: Res<Input<KeyCode>>,
) {
// assume we have exactly one player that jumps with Spacebar
let mut jump = q_player.single_mut();
if kbd.just_pressed(KeyCode::Space) {
jump.time.reset();
}
if kbd.pressed(KeyCode::Space) {
println!("Jumping for {} seconds.", jump.time.elapsed_secs());
// stopwatch has to be ticked to progress
jump.time.tick(time.delta());
}
}
Bevy Version: | 0.11 | (current) |
---|
Logging, Console Messages
Relevant official examples:
logs
.
You may have noticed how, when you run your Bevy project, you get messages in your console window. For example:
2022-06-12T13:28:25.445644Z WARN wgpu_hal::vulkan::instance: Unable to find layer: VK_LAYER_KHRONOS_validation
2022-06-12T13:28:25.565795Z INFO bevy_render::renderer: AdapterInfo { name: "AMD Radeon RX 6600 XT", vendor: 4098, device: 29695, device_type: DiscreteGpu, backend: Vulkan }
2022-06-12T13:28:25.565795Z INFO mygame: Entered new map area.
Log messages like this can come from Bevy, dependencies (like wgpu), and also from your own code.
Bevy offers a logging framework that is much more advanced than simply using
println
/eprintln
from Rust. Log messages can have metadata, like the
level, timestamp, and Rust module where it came from. You can see that this
metadata is printed alongside the contents of the message.
This is set up by Bevy's LogPlugin
. It is part of the
DefaultPlugins
plugin group, so most Bevy users
will have it automatically in every typical Bevy project.
Levels
Levels determine how important a message is, and allow messages to be filtered.
The available levels are: error
, warn
, info
, debug
, trace
.
A rough guideline for when to use each level, could be:
error
: something happened that prevents things from working correctlywarn
: something unusual happened, but things can continue to workinfo
: general informational messagesdebug
: for development, messages about what your code is doingtrace
: for very verbose debug data, like dumping values
Printing your own log messages
To display a message, just use the macro named after the level of the
message. The syntax is exactly the same as with Rust's println
. See the
std::fmt
documentation for more details.
#![allow(unused)] fn main() { error!("Unknown condition!"); warn!("Something unusual happened!"); info!("Entered game level: {}", level_id); debug!("x: {}, state: {:?}", x, state); trace!("entity transform: {:?}", transform); }
Filtering messages
To control what messages you would like to see, you can configure Bevy's
LogPlugin
:
#![allow(unused)] fn main() { use bevy::log::LogPlugin; app.add_plugins(DefaultPlugins.set(LogPlugin { filter: "info,wgpu_core=warn,wgpu_hal=warn,mygame=debug".into(), level: bevy::log::Level::DEBUG, })); }
The filter
field is a string specifying a list of rules for what level to
enable for different Rust modules/crates. In the example above, the string
means: show up to info
by default, limit wgpu_core
and wgpu_hal
to warn
level, for mygame
show debug
.
All levels higher than the one specified are also enabled. All levels lower than the one specified are disabled, and those messages will not be displayed.
The level
filter is a global limit on the lowest level to use. Messages
below that level will be ignored and most of the performance overhead avoided.
Environment Variable
You can override the filter string when running your app, using the RUST_LOG
environment variable.
RUST_LOG="warn,mygame=debug" ./mygame
Note that other Rust projects, such as cargo
, also use the same
environment variable to control their logging. This can lead to unexpected
consequences. For example, doing:
RUST_LOG="debug" cargo run
will cause your console to also be filled with debug messages from cargo
.
Different settings for debug and release builds
If you want to do different things in your Rust code for debug/release builds, an easy way to achieve it is using conditional compilation on "debug assertions".
#![allow(unused)] fn main() { use bevy::log::LogPlugin; // this code is compiled only if debug assertions are enabled (debug mode) #[cfg(debug_assertions)] app.add_plugins(DefaultPlugins.set(LogPlugin { level: bevy::log::Level::DEBUG, filter: "debug,wgpu_core=warn,wgpu_hal=warn,mygame=debug".into(), })); // this code is compiled only if debug assertions are disabled (release mode) #[cfg(not(debug_assertions))] app.add_plugins(DefaultPlugins.set(LogPlugin { level: bevy::log::Level::INFO, filter: "info,wgpu_core=warn,wgpu_hal=warn".into(), })); }
This is a good reason why you should not use release mode during development just for performance reasons.
On Microsoft Windows, your game EXE will also launch with a console window for displaying log messages by default. You might not want that in release builds. See here.
Performance Implications
Printing messages to the console is a relatively slow operation.
However, if you are not printing a large volume of messages, don't worry about it. Just avoid spamming lots of messages from performance-sensitive parts of your code like inner loops.
You can disable log levels like trace
and debug
in release builds.
Bevy Version: | 0.9 | (outdated!) |
---|
Hierarchical (Parent/Child) Entities
Relevant official examples:
hierarchy
,
parenting
.
Technically, the Entities/Components themselves cannot form a hierarchy (the ECS is a flat data structure). However, logical hierarchies are a common pattern in games.
Bevy supports creating such a logical link between entities, to form
a virtual "hierarchy", by simply adding Parent
and
Children
components on the respective entities.
When using Commands to spawn entities,
Commands
has methods for adding children to entities,
which automatically add the correct components:
// spawn the parent and get its Entity id
let parent = commands.spawn(MyParentBundle::default()).id();
// do the same for the child
let child = commands.spawn(MyChildBundle::default()).id();
// add the child to the parent
commands.entity(parent).push_children(&[child]);
// you can also use `with_children`:
commands.spawn(MyParentBundle::default())
.with_children(|parent| {
parent.spawn(MyChildBundle::default());
});
Note that this only sets up the Parent
and
Children
components, and nothing else. Notably, it does not
add transforms or visibility for you. If you
need that functionality, you need to add those components yourself, using
something like SpatialBundle
.
You can despawn an entire hierarchy with a single command:
fn close_menu(
mut commands: Commands,
query: Query<Entity, With<MainMenuUI>>,
) {
for entity in query.iter() {
// despawn the entity and its children
commands.entity(entity).despawn_recursive();
}
}
Accessing the Parent or Children
To make a system that works with the hierarchy, you typically need two queries:
- one with the components you need from the child entities
- one with the components you need from the parent entities
One of the two queries should include the appropriate component, to obtain the entity ids to use with the other one:
Parent
in the child query, if you want to iterate entities and look up their parents, orChildren
in the parent query, if you want to iterate entities and look up their children
For example, if we want to get the Transform
of cameras (Camera
) that have a parent, and the
GlobalTransform
of their parent:
fn camera_with_parent(
q_child: Query<(&Parent, &Transform), With<Camera>>,
q_parent: Query<&GlobalTransform>,
) {
for (parent, child_transform) in q_child.iter() {
// `parent` contains the Entity ID we can use
// to query components from the parent:
let parent_global_transform = q_parent.get(parent.get());
// do something with the components
}
}
As another example, say we are making a strategy game, and we have Units that are children of a Squad. Say we need to make a system that works on each Squad, and it needs some information about the children:
fn process_squad_damage(
q_parent: Query<(&MySquadDamage, &Children)>,
q_child: Query<&MyUnitHealth>,
) {
// get the properties of each squad
for (squad_dmg, children) in q_parent.iter() {
// `children` is a collection of Entity IDs
for &child in children.iter() {
// get the health of each child unit
let health = q_child.get(child);
// do something
}
}
}
Transform and Visibility Propagation
If your entities represent "objects in the game world", you probably expect the children to be affected by the parent.
Transform propagation allows children to be positioned relative to their parent and move with it.
Visibility propagation allows children to be hidden if you manually hide their parent.
Most Bundles that come with Bevy provide these behaviors automatically. Check the docs for the bundles you are using. Camera bundles, for example, have transforms, but not visibility.
Otherwise, you can use SpatialBundle
to make sure
your entities have all the necessary components.
Known Pitfalls
Despawning Child Entities
If you despawn an entity that has a parent, Bevy does not remove it from the
parent's Children
.
If you then query for that parent entity's children, you will get an invaild entity, and any attempt to manipulate it will likely lead to this error:
thread 'main' panicked at 'Attempting to create an EntityCommands for entity 7v0, which doesn't exist.'
The workaround is to manually call remove_children
alongside the despawn
:
commands.entity(parent_entity).remove_children(&[child_entity]);
commands.entity(child_entity).despawn();
Bevy Version: | 0.9 | (outdated!) |
---|
Fixed Timestep
Relevant official examples:
fixed_timestep
.
If you need something to happen at fixed time intervals (a common use case
is Physics updates), you can add the respective systems to
your app using Bevy's FixedTimestep
Run Criteria.
use bevy::time::FixedTimestep;
// The timestep says how many times to run the SystemSet every second
// For TIMESTEP_1, it's once every second
// For TIMESTEP_2, it's twice every second
const TIMESTEP_1_PER_SECOND: f64 = 60.0 / 60.0;
const TIMESTEP_2_PER_SECOND: f64 = 30.0 / 60.0;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_system_set(
SystemSet::new()
// This prints out "hello world" once every second
.with_run_criteria(FixedTimestep::step(TIMESTEP_1_PER_SECOND))
.with_system(slow_timestep)
)
.add_system_set(
SystemSet::new()
// This prints out "goodbye world" twice every second
.with_run_criteria(FixedTimestep::step(TIMESTEP_2_PER_SECOND))
.with_system(fast_timestep)
)
.run();
}
fn slow_timestep() {
println!("hello world");
}
fn fast_timestep() {
println!("goodbye world");
}
State
You can check the current state of the fixed timestep trackers, by accessing
the FixedTimesteps
resource. This lets
you know how much time remains until the next time it triggers, or how much
it has overstepped. You need to label your fixed timesteps.
See the official example, which illustrates this.
Caveats
The major problem with Bevy's fixed timestep comes from the fact that
it is implemented using Run Criteria. It cannot be
combined with other run criteria, such as states. This makes
it unusable for most projects, which need to rely on states for things
like implementing the main menu / loading screen / etc. Consider using
iyes_loopless
, which does not have this problem.
Also, note that your systems are still called as part of the regular frame-update cycle, along with all of the normal systems. So, the timing is not exact.
The FixedTimestep
run criteria simply checks how much
time passed since the last time your systems were ran, and decides whether
to run them during the current frame, or not, or run them multiple times,
as needed.
Danger! Lost events!
By default, Bevy's events are not reliable! They only persist for 2 frames, after which they are lost. If your fixed-timestep systems receive events, beware that you may miss some events if the framerate is higher than 2x the fixed timestep.
One way around that is to use events with manual clearing. This gives you control over how long events persist, but can also leak / waste memory if you forget to clear them.
Bevy Version: | 0.11 | (current) |
---|
Audio
Relevant official examples:
audio
,
audio_control
.
TODO
Spatial Audio
Relevant official examples:
spatial_audio_2d
,
spatial_audio_3d
.
TODO
Custom Audio Data Stream
Relevant official examples:
decodable
.
TODO
Bevy Version: | 0.9 | (outdated!) |
---|
Bevy Asset Management
Assets are the data that the game engine is working with: all of your images, 3D models, sounds, scenes, game-specific things like item descriptions, and more!
Bevy has a flexible system for loading and managing your game assets asynchronously (in the background, without causing lag spikes in your game).
In your code, you refer to individual assets using handles.
Asset data can be loaded from files and also accessed from code. Hot-reloading is supported to help you during development, by reloading asset files if they change while the game is running.
If you want to write some code to do something when assets finish loading, get modified, or are unloaded, you can use asset events.
Bevy Version: | 0.9 | (outdated!) |
---|
Handles
Handles are lightweight IDs that refer to a specific asset. You need them to use your assets, for example to spawn entities like 2D sprites or 3D models, or to access the data of the assets.
Handles have the Rust type Handle<T>
, where T
is the
asset type.
You can store handles in your entity components or resources.
Handles can refer to not-yet-loaded assets, meaning you can just spawn your entities anyway, using the handles, and the assets will just "pop in" when they become ready.
Obtaining Handles
If you are loading an asset from a file, the
asset_server.load(…)
call will give you the handle. The loading of the
data happens in the background, meaning that the handle will initially refer
to an unavailable asset, and the actual data will become available later.
If you are creating your own asset data from code,
the assets.add(…)
call will give you the handle.
Reference Counting; Strong and Weak Handles
Bevy keeps track of how many handles to a given asset exist at any time. Bevy will automatically unload unused assets, after the last handle is dropped.
For this reason, creating additional handles to the same asset requires you
to call handle.clone()
. This makes the operation explicit, to ensure you are
aware of all the places in your code where you create additional handles. The
.clone()
operation is cheap, so don't worry about performance (in most cases).
There are two kinds of handles: "strong" and "weak". Strong assets are
counted, weak handles are not. By default, handles are strong. If you want
to create a weak handle, use .clone_weak()
(instead of .clone()
) on an
existing handle. Bevy can unload the asset after all strong handles are gone,
even if you are still holding some weak handles.
Untyped Handles
Bevy also has a HandleUntyped
type. Use this type
of handle if you need to be able to refer to any asset, regardless of the
asset type.
This allows you to store a collection (such as Vec
or
HashMap
) containing assets of mixed types.
You can create an untyped handle using .clone_untyped()
on an existing
handle.
Just like regular handles, untyped handles can be strong or weak.
You need to do this to access the asset data.
You can convert an untyped handle into a typed handle with .typed::<T>()
,
specifying the type to use. You need to do this to access the asset
data.
Bevy Version: | 0.9 | (outdated!) |
---|
Load Assets from Files with AssetServer
Relevant official examples:
asset_loading
.
To load assets from files, use the AssetServer
resource.
#[derive(Resource)]
struct UiFont(Handle<Font>);
fn load_ui_font(
mut commands: Commands,
server: Res<AssetServer>
) {
let handle: Handle<Font> = server.load("font.ttf");
// we can store the handle in a resource:
// - to prevent the asset from being unloaded
// - if we want to use it to access the asset later
commands.insert_resource(UiFont(handle));
}
This queues the asset loading to happen in the background, and return a handle. The asset will take some time to become available. You cannot access the actual data immediately in the same system, but you can use the handle.
You can spawn entities like your 2D sprites, 3D models, and UI, using the handle, even before the asset has loaded. They will just "pop in" later, when the asset becomes ready.
Note that it is OK to call asset_server.load(…)
as many times as you want,
even if the asset is currently loading, or already loaded. It will just
provide you with the same handle. Every time you call it, it will just check
the status of the asset, begin loading it if needed, and give you a handle.
Bevy supports loading a variety of asset file formats, and can be extended to support more. The asset loader implementation to use is selected based on the file extension.
Untyped Loading
If you want an untyped handle, you can use
asset_server.load_untyped(…)
instead.
Untyped loading is possible, because Bevy always detects the file type from the file extension anyway.
Loading Folders
You can also load an entire folder of assets, regardless of how many
files are inside, using asset_server.load_folder(…)
. This gives you a
Vec<HandleUntyped>
with all the untyped handles.
#[derive(Resource)]
struct ExtraAssets(Vec<HandleUntyped>);
fn load_extra_assets(
mut commands: Commands,
server: Res<AssetServer>,
) {
if let Ok(handles) = server.load_folder("extra") {
commands.insert_resource(ExtraAssets(handles));
}
}
Loading folders is not supported by all I/O backends. Notably, it does not work on WASM/Web.
AssetPath and Labels
The asset path you use to identify an asset from the filesystem is actually
a special AssetPath
, which consists of the file path +
a label. Labels are used in situations where multiple assets are contained
in the same file. An example of this are GLTF files, which can
contain meshes, scenes, textures, materials, etc.
Asset paths can be created from a string, with the label (if any) attached
after a #
symbol.
fn load_gltf_things(
mut commands: Commands,
server: Res<AssetServer>
) {
// get a specific mesh
let my_mesh: Handle<Mesh> = server.load("my_scene.gltf#Mesh0/Primitive0");
// spawn a whole scene
let my_scene: Handle<Scene> = server.load("my_scene.gltf#Scene0");
commands.spawn(SceneBundle {
scene: my_scene,
..Default::default()
});
}
See the GLTF page for more info about working with 3D models.
Where are assets loaded from?
The asset server internally relies on an implementation of the
AssetIo
Rust trait, which is Bevy's way of providing
"backends" for fetching data from different types of storage.
Bevy provides its own default built-in I/O backends for each supported platform.
On desktop platforms, it treats asset paths as relative to a folder called
assets
, that must be placed at one of the following locations:
- Alongside the game's executable file, for distribution
- In your Cargo project folder, when running your game using
cargo
during development- This is identified by the
CARGO_MANIFEST_DIR
environment variable
- This is identified by the
On the web, it fetches assets using HTTP URLs pointing within an assets
folder located alongside the game's .wasm
file.
There are unofficial plugins available that provide alternative
I/O backend implementations, such as for loading assets from inside archive
files (.zip
), embedded inside the game executable, using a network protocol,
… many other possibilities.
Bevy Version: | 0.9 | (outdated!) |
---|
Access the Asset Data
To access the actual asset data from systems, use the
Assets<T>
resource.
You can identify your desired asset using the handle.
untyped handles need to be "upgraded" into typed handles.
#[derive(Resource)]
struct SpriteSheets {
map_tiles: Handle<TextureAtlas>,
}
fn use_sprites(
handles: Res<SpriteSheets>,
atlases: Res<Assets<TextureAtlas>>,
images: Res<Assets<Image>>,
) {
// Could be `None` if the asset isn't loaded yet
if let Some(atlas) = atlases.get(&handles.map_tiles) {
// do something with the texture atlas
}
}
Creating Assets from Code
You can also add assets to Assets<T>
manually.
Sometimes you need to create assets from code, rather than loading them from files. Some common examples of such use-cases are:
- creating texture atlases
- creating 3D or 2D materials
- procedurally-generating assets like images or 3D meshes
To do this, first create the data for the asset (an instance of the
asset type), and then add it .add(…)
it to the
Assets<T>
resource, for it to be stored and tracked by
Bevy. You will get a handle to use to refer to it, just like
any other asset.
fn add_material(
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let new_mat = StandardMaterial {
base_color: Color::rgba(0.25, 0.50, 0.75, 1.0),
unlit: true,
..Default::default()
};
let handle = materials.add(new_mat);
// do something with the handle
}
Bevy Version: | 0.9 | (outdated!) |
---|
React to Changes with Asset Events
If you need to perform specific actions when an asset is created,
modified, or removed, you can make a system that reacts to
AssetEvent
events.
#[derive(Resource)]
struct MyMapImage {
handle: Handle<Image>,
}
fn fixup_images(
mut ev_asset: EventReader<AssetEvent<Image>>,
mut assets: ResMut<Assets<Image>>,
map_img: Res<MyMapImage>,
) {
for ev in ev_asset.iter() {
match ev {
AssetEvent::Created { handle } => {
// a texture was just loaded or changed!
// WARNING: this mutable access will cause another
// AssetEvent (Modified) to be emitted!
let texture = assets.get_mut(handle).unwrap();
// ^ unwrap is OK, because we know it is loaded now
if *handle == map_img.handle {
// it is our special map image!
} else {
// it is some other image
}
}
AssetEvent::Modified { handle } => {
// an image was modified
}
AssetEvent::Removed { handle } => {
// an image was unloaded
}
}
}
}
Note: If you are handling Modified
events and doing a mutable access to
the data, the .get_mut
will trigger another Modified
event for the same
asset. If you are not careful, this could result in an infinite loop! (from
events caused by your own system)
Bevy Version: | 0.9 | (outdated!) |
---|
Track Loading Progress
There are good community plugins that can help with this. Otherwise, this page shows you how to do it yourself.
If you want to check the status of various asset files,
you can poll it from the AssetServer
. It will tell you
whether the asset(s) are loaded, still loading, not loaded, or encountered
an error.
To check an individual asset, you can use asset_server.get_load_state(…)
with
a handle or path to refer to the asset.
To check a group of many assets, you can add them to a single collection
(such as a Vec<HandleUntyped>
; untyped handles are very
useful for this) and use asset_server.get_group_load_state(…)
.
Here is a more complete code example:
#[derive(Resource)]
struct AssetsLoading(Vec<HandleUntyped>);
fn setup(server: Res<AssetServer>, mut loading: ResMut<AssetsLoading>) {
// we can have different asset types
let font: Handle<Font> = server.load("my_font.ttf");
let menu_bg: Handle<Image> = server.load("menu.png");
let scene: Handle<Scene> = server.load("level01.gltf#Scene0");
// add them all to our collection for tracking
loading.0.push(font.clone_untyped());
loading.0.push(menu_bg.clone_untyped());
loading.0.push(scene.clone_untyped());
}
fn check_assets_ready(
mut commands: Commands,
server: Res<AssetServer>,
loading: Res<AssetsLoading>
) {
use bevy::asset::LoadState;
match server.get_group_load_state(loading.0.iter().map(|h| h.id)) {
LoadState::Failed => {
// one of our assets had an error
}
LoadState::Loaded => {
// all assets are now ready
// this might be a good place to transition into your in-game state
// remove the resource to drop the tracking handles
commands.remove_resource::<AssetsLoading>();
// (note: if you don't have any other handles to the assets
// elsewhere, they will get unloaded after this)
}
_ => {
// NotLoaded/Loading: not fully ready yet
}
}
}
Bevy Version: | 0.9 | (outdated!) |
---|
Hot-Reloading Assets
Relevant official examples:
hot_asset_reloading
.
At runtime, if you modify the file of an asset
that is loaded into the game (via the
AssetServer
), Bevy can detect that and reload the
asset automatically. This is very useful for quick iteration. You can edit
your assets while the game is running and see the changes instantly in-game.
Not all file formats and use cases are supported equally well. Typical asset types like textures / images should work without issues, but complex GLTF or scene files, or assets involving custom logic, might not.
If you need to run custom logic as part of your hot-reloading
workflow, you could implement it in a system, using
AssetEvent
(learn more).
Hot reloading is opt-in and has to be enabled in order to work:
fn main() {
App::new()
.add_plugins(DefaultPlugins.set(AssetPlugin {
watch_for_changes: true,
..Default::default()
}))
.run();
}
Note that this requires the filesystem_watcher
Bevy cargo
feature. It is enabled by default, but if you have disabled
default features to customize Bevy, be sure to include it if you need it.
Shaders
Bevy also supports hot-reloading for shaders. You can edit your custom shader code and see the changes immediately.
This works for any shader loaded from a file path, such as shaders specified
in your Materials definitions, or shaders loaded via the
AssetServer
.
Shader code that does not come from asset files, such as if you include it as a static string in your source code, cannot be hot-reloaded (for obvious reasons).
Bevy Version: | 0.11 | (current) |
---|
Input Handling
Bevy supports the following inputs:
- Keyboard (detect when keys are pressed or released)
- Character (for text input; keyboard layout handled by the OS)
- Mouse (relative motion, buttons, scrolling)
- Motion (moving the mouse, not tied to OS cursor)
- Cursor (absolute pointer position)
- Buttons
- Scrolling (mouse wheel or touchpad gesture)
- Zoom/Rotate touchpad gestures
- Touchscreen (with multi-touch)
- Gamepad (Controller, Joystick) (via the gilrs library)
The following notable input devices are not supported:
- Accelerometers and gyroscopes for device tilt
- Other sensors, like temperature sensors
- Tracking individual fingers on a multi-touch trackpad, like on a touchscreen
- Microphones and other audio input devices
- MIDI (musical instruments), but there is an unofficial plugin:
bevy_midi
.
For most input types (where it makes sense), Bevy provides two ways of dealing with them:
- by checking the current state via resources (input resources),
- or via events (input events).
Some inputs are only provided as events.
Checking state is done using resources such as
Input
(for binary inputs like keys or buttons),
Axis
(for analog inputs), Touches
(for fingers on a touchscreen), etc. This way of handling input is very
convenient for implementing game logic. In these scenarios, you typically
only care about the specific inputs mapped to actions in your game. You can
check specific buttons/keys to see when they get pressed/released, or what
their current state is.
Events (input events) are a lower-level, more all-encompassing approach. Use them if you want to get all activity from that class of input device, rather than only checking for specific inputs.
Input Mapping
Bevy does not yet offer a built-in way to do input mapping (configure key bindings, etc). You need to come up with your own way of translating the inputs into logical actions in your game/app.
There are some community-made plugins that may help with that: see the input-section on bevy-assets. My personal recommendation: Input Manager plugin by Leafwing Studios.
It may be a good idea to build your own abstractions specific to your game. For example, if you need to handle player movement, you might want to have a system for reading inputs and converting them to your own internal "movement intent/action events", and then another system acting on those internal events, to actually move the player. Make sure to use explicit system ordering to avoid lag / frame delays.
Run Conditions
Bevy also provides run conditions (see all of them here) that you can attach to your systems, if you want a specific system to only run when a specific key or button is pressed.
This way, you can do input handling as part of the scheduling/configuration of your systems, and avoid running unnecessary code on the CPU.
Using these in real games is not recommended, because you have to hard-code the keys, which makes it impossible to make user-configurable keybindings.
To support configurable keybindings, you can implement your own run conditions that check your keybindings from the user settings.
If you are using the LWIM plugin, it also provides support for a similar run-condition-based workflow.
Bevy Version: | 0.9 | (outdated!) |
---|
Keyboard Input
Relevant official examples:
keyboard_input
,
keyboard_input_events
.
This page shows how to handle keyboard keys being pressed and released.
If you are interested in text input, see the Character Input page instead.
Note: Command Key on Mac corresponds to the Super/Windows Key on PC.
Checking Key State
Most commonly, you might be interested in specific known keys and detecting when
they are pressed or released. You can check specific Key Codes or Scan
Codes using the
Input<KeyCode>
/ Input<ScanCode>
resources.
fn keyboard_input(
keys: Res<Input<KeyCode>>,
) {
if keys.just_pressed(KeyCode::Space) {
// Space was pressed
}
if keys.just_released(KeyCode::LControl) {
// Left Ctrl was released
}
if keys.pressed(KeyCode::W) {
// W is being held down
}
// we can check multiple at once with `.any_*`
if keys.any_pressed([KeyCode::LShift, KeyCode::RShift]) {
// Either the left or right shift are being held down
}
if keys.any_just_pressed([KeyCode::Delete, KeyCode::Back]) {
// Either delete or backspace was just pressed
}
}
Keyboard Events
To get all keyboard activity, you can use
KeyboardInput
events:
fn keyboard_events(
mut key_evr: EventReader<KeyboardInput>,
) {
use bevy::input::ButtonState;
for ev in key_evr.iter() {
match ev.state {
ButtonState::Pressed => {
println!("Key press: {:?} ({})", ev.key_code, ev.scan_code);
}
ButtonState::Released => {
println!("Key release: {:?} ({})", ev.key_code, ev.scan_code);
}
}
}
}
These events give you both the Key Code and Scan Code.
Key Codes and Scan Codes
Keyboard keys can be identified by Key Code or Scan Code.
Key Codes represent the logical meaning of each key (usually the symbol/letter,
or function it performs). They are dependent on the keyboard layout currently
active in the user's OS. Bevy represents them with the KeyCode
enum.
Scan Codes represent the physical key on the keyboard, regardless of the system
layout. Bevy represents them using ScanCode
, which contains
an integer ID. The exact value of the integer is meaningless and OS-dependent,
but a given physical key on the keyboard will always produce the same value,
regardless of the user's language and keyboard layout settings.
Best Practices for Key Bindings
Here is some advice for how to implement user-friendly remappable key-bindings for your game, that can work well for international users or those with non-QWERTY keyboard layouts.
This section assumes that you have implemented some sort of system to allow the user to reconfigure their keybindings. You want to prompt the user to press their preferred key for a given in-game action, so you can store/remember it and later use it for gameplay.
The problem is that, if you simply use Key Codes, then users might accidentally switch their OS keyboard layout mid-game and suddenly have their keyboard not work as expected.
You should detect and store the user's chosen keys using Scan Codes, and use Scan Codes for detecting keyboard input during gameplay.
Key Codes can still be used for UI purposes, like to display the chosen key to the user.
Bevy Version: | 0.11 | (current) |
---|
Mouse
Relevant official examples:
mouse_input
,
mouse_input_events
.
Mouse Buttons
Similar to keyboard input, mouse buttons are available as an
Input
state resource, events, and run
conditions (see list). Use whichever
pattern feels most appropriate to your use case.
You can check the state of specific mouse buttons using
Input<MouseButton>
:
fn mouse_button_input(
buttons: Res<Input<MouseButton>>,
) {
if buttons.just_pressed(MouseButton::Left) {
// Left button was pressed
}
if buttons.just_released(MouseButton::Left) {
// Left Button was released
}
if buttons.pressed(MouseButton::Right) {
// Right Button is being held down
}
// we can check multiple at once with `.any_*`
if buttons.any_just_pressed([MouseButton::Left, MouseButton::Right]) {
// Either the left or the right button was just pressed
}
}
You can also iterate over any buttons that have been pressed or released:
fn mouse_button_iter(
buttons: Res<Input<MouseButton>>,
) {
for button in buttons.get_pressed() {
println!("{:?} is currently held down", button);
}
for button in buttons.get_just_pressed() {
println!("{:?} was pressed", button);
}
for button in buttons.get_just_released() {
println!("{:?} was released", button);
}
}
Alternatively, you can use MouseButtonInput
events to get all activity:
use bevy::input::mouse::MouseButtonInput;
fn mouse_button_events(
mut mousebtn_evr: EventReader<MouseButtonInput>,
) {
use bevy::input::ButtonState;
for ev in mousebtn_evr.iter() {
match ev.state {
ButtonState::Pressed => {
println!("Mouse button press: {:?}", ev.button);
}
ButtonState::Released => {
println!("Mouse button release: {:?}", ev.button);
}
}
}
}
You can also use Bevy's built-in run conditions, so your systems only run on mouse button input. Only recommended for prototyping; for proper projects you might want to implement your own run conditions, to support rebinding or other custom use cases.
use bevy::input::common_conditions::*;
app.add_systems(Update, (
handle_middleclick
.run_if(input_just_pressed(MouseButton::Middle)),
handle_drag
.run_if(input_pressed(MouseButton::Left)),
));
Mouse Scrolling / Wheel
To detect scrolling input, use MouseWheel
events:
use bevy::input::mouse::MouseWheel;
fn scroll_events(
mut scroll_evr: EventReader<MouseWheel>,
) {
use bevy::input::mouse::MouseScrollUnit;
for ev in scroll_evr.iter() {
match ev.unit {
MouseScrollUnit::Line => {
println!("Scroll (line units): vertical: {}, horizontal: {}", ev.y, ev.x);
}
MouseScrollUnit::Pixel => {
println!("Scroll (pixel units): vertical: {}, horizontal: {}", ev.y, ev.x);
}
}
}
}
The MouseScrollUnit
enum is important: it tells
you the type of scroll input. Line
is for hardware with fixed steps, like
the wheel on desktop mice. Pixel
is for hardware with smooth (fine-grained)
scrolling, like laptop touchpads.
You should probably handle each of these differently (with different sensitivity settings), to provide a good experience on both types of hardware.
Note: the Line
unit is not guaranteed to have whole number values/steps!
At least macOS does non-linear scaling / acceleration of
scrolling at the OS level, meaning your app will get weird values for the number
of lines, even when using a regular PC mouse with a fixed-stepping scroll wheel.
Mouse Motion
Use this if you don't care about the exact position of the mouse cursor, but rather you just want to see how much it moved from frame to frame. This is useful for things like controlling a 3D camera.
Use MouseMotion
events. Whenever the
mouse is moved, you will get an event with the delta.
use bevy::input::mouse::MouseMotion;
fn mouse_motion(
mut motion_evr: EventReader<MouseMotion>,
) {
for ev in motion_evr.iter() {
println!("Mouse moved: X: {} px, Y: {} px", ev.delta.x, ev.delta.y);
}
}
You might want to grab/lock the mouse inside the game window.
Mouse Cursor Position
Use this if you want to accurately track the position pointer / cursor. This is useful for things like clicking and hovering over objects in your game or UI.
You can get the current coordinates of the mouse pointer, from the respective
Window
(if the mouse is currently inside that window):
use bevy::window::PrimaryWindow;
fn cursor_position(
q_windows: Query<&Window, With<PrimaryWindow>>,
) {
// Games typically only have one window (the primary window)
if let Some(position) = q_windows.single().cursor_position() {
println!("Cursor is inside the primary window, at {:?}", position);
} else {
println!("Cursor is not in the game window.");
}
}
To detect when the pointer is moved, use CursorMoved
events to get the updated coordinates:
fn cursor_events(
mut cursor_evr: EventReader<CursorMoved>,
) {
for ev in cursor_evr.iter() {
println!(
"New cursor position: X: {}, Y: {}, in Window ID: {:?}",
ev.position.x, ev.position.y, ev.window
);
}
}
Note that you can only get the position of the mouse inside a window; you cannot get the global position of the mouse in the whole OS Desktop / on the screen as a whole.
The coordinates you get are in "window space". They represent window pixels, and the origin is the bottom left corner of the window. They do not relate to your camera or in-game coordinates in any way. See this cookbook example for converting these window cursor coordinates into world-space coordinates.
To track when the mouse cursor enters and leaves your window(s), use
CursorEntered
and CursorLeft
events.
Touchpad Gestures
Bevy supports the two-finger rotate and pinch-to-zoom gestures, but they currently only work on macOS, where the OS provides special events for them.
If you are interested in supporting these gestures in your app, you can do so
using TouchpadRotate
and
TouchpadMagnify
events:
use bevy::input::touchpad::{TouchpadMagnify, TouchpadRotate};
// these only work on macOS
fn touchpad_gestures(
mut evr_touchpad_magnify: EventReader<TouchpadMagnify>,
mut evr_touchpad_rotate: EventReader<TouchpadRotate>,
) {
for ev_magnify in evr_touchpad_magnify.iter() {
// Positive numbers are zooming in
// Negative numbers are zooming out
println!("Touchpad zoom by {}", ev_magnify.0);
}
for ev_rotate in evr_touchpad_rotate.iter() {
// Positive numbers are anticlockwise
// Negative numbers are clockwise
println!("Touchpad rotate by {}", ev_rotate.0);
}
}
Bevy Version: | 0.11 | (current) |
---|
Text / Character Input
Relevant official examples:
char_input_events
,
text_input
.
Use this (not keyboard input) if you want to implement text input in a Bevy app. This way, everything works as the user expects from their operating system, including Unicode support.
Bevy will produce a ReceivedCharacter
event for every Unicode code point coming from the OS.
This example shows how to let the user input text into a string (here stored as a local resource).
fn text_input(
mut evr_char: EventReader<ReceivedCharacter>,
kbd: Res<Input<KeyCode>>,
mut string: Local<String>,
) {
if kbd.just_pressed(KeyCode::Return) {
println!("Text input: {}", &*string);
string.clear();
}
if kbd.just_pressed(KeyCode::Back) {
string.pop();
}
for ev in evr_char.iter() {
// ignore control (special) characters
if !ev.char.is_control() {
string.push(ev.char);
}
}
}
Note: we are using Bevy's regular keyboard input to handle
the pressing of the enter and backspace keys. Character events are also sent
when these keys are pressed (they produce special control characters, like
ASCII newlines \n
), so, if we don't want these to be saved to our string,
we need to ignore them.
In your own application, you might also want to handle things like arrow keys in a way that is appropriate to your UI.
IME support
Bevy has support for IMEs (Input Method Editors), which is how people perform text input in languages with more complex scripts, like East Asian languages. It requires some special handling from you, however.
IMEs work by using a special "buffer", which shows the current in-progress text suggestions and allows users to select the correct characters before confirming them. The text suggestions / autocompletion is provided by the OS, but your app needs to display them for the user.
If you'd like all international users to be able to input text in their language, the way they usually do in other GUI apps on their OS, you should support IMEs.
To do this, you need to enable "IME mode" on the window, whenever you are expecting users to type text, and disable it afterwards. For example, if you prompt users to enter their name, before playing the game, you enable IME mode while the prompt is active.
While "IME mode" is enabled, if the user is using an IME, you will receive
Ime
events, instead of ReceivedCharacter
and regular keyboard input. However, if the user is not using an IME, then
everything will behave as normal, even when "IME mode" is enabled.
While the user has in-progress text, you will get Ime::Preedit
events, to tell
you the current contents of the "temporary buffer" and information about the
cursor/highlight you need to show, so that users can see what they are doing.
When the user confirms their input, you will get a Ime::Commit
event, to tell
you the text that the user wishes to insert into the app.
// for this simple example, we will just enable/disable IME mode on mouse click
fn ime_toggle(
mousebtn: Res<Input<MouseButton>>,
mut q_window: Query<&mut Window, With<PrimaryWindow>>,
) {
if mousebtn.just_pressed(MouseButton::Left) {
let mut window = q_window.single_mut();
// toggle "IME mode"
window.ime_enabled = !window.ime_enabled;
// We need to tell the OS the on-screen coordinates where the text will
// be displayed; for this simple example, let's just use the mouse cursor.
// In a real app, this might be the position of a UI text field, etc.
window.ime_position = window.cursor_position().unwrap();
}
}
fn ime_input(
mut evr_ime: EventReader<Ime>,
) {
for ev in evr_ime.iter() {
match ev {
Ime::Commit { value, .. } => {
println!("IME confirmed text: {}", value);
}
Ime::Preedit { value, cursor, .. } => {
println!("IME buffer: {:?}, cursor: {:?}", value, cursor);
}
Ime::Enabled { .. } => {
println!("IME mode enabled!");
}
Ime::Disabled { .. } => {
println!("IME mode disabled!");
}
}
}
}
For the sake of brevity, this example just prints the events to the console.
In a real app, you will want to display the "pre-edit" text on-screen, and use different formatting to show the cursor. On "commit", you can append the provided text to the actual string where you normally accept text input.
Bevy Version: | 0.9 | (outdated!) |
---|
Gamepad (Controller, Joystick)
Relevant official examples:
gamepad_input
,
gamepad_input_events
.
Bevy has support for gamepad input hardware: console controllers, joysticks, etc. Many different kinds of hardware should work, but if your device is not supported, you should file an issue with the gilrs project.
Gamepad IDs
Bevy assigns a unique ID (Gamepad
) to each connected
gamepad. This lets you associate the device with a specific player and
distinguish which one your inputs are coming from.
You can use the Gamepads
resource to list
the IDs of all the currently connected gamepad devices, or to check the
status of a specific one.
To detect when gamepads are connected or disconnected, you can use
GamepadEvent
events.
Example showing how to remember the first connected gamepad ID:
/// Simple resource to store the ID of the connected gamepad.
/// We need to know which gamepad to use for player input.
#[derive(Resource)]
struct MyGamepad(Gamepad);
fn gamepad_connections(
mut commands: Commands,
my_gamepad: Option<Res<MyGamepad>>,
mut gamepad_evr: EventReader<GamepadEvent>,
) {
for ev in gamepad_evr.iter() {
// the ID of the gamepad
let id = ev.gamepad;
match &ev.event_type {
GamepadEventType::Connected(info) => {
println!("New gamepad connected with ID: {:?}, name: {}", id, info.name);
// if we don't have any gamepad yet, use this one
if my_gamepad.is_none() {
commands.insert_resource(MyGamepad(id));
}
}
GamepadEventType::Disconnected => {
println!("Lost gamepad connection with ID: {:?}", id);
// if it's the one we previously associated with the player,
// disassociate it:
if let Some(MyGamepad(old_id)) = my_gamepad.as_deref() {
if *old_id == id {
commands.remove_resource::<MyGamepad>();
}
}
}
// other events are irrelevant
_ => {}
}
}
}
Handling Gamepad Inputs
You can handle the analog sticks and triggers with Axis<GamepadAxis>
(Axis
, GamepadAxis
). Buttons
can be handled with Input<GamepadButton>
(Input
,
GamepadButton
), similar to mouse
buttons or keyboard keys.
Notice that the names of buttons in the GamepadButton
are vendor-neutral (like South
and East
instead of X/O or A/B).
fn gamepad_input(
axes: Res<Axis<GamepadAxis>>,
buttons: Res<Input<GamepadButton>>,
my_gamepad: Option<Res<MyGamepad>>,
) {
let gamepad = if let Some(gp) = my_gamepad {
// a gamepad is connected, we have the id
gp.0
} else {
// no gamepad is connected
return;
};
// The joysticks are represented using a separate axis for X and Y
let axis_lx = GamepadAxis {
gamepad, axis_type: GamepadAxisType::LeftStickX
};
let axis_ly = GamepadAxis {
gamepad, axis_type: GamepadAxisType::LeftStickY
};
if let (Some(x), Some(y)) = (axes.get(axis_lx), axes.get(axis_ly)) {
// combine X and Y into one vector
let left_stick_pos = Vec2::new(x, y);
// Example: check if the stick is pushed up
if left_stick_pos.length() > 0.9 && left_stick_pos.y > 0.5 {
// do something
}
}
// In a real game, the buttons would be configurable, but here we hardcode them
let jump_button = GamepadButton {
gamepad, button_type: GamepadButtonType::South
};
let heal_button = GamepadButton {
gamepad, button_type: GamepadButtonType::East
};
if buttons.just_pressed(jump_button) {
// button just pressed: make the player jump
}
if buttons.pressed(heal_button) {
// button being held down: heal the player
}
}
You can also handle gamepad inputs using GamepadEvent
events:
fn gamepad_input_events(
my_gamepad: Option<Res<MyGamepad>>,
mut gamepad_evr: EventReader<GamepadEvent>,
) {
let gamepad = if let Some(gp) = my_gamepad {
// a gamepad is connected, we have the id
gp.0
} else {
// no gamepad is connected
return;
};
for ev in gamepad_evr.iter() {
if ev.gamepad != gamepad {
// event not from our gamepad
continue;
}
use GamepadEventType::{AxisChanged, ButtonChanged};
match ev.event_type {
AxisChanged(GamepadAxisType::RightStickX, x) => {
// Right Stick moved (X)
}
AxisChanged(GamepadAxisType::RightStickY, y) => {
// Right Stick moved (Y)
}
ButtonChanged(GamepadButtonType::DPadDown, val) => {
// buttons are also reported as analog, so use a threshold
if val > 0.5 {
// button pressed
}
}
_ => {} // don't care about other inputs
}
}
}
Gamepad Settings
You can use the GamepadSettings
resource
to configure dead-zones and other parameters of the various axes and
buttons. You can set the global defaults, as well as individually
per-axis/button.
Here is an example showing how to configure gamepads with custom settings (not necessarily good settings, please don't copy these blindly):
// this should be run once, when the game is starting
// (transition entering your in-game state might be a good place to put it)
fn configure_gamepads(
my_gamepad: Option<Res<MyGamepad>>,
mut settings: ResMut<GamepadSettings>,
) {
let gamepad = if let Some(gp) = my_gamepad {
// a gamepad is connected, we have the id
gp.0
} else {
// no gamepad is connected
return;
};
// add a larger default dead-zone to all axes (ignore small inputs, round to zero)
settings.default_axis_settings.set_deadzone_lowerbound(-0.1);
settings.default_axis_settings.set_deadzone_upperbound(0.1);
// make the right stick "binary", squash higher values to 1.0 and lower values to 0.0
let mut right_stick_settings = AxisSettings::default();
right_stick_settings.set_deadzone_lowerbound(-0.5);
right_stick_settings.set_deadzone_upperbound(0.5);
right_stick_settings.set_livezone_lowerbound(-0.5);
right_stick_settings.set_livezone_upperbound(0.5);
// the raw value should change by at least this much,
// for Bevy to register an input event:
right_stick_settings.set_threshold(0.01);
// make the triggers work in big/coarse steps, to get fewer events
// reduces noise and precision
let mut trigger_settings = AxisSettings::default();
trigger_settings.set_threshold(0.25);
// set these settings for the gamepad we use for our player
settings.axis_settings.insert(
GamepadAxis { gamepad, axis_type: GamepadAxisType::RightStickX },
right_stick_settings.clone()
);
settings.axis_settings.insert(
GamepadAxis { gamepad, axis_type: GamepadAxisType::RightStickY },
right_stick_settings.clone()
);
settings.axis_settings.insert(
GamepadAxis { gamepad, axis_type: GamepadAxisType::LeftZ },
trigger_settings.clone()
);
settings.axis_settings.insert(
GamepadAxis { gamepad, axis_type: GamepadAxisType::RightZ },
trigger_settings.clone()
);
// for buttons (or axes treated as buttons):
let mut button_settings = ButtonSettings::default();
// require them to be pressed almost all the way, to count
button_settings.set_press_threshold(0.9);
// require them to be released almost all the way, to count
button_settings.set_release_threshold(0.1);
settings.default_button_settings = button_settings;
}
Bevy Version: | 0.9 | (outdated!) |
---|
Touchscreen
Relevant official examples:
touch_input
,
touch_input_events
.
Multi-touch touchscreens are supported. You can track multiple fingers on the screen, with position and pressure/force information. Bevy does not offer gesture recognition.
The Touches
resource allows you to track any
fingers currently on the screen:
fn touches(
touches: Res<Touches>,
) {
// There is a lot more information available, see the API docs.
// This example only shows some very basic things.
for finger in touches.iter() {
if touches.just_pressed(finger.id()) {
println!("A new touch with ID {} just began.", finger.id());
}
println!(
"Finger {} is at position ({},{}), started from ({},{}).",
finger.id(),
finger.position().x,
finger.position().y,
finger.start_position().x,
finger.start_position().y,
);
}
}
Alternatively, you can use TouchInput
events:
fn touch_events(
mut touch_evr: EventReader<TouchInput>,
) {
use bevy::input::touch::TouchPhase;
for ev in touch_evr.iter() {
// in real apps you probably want to store and track touch ids somewhere
match ev.phase {
TouchPhase::Started => {
println!("Touch {} started at: {:?}", ev.id, ev.position);
}
TouchPhase::Moved => {
println!("Touch {} moved to: {:?}", ev.id, ev.position);
}
TouchPhase::Ended => {
println!("Touch {} ended at: {:?}", ev.id, ev.position);
}
TouchPhase::Cancelled => {
println!("Touch {} cancelled at: {:?}", ev.id, ev.position);
}
}
}
}
Bevy Version: | 0.9 | (outdated!) |
---|
Drag-and-Drop (Files)
Relevant official examples:
drag_and_drop
.
Bevy supports the Drag-and-Drop gesture common on most desktop operating systems, but only for files, not arbitrary data / objects.
If you drag a file (say, from the file manager app) into a Bevy app, Bevy
will produce a FileDragAndDrop
event,
containing the path of the file that was dropped in.
fn file_drop(
mut dnd_evr: EventReader<FileDragAndDrop>,
) {
for ev in dnd_evr.iter() {
println!("{:?}", ev);
if let FileDragAndDrop::DroppedFile { id, path_buf } = ev {
println!("Dropped file with path: {:?}, in window id: {:?}", path_buf, id);
}
}
}
Detecting the Position of the Drop
You may want to do different things depending on where the cursor was when the drop gesture ended. For example, add the file to some collection, if it was dropped over a specific UI element/panel.
Unfortunately, this is currently somewhat tricky to implement, due to winit
bug #1550. Bevy does not get CursorMoved
events while the drag gesture is ongoing, and therefore does not
respond to the mouse cursor. Bevy completely loses track of the cursor position.
Checking the cursor position from the Window
will also not work.
Systems that use cursor events to respond to cursor movements will not work
during a drag gesture. This includes Bevy UI's Interaction
detection, which is the usual way of detecting when a UI element is hovered over.
Workaround
The only way to workaround this issue is to store the file path somewhere
temporarily after receiving the drop event. Then, wait until the next
CursorMoved
event, and then process the file.
Note that this might not even be on the next frame update. The next cursor update will happen whenever the user moves the cursor. If the user does not immediately move the mouse after dropping the file and leaves the cursor in the same place for a while, there will be no events and your app will have no way of knowing the cursor position.
Bevy Version: | (any) |
---|
Window Management
This chapter covers topics related to working with the application's OS window.
Bevy Version: | 0.9 | (outdated!) |
---|
Window Properties
Page coming soon…
In the meantime, you can learn from Bevy's examples.
See the window_settings
example.
Bevy Version: | 0.9 | (outdated!) |
---|
Changing the Background Color
Relevant official examples:
clear_color
.
Click here for the full example code.
Use the ClearColor
resource to choose the
default background color. This color will be used as the default for all
cameras, unless overriden.
Note that the window will be black if no cameras exist. You must spawn at least one camera.
fn setup(
mut commands: Commands,
) {
commands.spawn(Camera2dBundle::default());
}
fn main() {
App::new()
// set the global default
.insert_resource(ClearColor(Color::rgb(0.9, 0.3, 0.6)))
.add_plugins(DefaultPlugins)
.add_startup_system(setup)
.run();
}
To override the default and use a different color for a specific
camera, you can set it using the Camera2d
or
Camera3d
components.
use bevy::core_pipeline::clear_color::ClearColorConfig;
// configure the background color (if any), for a specific camera (3D)
commands.spawn(Camera3dBundle {
camera_3d: Camera3d {
// clear the whole viewport with the given color
clear_color: ClearColorConfig::Custom(Color::rgb(0.8, 0.4, 0.2)),
..Default::default()
},
..Default::default()
});
// configure the background color (if any), for a specific camera (2D)
commands.spawn(Camera2dBundle {
camera_2d: Camera2d {
// disable clearing completely (pixels stay as they are)
// (preserves output from previous frame or camera/pass)
clear_color: ClearColorConfig::None,
},
..Default::default()
});
All of these locations (the components on specific cameras, the global default resource) can be mutated at runtime, and bevy will use your new color. Changing the default color using the resource will apply the new color to all existing cameras that do not specify a custom color, not just newly-spawned cameras.
Bevy Version: | 0.9 | (outdated!) |
---|
Grabbing the Mouse
Click here for the full example code.
Relevant official examples:
mouse_grab
.
You can lock/release the mouse cursor using bevy's window settings API.
Here is an example that locks and hides the cursor in the primary window
on mouse click and releases it when pressing
Esc
:
use bevy::window::CursorGrabMode;
fn cursor_grab_system(
mut windows: ResMut<Windows>,
btn: Res<Input<MouseButton>>,
key: Res<Input<KeyCode>>,
) {
let window = windows.get_primary_mut().unwrap();
if btn.just_pressed(MouseButton::Left) {
// if you want to use the cursor, but not let it leave the window,
// use `Confined` mode:
window.set_cursor_grab_mode(CursorGrabMode::Confined);
// for a game that doesn't use the cursor (like a shooter):
// use `Locked` mode to keep the cursor in one place
window.set_cursor_grab_mode(CursorGrabMode::Locked);
// also hide the cursor
window.set_cursor_visibility(false);
}
if key.just_pressed(KeyCode::Escape) {
window.set_cursor_grab_mode(CursorGrabMode::None);
window.set_cursor_visibility(true);
}
}
Bevy Version: | 0.9 | (outdated!) |
---|
Setting the Window Icon
Click here for the full example code.
You might want to set a custom Window Icon. On Windows and Linux, this is the icon image shown in the window title bar (if any) and task bar (if any).
Unfortunately, Bevy does not yet provide an easy and ergonomic built-in way
to do this. However, it can be done via the winit
APIs.
The way shown here is quite hacky. To save on code complexity, instead of
using Bevy's asset system to load the image in the background, we bypass
the assets system and directly load the file using the image
library.
There is some WIP on adding a proper API for this to Bevy; see PR #2268 and Issue #1031.
This example shows how to set the icon for the primary/main window, from a Bevy startup system.
use bevy::window::WindowId;
use bevy::winit::WinitWindows;
use winit::window::Icon;
fn set_window_icon(
// we have to use `NonSend` here
windows: NonSend<WinitWindows>,
) {
let primary = windows.get_window(WindowId::primary()).unwrap();
// here we use the `image` crate to load our icon data from a png file
// this is not a very bevy-native solution, but it will do
let (icon_rgba, icon_width, icon_height) = {
let image = image::open("my_icon.png")
.expect("Failed to open icon path")
.into_rgba8();
let (width, height) = image.dimensions();
let rgba = image.into_raw();
(rgba, width, height)
};
let icon = Icon::from_rgba(icon_rgba, icon_width, icon_height).unwrap();
primary.set_window_icon(Some(icon));
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_startup_system(set_window_icon)
.run();
}
Note: that WinitWindows
is a non-send
resource.
Note: you need to add winit
to your project's dependencies, and it must
be the same version as the one used by Bevy. You can use cargo tree
or
check Cargo.lock
to see which is the correct version. As of Bevy 0.9,
that should be winit = "0.27"
.
Bevy Version: | (any) |
---|
Bevy 2D
This chapter covers topics relevant to making 2D games with Bevy.
Bevy Version: | 0.11 | (current) |
---|
2D Camera Setup
Page coming soon…
In the meantime, you can learn from Bevy's examples.
Bevy Version: | 0.11 | (current) |
---|
Sprites and Atlases
Page coming soon…
In the meantime, you can learn from Bevy's examples.
Bevy Version: | (any) |
---|
Bevy 3D
This chapter covers topics relevant to making 3D games with Bevy.
Bevy Version: | 0.11 | (current) |
---|
3D Camera Setup
Page coming soon…
In the meantime, you can learn from Bevy's examples.
Bevy Version: | 0.9 | (outdated!) |
---|
3D Models and Scenes (GLTF)
Relevant official examples:
load_gltf
,
update_gltf_scene
.
Bevy uses the GLTF 2.0 file format for 3D assets.
(other formats may be unofficially available via 3rd-party plugins)
Quick-Start: Spawning 3D Models into your World
The simplest use case is to just load a "3D model" and spawn it into the game world.
"3D models" can often be complex, consisting of multiple parts. Think of a house: the windows, roof, doors, etc., are separate pieces, that are likely made of multiple meshes, materials, and textures. Bevy would technically need multiple ECS Entities to represent and render the whole thing.
This is why your GLTF "model" is represented by Bevy as a [Scene][cb::scene]. This way, you can easily spawn it, and Bevy will create all the relevant child entities and configure them correctly.
fn spawn_gltf(
mut commands: Commands,
ass: Res<AssetServer>,
) {
// note that we have to include the `Scene0` label
let my_gltf = ass.load("my.glb#Scene0");
// to position our 3d model, simply use the Transform
// in the SceneBundle
commands.spawn(SceneBundle {
scene: my_gltf,
transform: Transform::from_xyz(2.0, 0.0, -5.0),
..Default::default()
});
}
You could also use GLTF files to load an entire map/level. It works the same way.
The above example assumes that you have a simple GLTF file containing only one "default scene". GLTF is a very flexible file format. A single file can contain many "models" or more complex "scenes". To get a better understanding of GLTF and possible workflows, read the rest of this page. :)
Introduction to GLTF
GLTF is a modern open standard for exchanging 3D assets between different 3D software applications, like game engines and 3D modeling software.
The GLTF file format has two variants: human-readable ascii/text (*.gltf
)
and binary (*.glb
). The binary format is more compact and preferable
for packaging the assets with your game. The text format may be useful for
development, as it can be easier to manually inspect using a text editor.
A GLTF file can contain many objects (sub-assets): meshes, materials, textures, scenes, animation clips. When loading a GLTF file, Bevy will load all of the assets contained inside. They will be mapped to the appropriate Bevy-internal asset types.
The GLTF sub-assets
GLTF terminology can be confusing, as it sometimes uses the same words to refer to different things, compared to Bevy. This section will try explain the various GLTF terms.
To understand everything, it helps to mentally consider how these concepts are represented in different places: in your 3D modeling software (like Blender), in the GLTF file itself, and in Bevy.
GLTF Scenes are what you spawn into your game world. This is typically what you see on the screen in your 3D modeling software. Scenes combine all of the data needed for the game engine to create all the needed entities to represent what you want. Conceptually, think of a scene as one "unit". Depending on your use case, this could be one "3d model", or even a whole map or game level. In Bevy, these are represented as Bevy Scenes with all the child ECS entities.
GLTF Scenes are composed of GLTF Nodes. These describe the "objects"
in the scene, typically GLTF Meshes, but can also be other things like
Cameras and Lights. Each GLTF Node has a transform for positioning it in
the scene. GLTF Nodes do not have a core Bevy equivalent; Bevy just uses
this data to create the ECS Entities inside of a Scene. Bevy has a special
GltfNode
asset type, if you need access to this data.
GLTF Meshes represent one conceptual "3D object". These correspond
to the "objects" in your 3D modeling software. GLTF Meshes may be complex
and composed of multiple smaller pieces, called GLTF Primitives, each of
which may use a different Material. GLTF Meshes do not have a core Bevy
equivalent, but there is a special GltfMesh
asset type,
which describes the primitives.
GLTF Primitives are individual "units of 3D geometry", for the purposes of
rendering. They contain the actual geometry / vertex data, and reference the
Material to be used when drawing. In Bevy, each GLTF Primitive is represented
as a Bevy Mesh
asset, and must be spawned as a separate ECS
Entity to be rendered.
GLTF Materials describe the shading parameters for the surfaces of
your 3D models. They have full support for Physically-Based Rendering
(PBR). They also reference the textures to use. In Bevy, they are represented
as StandardMaterial
assets, as used by the Bevy
PBR 3D renderer.
GLTF Textures (images) can be embedded inside the GLTF file, or stored
externally in separate image files alongside it. For example, you can have
your textures as separate PNG/JPEG/KTX2 files for ease of development, or
package them all inside the GLTF file for ease of distribution. In Bevy,
GLTF textures are loaded as Bevy Image
assets.
GLTF Samplers describe the settings for how the GPU should use a
given Texture. Bevy does not keep these separate; this data is stored
inside the Bevy Image
asset (the sampler
field of type
SamplerDescriptor
).
GLTF Animations describe animations that interpolate various values,
such as transforms or mesh skeletons, over time. In Bevy, these are loaded
as AnimationClip
assets.
GLTF Usage Patterns
A single GLTF file can contain any number of sub-assets of any of the above types, referring to each other however they like.
Because GLTF is so flexible, it is up to you how to structure your assets.
A single GLTF file might be used:
- To represent a single "3D model", containing a single GLTF Scene with the model, so you can spawn it into your game.
- To represent a whole level, as a GLTF Scene, possibly also including the camera. This lets you load and spawn a whole level/map at once.
- To represent sections of a level/map, such as a rooms, as separate GLTF Scenes. They can share meshes and textures if needed.
- To contain a set of many different "3D models", each as a separate GLTF Scene. This lets you load and manage the whole collection at once and spawn them individually as needed.
- … others?
Tools for Creating GLTF Assets
If you are using a recent version of Blender (2.8+) for 3D modeling, GLTF is supported out of the box. Just export and choose GLTF as the format.
For other tools, you can try these exporter plugins:
- Old Blender (2.79)
- 3DSMax
- Autodesk Maya
- (or this alternative)
Be sure to check your export settings to make sure the GLTF file contains everything you expect.
If you need Tangents for normal maps, it is recommended that you include them in your GLTF files. This avoids Bevy having to autogenerate them at runtime. Many 3D editors do not enable this option by default.
Textures
For your Textures / image data, the GLTF format specification officially limits the supported formats to just PNG, JPEG, or Basis. However, Bevy does not enforce such "artificial limitations". You can use any image format supported by Bevy.
Your 3D editor will likely export your GLTF with PNG textures. This will "just work" and is nice for simple use cases.
However, mipmaps and compressed textures are very important to get good GPU performance, memory (VRAM) usage, and visual quality. You will only get these benefits if you use a format like KTX2 or DDS, that supports these features.
We recommend that you use KTX2, which natively supports all GPU texture
functionality + additional zstd
compression on top, to reduce file size.
If you do this, don't forget to enable the ktx2
and zstd
cargo
features for Bevy.
You can use the klafsa
tool to convert all the textures
used in your GLTF files from PNG/JPEG into KTX2, with mipmaps and GPU texture
compression of your choice.
TODO: show an example workflow for converting textures into the "optimal" format
Using GLTF Sub-Assets in Bevy
The various sub-assets contained in a GLTF file can be addressed in two ways:
- by index (integer id, in the order they appear in the file)
- by name (text string, the names you set in your 3D modeling software when creating the asset, which can be exported into the GLTF)
To get handles to the respective assets in Bevy, you can use the
Gltf
"master asset", or alternatively,
AssetPath with Labels.
Gltf
master asset
If you have a complex GLTF file, this is likely the most flexible and useful way of navigating its contents and using the different things inside.
You have to wait for the GLTF file to load, and then use the Gltf
asset.
use bevy::gltf::Gltf;
/// Helper resource for tracking our asset
#[derive(Resource)]
struct MyAssetPack(Handle<Gltf>);
fn load_gltf(
mut commands: Commands,
ass: Res<AssetServer>,
) {
let gltf = ass.load("my_asset_pack.glb");
commands.insert_resource(MyAssetPack(gltf));
}
fn spawn_gltf_objects(
mut commands: Commands,
my: Res<MyAssetPack>,
assets_gltf: Res<Assets<Gltf>>,
) {
// if the GLTF has loaded, we can navigate its contents
if let Some(gltf) = assets_gltf.get(&my.0) {
// spawn the first scene in the file
commands.spawn(SceneBundle {
scene: gltf.scenes[0].clone(),
..Default::default()
});
// spawn the scene named "YellowCar"
commands.spawn(SceneBundle {
scene: gltf.named_scenes["YellowCar"].clone(),
transform: Transform::from_xyz(1.0, 2.0, 3.0),
..Default::default()
});
// PERF: the `.clone()`s are just for asset handles, don't worry :)
}
}
For a more convoluted example, say we want to directly create a 3D PBR entity, for whatever reason. (This is not recommended; you should probably just use scenes)
use bevy::gltf::GltfMesh;
fn gltf_manual_entity(
mut commands: Commands,
my: Res<MyAssetPack>,
assets_gltf: Res<Assets<Gltf>>,
assets_gltfmesh: Res<Assets<GltfMesh>>,
) {
if let Some(gltf) = assets_gltf.get(&my.0) {
// Get the GLTF Mesh named "CarWheel"
// (unwrap safety: we know the GLTF has loaded already)
let carwheel = assets_gltfmesh.get(&gltf.named_meshes["CarWheel"]).unwrap();
// Spawn a PBR entity with the mesh and material of the first GLTF Primitive
commands.spawn(PbrBundle {
mesh: carwheel.primitives[0].mesh.clone(),
// (unwrap: material is optional, we assume this primitive has one)
material: carwheel.primitives[0].material.clone().unwrap(),
..Default::default()
});
}
}
AssetPath with Labels
This is another way to access specific sub-assets. It is less reliable, but may be easier to use in some cases.
Use the AssetServer
to convert a path string into a
Handle
.
The advantage is that you can get handles to your sub-assets immediately, even if your GLTF file hasn't loaded yet.
The disadvantage is that it is more error-prone. If you specify a sub-asset that doesn't actually exist in the file, or mis-type the label, or use the wrong label, it will just silently not work. Also, currently only using a numerial index is supported. You cannot address sub-assets by name.
fn use_gltf_things(
mut commands: Commands,
ass: Res<AssetServer>,
) {
// spawn the first scene in the file
let scene0 = ass.load("my_asset_pack.glb#Scene0");
commands.spawn(SceneBundle {
scene: scene0,
..Default::default()
});
// spawn the second scene
let scene1 = ass.load("my_asset_pack.glb#Scene1");
commands.spawn(SceneBundle {
scene: scene1,
transform: Transform::from_xyz(1.0, 2.0, 3.0),
..Default::default()
});
}
The following asset labels are supported ({}
is the numerical index):
Scene{}
: GLTF Scene as BevyScene
Node{}
: GLTF Node asGltfNode
Mesh{}
: GLTF Mesh asGltfMesh
Mesh{}/Primitive{}
: GLTF Primitive as BevyMesh
Mesh{}/Primitive{}/MorphTargets
: Morph target animation data for a GLTF PrimitiveTexture{}
: GLTF Texture as BevyImage
Material{}
: GLTF Material as BevyStandardMaterial
DefaultMaterial
: as above, if the GLTF file contains a default material with no indexAnimation{}
: GLTF Animation as BevyAnimationClip
Skin{}
: GLTF mesh skin as BevySkinnedMeshInverseBindposes
The GltfNode
and GltfMesh
asset types are only useful to help you navigate the contents of
your GLTF file. They are not core Bevy renderer types, and not used
by Bevy in any other way. The Bevy renderer expects Entities with
MaterialMeshBundle
; for that you need the
Mesh
and StandardMaterial
.
Bevy Limitations
Bevy does not fully support all features of the GLTF format and has some specific requirements about the data. Not all GLTF files can be loaded and rendered in Bevy. Unfortunately, in many of these cases, you will not get any error or diagnostic message.
Commonly-encountered limitations:
- Textures embedded in ascii (
*.gltf
) files (base64 encoding) cannot be loaded. Put your textures in external files, or use the binary (*.glb
) format. - Mipmaps are only supported if the texture files (in KTX2 or DDS format) contain them. The GLTF spec requires missing mipmap data to be generated by the game engine, but Bevy does not support this yet. If your assets are missing mipmaps, textures will look grainy/noisy.
This list is not exhaustive. There may be other unsupported scenarios that I did not know of or forgot to include here. :)
Bevy Version: | (any) |
---|
Bevy Render (GPU) Framework
NOTE: This chapter of the book is an early Work in Progress! Many links are still broken!
This chapter covers Bevy's rendering framework and how to work with the GPU.
Make sure you are well familiar with Bevy's Core Programming Framework. Everything here builds on top of it.
Here you will learn how to write custom rendering code. If you are simply interested in using the existing graphical features provided by Bevy, check out the chapters about 2D and 3D.
Bevy Version: | 0.9 | (outdated!) |
---|
Render Architecture Overview
NOTE: This chapter of the book is an early Work in Progress! Many links are still broken!
The current Bevy render architecture premiered in Bevy 0.6. The news blog post is another place you can learn about it. :)
It was inspired by the Destiny Render Architecture (from the Destiny game).
Pipelined Rendering
Bevy's renderer is architected in a way that operates independently from all the normal app logic. It operates in its own separate ECS World and has its own schedule, with stages and systems.
The plan is that, in a future Bevy version, the renderer will run in parallel with all the normal app logic, allowing for greater performance. This is called "pipelined rendering": rendering the previous frame at the same time as the app is processing the next frame update.
Every frame, the two parts are synchronized in a special stage called "Extract". The Extract stage has access to both ECS Worlds, allowing it to copy data from the main World into the render World.
From then on, the renderer only has access to the render World, and can only use data that is stored there.
Every frame, all entities in the render World are erased, but resources are kept. If you need to persist data from frame to frame, store it in resources. Dynamic data that could change every frame should be copied into the render world in the Extract stage, and typically stored using entities and components.
Core Architecture
The renderer operates in multiple render stages. This is how the work that needs to be performed on the CPU is managed.
The ordering of the workloads to be performed on the GPU is controlled using the render graph. The graph consists of nodes, each representing a workload for the GPU, typically a render pass. The nodes are connected using edges, representing their ordering/dependencies with regard to one another.
Layers of Abstraction
The Bevy rendering framework can accomodate you working at various different levels of abstraction, depending on how much you want to integrate with the Bevy ecosystem and built-in features, vs. have more direct control over the GPU.
For most things, you would be best served by the "high-level" or "mid-level" APIs.
Low-Level
Bevy works directly with wgpu
, a Rust-based cross-platform
graphics API. It is the abstraction layer over the GPU APIs of the underlying
platform. This way, the same GPU code can work on all
supported platforms. The API design of wgpu
is based on
the WebGPU standard, but with extensions to support native platform features,
going beyond the limitations of the web platform.
wgpu
(and hence Bevy) supports the following backends:
Platform | Backends (in order of priority) |
---|---|
Linux | Vulkan, GLES3 |
Windows | DirectX 12, Vulkan, GLES3 |
macOS | Metal |
iOS | Metal |
Android | Vulkan, GLES3 |
Web | WebGPU, WebGL2 |
On GLES3 and WebGL2, some renderer features are unsupported and performance is worse.
WebGPU is experimental and few browsers support it.
wgpu
forms the "lowest level" of Bevy rendering. If you really need the
most direct control over the GPU, you can pretty much use wgpu
directly,
from within the Bevy render framework.
Mid-Level
On top of wgpu
, Bevy provides some abstractions that can help you, and
integrate better with the rest of Bevy.
The first is pipeline caching and specialization. If you create your render pipelines via this interface, Bevy can manage them efficiently for you, creating them when they are first used, and then caching and reusing them, for optimal performance.
Caching and specialization are, analogously, also available for GPU Compute pipelines.
Similar to the pipeline cache, there is a texture cache. This is what you use for rendering-internal textures (for example: shadow maps, reflection maps, …), that do not originate from assets. It will manage and reuse the GPU memory allocation, and free it when it becomes unused.
For using data from assets, Bevy provides the Render Asset abstraction to help with extracting the data from different asset types.
Bevy can manage all the "objects to draw" using phases, which sort and draw phase items. This way, Bevy can sort each object to render, relative to everything else in the scene, for optimal performance and correct transparency (if any).
Phase Items are defined using render commands and/or draw functions. These are, conceputally, the rendering equivalents of ECS systems and exclusive systems, fetching data from the ECS World and generating draw calls for the GPU.
All of these things fit into the core architecture of the Bevy render graph and render stages. During the Render stage, graph nodes will execute render passes with the render phases, to draw everything as it was set up in the Prepare/Queue/PhaseSort stages.
The bevy_core_pipeline
crate defines a set of standard
phase/item and main pass types. If you can, you
should work with them, for best compatibility with the Bevy ecosystem.
High-Level
On top of all the mid-level APIs, Bevy provides abstractions to make many common kinds of workloads easier.
The most notable higher-level features are meshes and materials.
Meshes are the source of per-vertex data (vertex attributes) to be fed into your shaders. The material specifies what shaders to use and any other data that needs to be fed into it, like textures.
Bevy Version: | 0.9 | (outdated!) |
---|
Render Stages
Everything on the CPU side (the whole process of driving the GPU workloads) is structured in a sequence of "render stages":
Timings
Note: Pipelined rendering is not yet actually enabled in Bevy 0.9. This section explains the intended behavior, which will land in a future Bevy version. You have to understand it, because any custom rendering code you write will have to work with it in mind.
Every frame, Extract serves as the synchronization point.
When the Render Schedule completes, it will start again, but Extract will wait for the App Schedule, if it has not completed yet. The App Schedule will start again as soon as Extract has completed.
Therefore:
- in an App-bound scenario (if app takes longer than render):
- The start of Extract is waiting for App to finish
- in a Render-bound scenario (if render takes longer than app):
- The start of App is waiting for Extract to finish
If vsync is enabled, the wait for the next refresh of the screen will happen in the Prepare stage. This has the effect of prolonging the Prepare stage in the Render schedule. Therefore, in practice, your game will behave like the "Render-bound" scenario shown above.
The final render (the framebuffer with the pixels to show in the window) is presented to the OS/driver at the end of the Render stage.
Bevy updates its timing information (in Res<Time>
)
at the start of the First stage in the main App schedule. The value to
use is measured at "presentation time", in the render world, and the
Instant
is sent over a channel, to be applied on the
next frame.
Adding Systems to Render Stages
If you are implementing custom rendering functionality in Bevy, you will likely need to add some of your own systems to at least some of the render stages:
-
Anything that needs data from your main App World will need a system in Extract to copy that data. In practice, this is almost everything, unless it is fully contained on the GPU, or only uses renderer-internal generated data.
-
Most use cases will need to do some setup of GPU resources in Prepare and/or Queue.
-
In Cleanup, all entities are cleared automatically. If you have some custom data stored in resources, you can let it stay for the next frame, or add a system to clear it, if you want.
The way Bevy is set up, you shouldn't need to do anything in Render or PhaseSort. If your custom rendering is part of the Bevy render graph, it will just be handled automatically when Bevy executes the render graph in the Render stage. If you are implementing custom phase items, the Main Pass render graph node will render them together with everything else.
You can add your rendering systems to the respective stages, using the render sub-app:
// TODO: code example
Extract
Extract is a very important and special stage. It is the synchronization point that links the two ECS Worlds. This is where the data required for rendering is copied ("extracted") from the main App World into the Render World, allowing for pipelined rendering.
During the Extract stage, nothing else can run in parallel, on either the main App World or the Render World. Hence, Extract should be kept minimal and complete its work as quickly as possible.
It is recommended that you avoid doing any computations in Extract, if possible. Just copy data.
It is recommended that you only copy the data you actually need for rendering. Create new component types and resources just for use within the render World, with only the data you need.
For example, Bevy's 2D sprites uses a struct ExtractedSprite
, where it copies the relevant data
from the "user-facing" components of sprite and spritesheet entities in the
main World.
Bevy reserves Entity IDs in the render World, matching all the Entities existing in the main World. In most cases, you do not need to spawn new entities in the render World. You can just insert components with Commands on the same Entity IDs as from the main World.
// TODO: code example
Prepare
Prepare is the stage to use if you need to set up any data on the GPU. This is where you can create GPU buffers, textures, and bind groups.
// TODO: elaborate on different ways Bevy is using it internally
// TODO: code example
Queue
Queue is the stage where you can set up the "rendering jobs" you will need to execute.
Typically, this means creating phase items with the correct render pipeline and draw function, for everything that you need to draw.
For other things, analogously, Queue is where you would set up the workloads (like compute or draw calls) that the GPU would need to perform.
// TODO: elaborate on different ways Bevy is using it internally
// TODO: code example
PhaseSort
This stage exists for Bevy to sort all of the phase items that were set up during the Queue stage, before rendering in the Render stage.
It is unlikely that you will need to add anything custom here. I'm not aware of use cases. Let me know if you know of any.
Render
Render is the stage where Bevy executes the Render Graph.
The built-in behavior is configured using Cameras. For each active Camera, Bevy will execute its associated render graph, configured to output to its associated render target.
If you are using any of the standard render phases, you don't need to do anything. Your custom phase items will be rendered automatically as part of the Main Pass built-in render graph nodes, alongside everything else.
If you are implementing a rendering feature that needs a separate step, you can add it as a render graph node, and it will be rendered automatically.
The only time you might need to do something custom here is if you really
want to sidestep Bevy's frameworks and reach for low-level wgpu
access.
You could place it in the Render stage.
Cleanup
Bevy has a built-in system in Cleanup that clears all entities in the render World. Therefore, all data stored in components will be lost. It is expected that fresh data will be obtained in the next frame's Extract stage.
To persist rendering data over multiple frames, you should store it in resources. That way you have control over it.
If you need to clear some data from your resources sometimes, you could add a custom system to the Cleanup stage to do it.
// TODO: code example
Bevy Version: | (any) |
---|
Programming Patterns
This chapter is about any non-obvious tricks, programming techniques, patterns and idioms, that may be useful when programming with Bevy.
These topics are an extension of the topics covered in the Bevy Programming Framework chapter. See that chapter to learn the foundational concepts.
Some of the things covered in this chapter might be controversial or only useful to specific use cases. Don't take this chapter as teaching "general best practice".
Bevy Version: | 0.9 | (outdated!) |
---|
Generic Systems
Bevy systems are just plain rust functions, which means they can be generic. You can add the same system multiple times, parametrized to work on different Rust types or values.
Generic over Component types
You can use the generic type parameter to specify what component types (and hence what entities) your system should operate on.
This can be useful when combined with Bevy states. You can do the same thing to different sets of entities depending on state.
Example: Cleanup
One straightforward use-case is for cleanup. We can make a generic cleanup system that just despawns all entities that have a certain component type. Then, trivially run it on exiting different states.
use bevy::ecs::component::Component;
fn cleanup_system<T: Component>(
mut commands: Commands,
q: Query<Entity, With<T>>,
) {
for e in q.iter() {
commands.entity(e).despawn_recursive();
}
}
Menu entities can be tagged with cleanup::MenuExit
, entities from the game
map can be tagged with cleanup::LevelUnload
.
We can add the generic cleanup system to our state transitions, to take care of the respective entities:
/// Marker components to group entities for cleanup
mod cleanup {
use bevy::prelude::*;
#[derive(Component)]
pub struct LevelUnload;
#[derive(Component)]
pub struct MenuClose;
}
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
enum AppState {
MainMenu,
InGame,
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_state(AppState::MainMenu)
// add the cleanup systems
.add_system_set(SystemSet::on_exit(AppState::MainMenu)
.with_system(cleanup_system::<cleanup::MenuClose>))
.add_system_set(SystemSet::on_exit(AppState::InGame)
.with_system(cleanup_system::<cleanup::LevelUnload>))
.run();
}
Using Traits
You can use this in combination with Traits, for when you need some sort of varying implementation/functionality for each type.
Example: Bevy's Camera Projections
(this is a use-case within Bevy itself)
Bevy has a CameraProjection
trait. Different
projection types like PerspectiveProjection
and OrthographicProjection
implement that
trait, providing the correct logic for how to respond to resizing the window,
calculating the projection matrix, etc.
There is a generic system fn camera_system::<T: CameraProjection + Component>
, which handles all the cameras with a given projection type. It
will call the trait methods when appropriate (like on window resize events).
The Bevy Cookbook Custom Camera Projection Example shows this API in action.
Using Const Generics
Now that Rust has support for Const Generics, functions can also be parametrized by values, not just types.
fn process_layer<const LAYER_ID: usize>(
// system params
) {
// do something for this `LAYER_ID`
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_system(process_layer::<1>)
.add_system(process_layer::<2>)
.add_system(process_layer::<3>)
.run();
}
Note that these values are static / constant at compile-time. This can be a severe limitation. In some cases, when you might suspect that you could use const generics, you might realize that you actually want a runtime value.
If you need to "configure" your system by passing in some data, you could, instead, use a Resource or Local.
Note: As of Rust 1.65, support for using enum
values as const generics is
not yet stable. To use enum
s, you need Rust Nightly, and to enable the
experimental/unstable feature (put this at the top of your main.rs
or
lib.rs
):
#![feature(adt_const_params)]
Bevy Version: | 0.9 | (outdated!) |
---|
Component Storage (Table/Sparse-Set)
Bevy ECS provides two different ways of storing data: tables and sparse sets. The two storage kinds offer different performance characteristics.
The kind of storage to be used can be chosen per component
type. When you derive the Component
trait, you can
specify it. The default, if unspecified, is table storage. You can have
components with a mixture of different storage kinds on the same entity.
The rest of this page is dedicated to explaining the performance trade-offs and why you might want to choose one storage kind vs. the other.
/// Component for entities that can cast magic spells
#[derive(Component)] // Use the default table storage
struct Mana {
mana: f32,
}
/// Component for enemies that currently "see" the player
/// Every frame, add/remove to entities based on visibility
/// (use sparse-set storage due to frequent add/remove)
#[derive(Component)]
#[component(storage = "SparseSet")]
struct CanSeePlayer;
/// Component for entities that are currently taking bleed damage
/// Add to entities to apply bleed effect, remove when done
/// (use sparse-set storage to not fragment tables,
/// as this is a "temporary effect")
#[derive(Component)]
#[component(storage = "SparseSet")]
struct Bleeding {
damage_rate: f32,
}
Table Storage
Table storage is optimized for fast query iteration. If the way you usually use a specific component type is to iterate over its data across many entities, this will offer the best performance.
However, adding/removing table components to existing entities is a relatively slow operation. It requires copying the data of all table components for the entity to a different location in memory.
It's OK if you have to do this sometimes, but if you are likely to add/remove a component very frequently, you might want to switch that component type to sparse-set storage.
You can see why table storage was chosen as Bevy's default. Most component types are rarely added/removed in practice. You typically spawn entities with all the components they should have, and then access the data via queries, usually every frame. Sometimes you might add or remove a component to change an entity's behavior, but probably not nearly as often, or every frame.
Sparse-Set Storage
Sparse-Set storage is optimized for fast adding/removing of a component to existing entities, at the cost of slower querying. It can be more efficient for components that you would like to add/remove very frequently.
An example of this might be a marker component indicating whether an enemy is currently aware of the player. You might want to have such a component type, so that you can easily use a query filter to find all the enemies that are currently tracking the player. However, this is something that can change every frame, as enemies or the player move around the game level. If you add/remove this component every time the visibility status changed, that's a lot of additions and removals.
You can see that situations like these are more niche and do not apply to most typical component types. Treat sparse-set storage as a potential optimization you could try in specific circumstances.
Even in situations like the example above, it might not be a performance win. Everything depends on your application's unique usage patterns. You have to measure and try.
Table Fragmentation
Furthermore, the actual memory layout of the "tables" depends on the set of all table components that each of your entities has.
ECS queries perform best when many of the entities they match have the same overall set of components.
Having a large number of entities, that all have the same component types, is very efficient in terms of data access performance. Having diverse entities with a varied mixture of different component types, means that their data will be fragmented in memory and be less efficient to access.
Sparse-Set components do not affect the memory layout of tables. Hence, components that are only used on a few entities or as a "temporary effect", might also be good candidates for sparse-set storage. That way they don't fragment the memory of the other (table) components. Systems that do not care about these components will be completely unaffected by them existing.
Overall Advice
While this page describes the general performance characteristics and gives some guidelines, you often cannot know if something improves performance without benchmarking.
When your game grows complex enough and you have something to benchmark, you could try to apply sparse-set storage to situations where it might make sense, as described above, and see how it affects your results.
Bevy Version: | 0.9 | (outdated!) |
---|
Manual Event Clearing
Click here to download a full example file with the code from this page.
The event queue needs to be cleared periodically, so that it does not grow indefinitely and waste unbounded memory.
Bevy's default cleanup strategy is to clear events every frame, but with double buffering, so that events from the previous frame update stay available. This means that you can handle the events only until the end of the next frame after the one when they are sent.
This default works well for systems that run every frame and check for events every time, which is the typical usage pattern.
However, if you have systems that do not read events every frame, they might miss some events. Some common scenarios where this occurs are:
- systems with an early-return, that don't read events every time they run
- when using fixed timestep
- systems that only run in specific states, such as if your game has a pause state
- when using custom run criteria to control your systems
To be able to reliably manage events in such circumstances, you might want to have manual control over how long the events are held in memory.
You can replace Bevy's default cleanup strategy with your own.
To do this, simply add your event type (wrapped as Events<T>
)
to the app builder using .init_resource
, instead of .add_event
.
(.add_event
is actually just a convenience method that initializes the
resource and adds Bevy's built-in system (generic
over your event type) for the default cleanup strategy)
You must then clear the events at your discretion. If you don't do this often enough, your events might pile up and waste memory.
Example
We can create generic systems for this. Implement
the custom cleanup strategy, and then add that system to your
App
as many times as you need, for each event type
where you want to use your custom behavior.
use bevy::ecs::event::Events;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// add the `Events<T>` resource manually
// these events will not have automatic cleanup
.init_resource::<Events<MySpecialEvent>>()
// this is a regular event type with automatic cleanup
.add_event::<MyRegularEvent>()
// add the cleanup systems
.add_system(my_event_manager::<MySpecialEvent>)
.run();
}
/// Custom cleanup strategy for events
///
/// Generic to allow using for any custom event type
fn my_event_manager<T: 'static + Send + Sync>(
mut events: ResMut<Events<T>>,
) {
// TODO: implement your custom logic
// for deciding when to clear the events
// clear all events like this:
events.clear();
// or with double-buffering
// (this is what Bevy's default strategy does)
events.update();
// or drain them, if you want to iterate,
// to access the values:
for event in events.drain() {
// TODO: do something with each event
}
}
Bevy Version: | 0.9 | (outdated!) |
---|
Writing Tests for Systems
You might want to write and run automated tests for your systems.
You can use the regular Rust testing features (cargo test
) with Bevy.
To do this, you can create an empty ECS World
in your
tests, and then, using direct World access, insert whatever
entities and resources you need for testing. Create
a standalone stage with the systems you want to
run, and manually run it on the World
.
Bevy's official repository has a fantastic example of how to do this.
Bevy Version: | (any) |
---|
Bevy Cookbook
This chapter shows you how to do various practical things using Bevy.
Indended as a supplement to Bevy's official examples.
The examples are written to only focus on the relevant information for the task at hand.
Only the relevant parts of the code are shown. Full compilable example files are available and linked on each page.
It is assumed that you are already familiar with Bevy Programming.
Bevy Version: | 0.9 | (outdated!) |
---|
Show Framerate in Console
Click here for the full example code.
You can use bevy's builtin diagnostics system to print framerate (FPS) to the console, for monitoring performance.
use bevy::diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugin(LogDiagnosticsPlugin::default())
.add_plugin(FrameTimeDiagnosticsPlugin::default())
.run();
}
Bevy Version: | 0.9 | (outdated!) |
---|
Convert cursor to world coordinates
Click here for the full example code.
3D games
There is a good (unofficial) plugin:
bevy_mod_picking
.
2D games
Starting from Bevy 0.9, there are camera methods to help you convert between screen-space (viewport) and world-space coordinates. We can use this to easily find the position of the mouse cursor.
This code will work regardless of the camera's projection settings and transform.
(there will likely be slight inaccuracy from floating-point calculations)
/// Used to help identify our main camera
#[derive(Component)]
struct MainCamera;
fn setup(mut commands: Commands) {
commands.spawn((Camera2dBundle::default(), MainCamera));
}
fn my_cursor_system(
// need to get window dimensions
windows: Res<Windows>,
// query to get camera transform
camera_q: Query<(&Camera, &GlobalTransform), With<MainCamera>>,
) {
// get the camera info and transform
// assuming there is exactly one main camera entity, so query::single() is OK
let (camera, camera_transform) = camera_q.single();
// get the window that the camera is displaying to (or the primary window)
let window = if let RenderTarget::Window(id) = camera.target {
windows.get(id).unwrap()
} else {
windows.get_primary().unwrap()
};
// check if the cursor is inside the window and get its position
// then, ask bevy to convert into world coordinates, and truncate to discard Z
if let Some(world_position) = window.cursor_position()
.and_then(|cursor| camera.viewport_to_world(camera_transform, cursor))
.map(|ray| ray.origin.truncate())
{
eprintln!("World coords: {}/{}", world_position.x, world_position.y);
}
}
In older versions of Bevy, there were no such coordinate conversion methods, and the math had to be done manually. If you are interested in how that works, see the example from an old version of the book, here.
Bevy Version: | 0.9 | (outdated!) |
---|
Custom Camera Projection
Click here for the full example code.
Note: this example is showing you how to do something not officially supported/endorsed by Bevy. Do at your own risk.
Camera with a custom projection (not using one of Bevy's standard perspective or orthographic projections).
You could also use this to change the coordinate system, if you insist on using something other than Bevy's default coordinate system, for whatever reason.
Here we implement a simple orthographic projection that maps -1.0
to 1.0
to the vertical axis of the window, and respects the window's aspect ratio
for the horizontal axis:
See how Bevy constructs its camera bundles, for reference:
This example is based on the setup for a 2D camera:
use bevy::core_pipeline::tonemapping::Tonemapping;
use bevy::render::primitives::Frustum;
use bevy::render::camera::{Camera, CameraProjection};
use bevy::render::view::VisibleEntities;
#[derive(Component, Debug, Clone, Reflect)]
#[reflect(Component, Default)]
struct SimpleOrthoProjection {
near: f32,
far: f32,
aspect: f32,
}
impl CameraProjection for SimpleOrthoProjection {
fn get_projection_matrix(&self) -> Mat4 {
Mat4::orthographic_rh(
-self.aspect, self.aspect, -1.0, 1.0, self.near, self.far
)
}
// what to do on window resize
fn update(&mut self, width: f32, height: f32) {
self.aspect = width / height;
}
fn far(&self) -> f32 {
self.far
}
}
impl Default for SimpleOrthoProjection {
fn default() -> Self {
Self { near: 0.0, far: 1000.0, aspect: 1.0 }
}
}
fn setup(mut commands: Commands) {
// We need all the components that Bevy's built-in camera bundles would add
// Refer to the Bevy source code to make sure you do it correctly:
// here we show a 2d example
let projection = SimpleOrthoProjection::default();
// position the camera like bevy would do by default for 2D:
let transform = Transform::from_xyz(0.0, 0.0, projection.far - 0.1);
// frustum construction code copied from Bevy
let view_projection =
projection.get_projection_matrix() * transform.compute_matrix().inverse();
let frustum = Frustum::from_view_projection(
&view_projection,
&transform.translation,
&transform.back(),
projection.far,
);
commands.spawn((
bevy::render::camera::CameraRenderGraph::new(bevy::core_pipeline::core_2d::graph::NAME),
projection,
frustum,
transform,
GlobalTransform::default(),
VisibleEntities::default(),
Camera::default(),
Camera2d::default(),
Tonemapping::Disabled,
));
}
fn main() {
// need to add bevy-internal camera projection management functionality
// for our custom projection type
use bevy::render::camera::CameraProjectionPlugin;
App::new()
.add_plugins(DefaultPlugins)
.add_startup_system(setup)
.add_plugin(CameraProjectionPlugin::<SimpleOrthoProjection>::default())
.run();
}
Bevy Version: | 0.9 | (outdated!) |
---|
Pan + Orbit Camera
Click here for the full example code.
This code is a community contribution.
Current version developed by @mirenbharta. Initial work by @skairunner.
This is a camera controller similar to the ones in 3D editors like Blender.
Use the right mouse button to rotate, middle button to pan, scroll wheel to move inwards/outwards.
This is largely shown for illustrative purposes, as an example
to learn from. In your projects, you may want to try the
[bevy_config_cam
][project::bevy_config_cam] plugin.
/// Tags an entity as capable of panning and orbiting.
#[derive(Component)]
struct PanOrbitCamera {
/// The "focus point" to orbit around. It is automatically updated when panning the camera
pub focus: Vec3,
pub radius: f32,
pub upside_down: bool,
}
impl Default for PanOrbitCamera {
fn default() -> Self {
PanOrbitCamera {
focus: Vec3::ZERO,
radius: 5.0,
upside_down: false,
}
}
}
/// Pan the camera with middle mouse click, zoom with scroll wheel, orbit with right mouse click.
fn pan_orbit_camera(
windows: Res<Windows>,
mut ev_motion: EventReader<MouseMotion>,
mut ev_scroll: EventReader<MouseWheel>,
input_mouse: Res<Input<MouseButton>>,
mut query: Query<(&mut PanOrbitCamera, &mut Transform, &Projection)>,
) {
// change input mapping for orbit and panning here
let orbit_button = MouseButton::Right;
let pan_button = MouseButton::Middle;
let mut pan = Vec2::ZERO;
let mut rotation_move = Vec2::ZERO;
let mut scroll = 0.0;
let mut orbit_button_changed = false;
if input_mouse.pressed(orbit_button) {
for ev in ev_motion.iter() {
rotation_move += ev.delta;
}
} else if input_mouse.pressed(pan_button) {
// Pan only if we're not rotating at the moment
for ev in ev_motion.iter() {
pan += ev.delta;
}
}
for ev in ev_scroll.iter() {
scroll += ev.y;
}
if input_mouse.just_released(orbit_button) || input_mouse.just_pressed(orbit_button) {
orbit_button_changed = true;
}
for (mut pan_orbit, mut transform, projection) in query.iter_mut() {
if orbit_button_changed {
// only check for upside down when orbiting started or ended this frame
// if the camera is "upside" down, panning horizontally would be inverted, so invert the input to make it correct
let up = transform.rotation * Vec3::Y;
pan_orbit.upside_down = up.y <= 0.0;
}
let mut any = false;
if rotation_move.length_squared() > 0.0 {
any = true;
let window = get_primary_window_size(&windows);
let delta_x = {
let delta = rotation_move.x / window.x * std::f32::consts::PI * 2.0;
if pan_orbit.upside_down { -delta } else { delta }
};
let delta_y = rotation_move.y / window.y * std::f32::consts::PI;
let yaw = Quat::from_rotation_y(-delta_x);
let pitch = Quat::from_rotation_x(-delta_y);
transform.rotation = yaw * transform.rotation; // rotate around global y axis
transform.rotation = transform.rotation * pitch; // rotate around local x axis
} else if pan.length_squared() > 0.0 {
any = true;
// make panning distance independent of resolution and FOV,
let window = get_primary_window_size(&windows);
if let Projection::Perspective(projection) = projection {
pan *= Vec2::new(projection.fov * projection.aspect_ratio, projection.fov) / window;
}
// translate by local axes
let right = transform.rotation * Vec3::X * -pan.x;
let up = transform.rotation * Vec3::Y * pan.y;
// make panning proportional to distance away from focus point
let translation = (right + up) * pan_orbit.radius;
pan_orbit.focus += translation;
} else if scroll.abs() > 0.0 {
any = true;
pan_orbit.radius -= scroll * pan_orbit.radius * 0.2;
// dont allow zoom to reach zero or you get stuck
pan_orbit.radius = f32::max(pan_orbit.radius, 0.05);
}
if any {
// emulating parent/child to make the yaw/y-axis rotation behave like a turntable
// parent = x and y rotation
// child = z-offset
let rot_matrix = Mat3::from_quat(transform.rotation);
transform.translation = pan_orbit.focus + rot_matrix.mul_vec3(Vec3::new(0.0, 0.0, pan_orbit.radius));
}
}
// consume any remaining events, so they don't pile up if we don't need them
// (and also to avoid Bevy warning us about not checking events every frame update)
ev_motion.clear();
}
fn get_primary_window_size(windows: &Res<Windows>) -> Vec2 {
let window = windows.get_primary().unwrap();
let window = Vec2::new(window.width() as f32, window.height() as f32);
window
}
/// Spawn a camera like this
fn spawn_camera(mut commands: Commands) {
let translation = Vec3::new(-2.0, 2.5, 5.0);
let radius = translation.length();
commands.spawn((
Camera3dBundle {
transform: Transform::from_translation(translation)
.looking_at(Vec3::ZERO, Vec3::Y),
..Default::default()
},
PanOrbitCamera {
radius,
..Default::default()
},
));
}
Bevy Version: | 0.9 | (outdated!) |
---|
List All Resource Types
Click here for the full example code.
This example shows how to print a list of all types that have been added as resources.
fn print_resources(world: &World) {
let components = world.components();
let mut r: Vec<_> = world
.storages()
.resources
.iter()
.map(|(id, _)| components.get_info(id).unwrap())
.map(|info| info.name())
.collect();
// sort list alphebetically
r.sort();
r.iter().for_each(|name| println!("{}", name));
}
Note that this does not give you a comprehensive list of every Bevy-provided type that is useful as a resource. It lists the types of all the resources currently added to the app (by all registered plugins, your own, etc.).
See here for a more useful list types provided in Bevy.
Bevy Version: | 0.9 | (outdated!) |
---|
Bevy on Different Platforms
This chapter is a collection of platform-specific information, about using Bevy with different operating systems or environments.
Feel free to suggest things to add.
Platform Support
Bevy aims to also make it easy to target different platforms, such as the various desktop operating systems, web browsers (via WebAssembly), mobile (Android and iOS), and game consoles. Your Bevy code can be the same for all platforms, with differences only in the build process and environment setup.
However, that vision is not fully met yet. Currently, support for non-desktop platforms is limited, and requires more complex configuration.
Desktop
Bevy trivially works out-of-the-box on the three major desktop operating systems: Linux, macOS, Windows. No special configuration is required.
See the following pages for specific tips/advice when developing for the desktop platforms:
All features are fully supported on each of the above.
If you are working in Linux, see here for how to build Windows EXEs for your Windows users.
Web
Bevy works quite well on the web (using WebAssembly), but with some limitations.
Multithreading is not supported, so you will have limited performance and possible audio glitches. Rendering is limited to the features of the WebGL2 API, meaning worse performance and limitations like only supporting a maximum of 256 lights in 3D scenes.
For inspiration, check out the entries in the first Bevy Game Jam. Many of them have web builds you can play in your browser.
Mobile
Apple iOS is well-supported and most features work well. There are developers in the Bevy community that have successfully shipped Bevy-based apps to the App Store.
Android support is still limited. Your app will build and run. You can get started. However, some features may be missing or broken, and there are a few major bugs. The worst one is that Bevy cannot yet handle being put into the background, and will crash when the user presses the home button to leave the app.
Android support is actively being worked on. Please join the development community on Discord if you are interested.
Bevy has been known to have issues with emulator devices. It is recommended you test your app on real hardware.
Game Consoles
Unfortunately, due to NDA requirements, developing for consoles is inaccessible to most community developers who work in the open, and Bevy support is still mostly nonexistent.
At least one person is working on PlayStation 5 support. If you are interested, join Discord and ask around. Maybe you can find each other and work together.
The Rust Programming Language aims to make Nintendo Switch a supported target, but that work is in its early days and has not progressed enough to be useful for Bevy yet. It should be possible to work on Nintendo Switch support in the open, without NDAs, using emulators.
Bevy Version: | 0.11 | (current) |
---|
Linux Desktop
If you have any additional Linux-specific knowledge, please help improve this page!
Create Issues or PRs on GitHub.
Desktop Linux is one of the best-supported platforms by Bevy.
There are some development dependencies you may need to setup, depending on your distribution. See instructions in official Bevy repo.
See here if you also want to build Windows EXEs from Linux.
GPU Drivers
Bevy apps need support for the Vulkan graphics API to run best. There is a fallback on OpenGL ES 3 for systems where Vulkan is unsupported, but it might not work and will have limited features and performance.
You (and your users) must ensure that you have compatible hardware and drivers installed. On most modern distributions and computers, this should be no problem.
If Bevy apps refuse to run and print an error to the console about not being able to find a compatible GPU, the problem is most likely with the Vulkan components of your graphics driver not being installed correctly. You may need to install some extra packages or reinstall your graphics drivers. Check with your Linux distribution for what to do.
To confirm that Vulkan is working, you can try to run this command (found in
a package called vulkan-tools
on most distributions):
vulkaninfo
X11 and Wayland
As of the year 2023, the Linux desktop ecosystem is fragmented between the legacy X11 stack and the modern Wayland stack. Many distributions are switching to Wayland-based desktop environments by default.
Bevy supports both, but only X11 support is enabled by default. If you are running a Wayland-based desktop, this means your Bevy app will run in the XWayland compatibility layer.
To enable native Wayland support for Bevy, enable the wayland
cargo feature:
[dependencies]
bevy = { version = "0.11", features = ["wayland"] }
Now your app will be built with support for both X11 and Wayland.
If you want to remove X11 support for whatever reason, you will have to disable
the default features and re-enable everything you need, without the x11
feature. See here to learn how to configure Bevy features.
If both are enabled, you can override which display protocol to use at runtime, using an environment variable:
export WINIT_UNIX_BACKEND=x11
(to run using X11/XWayland on a Wayland desktop)
or
export WINIT_UNIX_BACKEND=wayland
(to require the use of Wayland)
Bevy Version: | 0.11 | (current) |
---|
macOS Desktop
If you have any additional macOS-specific knowledge, please help improve this page!
Create Issues or PRs on GitHub.
See here if you also want to build Windows EXEs from macOS.
Known Pitfalls
Input Peculiarities
Mouse wheel scrolling behaves in a peculiar manner,
because macOS does "scroll acceleration" at the OS level. Other OSs, with
regular PC mice, provide Line
scroll events with whole number values, where
1.0 corresponds to one step on the scroll wheel. macOS scales the value
depending on how fast the user is spinning the wheel. You do not get whole
numbers. They can range anywhere from tiny values <0.1 (for the starting event,
before the scroll speed ramps up), up to values as big as >10.0 (say, for a fast
flick of the wheel), per event.
macOS provides special events for touchpad gestures for zooming and rotation, which you can handle in Bevy.
Some keyboard keys have a somewhat-unintuitive mapping:
- The Command (⌘) key is
KeyCode::{SuperLeft, SuperRight}
. - The Option (⌥) key is
KeyCode::{AltLeft, AltRight}
.
Other key codes have their intuitive names.
Window Management Apps Compatability
Bevy apps can encounter performance issues (such as lag when dragging the window
around the screen) when window management apps like "Magnet" are used. This is a
bug in winit
(the OS window management library that Bevy uses). This issue can
be tracked here.
Until that bug is fixed, advise closing the window management apps, if encountering performance issues.
Creating an Application Bundle
When you build your Bevy project normally, cargo/Rust will produce a bare executable file, similar to other operating systems. However, this is not how "normal" macOS apps look and behave. You probably want to create a proper native-feeling Mac app for distribution to your users.
You need to do this, to have your app play nicely with the Mac desktop GUI, such as to have a nice icon appear in the dock.
macOS applications are typically stored on the filesystem as "bundles" – special
directories/folders that end in .app
, that the OS displays to the user as one
item. macOS expects to find a special hieararchy of subfolders and files inside.
A minimal app bundle might have the following files:
MyGame.app/Contents/MacOS/MyGame
: the actual executable fileMyGame.app/Contents/MacOS/assets/
: your Bevy assets folderMyGame.app/Contents/Info.plist
: metadata (see below)MyGame.app/Contents/Resources/AppIcon.icns
: the app's icon
Only the executable file is technically mandatory. If you have nothing else, the app will run, as long as the executable file name matches the app bundle file name. You should, however, follow the below instructions, if you want to make a proper nice Mac app. :)
Executable File
The executable file produced by the Rust compiler (in the target
directory) is
a single-architecture binary for your current development machine. You could
just copy this file into the app bundle, but then you will not support all Mac
hardware natively.
If you want to support both machines with Intel CPUs and with Apple Silicon
(Arm) CPUs, you need to compile for both of them, and then combine them into a
single executable using Apple's lipo
tool.
First, make sure you have Rust toolchain support for both architectures installed:
rustup target add x86_64-apple-darwin
rustup target add aarch64-apple-darwin
Now, you can compile for both architectures:
cargo build --release --target x86_64-apple-darwin
cargo build --release --target aarch64-apple-darwin
Now, you can combine the two executables into one, for your app bundle.
lipo "target/x86_64-apple-darwin/release/my_game" \
"target/aarch64-apple-darwin/release/my_game" \
-create -output "MyGame.app/Contents/MacOS/MyGame"
Note: please ensure the Bevy dynamic_linking
cargo feature is not enabled.
Game Assets
Your Bevy assets
folder needs to be placed alongside the executable file,
for Bevy to find it and be able to load your assets. Just copy it into
Contents/MacOS
in your app bundle.
Note: This is not the standard conventional location as prescribed by Apple.
Typically, macOS apps store their data files in Contents/Resources
. However,
Bevy will not find them there. Thankfully, Apple does not enforce this, so we
are free to do something unusual when we have to.
Info.plist
This file contains all the metadata that macOS wants.
If you do not create this file, or if it is missing some of the fields, macOS
will try to guess them, so your app can still run. Ideally, you want to create a
proper Info.plist
file, to prevent issues.
Download an example file as a starting point.
You can edit this file using Apple XCode or a text editor. Check that all the values make sense for your app. Pay special attention to these values:
CFBundleName
(Bundle name)- Short user-visible name of your app
CFBundleDisplayName
(Bundle display name)- Optional: You can set a longer user-visible name here, if you want
CFBundleExecutable
(Executable file)- The name of the executable file
CFIconFile
(Icon file)- The name of the icon file
CFBundleIdentifier
(Bundle identifier)- Apple wants an ID for your app, in domain format, like:
com.mycompany.mygame
- Apple wants an ID for your app, in domain format, like:
CFBundleShortVersionString
(Bundle version string (short))- The version of your app, like
0.1.0
.
- The version of your app, like
App Icon
The icon file needs to be in a special Apple format.
Such a file can be created from a collection of PNGs of different standard sizes (powers of two). If you want your app to look nice at all sizes, you can hand-craft an image for each size, following Apple Design Guidelines. If you don't care, you can just take one image (ideally 1024x1024, the biggest size used by macOS) and scale it to different sizes.
Here is a script that does that:
SOURCE_IMAGE="myicon1024.png"
mkdir -p AppIcon.iconset
sips -z 16 16 "${SOURCE_IMAGE}" --out AppIcon.iconset/icon_16x16.png
sips -z 32 32 "${SOURCE_IMAGE}" --out AppIcon.iconset/icon_16x16@2x.png
sips -z 32 32 "${SOURCE_IMAGE}" --out AppIcon.iconset/icon_32x32.png
sips -z 64 64 "${SOURCE_IMAGE}" --out AppIcon.iconset/icon_32x32@2x.png
sips -z 128 128 "${SOURCE_IMAGE}" --out AppIcon.iconset/icon_128x128.png
sips -z 256 256 "${SOURCE_IMAGE}" --out AppIcon.iconset/icon_128x128@2x.png
sips -z 256 256 "${SOURCE_IMAGE}" --out AppIcon.iconset/icon_256x256.png
sips -z 512 512 "${SOURCE_IMAGE}" --out AppIcon.iconset/icon_256x256@2x.png
sips -z 512 512 "${SOURCE_IMAGE}" --out AppIcon.iconset/icon_512x512.png
cp "${SOURCE_IMAGE}" AppIcon.iconset/icon_512x512@2x.png
iconutil -c icns AppIcon.iconset
## move it into the app bundle
mv AppIcon.icns MyGame.app/Contents/Resources
It works by creating a special iconset
folder, with all the PNG files at different
sizes, created by resizing your source image. Then, it uses iconutil
to produce
the final Apple ICNS file for your app bundle.
If you want hand-crafted icons for each size, you could use a similar process.
Create an iconset
folder with your PNGs, and run iconutil -c icns
on it.
Alternatively, Apple XCode has GUI tools for creating and editing app icons.
Putting Everything Together
Here is a simple shell script to build a Mac app. It follows the recommendations on this page. Adjust everything as necessary for your project.
# set the name of the Mac App
APP_NAME="MyGame"
# set the name of your rust crate
RUST_CRATE_NAME="my_game"
# create the folder structure
mkdir -p "${APP_NAME}.app/Contents/MacOS"
mkdir -p "${APP_NAME}.app/Contents/Resources"
# copy Info.plist
cp Info.plist "${APP_NAME}.app/Contents/Info.plist"
# copy the icon (assuming you already have it in Apple ICNS format)
cp AppIcon.icns "${APP_NAME}.app/Contents/Resources/AppIcon.icns"
# copy your Bevy game assets
cp -a assets "${APP_NAME}.app/Contents/MacOS/"
# compile the executables for each architecture
cargo build --release --target x86_64-apple-darwin # build for Intel
cargo build --release --target aarch64-apple-darwin # build for Apple Silicon
# combine the executables into a single file and put it in the bundle
lipo "target/x86_64-apple-darwin/release/${RUST_CRATE_NAME}" \
"target/aarch64-apple-darwin/release/${RUST_CRATE_NAME}" \
-create -output "${APP_NAME}.app/Contents/MacOS/${APP_NAME}"
Note: please ensure the Bevy dynamic_linking
cargo feature is not enabled.
Creating a DMG file
It is common for Mac apps downloadable from the internet to be distributed as
DMG files – Apple's "disk image" format. Users can drag-and-drop the app bundle
inside into their Applications
folder on their system.
You can create a very simple one from the command-line, using hdiutil
:
hdiutil create -fs HFS+ \
-volname "My Bevy Game" \
-srcfolder "MyGame.app" \
"mybevygame_release_mac.dmg"
Specify the Volume Name (how it appears when opened), the name of your app
bundle, and the name of the output DMG file, respectively. You can use
-srcfolder
multiple times, if you want to add more files and folders to the
DMG image.
If you want to create a DMG file using a GUI, you can use Apple's "Disk Utility" app that comes preinstalled with macOS.
Bevy Version: | 0.11 | (current) |
---|
Windows Desktop
If you have any additional Windows-specific knowledge, please help improve this page!
Create Issues or PRs on GitHub.
Windows is one of the best-supported platforms by Bevy.
Both the MSVC and the GNU compiler toolchains should work.
You can also build Windows EXEs while working in Linux.
Distributing Your App
The EXE built with cargo build
can work standalone without any extra files or DLLs.
Your assets
folder needs be distributed alongside it. Bevy will search for it in
the same directory as the EXE on the user's computer.
The easiest way to give your game to other people to play is to put them
together in a ZIP file. If you use some other method of installation,
install the assets
folder and the EXE to the same path.
If built with the MSVC toolchain, your users may need the Microsoft C/C++ Runtime Redistributables installed.
Disabling the Windows Console
By default, when you run a Bevy app (or any Rust program for that matter)
on Windows, a Console window also shows up. To disable this,
place this Rust attribute at the top of your main.rs
:
#![windows_subsystem = "windows"]
This tells Windows that your executable is a graphical application, not a command-line program. Windows will know not display a console.
However, the console can be useful for development, to see log messages. You can disable it only for release builds, and leave it enabled in debug builds, like this:
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
Working in WSL2
If you prefer to have a more Linux-centric development workflow, you might want to work inside of WSL2 and build your project there. Another reason to do it is compile times; they are often much faster in WSL2 than on the Windows host system.
Fortunately, this can actually work quite well! The trick is that you want to cross-compile for Windows. The Windows EXE you build inside of WSL2 can be run just fine from the Linux commandline, and it will seamlessly run on the host system! This way, you don't need any GPU drivers or GUI support inside your WSL2 Linux environment.
Note that when you run Windows binaries from WSL2, they don't get the Linux
environment variables. cargo run
does not just work, because your Bevy game
will look for its assets
folder in the path where the EXE is (which would be
in the target
build output folder). My simple solution is to just copy the
EXE into the project folder after building, and run it directly from there.
This can be automated with a little script, to use instead of cargo run
:
#!/bin/sh
cargo build --target x86_64-pc-windows-msvc &&
cp target/x86_64-pc-windows-msvc/debug/mygame.exe . &&
exec ./mygame.exe "$@"
This way you also don't have to type the cross-compilation target every time (and you can also add any other options you want there).
Creating an icon for your app
There are two places where you might want to put your application icon:
- The EXE file (how it looks in the file explorer)
- The window at runtime (how it looks in the taskbar and the window title bar)
Setting the EXE icon
(adapted from here)
The EXE icon can be set using a cargo build script.
Add a build dependency of embed_resources
to your Cargo.toml
allow embedding assets into your compiled executables
[build-dependencies]
embed-resource = "1.6.3"
Create a build.rs
file in your project folder:
extern crate embed_resource;
fn main() {
let target = std::env::var("TARGET").unwrap();
if target.contains("windows") {
embed_resource::compile("icon.rc");
}
}
Create a icon.rc
file in your project folder:
app_icon ICON "icon.ico"
Create your icon as icon.ico
in your project folder.
Setting the Window Icon
See: Setting the Window Icon.
Bevy Version: | 0.9 | (outdated!) |
---|
Browser (WebAssembly)
Introduction
You can make web browser games using Bevy. This chapter will help you with the things you need to know to do it. This page gives an overview of Bevy's Web support.
Your Bevy app will be compiled for WebAssembly (WASM), which allows it to be embedded in a web page and run inside the browser.
Performance will be limited, as WebAssembly is slower than native code and does not currently support multithreading.
Not all 3rd-party plugins are compatible. If you need extra unofficial plugins, you will have to check if they are compatible with WASM.
Project Setup
The same Bevy project, without any special code modifications, can be built for either web or desktop/native.
However, you will need a "website" with some HTML and JavaScript to load and run your game. For development and testing, this could be just a minimal shim. It can be easily autogenerated.
To deploy, you will need a server to host your website for other people to access. You could use GitHub's hosting service: GitHub Pages.
Additional Caveats
When users load your site to play your game, their browser will need to download the files. Optimizing for size is important, so that your game can load fast and not waste data bandwidth.
Some minor extra configuration is needed to be able to:
Note: the dynamic
feature flag is not supported for
WASM builds. You cannot use it.
Quick Start
First, add WASM support to your Rust installation. Using Rustup:
rustup target install wasm32-unknown-unknown
Now, to run your Bevy project in the browser.
wasm-server-runner
The easiest and most automatic way to get started is the
wasm-server-runner
tool.
Install it:
cargo install wasm-server-runner
Set up cargo
to use it, in .cargo/config.toml
(in your project folder,
or globally in your user home folder):
[target.wasm32-unknown-unknown]
runner = "wasm-server-runner"
Alternatively, you can also set the runner using an environment variable:
export CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER=wasm-server-runner
Now you can just run your game with:
cargo run --target wasm32-unknown-unknown
It will automatically run a minimal local webserver and open your game in your browser.
wasm-bindgen
wasm-bindgen
is the tool to generate all the files needed to put the game on your website.
Run:
cargo build --release --target wasm32-unknown-unknown
wasm-bindgen --out-dir ./out/ --target web ./target/
./out/
is the directory where it will place the output files.
You need to put these on your web server.
Higher-level Tools
Here are some higher-level alternatives. These tools can do more for you and automate more of your workflow, but are more opinionated in how they work.
Bevy Version: | 0.9 | (outdated!) |
---|
Panic Messages
Unless we do something about it, you will not be able to see Rust panic messages when running in a web browser. This means that, if your game crashes, you will not know why.
To fix this, we can set up a panic hook that will cause the messages to appear in the browser console, using the console_error_panic_hook crate.
Add the crate to your dependencies in Cargo.toml
:
[dependencies]
console_error_panic_hook = "0.1"
At the start of your main function, before doing anything else, add this:
// When building for WASM, print panics to the browser console
#[cfg(target_arch = "wasm32")]
console_error_panic_hook::set_once();
Bevy Version: | 0.9 | (outdated!) |
---|
Optimize for Size
When serving a WASM binary, the smaller it is, the faster the browser can download it. Faster downloads means faster page load times and less data bandwidth use, and that means happier users.
This page gives some suggestions for how to make your WASM files smaller.
Do not prematurely optimize! You probably don't need small WASM files during development, and many of these techniques can get in the way of your workflow! They may come at the cost of longer compile times or less debuggability.
Depending on the nature of your application, your mileage may vary, and performing measurements of binary size and execution speed is recommended.
Twiggy is a code size profiler for WASM binaries, which you can use to make measurements.
For additional information and more techniques, refer to the Code Size chapter in the Rust WASM book.
Compiling for size instead of speed
You can change the optimization profile of the compiler, to tell it to prioritize small output size, rather than performance.
(although in some rare cases, optimizing for size can actually improve speed)
In Cargo.toml
, add one of the following:
[profile.release]
opt-level = 's'
[profile.release]
opt-level = 'z'
These are two different profiles for size optimization. Usually, z
produces
smaller files than s
, but sometimes it can be the opposite. Measure to
confirm which one works better for you.
Link-Time Optimization (LTO)
In Cargo.toml
, add the following:
[profile.release]
lto = "thin"
LTO tells the compiler to optimize all code together, considering all crates as if they were one. It may be able to inline and prune functions much more aggressively.
This typically results in smaller size and better performance, but do measure to confirm. Sometimes, the size can actually be larger.
The downside here is that compilation will take much longer. Do this only for release builds you publish for other users.
Use the wasm-opt
tool
The binaryen toolkit is a set of extra tools for working
with WASM. One of them is wasm-opt
. It goes much further than what the
compiler can do, and can be used to further optimize for either speed or size:
# Optimize for size (s profile).
wasm-opt -Os -o output.wasm input.wasm
# Optimize for size (z profile).
wasm-opt -Oz -o output.wasm input.wasm
# Optimize aggressively for speed.
wasm-opt -O3 -o output.wasm input.wasm
# Optimize aggressively for both size and speed.
wasm-opt -O -ol 100 -s 100 -o output.wasm input.wasm
Do you know of more WASM size-optimization techniques? Post about them in the GitHub Issue Tracker so that they can be added to this page!
Bevy Version: | 0.9 | (outdated!) |
---|
Hosting on GitHub Pages
GitHub Pages is a hosting service that allows you to publish your website on GitHub's servers.
For more details, visit the official GitHub Pages documentation.
Deploying a website (like your WASM game) to GitHub pages is done by putting the files in a special branch in a GitHub repository. You could create a separate repository for this, but you could also do it from the same repository as your source code.
You will need the final website files for deployment.
Create an empty branch in your git repository:
git checkout --orphan web
git reset --hard
You should now be in an empty working directory.
Put all files necessary for hosting, including your HTML, WASM, JavaScript,
and assets
files, and commit them into git:
git add *
git commit
(or better, manually list your files in the above command, in place of the *
wildcard)
Push your new branch to GitHub:
git push -u origin web --force
In the GitHub Web UI, go to the repository settings, go to the "GitHub Pages"
section, then under "Source" pick the branch "web" and the /
(root) folder.
Then click "Save".
Wait a little bit, and your site should become available at
https://your-name.github.io/your-repo
.
Bevy Version: | (any) |
---|
Cross-Compilation
This sub-chapter covers how to make builds of your Bevy apps to run on a different Operating System than the one you are working on.
Bevy Version: | (any) |
---|
Build Windows EXEs from Linux
(also check out the Windows Platform page for info about developing for Windows generally)
Rust offers two different toolchains for building for Windows:
- MSVC: the default when working in Windows, requires downloading Microsoft SDKs
- GNU: alternative MINGW-based build
The instructions on this page use the x86_64
architecture, but you could also
set up a toolchain to target i686
(32-bit) or aarch64
(Windows-on-Arm) the
same way.
First-Time Setup (MSVC)
The MSVC toolchain is what the Rust community usually recommends for targetting the Windows platform. You can actually set it up and use it on Linux (and other UNIX-like systems), using some special tooling, which will be explained below.
Rust Toolchain (MSVC)
Add the target to your Rust installation (assuming you use rustup
):
rustup target add x86_64-pc-windows-msvc
This installs the files Rust needs to compile for Windows, including the Rust standard library.
Microsoft Windows SDKs
You need to install the Microsoft Windows SDKs, just like when working on
Windows. On Linux, this can be done with an easy script called xwin
. You
need to accept Microsoft's proprietary license.
Install xwin
:
cargo install xwin
Now, use xwin
to accept the Microsoft license, download all the files
from Microsoft servers, and install them to a directory of your choosing.
(The --accept-license
option is to not prompt you, assuming you have already
seen the license. To read the license and be prompted to accept it, omit that
option.)
To install to .xwin/
in your home folder:
xwin --accept-license splat --output /home/me/.xwin
Linking (MSVC)
Rust needs to know how to link the final EXE file.
The default Microsoft linker (link.exe
) is only available on Windows. Instead,
we need to use the LLD linker (this is also recommended when working on Windows
anyway). Just install the lld
package from your Linux distro.
We also need to tell Rust the location of the Microsoft Windows SDK libraries
(that were installed with xwin
in the previous step).
Add this to .cargo/config.toml
(in your home folder or in your bevy project):
[target.x86_64-pc-windows-msvc]
linker = "lld"
rustflags = [
"-Lnative=/home/me/.xwin/crt/lib/x86_64",
"-Lnative=/home/me/.xwin/sdk/lib/um/x86_64",
"-Lnative=/home/me/.xwin/sdk/lib/ucrt/x86_64"
]
Note: you need to specify the correct full absolute paths to the SDK files, wherever you installed them.
First-Time Setup (GNU)
On many Linux distros, the alternative GNU/MINGW toolchain might be an easier option. Your distro might provide packages that you can easily install. Also, you do not need to accept any Microsoft licenses.
Rust Toolchain (GNU)
Add the target to your Rust installation (assuming you use rustup
):
rustup target add x86_64-pc-windows-gnu
This installs the files Rust needs to compile for Windows, including the Rust standard library.
MINGW
The GNU toolchain requires the MINGW environment to be installed. Your distro likely provides a package for it. Search your distro for a cross-compilation mingw package.
It might be called something like: cross-x86_64-w64-mingw32
, but that varies in different distros.
You don't need any files from Microsoft.
Building Your Project
Finally, with all the setup done, you can just build your Rust/Bevy projects for Windows:
MSVC:
cargo build --target=x86_64-pc-windows-msvc --release
MinGW:
cargo build --target=x86_64-pc-windows-gnu --release
Bevy Version: | (any) |
---|
Build Windows EXEs from macOS
(also check out the Windows Platform page for info about developing for Windows generally)
Rust offers two different toolchains for building for Windows:
- MSVC: the default when working in Windows, requires downloading Microsoft SDKs
- GNU: alternative MINGW-based build
On macOS, the GNU software is not readily-available. I don't know how it could be installed. Even if possible, it might be difficult to set up.
This page will teach you how to setup a MSVC-based toolchain, which works on macOS and can be set up similarly to how it can be done on Linux.. You will need to accept Microsoft licenses.
The instructions on this page use the x86_64
architecture, but you could also
set up a toolchain to target i686
(32-bit) or aarch64
(Windows-on-Arm) the
same way.
First-Time Setup
Rust Toolchain
Add the target to your Rust installation (assuming you use rustup
):
rustup target add x86_64-pc-windows-msvc
This installs the files Rust needs to compile for Windows, including the Rust standard library.
Microsoft Windows SDKs
You need to install the Microsoft Windows SDKs, just like when working on
Windows. This can be done with an easy script called xwin
. You need to accept
Microsoft's proprietary license.
Install xwin
:
cargo install xwin
Now, use xwin
to accept the Microsoft license, download all the files
from Microsoft servers, and install them to a directory of your choosing.
(The --accept-license
option is to not prompt you, assuming you have already
seen the license. To read the license and be prompted to accept it, omit that
option.)
To install to .xwin/
in your home folder:
xwin --accept-license splat --disable-symlinks --output /Users/me/.xwin
On Windows and macOS, the filesystem is case-insensitive. On Linux and BSD, the
filesystem is case-sensitive. xwin
was made for Linux, so it tries to work
around this by default, by creating symlinks. On macOS, we need to tell xwin
not to do this, using the --disable-symlinks
option.
Linking
Rust needs to know how to link the final EXE file.
The default Microsoft linker (link.exe
) is only available on Windows. Instead,
we need to use the LLD linker (this is also recommended when working on Windows
anyway).
Installing LLD
Unfortunately, last I checked, neither brew
nor macports
offer packages (LLD
is not commonly used when developing for macOS).
We can, however, build it ourselves from source. You need a C++ compiler and CMake. You probably already have the C++ toolchain installed, if you have installed Apple XCode development tools.
CMake can be installed from brew
(Homebrew):
brew install cmake
Now, we are ready to compile LLD from the LLVM project:
Note: the --depth=1
option to git clone
allows us to save a lot of disk
space and download bandwidth, because the LLVM respository is huge.
git clone --depth=1 https://github.com/llvm/llvm-project
cd llvm-project
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_PROJECTS=lld -DCMAKE_INSTALL_PREFIX=/usr/local ../llvm
sudo make -j10 install # adjust `-j10` based on your number of CPU cores
cd ../../; rm -rf llvm-project # delete the git repo and build files to free disk space
This will install it to /usr/local
. Change the path above if you would rather
have it somewhere else, to not pollute your macOS or need sudo
/ root privileges.
Using LLD
We also need to tell Rust to use our linker, and the location of the Microsoft
Windows SDK libraries (that were installed with xwin
in the previous
step).
Add this to .cargo/config.toml
(in your home folder or in your bevy project):
[target.x86_64-pc-windows-msvc]
linker = "/usr/local/bin/lld"
rustflags = [
"-Lnative=/Users/me/.xwin/crt/lib/x86_64",
"-Lnative=/Users/me/.xwin/sdk/lib/um/x86_64",
"-Lnative=/Users/me/.xwin/sdk/lib/ucrt/x86_64"
]
Note: you need to specify the correct full absolute paths to the SDK files, wherever you installed them.
Building Your Project
Finally, with all the setup done, you can just build your Rust/Bevy projects for Windows:
cargo build --target=x86_64-pc-windows-msvc --release
Bevy Version: | (any) |
---|
Appendix: General Concepts
This chapter teaches general knowledge, independent of Bevy. If you are new to game development in general and don't understand some general concepts, there might be something in this chapter to give you the background theory you need.
To learn how these things work in Bevy, the relevant pages (located elsewhere in the book) will be linked on each page in this chapter.
Bevy Version: | (any) |
---|
Credits
While the majority of this book was authored by me, Ida Iyes (@inodentry
), a
number of folks have made large contributions to help! Thank you all so much! ❤️
- Alice I. Cecile
@alice-i-cecile
: review, advice, reporting lots of good suggestions - nile
@TheRawMeatball
: review, useful issue reports @Zaszi
: writing the initial draft of the WASM chapter@skairunner
and@mirenbharta
: developing the Pan+Orbit camera example
Thanks to everyone who has submitted GitHub issues!
Big thanks to all sponsors! ❤️
Thanks to you, I can actually keep working on this book, improving and maintaining it!
And of course, the biggest thanks goes to the Bevy project
itself and its founder, @cart
, for creating this awesome community and
game engine in the first place! It makes all of this possible. You literally
changed my life! ❤️
Bevy Version: | (any) |
---|
Contact Me
You can find me in the following places:
- Discord:
Ida Iyes#0981
- Mastodon:
@iyes@tech.lgbt
- GitHub:
@inodentry
- Reddit:
iyesgames
For improvements or fixes to this book, please file an issue on GitHub.
If you need help with Bevy or Rust, I offer private tutoring. Reach out if you are interested, to discuss rates and how I could best help you. :)
Bevy Version: | (any) |
---|
Contributing to Bevy
If you want to help out the Bevy Game Engine project, check out Bevy's official contributing guide.
Bevy Version: | (any) |
---|
Contributing
Be civil. If you need a code of conduct, have a look at Bevy's.
If you have any suggestions for the book, such as ideas for new content, or if you notice anything that is incorrect or misleading, please file issues in the GitHub repository!
GitHub Issues
If you want something to be added or changed in the book, file an issue! Tell me what you want, and I will figure out how to present it in the book. If you have some code snippet or other thing you want to include, you can put it in the issue.
That sort of workflow works much better for me, compared to Pull Requests. I am quite opinionated and meticulous about how everything is presented in the book, so I often can't just merge/accept things as written by someone else.
GitHub Pull Requests
PLEASE DO NOT CREATE PULL REQUESTS FOR BOOK CONTENT.
The only exception to this might be trivial fixes. If you are just fixing a typo or small mistake, or a bug in some code example, that's fine.
If you are adding or changing any of the book content, your PR will probably be ignored or closed. I will probably treat it like I do issues: go do the thing myself eventually, and then close your PR.
PRs create more work for me. They make life harder, not easier. Every time someone has made a PR before, I've had to basically rewrite it / redo the work myself. And also figure out how to respond to the author. And also wrangle merge conflicts and git branches. Please don't. I'm tired.
Licensing
To avoid complications with copyright and licensing, you agree to provide any contributions you make to the project under the MIT-0 No Attribution License.
Note that this allows your work to be relicensed without preserving your copyright.
As described previously, the actual published content in the book will be my own derivative work based on your contributions. I will license it consistently with the rest of the book; see: License.