bevy/examples
Carter Anderson 35073cf7aa
Multiple Asset Sources (#9885)
This adds support for **Multiple Asset Sources**. You can now register a
named `AssetSource`, which you can load assets from like you normally
would:

```rust
let shader: Handle<Shader> = asset_server.load("custom_source://path/to/shader.wgsl");
```

Notice that `AssetPath` now supports `some_source://` syntax. This can
now be accessed through the `asset_path.source()` accessor.

Asset source names _are not required_. If one is not specified, the
default asset source will be used:

```rust
let shader: Handle<Shader> = asset_server.load("path/to/shader.wgsl");
```

The behavior of the default asset source has not changed. Ex: the
`assets` folder is still the default.

As referenced in #9714

## Why?

**Multiple Asset Sources** enables a number of often-asked-for
scenarios:

* **Loading some assets from other locations on disk**: you could create
a `config` asset source that reads from the OS-default config folder
(not implemented in this PR)
* **Loading some assets from a remote server**: you could register a new
`remote` asset source that reads some assets from a remote http server
(not implemented in this PR)
* **Improved "Binary Embedded" Assets**: we can use this system for
"embedded-in-binary assets", which allows us to replace the old
`load_internal_asset!` approach, which couldn't support asset
processing, didn't support hot-reloading _well_, and didn't make
embedded assets accessible to the `AssetServer` (implemented in this pr)

## Adding New Asset Sources

An `AssetSource` is "just" a collection of `AssetReader`, `AssetWriter`,
and `AssetWatcher` entries. You can configure new asset sources like
this:

```rust
app.register_asset_source(
    "other",
    AssetSource::build()
        .with_reader(|| Box::new(FileAssetReader::new("other")))
    )
)
```

Note that `AssetSource` construction _must_ be repeatable, which is why
a closure is accepted.
`AssetSourceBuilder` supports `with_reader`, `with_writer`,
`with_watcher`, `with_processed_reader`, `with_processed_writer`, and
`with_processed_watcher`.

Note that the "asset source" system replaces the old "asset providers"
system.

## Processing Multiple Sources

The `AssetProcessor` now supports multiple asset sources! Processed
assets can refer to assets in other sources and everything "just works".
Each `AssetSource` defines an unprocessed and processed `AssetReader` /
`AssetWriter`.

Currently this is all or nothing for a given `AssetSource`. A given
source is either processed or it is not. Later we might want to add
support for "lazy asset processing", where an `AssetSource` (such as a
remote server) can be configured to only process assets that are
directly referenced by local assets (in order to save local disk space
and avoid doing extra work).

## A new `AssetSource`: `embedded`

One of the big features motivating **Multiple Asset Sources** was
improving our "embedded-in-binary" asset loading. To prove out the
**Multiple Asset Sources** implementation, I chose to build a new
`embedded` `AssetSource`, which replaces the old `load_interal_asset!`
system.

The old `load_internal_asset!` approach had a number of issues:

* The `AssetServer` was not aware of (or capable of loading) internal
assets.
* Because internal assets weren't visible to the `AssetServer`, they
could not be processed (or used by assets that are processed). This
would prevent things "preprocessing shaders that depend on built in Bevy
shaders", which is something we desperately need to start doing.
* Each "internal asset" needed a UUID to be defined in-code to reference
it. This was very manual and toilsome.

The new `embedded` `AssetSource` enables the following pattern:

```rust
// Called in `crates/bevy_pbr/src/render/mesh.rs`
embedded_asset!(app, "mesh.wgsl");

// later in the app
let shader: Handle<Shader> = asset_server.load("embedded://bevy_pbr/render/mesh.wgsl");
```

Notice that this always treats the crate name as the "root path", and it
trims out the `src` path for brevity. This is generally predictable, but
if you need to debug you can use the new `embedded_path!` macro to get a
`PathBuf` that matches the one used by `embedded_asset`.

You can also reference embedded assets in arbitrary assets, such as WGSL
shaders:

```rust
#import "embedded://bevy_pbr/render/mesh.wgsl"
```

This also makes `embedded` assets go through the "normal" asset
lifecycle. They are only loaded when they are actually used!

We are also discussing implicitly converting asset paths to/from shader
modules, so in the future (not in this PR) you might be able to load it
like this:

```rust
#import bevy_pbr::render::mesh::Vertex
```

Compare that to the old system!

```rust
pub const MESH_SHADER_HANDLE: Handle<Shader> = Handle::weak_from_u128(3252377289100772450);

load_internal_asset!(app, MESH_SHADER_HANDLE, "mesh.wgsl", Shader::from_wgsl);

// The mesh asset is the _only_ accessible via MESH_SHADER_HANDLE and _cannot_ be loaded via the AssetServer.
```

## Hot Reloading `embedded`

You can enable `embedded` hot reloading by enabling the
`embedded_watcher` cargo feature:

```
cargo run --features=embedded_watcher
```

## Improved Hot Reloading Workflow

First: the `filesystem_watcher` cargo feature has been renamed to
`file_watcher` for brevity (and to match the `FileAssetReader` naming
convention).

More importantly, hot asset reloading is no longer configured in-code by
default. If you enable any asset watcher feature (such as `file_watcher`
or `rust_source_watcher`), asset watching will be automatically enabled.

This removes the need to _also_ enable hot reloading in your app code.
That means you can replace this:

```rust
app.add_plugins(DefaultPlugins.set(AssetPlugin::default().watch_for_changes()))
```

with this:

```rust
app.add_plugins(DefaultPlugins)
```

If you want to hot reload assets in your app during development, just
run your app like this:

```
cargo run --features=file_watcher
```

This means you can use the same code for development and deployment! To
deploy an app, just don't include the watcher feature

```
cargo build --release
```

My intent is to move to this approach for pretty much all dev workflows.
In a future PR I would like to replace `AssetMode::ProcessedDev` with a
`runtime-processor` cargo feature. We could then group all common "dev"
cargo features under a single `dev` feature:

```sh
# this would enable file_watcher, embedded_watcher, runtime-processor, and more
cargo run --features=dev
```

## AssetMode

`AssetPlugin::Unprocessed`, `AssetPlugin::Processed`, and
`AssetPlugin::ProcessedDev` have been replaced with an `AssetMode` field
on `AssetPlugin`.

```rust
// before 
app.add_plugins(DefaultPlugins.set(AssetPlugin::Processed { /* fields here */ })

// after 
app.add_plugins(DefaultPlugins.set(AssetPlugin { mode: AssetMode::Processed, ..default() })
```

This aligns `AssetPlugin` with our other struct-like plugins. The old
"source" and "destination" `AssetProvider` fields in the enum variants
have been replaced by the "asset source" system. You no longer need to
configure the AssetPlugin to "point" to custom asset providers.

## AssetServerMode

To improve the implementation of **Multiple Asset Sources**,
`AssetServer` was made aware of whether or not it is using "processed"
or "unprocessed" assets. You can check that like this:

```rust
if asset_server.mode() == AssetServerMode::Processed {
    /* do something */
}
```

Note that this refactor should also prepare the way for building "one to
many processed output files", as it makes the server aware of whether it
is loading from processed or unprocessed sources. Meaning we can store
and read processed and unprocessed assets differently!

## AssetPath can now refer to folders

The "file only" restriction has been removed from `AssetPath`. The
`AssetServer::load_folder` API now accepts an `AssetPath` instead of a
`Path`, meaning you can load folders from other asset sources!

## Improved AssetPath Parsing

AssetPath parsing was reworked to support sources, improve error
messages, and to enable parsing with a single pass over the string.
`AssetPath::new` was replaced by `AssetPath::parse` and
`AssetPath::try_parse`.

## AssetWatcher broken out from AssetReader

`AssetReader` is no longer responsible for constructing `AssetWatcher`.
This has been moved to `AssetSourceBuilder`.


## Duplicate Event Debouncing

Asset V2 already debounced duplicate filesystem events, but this was
_input_ events. Multiple input event types can produce the same _output_
`AssetSourceEvent`. Now that we have `embedded_watcher`, which does
expensive file io on events, it made sense to debounce output events
too, so I added that! This will also benefit the AssetProcessor by
preventing integrity checks for duplicate events (and helps keep the
noise down in trace logs).

## Next Steps

* **Port Built-in Shaders**: Currently the primary (and essentially
only) user of `load_interal_asset` in Bevy's source code is "built-in
shaders". I chose not to do that in this PR for a few reasons:
1. We need to add the ability to pass shader defs in to shaders via meta
files. Some shaders (such as MESH_VIEW_TYPES) need to pass shader def
values in that are defined in code.
2. We need to revisit the current shader module naming system. I think
we _probably_ want to imply modules from source structure (at least by
default). Ideally in a way that can losslessly convert asset paths
to/from shader modules (to enable the asset system to resolve modules
using the asset server).
  3. I want to keep this change set minimal / get this merged first.
* **Deprecate `load_internal_asset`**: we can't do that until we do (1)
and (2)
* **Relative Asset Paths**: This PR significantly increases the need for
relative asset paths (which was already pretty high). Currently when
loading dependencies, it is assumed to be an absolute path, which means
if in an `AssetLoader` you call `context.load("some/path/image.png")` it
will assume that is the "default" asset source, _even if the current
asset is in a different asset source_. This will cause breakage for
AssetLoaders that are not designed to add the current source to whatever
paths are being used. AssetLoaders should generally not need to be aware
of the name of their current asset source, or need to think about the
"current asset source" generally. We should build apis that support
relative asset paths and then encourage using relative paths as much as
possible (both via api design and docs). Relative paths are also
important because they will allow developers to move folders around
(even across providers) without reprocessing, provided there is no path
breakage.
2023-10-13 23:17:32 +00:00
..
2d fix example mesh2d_manual (#9941) 2023-10-06 20:13:09 +00:00
3d Configurable colors for wireframe (#5303) 2023-10-13 00:06:24 +00:00
animation Add consuming builder methods for more ergonomic Mesh creation (#10056) 2023-10-09 19:47:41 +00:00
app Allow other plugins to create renderer resources (#9925) 2023-09-26 19:35:08 +00:00
asset Multiple Asset Sources (#9885) 2023-10-13 23:17:32 +00:00
async_tasks Allow using async_io::block_on in bevy_tasks (#9626) 2023-09-25 19:59:50 +00:00
audio More ergonomic spatial audio (#9800) 2023-10-09 19:43:56 +00:00
diagnostics Allow tuples and single plugins in add_plugins, deprecate add_plugin (#8097) 2023-06-21 20:51:03 +00:00
ecs Allow clippy::type_complexity in more places. (#9796) 2023-10-02 21:55:16 +00:00
games Allow clippy::type_complexity in more places. (#9796) 2023-10-02 21:55:16 +00:00
input Allow clippy::type_complexity in more places. (#9796) 2023-10-02 21:55:16 +00:00
mobile Improve selection of iOS device in mobile example (#9282) 2023-10-08 20:57:41 +00:00
reflection reflect: TypePath part 2 (#8768) 2023-10-09 19:33:03 +00:00
scene Multiple Asset Sources (#9885) 2023-10-13 23:17:32 +00:00
shader Multiple Asset Sources (#9885) 2023-10-13 23:17:32 +00:00
stress_tests foxes shouldn't march in sync (#10070) 2023-10-09 22:45:02 +00:00
tools Multiple Asset Sources (#9885) 2023-10-13 23:17:32 +00:00
transforms Fix ambiguities in transform example (#9845) 2023-09-19 05:57:21 +00:00
ui UI node outlines (#9931) 2023-10-05 12:10:32 +00:00
wasm Remove wasm specific examples (#3705) 2022-01-17 22:38:05 +00:00
window Remove monkey.gltf (#9974) 2023-09-30 02:50:31 +00:00
hello_world.rs Schedule-First: the new and improved add_systems (#8079) 2023-03-18 01:45:34 +00:00
README.md Deferred Renderer (#9258) 2023-10-12 22:10:38 +00:00

Examples

These examples demonstrate the main features of Bevy and how to use them. To run an example, use the command cargo run --example <Example>, and add the option --features x11 or --features wayland to force the example to run on a specific window compositor, e.g.

cargo run --features wayland --example hello_world

⚠️ Note: for users of releases on crates.io!

There are often large differences and incompatible API changes between the latest crates.io release and the development version of Bevy in the git main branch!

If you are using a released version of bevy, you need to make sure you are viewing the correct version of the examples!

When you clone the repo locally to run the examples, use git checkout to get the correct version:

# `latest` always points to the newest release
git checkout latest
# or use a specific version
git checkout v0.4.0

Table of Contents

The Bare Minimum

Hello, World!

Example Description
hello_world.rs Runs a minimal example that outputs "hello world"

Cross-Platform Examples

2D Rendering

Example Description
2D Bloom Illustrates bloom post-processing in 2d
2D Gizmos A scene showcasing 2D gizmos
2D Rotation Demonstrates rotating entities in 2D with quaternions
2D Shapes Renders a rectangle, circle, and hexagon
2D Viewport To World Demonstrates how to use the Camera::viewport_to_world_2d method
Custom glTF vertex attribute 2D Renders a glTF mesh in 2D with a custom vertex attribute
Manual Mesh 2D Renders a custom mesh "manually" with "mid-level" renderer apis
Mesh 2D Renders a 2d mesh
Mesh 2D With Vertex Colors Renders a 2d mesh with vertex color attributes
Move Sprite Changes the transform of a sprite
Pixel Perfect Demonstrates pixel perfect in 2d
Sprite Renders a sprite
Sprite Flipping Renders a sprite flipped along an axis
Sprite Sheet Renders an animated sprite
Text 2D Generates text in 2D
Texture Atlas Generates a texture atlas (sprite sheet) from individual sprites
Transparency in 2D Demonstrates transparency in 2d

3D Rendering

Example Description
3D Bloom Illustrates bloom configuration using HDR and emissive materials
3D Gizmos A scene showcasing 3D gizmos
3D Scene Simple 3D scene with basic shapes and lighting
3D Shapes A scene showcasing the built-in 3D shapes
3D Viewport To World Demonstrates how to use the Camera::viewport_to_world method
Anti-aliasing Compares different anti-aliasing methods
Atmospheric Fog A scene showcasing the atmospheric fog effect
Blend Modes Showcases different blend modes
Deferred Rendering Renders meshes with both forward and deferred pipelines
Fog A scene showcasing the distance fog effect
Generate Custom Mesh Simple showcase of how to generate a custom mesh with a custom texture
Lighting Illustrates various lighting options in a simple scene
Lines Create a custom material to draw 3d lines
Load glTF Loads and renders a glTF file as a scene
Orthographic View Shows how to create a 3D orthographic view (for isometric-look in games or CAD applications)
Parallax Mapping Demonstrates use of a normal map and depth map for parallax mapping
Parenting Demonstrates parent->child relationships and relative transformations
Physically Based Rendering Demonstrates use of Physically Based Rendering (PBR) properties
Render to Texture Shows how to render to a texture, useful for mirrors, UI, or exporting images
Screen Space Ambient Occlusion A scene showcasing screen space ambient occlusion
Shadow Biases Demonstrates how shadow biases affect shadows in a 3d scene
Shadow Caster and Receiver Demonstrates how to prevent meshes from casting/receiving shadows in a 3d scene
Skybox Load a cubemap texture onto a cube like a skybox and cycle through different compressed texture formats.
Spherical Area Lights Demonstrates how point light radius values affect light behavior
Split Screen Demonstrates how to render two cameras to the same window to accomplish "split screen"
Spotlight Illustrates spot lights
Texture Shows configuration of texture materials
Tonemapping Compares tonemapping options
Transparency in 3D Demonstrates transparency in 3d
Two Passes Renders two 3d passes to the same window from different perspectives
Update glTF Scene Update a scene from a glTF file, either by spawning the scene as a child of another entity, or by accessing the entities of the scene
Vertex Colors Shows the use of vertex colors
Wireframe Showcases wireframe rendering

Animation

Example Description
Animated Fox Plays an animation from a skinned glTF
Animated Transform Create and play an animation defined by code that operates on the Transform component
Cubic Curve Bezier curve example showing a cube following a cubic curve
Custom Skinned Mesh Skinned mesh example with mesh and joints data defined in code
Morph Targets Plays an animation from a glTF file with meshes with morph targets
glTF Skinned Mesh Skinned mesh example with mesh and joints data loaded from a glTF file

Application

Example Description
Custom Loop Demonstrates how to create a custom runner (to update an app manually)
Drag and Drop An example that shows how to handle drag and drop in an app
Empty An empty application (does nothing)
Empty with Defaults An empty application with default plugins
Headless An application that runs without default plugins
Logs Illustrate how to use generate log output
No Renderer An application that runs with default plugins and displays an empty window, but without an actual renderer
Plugin Demonstrates the creation and registration of a custom plugin
Plugin Group Demonstrates the creation and registration of a custom plugin group
Return after Run Show how to return to main after the Bevy app has exited
Thread Pool Resources Creates and customizes the internal thread pool
Without Winit Create an application without winit (runs single time, no event loop)

Assets

Example Description
Asset Loading Demonstrates various methods to load assets
Asset Processing Demonstrates how to process and load custom assets
Custom Asset Implements a custom asset loader
Custom Asset IO Implements a custom AssetReader
Hot Reloading of Assets Demonstrates automatic reloading of assets when modified on disk

Async Tasks

Example Description
Async Compute How to use AsyncComputeTaskPool to complete longer running tasks
External Source of Data on an External Thread How to use an external thread to run an infinite task and communicate with a channel

Audio

Example Description
Audio Shows how to load and play an audio file
Audio Control Shows how to load and play an audio file, and control how it's played
Decodable Shows how to create and register a custom audio source by implementing the Decodable type.
Pitch Shows how to directly play a simple pitch
Spatial Audio 2D Shows how to play spatial audio, and moving the emitter in 2D
Spatial Audio 3D Shows how to play spatial audio, and moving the emitter in 3D

Diagnostics

Example Description
Custom Diagnostic Shows how to create a custom diagnostic
Log Diagnostics Add a plugin that logs diagnostics, like frames per second (FPS), to the console

ECS (Entity Component System)

Example Description
Apply System Buffers Show how to use apply_deferred system
Component Change Detection Change detection on components
Custom Query Parameters Groups commonly used compound queries and query filters into a single type
ECS Guide Full guide to Bevy's ECS
Event Illustrates event creation, activation, and reception
Fixed Timestep Shows how to create systems that run every fixed timestep, rather than every tick
Generic System Shows how to create systems that can be reused with different types
Hierarchy Creates a hierarchy of parents and children entities
Iter Combinations Shows how to iterate over combinations of query results
Nondeterministic System Order Systems run in parallel, but their order isn't always deterministic. Here's how to detect and fix this.
One Shot Systems Shows how to flexibly run systems without scheduling them
Parallel Query Illustrates parallel queries with ParallelIterator
Removal Detection Query for entities that had a specific component removed earlier in the current frame
Run Conditions Run systems only when one or multiple conditions are met
Startup System Demonstrates a startup system (one that runs once when the app starts up)
State Illustrates how to use States to control transitioning from a Menu state to an InGame state
System Closure Show how to use closures as systems, and how to configure Local variables by capturing external state
System Parameter Illustrates creating custom system parameters with SystemParam
System Piping Pipe the output of one system into a second, allowing you to handle any errors gracefully
Timers Illustrates ticking Timer resources inside systems and handling their state

Games

Example Description
Alien Cake Addict Eat the cakes. Eat them all. An example 3D game
Breakout An implementation of the classic game "Breakout"
Contributors Displays each contributor as a bouncy bevy-ball!
Game Menu A simple game menu

Input

Example Description
Char Input Events Prints out all chars as they are inputted
Gamepad Input Shows handling of gamepad input, connections, and disconnections
Gamepad Input Events Iterates and prints gamepad input and connection events
Gamepad Rumble Shows how to rumble a gamepad using force feedback
Keyboard Input Demonstrates handling a key press/release
Keyboard Input Events Prints out all keyboard events
Keyboard Modifiers Demonstrates using key modifiers (ctrl, shift)
Mouse Grab Demonstrates how to grab the mouse, locking the cursor to the app's screen
Mouse Input Demonstrates handling a mouse button press/release
Mouse Input Events Prints out all mouse events (buttons, movement, etc.)
Text Input Simple text input with IME support
Touch Input Displays touch presses, releases, and cancels
Touch Input Events Prints out all touch inputs

Reflection

Example Description
Generic Reflection Registers concrete instances of generic types that may be used with reflection
Reflection Demonstrates how reflection in Bevy provides a way to dynamically interact with Rust types
Reflection Types Illustrates the various reflection types available
Trait Reflection Allows reflection with trait objects

Scene

Example Description
Scene Demonstrates loading from and saving scenes to files

Shaders

These examples demonstrate how to implement different shaders in user code.

A shader in its most common usage is a small program that is run by the GPU per-vertex in a mesh (a vertex shader) or per-affected-screen-fragment (a fragment shader.) The GPU executes these programs in a highly parallel way.

There are also compute shaders which are used for more general processing leveraging the GPU's parallelism.

Example Description
Animated A shader that uses dynamic data like the time since startup
Array Texture A shader that shows how to reuse the core bevy PBR shading functionality in a custom material that obtains the base color from an array texture.
Compute - Game of Life A compute shader that simulates Conway's Game of Life
Custom Vertex Attribute A shader that reads a mesh's custom vertex attribute
Instancing A shader that renders a mesh multiple times in one draw call
Material A shader and a material that uses it
Material - GLSL A shader that uses the GLSL shading language
Material - Screenspace Texture A shader that samples a texture with view-independent UV coordinates
Material Prepass A shader that uses the various textures generated by the prepass
Post Processing - Custom Render Pass A custom post processing effect, using a custom render pass that runs after the main pass
Shader Defs A shader that uses "shaders defs" (a bevy tool to selectively toggle parts of a shader)
Texture Binding Array (Bindless Textures) A shader that shows how to bind and sample multiple textures as a binding array (a.k.a. bindless textures).

Stress Tests

These examples are used to test the performance and stability of various parts of the engine in an isolated way.

Due to the focus on performance it's recommended to run the stress tests in release mode:

cargo run --release --example <example name>
Example Description
Bevymark A heavy sprite rendering workload to benchmark your system with Bevy
Many Animated Sprites Displays many animated sprites in a grid arrangement with slight offsets to their animation timers. Used for performance testing.
Many Buttons Test rendering of many UI elements
Many Cubes Simple benchmark to test per-entity draw overhead. Run with the sphere argument to test frustum culling
Many Foxes Loads an animated fox model and spawns lots of them. Good for testing skinned mesh performance. Takes an unsigned integer argument for the number of foxes to spawn. Defaults to 1000
Many Gizmos Test rendering of many gizmos
Many Glyphs Simple benchmark to test text rendering.
Many Lights Simple benchmark to test rendering many point lights. Run with WGPU_SETTINGS_PRIO=webgl2 to restrict to uniform buffers and max 256 lights
Many Sprites Displays many sprites in a grid arrangement! Used for performance testing. Use --colored to enable color tinted sprites.
Text Pipeline Text Pipeline benchmark
Transform Hierarchy Various test cases for hierarchy and transform propagation performance

Tools

Example Description
Gamepad Viewer Shows a visualization of gamepad buttons, sticks, and triggers
Scene Viewer A simple way to view glTF models with Bevy. Just run cargo run --release --example scene_viewer /path/to/model.gltf#Scene0, replacing the path as appropriate. With no arguments it will load the FieldHelmet glTF model from the repository assets subdirectory

Transforms

Example Description
3D Rotation Illustrates how to (constantly) rotate an object around an axis
Scale Illustrates how to scale an object in each direction
Transform Shows multiple transformations of objects
Translation Illustrates how to move an object along an axis

UI (User Interface)

Example Description
Borders Demonstrates how to create a node with a border
Button Illustrates creating and updating a button
CSS Grid An example for CSS Grid layout
Display and Visibility Demonstrates how Display and Visibility work in the UI.
Flex Layout Demonstrates how the AlignItems and JustifyContent properties can be composed to layout nodes and position text
Font Atlas Debug Illustrates how FontAtlases are populated (used to optimize text rendering internally)
Overflow Simple example demonstrating overflow behavior
Overflow and Clipping Debug An example to debug overflow and clipping behavior
Relative Cursor Position Showcases the RelativeCursorPosition component
Size Constraints Demonstrates how the to use the size constraints to control the size of a UI node.
Text Illustrates creating and updating text
Text Debug An example for debugging text layout
Text Wrap Debug Demonstrates text wrapping
Transparency UI Demonstrates transparency for UI
UI Illustrates various features of Bevy UI
UI Scaling Illustrates how to scale the UI
UI Texture Atlas Illustrates how to use TextureAtlases in UI
UI Z-Index Demonstrates how to control the relative depth (z-position) of UI elements
Viewport Debug An example for debugging viewport coordinates
Window Fallthrough Illustrates how to access winit::window::Window's hittest functionality.

Window

Example Description
Clear Color Creates a solid color window
Low Power Demonstrates settings to reduce power use for bevy applications
Multiple Windows Demonstrates creating multiple windows, and rendering to them
Scale Factor Override Illustrates how to customize the default window settings
Screenshot Shows how to save screenshots to disk
Transparent Window Illustrates making the window transparent and hiding the window decoration
Window Resizing Demonstrates resizing and responding to resizing a window
Window Settings Demonstrates customizing default window settings

Tests

Example Description
How to Test Systems How to test systems with commands, queries or resources

Platform-Specific Examples

Android

Setup

rustup target add aarch64-linux-android armv7-linux-androideabi
cargo install cargo-apk

The Android SDK must be installed, and the environment variable ANDROID_SDK_ROOT set to the root Android sdk folder.

When using NDK (Side by side), the environment variable ANDROID_NDK_ROOT must also be set to one of the NDKs in sdk\ndk\[NDK number].

Build & Run

To run on a device setup for Android development, run:

cargo apk run -p bevy_mobile_example

When using Bevy as a library, the following fields must be added to Cargo.toml:

[package.metadata.android]
build_targets = ["aarch64-linux-android", "armv7-linux-androideabi"]

[package.metadata.android.sdk]
target_sdk_version = 31

Please reference cargo-apk README for other Android Manifest fields.

Debugging

You can view the logs with the following command:

adb logcat | grep 'RustStdoutStderr\|bevy\|wgpu'

In case of an error getting a GPU or setting it up, you can try settings logs of wgpu_hal to DEBUG to get more information.

Sometimes, running the app complains about an unknown activity. This may be fixed by uninstalling the application:

adb uninstall org.bevyengine.example

Old phones

Bevy by default targets Android API level 31 in its examples which is the Play Store's minimum API to upload or update apps. Users of older phones may want to use an older API when testing.

To use a different API, the following fields must be updated in Cargo.toml:

[package.metadata.android.sdk]
target_sdk_version = >>API<<
min_sdk_version = >>API or less<<
Example File Description
android mobile/src/lib.rs A 3d Scene with a button and playing sound

iOS

Setup

You need to install the correct rust targets:

  • aarch64-apple-ios: iOS devices
  • x86_64-apple-ios: iOS simulator on x86 processors
  • aarch64-apple-ios-sim: iOS simulator on Apple processors
rustup target add aarch64-apple-ios x86_64-apple-ios aarch64-apple-ios-sim

Build & Run

Using bash:

cd examples/mobile
make run

In an ideal world, this will boot up, install and run the app for the first iOS simulator in your xcrun simctl devices list. If this fails, you can specify the simulator device UUID via:

DEVICE_ID=${YOUR_DEVICE_ID} make run

If you'd like to see xcode do stuff, you can run

open bevy_mobile_example.xcodeproj/

which will open xcode. You then must push the zoom zoom play button and wait for the magic.

Example File Description
ios mobile/src/lib.rs A 3d Scene with a button and playing sound

WASM

Setup

rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli

Build & Run

Following is an example for lighting. For other examples, change the lighting in the following commands.

cargo build --release --example lighting --target wasm32-unknown-unknown
wasm-bindgen --out-name wasm_example \
  --out-dir examples/wasm/target \
  --target web target/wasm32-unknown-unknown/release/examples/lighting.wasm

The first command will build the example for the wasm target, creating a binary. Then, wasm-bindgen-cli is used to create javascript bindings to this wasm file in the output file examples/wasm/target/wasm_example.js, which can be loaded using this example HTML file.

Then serve examples/wasm directory to browser. i.e.

# cargo install basic-http-server
basic-http-server examples/wasm

# with python
python3 -m http.server --directory examples/wasm

# with ruby
ruby -run -ehttpd examples/wasm

WebGL2 and WebGPU

Bevy support for WebGPU is being worked on, but is currently experimental.

To build for WebGPU, you'll need to disable default features and add all those you need, making sure to omit the webgl2 feature.

Bevy has an helper to build its examples:

  • Build for WebGL2: cargo run -p build-wasm-example -- --api webgl2 load_gltf
  • Build for WebGPU: cargo run -p build-wasm-example -- --api webgpu load_gltf

This helper will log the command used to build the examples.

Audio in the browsers

For the moment, everything is single threaded, this can lead to stuttering when playing audio in browsers. Not all browsers react the same way for all games, you will have to experiment for your game.

In browsers, audio is not authorized to start without being triggered by an user interaction. This is to avoid multiple tabs all starting to auto play some sounds. You can find more context and explanation for this on Google Chrome blog. This page also describes a JS workaround to resume audio as soon as the user interact with your game.

Optimizing

On the web, it's useful to reduce the size of the files that are distributed. With rust, there are many ways to improve your executable sizes. Here are some.

1. Tweak your Cargo.toml

Add a new profile to your Cargo.toml:

[profile.wasm-release]
# Use release profile as default values
inherits = "release"

# Optimize with size in mind, also try "s", sometimes it is better.
# This doesn't increase compilation times compared to -O3, great improvements
opt-level = "z"

# Do a second optimization pass removing duplicate or unused code from dependencies.
# Slows compile times, marginal improvements
lto = "fat"

# When building crates, optimize larger chunks at a time
# Slows compile times, marginal improvements
codegen-units = 1

Now, when building the final executable, use the wasm-release profile by replacing --release by --profile wasm-release in the cargo command.

cargo build --profile wasm-release --example lighting --target wasm32-unknown-unknown

Make sure your final executable size is smaller, some of those optimizations may not be worth keeping, due to compilation time increases.

2. Use wasm-opt from the binaryen package

Binaryen is a set of tools for working with wasm. It has a wasm-opt CLI tool.

First download the binaryen package, then locate the .wasm file generated by wasm-bindgen. It should be in the --out-dir you specified in the command line, the file name should end in _bg.wasm.

Then run wasm-opt with the -Oz flag. Note that wasm-opt is very slow.

Note that wasm-opt optimizations might not be as effective if you didn't apply the optimizations from the previous section.

wasm-opt -Oz --output optimized.wasm examples/wasm/target/lighting_bg.wasm
mv optimized.wasm examples/wasm/target/lighting_bg.wasm

For a small project with a basic 3d model and two lights, the generated file sizes are, as of July 2022, as follows:

profile wasm-opt no wasm-opt
Default 8.5M 13.0M
opt-level = "z" 6.1M 12.7M
"z" + lto = "thin" 5.9M 12M
"z" + lto = "fat" 5.1M 9.4M
"z" + "thin" + codegen-units = 1 5.3M 11M
"z" + "fat" + codegen-units = 1 4.8M 8.5M

There are more advanced optimization options available, check the following pages for more info:

Loading Assets

To load assets, they need to be available in the folder examples/wasm/assets. Cloning this repository will set it up as a symlink on Linux and macOS, but you will need to manually move the assets on Windows.