bevy/examples
Carter Anderson 08969a24b8 Modular Rendering (#2831)
This changes how render logic is composed to make it much more modular. Previously, all extraction logic was centralized for a given "type" of rendered thing. For example, we extracted meshes into a vector of ExtractedMesh, which contained the mesh and material asset handles, the transform, etc. We looked up bindings for "drawn things" using their index in the `Vec<ExtractedMesh>`. This worked fine for built in rendering, but made it hard to reuse logic for "custom" rendering. It also prevented us from reusing things like "extracted transforms" across contexts.

To make rendering more modular, I made a number of changes:

* Entities now drive rendering:
  * We extract "render components" from "app components" and store them _on_ entities. No more centralized uber lists! We now have true "ECS-driven rendering"
  * To make this perform well, I implemented #2673 in upstream Bevy for fast batch insertions into specific entities. This was merged into the `pipelined-rendering` branch here: #2815
* Reworked the `Draw` abstraction:
  * Generic `PhaseItems`: each draw phase can define its own type of "rendered thing", which can define its own "sort key"
  * Ported the 2d, 3d, and shadow phases to the new PhaseItem impl (currently Transparent2d, Transparent3d, and Shadow PhaseItems)
  * `Draw` trait and and `DrawFunctions` are now generic on PhaseItem
  * Modular / Ergonomic `DrawFunctions` via `RenderCommands`
    * RenderCommand is a trait that runs an ECS query and produces one or more RenderPass calls. Types implementing this trait can be composed to create a final DrawFunction. For example the DrawPbr DrawFunction is created from the following DrawCommand tuple. Const generics are used to set specific bind group locations:
        ```rust
         pub type DrawPbr = (
            SetPbrPipeline,
            SetMeshViewBindGroup<0>,
            SetStandardMaterialBindGroup<1>,
            SetTransformBindGroup<2>,
            DrawMesh,
        );
        ```
    * The new `custom_shader_pipelined` example illustrates how the commands above can be reused to create a custom draw function:
       ```rust
       type DrawCustom = (
           SetCustomMaterialPipeline,
           SetMeshViewBindGroup<0>,
           SetTransformBindGroup<2>,
           DrawMesh,
       );
       ``` 
* ExtractComponentPlugin and UniformComponentPlugin:
  * Simple, standardized ways to easily extract individual components and write them to GPU buffers
* Ported PBR and Sprite rendering to the new primitives above.
* Removed staging buffer from UniformVec in favor of direct Queue usage
  * Makes UniformVec much easier to use and more ergonomic. Completely removes the need for custom render graph nodes in these contexts (see the PbrNode and view Node removals and the much simpler call patterns in the relevant Prepare systems).
* Added a many_cubes_pipelined example to benchmark baseline 3d rendering performance and ensure there were no major regressions during this port. Avoiding regressions was challenging given that the old approach of extracting into centralized vectors is basically the "optimal" approach. However thanks to a various ECS optimizations and render logic rephrasing, we pretty much break even on this benchmark!
* Lifetimeless SystemParams: this will be a bit divisive, but as we continue to embrace "trait driven systems" (ex: ExtractComponentPlugin, UniformComponentPlugin, DrawCommand), the ergonomics of `(Query<'static, 'static, (&'static A, &'static B, &'static)>, Res<'static, C>)` were getting very hard to bear. As a compromise, I added "static type aliases" for the relevant SystemParams. The previous example can now be expressed like this: `(SQuery<(Read<A>, Read<B>)>, SRes<C>)`. If anyone has better ideas / conflicting opinions, please let me know!
* RunSystem trait: a way to define Systems via a trait with a SystemParam associated type. This is used to implement the various plugins mentioned above. I also added SystemParamItem and QueryItem type aliases to make "trait stye" ecs interactions nicer on the eyes (and fingers).
* RenderAsset retrying: ensures that render assets are only created when they are "ready" and allows us to create bind groups directly inside render assets (which significantly simplified the StandardMaterial code). I think ultimately we should swap this out on "asset dependency" events to wait for dependencies to load, but this will require significant asset system changes.
* Updated some built in shaders to account for missing MeshUniform fields
2021-09-23 06:16:11 +00:00
..
2d Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
3d Modular Rendering (#2831) 2021-09-23 06:16:11 +00:00
android Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
app Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
asset Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
async_tasks Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
audio Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
diagnostics Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
ecs Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
game Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
input Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
ios Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
reflection Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
scene Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
shader Modular Rendering (#2831) 2021-09-23 06:16:11 +00:00
tools Modular Rendering (#2831) 2021-09-23 06:16:11 +00:00
ui Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
wasm Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
window Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
hello_world.rs Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
README.md Modular Rendering (#2831) 2021-09-23 06:16:11 +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 File Description
hello_world hello_world.rs Runs a minimal example that outputs "hello world"

Cross-Platform Examples

2D Rendering

Example File Description
contributors 2d/contributors.rs Displays each contributor as a bouncy bevy-ball!
many_sprites 2d/many_sprites.rs Displays many sprites in a grid arragement! Used for performance testing.
mesh 2d/mesh.rs Renders a custom mesh
pipelined_texture_atlas 2d/pipelined_texture_atlas.rs Generates a texture atlas (sprite sheet) from individual sprites
sprite 2d/sprite.rs Renders a sprite
sprite_sheet 2d/sprite_sheet.rs Renders an animated sprite
text2d 2d/text2d.rs Generates text in 2d
sprite_flipping 2d/sprite_flipping.rs Renders a sprite flipped along an axis
texture_atlas 2d/texture_atlas.rs Generates a texture atlas (sprite sheet) from individual sprites

3D Rendering

Example File Description
3d_scene 3d/3d_scene.rs Simple 3D scene with basic shapes and lighting
3d_scene_pipelined 3d/3d_scene_pipelined.rs Simple 3D scene with basic shapes and lighting
cornell_box_pipelined 3d/cornell_box_pipelined.rs Re-production of the cornell box
load_gltf 3d/load_gltf.rs Loads and renders a gltf file as a scene
load_gltf_pipelined 3d/load_gltf_pipelined.rs Loads and renders a gltf file as a scene
many_cubes_pipelined 3d/many_cubes_pipelined.rs Simple benchmark to test per-entity draw overhead
msaa 3d/msaa.rs Configures MSAA (Multi-Sample Anti-Aliasing) for smoother edges
orthographic 3d/orthographic.rs Shows how to create a 3D orthographic view (for isometric-look games or CAD applications)
orthographic_pipelined 3d/orthographic_pipelined.rs Shows how to create a 3D orthographic view (for isometric-look games or CAD applications)
parenting 3d/parenting.rs Demonstrates parent->child relationships and relative transformations
pbr 3d/pbr.rs Demonstrates use of Physically Based Rendering (PBR) properties
pbr_pipelined 3d/pbr_pipelined.rs Demonstrates use of Physically Based Rendering (PBR) properties
render_to_texture 3d/render_to_texture.rs Shows how to render to texture
shadow_caster_receiver_pipelined 3d/shadow_caster_receiver_pipelined.rs Demonstrates how to prevent meshes from casting/receiving shadows in a 3d scene
shadow_biases_pipelined 3d/shadow_biases_pipelined.rs Demonstrates how shadow biases affect shadows in a 3d scene
spawner 3d/spawner.rs Renders a large number of cubes with changing position and material
texture 3d/texture.rs Shows configuration of texture materials
texture_pipelined 3d/texture_pipelined.rs Shows configuration of texture materials
update_gltf_scene 3d/update_gltf_scene.rs 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
wireframe 3d/wireframe.rs Showcases wireframe rendering
z_sort_debug 3d/z_sort_debug.rs Visualizes camera Z-ordering

Application

Example File Description
custom_loop app/custom_loop.rs Demonstrates how to create a custom runner (to update an app manually).
drag_and_drop app/drag_and_drop.rs An example that shows how to handle drag and drop in an app.
empty app/empty.rs An empty application (does nothing)
empty_defaults app/empty_defaults.rs An empty application with default plugins
headless app/headless.rs An application that runs without default plugins
logs app/logs.rs Illustrate how to use generate log output
plugin app/plugin.rs Demonstrates the creation and registration of a custom plugin
plugin_group app/plugin_group.rs Demonstrates the creation and registration of a custom plugin group
return_after_run app/return_after_run.rs Show how to return to main after the Bevy app has exited
thread_pool_resources app/thread_pool_resources.rs Creates and customizes the internal thread pool

Assets

Example File Description
asset_loading asset/asset_loading.rs Demonstrates various methods to load assets
custom_asset asset/custom_asset.rs Implements a custom asset loader
custom_asset_io asset/custom_asset_io.rs Implements a custom asset io loader
hot_asset_reloading asset/hot_asset_reloading.rs Demonstrates automatic reloading of assets when modified on disk

Async Tasks

Example File Description
async_compute async_tasks/async_compute.rs How to use AsyncComputeTaskPool to complete longer running tasks

Audio

Example File Description
audio audio/audio.rs Shows how to load and play an audio file

Diagnostics

Example File Description
custom_diagnostic diagnostics/custom_diagnostic.rs Shows how to create a custom diagnostic
log_diagnostics diagnostics/log_diagnostics.rs Add a plugin that logs diagnostics, like frames per second (FPS), to the console

ECS (Entity Component System)

Example File Description
ecs_guide ecs/ecs_guide.rs Full guide to Bevy's ECS
component_change_detection ecs/component_change_detection.rs Change detection on components
event ecs/event.rs Illustrates event creation, activation, and reception
fixed_timestep ecs/fixed_timestep.rs Shows how to create systems that run every fixed timestep, rather than every tick
hierarchy ecs/hierarchy.rs Creates a hierarchy of parents and children entities
iter_combinations ecs/iter_combinations.rs Shows how to iterate over combinations of query results.
parallel_query ecs/parallel_query.rs Illustrates parallel queries with ParallelIterator
removal_detection ecs/removal_detection.rs Query for entities that had a specific component removed in a previous stage during the current frame.
startup_system ecs/startup_system.rs Demonstrates a startup system (one that runs once when the app starts up)
state ecs/state.rs Illustrates how to use States to control transitioning from a Menu state to an InGame state
system_chaining ecs/system_chaining.rs Chain two systems together, specifying a return type in a system (such as Result)
system_param ecs/system_param.rs Illustrates creating custom system parameters with SystemParam
system_sets ecs/system_sets.rs Shows SystemSet use along with run criterion
timers ecs/timers.rs Illustrates ticking Timer resources inside systems and handling their state

Games

Example File Description
alien_cake_addict game/alien_cake_addict.rs Eat the cakes. Eat them all. An example 3D game
breakout game/breakout.rs An implementation of the classic game "Breakout"

Input

Example File Description
char_input_events input/char_input_events.rs Prints out all chars as they are inputted.
gamepad_input input/gamepad_input.rs Shows handling of gamepad input, connections, and disconnections
gamepad_input_events input/gamepad_input_events.rs Iterates and prints gamepad input and connection events
keyboard_input input/keyboard_input.rs Demonstrates handling a key press/release
keyboard_input_events input/keyboard_input_events.rs Prints out all keyboard events
keyboard_modifiers input/keyboard_modifiers.rs Demonstrates using key modifiers (ctrl, shift)
mouse_input input/mouse_input.rs Demonstrates handling a mouse button press/release
mouse_input_events input/mouse_input_events.rs Prints out all mouse events (buttons, movement, etc.)
touch_input input/touch_input.rs Displays touch presses, releases, and cancels
touch_input_events input/touch_input_events.rs Prints out all touch inputs

Reflection

Example File Description
reflection reflection/reflection.rs Demonstrates how reflection in Bevy provides a way to dynamically interact with Rust types
generic_reflection reflection/generic_reflection.rs Registers concrete instances of generic types that may be used with reflection
reflection_types reflection/reflection_types.rs Illustrates the various reflection types available
trait_reflection reflection/trait_reflection.rs Allows reflection with trait objects

Scene

Example File Description
scene scene/scene.rs Demonstrates loading from and saving scenes to files

Shaders

Example File Description
animate_shader shader/animate_shader.rs Shows how to animate a shader by accessing a time uniform variable
array_texture shader/array_texture.rs Illustrates how to create a texture for use with a texture2DArray shader uniform variable
custom_shader_pipelined shader/custom_shader_pipelined.rs Illustrates how to create custom shaders
hot_shader_reloading shader/hot_shader_reloading.rs Illustrates how to load shaders such that they can be edited while the example is still running
mesh_custom_attribute shader/mesh_custom_attribute.rs Illustrates how to add a custom attribute to a mesh and use it in a custom shader
shader_custom_material shader/shader_custom_material.rs Illustrates creating a custom material and a shader that uses it
shader_defs shader/shader_defs.rs Demonstrates creating a custom material that uses "shaders defs" (a tool to selectively toggle parts of a shader)

Tests

Example File Description
how_to_test_systems ../tests/how_to_test_systems.rs How to test systems with commands, queries or resources

Tools

Example File Description
bevymark tools/bevymark.rs A heavy workload to benchmark your system with Bevy
bevymark_pipelined tools/bevymark_pipelined.rs A heavy workload to benchmark your system with Bevy

UI (User Interface)

Example File Description
button ui/button.rs Illustrates creating and updating a button
font_atlas_debug ui/font_atlas_debug.rs Illustrates how FontAtlases are populated (used to optimize text rendering internally)
text ui/text.rs Illustrates creating and updating text
text_debug ui/text_debug.rs An example for debugging text layout
ui ui/ui.rs Illustrates various features of Bevy UI

Window

Example File Description
clear_color window/clear_color.rs Creates a solid color window
clear_color_pipelined window/clear_color_pipelined.rs Creates a solid color window with the pipelined renderer
multiple_windows window/multiple_windows.rs Creates two windows and cameras viewing the same mesh
scale_factor_override window/scale_factor_override.rs Illustrates how to customize the default window settings
window_settings window/window_settings.rs Demonstrates customizing default window settings

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 --example android

⚠️ At this time Bevy does not work in Android Emulator.

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"]
target_sdk_version = 29
min_sdk_version = 16

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

Old phones

Bevy by default targets Android API level 29 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]
target_sdk_version = >>API<<
min_sdk_version = >>API or less<<
Example File Description
android android/android.rs The 3d/3d_scene.rs example for Android

iOS

Setup

rustup target add aarch64-apple-ios x86_64-apple-ios
cargo install cargo-lipo

Build & Run

Using bash:

cd examples/ios
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_ios_example.xcodeproj/

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

The Xcode build GUI will by default build the rust library for both x86_64-apple-ios, and aarch64-apple-ios which may take a while. If you'd like speed this up, you update the IOS_TARGETS User-Defined environment variable in the "cargo_ios target" to be either x86_64-apple-ios or aarch64-apple-ios depending on your goal.

Note: if you update this variable in Xcode, it will also change the default used for the Makefile.

Example File Description
ios ios/src/lib.rs The 3d/3d_scene.rs example for iOS

WASM

Setup

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

Build & Run

Following is an example for headless_wasm. For other examples in wasm/ directory, change the headless_wasm in the following commands and edit examples/wasm/index.html to point to the correct .js file.

cargo build --example headless_wasm --target wasm32-unknown-unknown --no-default-features
wasm-bindgen --out-dir examples/wasm/target --target web target/wasm32-unknown-unknown/debug/examples/headless_wasm.wasm

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

basic-http-server examples/wasm
Example File Description
hello_wasm wasm/hello_wasm.rs Runs a minimal example that logs "hello world" to the browser's console
assets_wasm wasm/assets_wasm.rs Demonstrates how to load assets from wasm
headless_wasm wasm/headless_wasm.rs Sets up a schedule runner and continually logs a counter to the browser's console
winit_wasm wasm/winit_wasm.rs Logs user input to the browser's console. Requires the bevy_winit features