bevy/examples
Carter Anderson 40d4992401 Visibilty Inheritance, universal ComputedVisibility and RenderLayers support (#5310)
# Objective

Fixes #4907. Fixes #838. Fixes #5089.
Supersedes #5146. Supersedes #2087. Supersedes #865. Supersedes #5114

Visibility is currently entirely local. Set a parent entity to be invisible, and the children are still visible. This makes it hard for users to hide entire hierarchies of entities.

Additionally, the semantics of `Visibility` vs `ComputedVisibility` are inconsistent across entity types. 3D meshes use `ComputedVisibility` as the "definitive" visibility component, with `Visibility` being just one data source. Sprites just use `Visibility`, which means they can't feed off of `ComputedVisibility` data, such as culling information, RenderLayers, and (added in this pr) visibility inheritance information.

## Solution

Splits `ComputedVisibilty::is_visible` into `ComputedVisibilty::is_visible_in_view` and `ComputedVisibilty::is_visible_in_hierarchy`. For each visible entity, `is_visible_in_hierarchy` is computed by propagating visibility down the hierarchy. The `ComputedVisibility::is_visible()` function combines these two booleans for the canonical "is this entity visible" function.

Additionally, all entities that have `Visibility` now also have `ComputedVisibility`.  Sprites, Lights, and UI entities now use `ComputedVisibility` when appropriate.

This means that in addition to visibility inheritance, everything using Visibility now also supports RenderLayers. Notably, Sprites (and other 2d objects) now support `RenderLayers` and work properly across multiple views.

Also note that this does increase the amount of work done per sprite. Bevymark with 100,000 sprites on `main` runs in `0.017612` seconds and this runs in `0.01902`. That is certainly a gap, but I believe the api consistency and extra functionality this buys us is worth it. See [this thread](https://github.com/bevyengine/bevy/pull/5146#issuecomment-1182783452) for more info. Note that #5146 in combination with #5114 _are_ a viable alternative to this PR and _would_ perform better, but that comes at the cost of api inconsistencies and doing visibility calculations in the "wrong" place. The current visibility system does have potential for performance improvements. I would prefer to evolve that one system as a whole rather than doing custom hacks / different behaviors for each feature slice.

Here is a "split screen" example where the left camera uses RenderLayers to filter out the blue sprite.

![image](https://user-images.githubusercontent.com/2694663/178814868-2e9a2173-bf8c-4c79-8815-633899d492c3.png)


Note that this builds directly on #5146 and that @james7132 deserves the credit for the baseline visibility inheritance work. This pr moves the inherited visibility field into `ComputedVisibility`, then does the additional work of porting everything to `ComputedVisibility`. See my [comments here](https://github.com/bevyengine/bevy/pull/5146#issuecomment-1182783452) for rationale. 

## Follow up work

* Now that lights use ComputedVisibility, VisibleEntities now includes "visible lights" in the entity list. Functionally not a problem as we use queries to filter the list down in the desired context. But we should consider splitting this out into a separate`VisibleLights` collection for both clarity and performance reasons. And _maybe_ even consider scoping `VisibleEntities` down to `VisibleMeshes`?.
* Investigate alternative sprite rendering impls (in combination with visibility system tweaks) that avoid re-generating a per-view fixedbitset of visible entities every frame, then checking each ExtractedEntity. This is where most of the performance overhead lives. Ex: we could generate ExtractedEntities per-view using the VisibleEntities list, avoiding the need for the bitset.
* Should ComputedVisibility use bitflags under the hood? This would cut down on the size of the component, potentially speed up the `is_visible()` function, and allow us to cheaply expand ComputedVisibility with more data (ex: split out local visibility and parent visibility, add more culling classes, etc).
---

## Changelog

* ComputedVisibility now takes hierarchy visibility into account.
* 2D, UI and Light entities now use the ComputedVisibility component.

## Migration Guide

If you were previously reading `Visibility::is_visible` as the "actual visibility" for sprites or lights, use `ComputedVisibilty::is_visible()` instead:

```rust
// before (0.7)
fn system(query: Query<&Visibility>) {
  for visibility in query.iter() {
    if visibility.is_visible {
       log!("found visible entity");
    }
  }
}

// after (0.8)
fn system(query: Query<&ComputedVisibility>) {
  for visibility in query.iter() {
    if visibility.is_visible() {
       log!("found visible entity");
    }
  }
}
``` 


Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-07-15 23:24:42 +00:00
..
2d Visibilty Inheritance, universal ComputedVisibility and RenderLayers support (#5310) 2022-07-15 23:24:42 +00:00
3d add a 3d lines example (#5319) 2022-07-15 22:37:05 +00:00
android android - fix issues other than the rendering (#5130) 2022-06-30 19:42:45 +00:00
animation Update codebase to use IntoIterator where possible. (#5269) 2022-07-11 15:28:50 +00:00
app Rename headless_defaults example to no_renderer for clarity (#5263) 2022-07-11 14:11:32 +00:00
asset add a SceneBundle to spawn a scene (#2424) 2022-06-09 20:34:09 +00:00
async_tasks Update codebase to use IntoIterator where possible. (#5269) 2022-07-11 15:28:50 +00:00
audio Clippy improvements (#4665) 2022-05-31 01:38:07 +00:00
diagnostics Cleanups in diagnostics (#3871) 2022-06-20 17:02:25 +00:00
ecs Implement From<bool> for ShouldRun. (#5306) 2022-07-14 17:26:40 +00:00
games Update codebase to use IntoIterator where possible. (#5269) 2022-07-11 15:28:50 +00:00
input Very minor doc formatting changes (#5287) 2022-07-12 13:06:16 +00:00
ios Update codebase to use IntoIterator where possible. (#5269) 2022-07-11 15:28:50 +00:00
reflection fix new clippy lints (#5160) 2022-07-01 13:41:23 +00:00
scene Update codebase to use IntoIterator where possible. (#5269) 2022-07-11 15:28:50 +00:00
shader update wgpu to 0.13 (#5168) 2022-07-14 21:17:16 +00:00
stress_tests Visibilty Inheritance, universal ComputedVisibility and RenderLayers support (#5310) 2022-07-15 23:24:42 +00:00
tools Update codebase to use IntoIterator where possible. (#5269) 2022-07-11 15:28:50 +00:00
transforms Update codebase to use IntoIterator where possible. (#5269) 2022-07-11 15:28:50 +00:00
ui update wgpu to 0.13 (#5168) 2022-07-14 21:17:16 +00:00
wasm Remove wasm specific examples (#3705) 2022-01-17 22:38:05 +00:00
window update wgpu to 0.13 (#5168) 2022-07-14 21:17:16 +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 add a 3d lines example (#5319) 2022-07-15 22:37:05 +00:00
README.md.tpl android - fix issues other than the rendering (#5130) 2022-06-30 19:42:45 +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 Rotation Demonstrates rotating entities in 2D with quaternions
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
Shapes Renders a rectangle, circle, and hexagon
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 Scene Simple 3D scene with basic shapes and lighting
3D Shapes A scene showcasing the built-in 3D shapes
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
MSAA Configures MSAA (Multi-Sample Anti-Aliasing) for smoother edges
Orthographic View Shows how to create a 3D orthographic view (for isometric-look in games or CAD applications)
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
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
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
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
Custom Skinned Mesh Skinned mesh example with mesh and joints data defined in code
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
Custom Asset Implements a custom asset loader
Custom Asset IO Implements a custom asset io loader
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

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
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
Parallel Query Illustrates parallel queries with ParallelIterator
Removal Detection Query for entities that had a specific component removed in a previous stage during the current frame
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 Chaining Chain two systems together, specifying a return type in a system (such as Result)
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 Sets Shows SystemSet use along with run criterion
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
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.)
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
Post Processing A custom post processing effect, using two cameras, with one reusing the render texture of the first one
Shader Defs A shader that uses "shaders defs" (a bevy tool to selectively toggle parts of a shader)

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 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 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.
Transform Hierarchy Various test cases for hierarchy and transform propagation performance

Tools

Example Description
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
Global / Local Translation Illustrates the difference between direction of a translation in respect to local object or global object Transform
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
Button Illustrates creating and updating a button
Font Atlas Debug Illustrates how FontAtlases are populated (used to optimize text rendering internally)
Text Illustrates creating and updating text
Text Debug An example for debugging text layout
Transparency UI Demonstrates transparency for UI
UI Illustrates various features of Bevy UI

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
Transparent Window Illustrates making the window transparent and hiding the window decoration
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 --example android_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 informations.

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 android/android.rs The 3d/3d_scene.rs example for Android

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/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.

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 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, 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

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.