2021-02-22 04:50:05 +00:00
<!-- MD024 - The Headers from the Platform - Specific Examples should be identical -->
2023-04-17 16:13:24 +00:00
<!-- Use 'cargo run - p build - templated - pages - - build - example - page' to generate the final example README.md -->
2021-02-22 04:50:05 +00:00
<!-- markdownlint - disable - file MD024 -->
2020-08-17 23:02:59 +00:00
# Examples
These examples demonstrate the main features of Bevy and how to use them.
2020-08-25 00:06:08 +00:00
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.
2020-11-03 19:32:48 +00:00
```sh
2020-09-11 19:19:53 +00:00
cargo run --features wayland --example hello_world
2020-08-25 00:06:08 +00:00
```
2020-08-17 23:02:59 +00:00
2021-02-22 04:50:05 +00:00
**⚠️ Note: for users of releases on crates.io!**
2020-11-12 01:15:19 +00:00
2021-03-12 02:46:51 +00:00
There are often large differences and incompatible API changes between the latest [crates.io ](https://crates.io/crates/bevy ) release and the development version of Bevy in the git main branch!
2020-11-12 01:15:19 +00:00
2021-03-12 02:46:51 +00:00
If you are using a released version of bevy, you need to make sure you are viewing the correct version of the examples!
2021-04-13 17:18:47 +00:00
- Latest release: [https://github.com/bevyengine/bevy/tree/latest/examples ](https://github.com/bevyengine/bevy/tree/latest/examples )
- Specific version, such as `0.4` : [https://github.com/bevyengine/bevy/tree/v0.4.0/examples ](https://github.com/bevyengine/bevy/tree/v0.4.0/examples )
2021-03-12 02:46:51 +00:00
When you clone the repo locally to run the examples, use `git checkout` to get the correct version:
2021-02-22 04:50:05 +00:00
```bash
2021-03-12 02:46:51 +00:00
# `latest` always points to the newest release
git checkout latest
# or use a specific version
2021-02-01 04:19:10 +00:00
git checkout v0.4.0
2020-11-12 01:15:19 +00:00
```
---
2021-02-22 04:50:05 +00:00
## Table of Contents
2020-11-12 01:15:19 +00:00
Adding `WorldQuery` for `WithBundle` (#2024)
In response to #2023, here is a draft for a PR.
Fixes #2023
I've added an example to show how to use `WithBundle`, and also to test it out.
Right now there is a bug: If a bundle and a query are "the same", then it doesn't filter out
what it needs to filter out.
Example:
```
Print component initated from bundle.
[examples/ecs/query_bundle.rs:57] x = Dummy( <========= This should not get printed
111,
)
[examples/ecs/query_bundle.rs:57] x = Dummy(
222,
)
Show all components
[examples/ecs/query_bundle.rs:50] x = Dummy(
111,
)
[examples/ecs/query_bundle.rs:50] x = Dummy(
222,
)
```
However, it behaves the right way, if I add one more component to the bundle,
so the query and the bundle doesn't look the same:
```
Print component initated from bundle.
[examples/ecs/query_bundle.rs:57] x = Dummy(
222,
)
Show all components
[examples/ecs/query_bundle.rs:50] x = Dummy(
111,
)
[examples/ecs/query_bundle.rs:50] x = Dummy(
222,
)
```
I hope this helps. I'm definitely up for tinkering with this, and adding anything that I'm asked to add
or change.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-04-28 21:03:10 +00:00
- [Examples ](#examples )
- [Table of Contents ](#table-of-contents )
2020-11-15 19:24:18 +00:00
- [The Bare Minimum ](#the-bare-minimum )
- [Hello, World! ](#hello-world )
- [Cross-Platform Examples ](#cross-platform-examples )
- [2D Rendering ](#2d-rendering )
- [3D Rendering ](#3d-rendering )
2022-03-29 18:31:13 +00:00
- [Animation ](#animation )
2020-11-15 19:24:18 +00:00
- [Application ](#application )
- [Assets ](#assets )
2021-05-23 20:13:55 +00:00
- [Async Tasks ](#async-tasks )
2020-11-15 19:24:18 +00:00
- [Audio ](#audio )
- [Diagnostics ](#diagnostics )
- [ECS (Entity Component System) ](#ecs-entity-component-system )
- [Games ](#games )
- [Input ](#input )
2020-12-02 22:35:27 +00:00
- [Reflection ](#reflection )
2020-11-15 19:24:18 +00:00
- [Scene ](#scene )
- [Shaders ](#shaders )
2022-04-10 02:05:21 +00:00
- [Stress Tests ](#stress-tests )
2023-10-28 16:05:03 +00:00
- [Time ](#time )
2020-11-15 19:24:18 +00:00
- [Tools ](#tools )
2022-03-15 05:49:49 +00:00
- [Transforms ](#transforms )
2020-11-15 19:24:18 +00:00
- [UI (User Interface) ](#ui-user-interface )
- [Window ](#window )
2022-06-25 20:23:24 +00:00
- [Tests ](#tests )
2020-11-15 19:24:18 +00:00
- [Platform-Specific Examples ](#platform-specific-examples )
- [Android ](#android )
Adding `WorldQuery` for `WithBundle` (#2024)
In response to #2023, here is a draft for a PR.
Fixes #2023
I've added an example to show how to use `WithBundle`, and also to test it out.
Right now there is a bug: If a bundle and a query are "the same", then it doesn't filter out
what it needs to filter out.
Example:
```
Print component initated from bundle.
[examples/ecs/query_bundle.rs:57] x = Dummy( <========= This should not get printed
111,
)
[examples/ecs/query_bundle.rs:57] x = Dummy(
222,
)
Show all components
[examples/ecs/query_bundle.rs:50] x = Dummy(
111,
)
[examples/ecs/query_bundle.rs:50] x = Dummy(
222,
)
```
However, it behaves the right way, if I add one more component to the bundle,
so the query and the bundle doesn't look the same:
```
Print component initated from bundle.
[examples/ecs/query_bundle.rs:57] x = Dummy(
222,
)
Show all components
[examples/ecs/query_bundle.rs:50] x = Dummy(
111,
)
[examples/ecs/query_bundle.rs:50] x = Dummy(
222,
)
```
I hope this helps. I'm definitely up for tinkering with this, and adding anything that I'm asked to add
or change.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-04-28 21:03:10 +00:00
- [Setup ](#setup )
- [Build & Run ](#build--run )
- [Old phones ](#old-phones )
2020-11-15 19:24:18 +00:00
- [iOS ](#ios )
Adding `WorldQuery` for `WithBundle` (#2024)
In response to #2023, here is a draft for a PR.
Fixes #2023
I've added an example to show how to use `WithBundle`, and also to test it out.
Right now there is a bug: If a bundle and a query are "the same", then it doesn't filter out
what it needs to filter out.
Example:
```
Print component initated from bundle.
[examples/ecs/query_bundle.rs:57] x = Dummy( <========= This should not get printed
111,
)
[examples/ecs/query_bundle.rs:57] x = Dummy(
222,
)
Show all components
[examples/ecs/query_bundle.rs:50] x = Dummy(
111,
)
[examples/ecs/query_bundle.rs:50] x = Dummy(
222,
)
```
However, it behaves the right way, if I add one more component to the bundle,
so the query and the bundle doesn't look the same:
```
Print component initated from bundle.
[examples/ecs/query_bundle.rs:57] x = Dummy(
222,
)
Show all components
[examples/ecs/query_bundle.rs:50] x = Dummy(
111,
)
[examples/ecs/query_bundle.rs:50] x = Dummy(
222,
)
```
I hope this helps. I'm definitely up for tinkering with this, and adding anything that I'm asked to add
or change.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-04-28 21:03:10 +00:00
- [Setup ](#setup-1 )
- [Build & Run ](#build--run-1 )
2020-11-15 19:24:18 +00:00
- [WASM ](#wasm )
Adding `WorldQuery` for `WithBundle` (#2024)
In response to #2023, here is a draft for a PR.
Fixes #2023
I've added an example to show how to use `WithBundle`, and also to test it out.
Right now there is a bug: If a bundle and a query are "the same", then it doesn't filter out
what it needs to filter out.
Example:
```
Print component initated from bundle.
[examples/ecs/query_bundle.rs:57] x = Dummy( <========= This should not get printed
111,
)
[examples/ecs/query_bundle.rs:57] x = Dummy(
222,
)
Show all components
[examples/ecs/query_bundle.rs:50] x = Dummy(
111,
)
[examples/ecs/query_bundle.rs:50] x = Dummy(
222,
)
```
However, it behaves the right way, if I add one more component to the bundle,
so the query and the bundle doesn't look the same:
```
Print component initated from bundle.
[examples/ecs/query_bundle.rs:57] x = Dummy(
222,
)
Show all components
[examples/ecs/query_bundle.rs:50] x = Dummy(
111,
)
[examples/ecs/query_bundle.rs:50] x = Dummy(
222,
)
```
I hope this helps. I'm definitely up for tinkering with this, and adding anything that I'm asked to add
or change.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-04-28 21:03:10 +00:00
- [Setup ](#setup-2 )
- [Build & Run ](#build--run-2 )
2023-05-17 23:54:35 +00:00
- [WebGL2 and WebGPU ](#webgl2-and-webgpu )
- [Audio in the browsers ](#audio-in-the-browsers )
- [Optimizing ](#optimizing )
2022-04-10 02:05:21 +00:00
- [Loading Assets ](#loading-assets )
2020-11-15 19:24:18 +00:00
# The Bare Minimum
2020-11-12 01:15:19 +00:00
2021-02-22 04:50:05 +00:00
<!-- MD026 - Hello, World! looks better with the ! -->
<!-- markdownlint - disable - next - line MD026 -->
2020-08-17 23:02:59 +00:00
## Hello, World!
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
[`hello_world.rs` ](./hello_world.rs ) | Runs a minimal example that outputs "hello world"
2020-08-17 23:02:59 +00:00
2020-11-15 19:24:18 +00:00
# Cross-Platform Examples
2020-08-17 23:02:59 +00:00
## 2D Rendering
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
2023-03-04 12:05:26 +00:00
[2D Bloom ](../examples/2d/bloom_2d.rs ) | Illustrates bloom post-processing in 2d
2023-03-20 20:57:54 +00:00
[2D Gizmos ](../examples/2d/2d_gizmos.rs ) | A scene showcasing 2D gizmos
2022-06-25 20:23:24 +00:00
[2D Rotation ](../examples/2d/rotation.rs ) | Demonstrates rotating entities in 2D with quaternions
2022-09-25 00:57:07 +00:00
[2D Shapes ](../examples/2d/2d_shapes.rs ) | Renders a rectangle, circle, and hexagon
2023-09-11 18:52:11 +00:00
[2D Viewport To World ](../examples/2d/2d_viewport_to_world.rs ) | Demonstrates how to use the `Camera::viewport_to_world_2d` method
2023-04-24 14:20:13 +00:00
[Custom glTF vertex attribute 2D ](../examples/2d/custom_gltf_vertex_attribute.rs ) | Renders a glTF mesh in 2D with a custom vertex attribute
2022-06-25 20:23:24 +00:00
[Manual Mesh 2D ](../examples/2d/mesh2d_manual.rs ) | Renders a custom mesh "manually" with "mid-level" renderer apis
[Mesh 2D ](../examples/2d/mesh2d.rs ) | Renders a 2d mesh
[Mesh 2D With Vertex Colors ](../examples/2d/mesh2d_vertex_color_texture.rs ) | Renders a 2d mesh with vertex color attributes
[Move Sprite ](../examples/2d/move_sprite.rs ) | Changes the transform of a sprite
2022-11-14 22:15:46 +00:00
[Pixel Perfect ](../examples/2d/pixel_perfect.rs ) | Demonstrates pixel perfect in 2d
2022-06-25 20:23:24 +00:00
[Sprite ](../examples/2d/sprite.rs ) | Renders a sprite
[Sprite Flipping ](../examples/2d/sprite_flipping.rs ) | Renders a sprite flipped along an axis
[Sprite Sheet ](../examples/2d/sprite_sheet.rs ) | Renders an animated sprite
[Text 2D ](../examples/2d/text2d.rs ) | Generates text in 2D
[Texture Atlas ](../examples/2d/texture_atlas.rs ) | Generates a texture atlas (sprite sheet) from individual sprites
[Transparency in 2D ](../examples/2d/transparency_2d.rs ) | Demonstrates transparency in 2d
2020-08-17 23:02:59 +00:00
## 3D Rendering
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
2023-03-04 12:05:26 +00:00
[3D Bloom ](../examples/3d/bloom_3d.rs ) | Illustrates bloom configuration using HDR and emissive materials
2023-03-20 20:57:54 +00:00
[3D Gizmos ](../examples/3d/3d_gizmos.rs ) | A scene showcasing 3D gizmos
2022-06-25 20:23:24 +00:00
[3D Scene ](../examples/3d/3d_scene.rs ) | Simple 3D scene with basic shapes and lighting
2022-09-25 00:57:07 +00:00
[3D Shapes ](../examples/3d/3d_shapes.rs ) | A scene showcasing the built-in 3D shapes
2023-09-11 18:52:11 +00:00
[3D Viewport To World ](../examples/3d/3d_viewport_to_world.rs ) | Demonstrates how to use the `Camera::viewport_to_world` method
Temporal Antialiasing (TAA) (#7291)
![image](https://user-images.githubusercontent.com/47158642/214374911-412f0986-3927-4f7a-9a6c-413bdee6b389.png)
# Objective
- Implement an alternative antialias technique
- TAA scales based off of view resolution, not geometry complexity
- TAA filters textures, firefly pixels, and other aliasing not covered
by MSAA
- TAA additionally will reduce noise / increase quality in future
stochastic rendering techniques
- Closes https://github.com/bevyengine/bevy/issues/3663
## Solution
- Add a temporal jitter component
- Add a motion vector prepass
- Add a TemporalAntialias component and plugin
- Combine existing MSAA and FXAA examples and add TAA
## Followup Work
- Prepass motion vector support for skinned meshes
- Move uniforms needed for motion vectors into a separate bind group,
instead of using different bind group layouts
- Reuse previous frame's GPU view buffer for motion vectors, instead of
recomputing
- Mip biasing for sharper textures, and or unjitter texture UVs
https://github.com/bevyengine/bevy/issues/7323
- Compute shader for better performance
- Investigate FSR techniques
- Historical depth based disocclusion tests, for geometry disocclusion
- Historical luminance/hue based tests, for shading disocclusion
- Pixel "locks" to reduce blending rate / revamp history confidence
mechanism
- Orthographic camera support for TemporalJitter
- Figure out COD's 1-tap bicubic filter
---
## Changelog
- Added MotionVectorPrepass and TemporalJitter
- Added TemporalAntialiasPlugin, TemporalAntialiasBundle, and
TemporalAntialiasSettings
---------
Co-authored-by: IceSentry <c.giguere42@gmail.com>
Co-authored-by: IceSentry <IceSentry@users.noreply.github.com>
Co-authored-by: Robert Swain <robert.swain@gmail.com>
Co-authored-by: Daniel Chia <danstryder@gmail.com>
Co-authored-by: robtfm <50659922+robtfm@users.noreply.github.com>
Co-authored-by: Brandon Dyer <brandondyer64@gmail.com>
Co-authored-by: Edgar Geier <geieredgar@gmail.com>
2023-03-27 22:22:40 +00:00
[Anti-aliasing ](../examples/3d/anti_aliasing.rs ) | Compares different anti-aliasing methods
Add Distance and Atmospheric Fog support (#6412)
<img width="1392" alt="image" src="https://user-images.githubusercontent.com/418473/203873533-44c029af-13b7-4740-8ea3-af96bd5867c9.png">
<img width="1392" alt="image" src="https://user-images.githubusercontent.com/418473/203873549-36be7a23-b341-42a2-8a9f-ceea8ac7a2b8.png">
# Objective
- Add support for the “classic” distance fog effect, as well as a more advanced atmospheric fog effect.
## Solution
This PR:
- Introduces a new `FogSettings` component that controls distance fog per-camera.
- Adds support for three widely used “traditional” fog falloff modes: `Linear`, `Exponential` and `ExponentialSquared`, as well as a more advanced `Atmospheric` fog;
- Adds support for directional light influence over fog color;
- Extracts fog via `ExtractComponent`, then uses a prepare system that sets up a new dynamic uniform struct (`Fog`), similar to other mesh view types;
- Renders fog in PBR material shader, as a final adjustment to the `output_color`, after PBR is computed (but before tone mapping);
- Adds a new `StandardMaterial` flag to enable fog; (`fog_enabled`)
- Adds convenience methods for easier artistic control when creating non-linear fog types;
- Adds documentation around fog.
---
## Changelog
### Added
- Added support for distance-based fog effects for PBR materials, controllable per-camera via the new `FogSettings` component;
- Added `FogFalloff` enum for selecting between three widely used “traditional” fog falloff modes: `Linear`, `Exponential` and `ExponentialSquared`, as well as a more advanced `Atmospheric` fog;
2023-01-29 15:28:56 +00:00
[Atmospheric Fog ](../examples/3d/atmospheric_fog.rs ) | A scene showcasing the atmospheric fog effect
2023-01-21 21:46:53 +00:00
[Blend Modes ](../examples/3d/blend_modes.rs ) | Showcases different blend modes
2023-10-12 22:10:38 +00:00
[Deferred Rendering ](../examples/3d/deferred_rendering.rs ) | Renders meshes with both forward and deferred pipelines
Add Distance and Atmospheric Fog support (#6412)
<img width="1392" alt="image" src="https://user-images.githubusercontent.com/418473/203873533-44c029af-13b7-4740-8ea3-af96bd5867c9.png">
<img width="1392" alt="image" src="https://user-images.githubusercontent.com/418473/203873549-36be7a23-b341-42a2-8a9f-ceea8ac7a2b8.png">
# Objective
- Add support for the “classic” distance fog effect, as well as a more advanced atmospheric fog effect.
## Solution
This PR:
- Introduces a new `FogSettings` component that controls distance fog per-camera.
- Adds support for three widely used “traditional” fog falloff modes: `Linear`, `Exponential` and `ExponentialSquared`, as well as a more advanced `Atmospheric` fog;
- Adds support for directional light influence over fog color;
- Extracts fog via `ExtractComponent`, then uses a prepare system that sets up a new dynamic uniform struct (`Fog`), similar to other mesh view types;
- Renders fog in PBR material shader, as a final adjustment to the `output_color`, after PBR is computed (but before tone mapping);
- Adds a new `StandardMaterial` flag to enable fog; (`fog_enabled`)
- Adds convenience methods for easier artistic control when creating non-linear fog types;
- Adds documentation around fog.
---
## Changelog
### Added
- Added support for distance-based fog effects for PBR materials, controllable per-camera via the new `FogSettings` component;
- Added `FogFalloff` enum for selecting between three widely used “traditional” fog falloff modes: `Linear`, `Exponential` and `ExponentialSquared`, as well as a more advanced `Atmospheric` fog;
2023-01-29 15:28:56 +00:00
[Fog ](../examples/3d/fog.rs ) | A scene showcasing the distance fog effect
2023-06-23 19:26:37 +00:00
[Generate Custom Mesh ](../examples/3d/generate_custom_mesh.rs ) | Simple showcase of how to generate a custom mesh with a custom texture
2022-06-25 20:23:24 +00:00
[Lighting ](../examples/3d/lighting.rs ) | Illustrates various lighting options in a simple scene
2022-07-15 22:37:05 +00:00
[Lines ](../examples/3d/lines.rs ) | Create a custom material to draw 3d lines
2022-06-25 20:23:24 +00:00
[Load glTF ](../examples/3d/load_gltf.rs ) | Loads and renders a glTF file as a scene
[Orthographic View ](../examples/3d/orthographic.rs ) | Shows how to create a 3D orthographic view (for isometric-look in games or CAD applications)
Add parallax mapping to bevy PBR (#5928)
# Objective
Add a [parallax mapping] shader to bevy. Please note that
this is a 3d technique, NOT a 2d sidescroller feature.
## Solution
- Add related fields to `StandardMaterial`
- update the pbr shader
- Add an example taking advantage of parallax mapping
A pre-existing implementation exists at:
https://github.com/nicopap/bevy_mod_paramap/
The implementation is derived from:
https://web.archive.org/web/20150419215321/http://sunandblackcat.com/tipFullView.php?l=eng&topicid=28
Further discussion on literature is found in the `bevy_mod_paramap`
README.
### Limitations
- The mesh silhouette isn't affected by the depth map.
- The depth of the pixel does not reflect its visual position, resulting
in artifacts for depth-dependent features such as fog or SSAO
- GLTF does not define a height map texture, so somehow the user will
always need to work around this limitation, though [an extension is in
the works][gltf]
### Future work
- It's possible to update the depth in the depth buffer to follow the
parallaxed texture. This would enable interop with depth-based
visual effects, it also allows `discard`ing pixels of materials when
computed depth is higher than the one in depth buffer
- Cheap lower quality single-sample method using [offset limiting]
- Add distance fading, to disable parallaxing (relatively expensive)
on distant objects
- GLTF extension to allow defining height maps. Or a workaround
implemented through a blender plugin to the GLTF exporter that
uses the `extras` field to add height map.
- [Quadratic surface vertex attributes][oliveira_3] to enable parallax
mapping on bending surfaces and allow clean silhouetting.
- noise based sampling, to limit the pancake artifacts.
- Cone mapping ([GPU gems], [Simcity (2013)][simcity]). Requires
preprocessing, increase depth map size, reduces sample count greatly.
- [Quadtree parallax mapping][qpm] (also requires preprocessing)
- Self-shadowing of parallax-mapped surfaces by modifying the shadow map
- Generate depth map from normal map [link to slides], [blender
question]
https://user-images.githubusercontent.com/26321040/223563792-dffcc6ab-70e8-4ff9-90d1-b36c338695ad.mp4
[blender question]:
https://blender.stackexchange.com/questions/89278/how-to-get-a-smooth-curvature-map-from-a-normal-map
[link to slides]:
https://developer.download.nvidia.com/assets/gamedev/docs/nmap2displacement.pdf
[oliveira_3]:
https://www.inf.ufrgs.br/~oliveira/pubs_files/Oliveira_Policarpo_RP-351_Jan_2005.pdf
[GPU gems]:
https://developer.nvidia.com/gpugems/gpugems3/part-iii-rendering/chapter-18-relaxed-cone-stepping-relief-mapping
[simcity]:
https://community.simtropolis.com/omnibus/other-games/building-and-rendering-simcity-2013-r247/
[offset limiting]:
https://raw.githubusercontent.com/marcusstenbeck/tncg14-parallax-mapping/master/documents/Parallax%20Mapping%20with%20Offset%20Limiting%20-%20A%20Per-Pixel%20Approximation%20of%20Uneven%20Surfaces.pdf
[gltf]: https://github.com/KhronosGroup/glTF/pull/2196
[qpm]:
https://www.gamedevs.org/uploads/quadtree-displacement-mapping-with-height-blending.pdf
---
## Changelog
- Add a `depth_map` field to the `StandardMaterial`, it is a grayscale
image where white represents bottom and black the top. If `depth_map`
is set, bevy's pbr shader will use it to do [parallax mapping] to
give an increased feel of depth to the material. This is similar to a
displacement map, but with infinite precision at fairly low cost.
- The fields `parallax_mapping_method`, `parallax_depth_scale` and
`max_parallax_layer_count` allow finer grained control over the
behavior of the parallax shader.
- Add the `parallax_mapping` example to show off the effect.
[parallax mapping]: https://en.wikipedia.org/wiki/Parallax_mapping
---------
Co-authored-by: Robert Swain <robert.swain@gmail.com>
2023-04-15 10:25:14 +00:00
[Parallax Mapping ](../examples/3d/parallax_mapping.rs ) | Demonstrates use of a normal map and depth map for parallax mapping
2022-06-25 20:23:24 +00:00
[Parenting ](../examples/3d/parenting.rs ) | Demonstrates parent->child relationships and relative transformations
[Physically Based Rendering ](../examples/3d/pbr.rs ) | Demonstrates use of Physically Based Rendering (PBR) properties
[Render to Texture ](../examples/3d/render_to_texture.rs ) | Shows how to render to a texture, useful for mirrors, UI, or exporting images
Screen Space Ambient Occlusion (SSAO) MVP (#7402)
![image](https://github.com/bevyengine/bevy/assets/47158642/dbb62645-f639-4f2b-b84b-26fd915c186d)
# Objective
- Add Screen space ambient occlusion (SSAO). SSAO approximates
small-scale, local occlusion of _indirect_ diffuse light between
objects. SSAO does not apply to direct lighting, such as point or
directional lights.
- This darkens creases, e.g. on staircases, and gives nice contact
shadows where objects meet, giving entities a more "grounded" feel.
- Closes https://github.com/bevyengine/bevy/issues/3632.
## Solution
- Implement the GTAO algorithm.
-
https://www.activision.com/cdn/research/Practical_Real_Time_Strategies_for_Accurate_Indirect_Occlusion_NEW%20VERSION_COLOR.pdf
-
https://blog.selfshadow.com/publications/s2016-shading-course/activision/s2016_pbs_activision_occlusion.pdf
- Source code heavily based on [Intel's
XeGTAO](https://github.com/GameTechDev/XeGTAO/blob/0d177ce06bfa642f64d8af4de1197ad1bcb862d4/Source/Rendering/Shaders/XeGTAO.hlsli).
- Add an SSAO bevy example.
## Algorithm Overview
* Run a depth and normal prepass
* Create downscaled mips of the depth texture (preprocess_depths pass)
* GTAO pass - for each pixel, take several random samples from the
depth+normal buffers, reconstruct world position, raytrace in screen
space to estimate occlusion. Rather then doing completely random samples
on a hemisphere, you choose random _slices_ of the hemisphere, and then
can analytically compute the full occlusion of that slice. Also compute
edges based on depth differences here.
* Spatial denoise pass - bilateral blur, using edge detection to not
blur over edges. This is the final SSAO result.
* Main pass - if SSAO exists, sample the SSAO texture, and set occlusion
to be the minimum of ssao/material occlusion. This then feeds into the
rest of the PBR shader as normal.
---
## Future Improvements
- Maybe remove the low quality preset for now (too noisy)
- WebGPU fallback (see below)
- Faster depth->world position (see reverted code)
- Bent normals
- Try interleaved gradient noise or spatiotemporal blue noise
- Replace the spatial denoiser with a combined spatial+temporal denoiser
- Render at half resolution and use a bilateral upsample
- Better multibounce approximation
(https://drive.google.com/file/d/1SyagcEVplIm2KkRD3WQYSO9O0Iyi1hfy/view)
## Far-Future Performance Improvements
- F16 math (missing naga-wgsl support
https://github.com/gfx-rs/naga/issues/1884)
- Faster coordinate space conversion for normals
- Faster depth mipchain creation
(https://github.com/GPUOpen-Effects/FidelityFX-SPD) (wgpu/naga does not
currently support subgroup ops)
- Deinterleaved SSAO for better cache efficiency
(https://developer.nvidia.com/sites/default/files/akamai/gameworks/samples/DeinterleavedTexturing.pdf)
## Other Interesting Papers
- Visibility bitmask
(https://link.springer.com/article/10.1007/s00371-022-02703-y,
https://cdrinmatane.github.io/posts/cgspotlight-slides/)
- Screen space diffuse lighting
(https://github.com/Patapom/GodComplex/blob/master/Tests/TestHBIL/2018%20Mayaux%20-%20Horizon-Based%20Indirect%20Lighting%20(HBIL).pdf)
## Platform Support
* SSAO currently does not work on DirectX12 due to issues with wgpu and
naga:
* https://github.com/gfx-rs/wgpu/pull/3798
* https://github.com/gfx-rs/naga/pull/2353
* SSAO currently does not work on WebGPU because r16float is not a valid
storage texture format
https://gpuweb.github.io/gpuweb/wgsl/#storage-texel-formats. We can fix
this with a fallback to r32float.
---
## Changelog
- Added ScreenSpaceAmbientOcclusionSettings,
ScreenSpaceAmbientOcclusionQualityLevel, and
ScreenSpaceAmbientOcclusionBundle
---------
Co-authored-by: IceSentry <c.giguere42@gmail.com>
Co-authored-by: IceSentry <IceSentry@users.noreply.github.com>
Co-authored-by: Daniel Chia <danstryder@gmail.com>
Co-authored-by: Elabajaba <Elabajaba@users.noreply.github.com>
Co-authored-by: Robert Swain <robert.swain@gmail.com>
Co-authored-by: robtfm <50659922+robtfm@users.noreply.github.com>
Co-authored-by: Brandon Dyer <brandondyer64@gmail.com>
Co-authored-by: Edgar Geier <geieredgar@gmail.com>
Co-authored-by: Nicola Papale <nicopap@users.noreply.github.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-06-18 21:05:55 +00:00
[Screen Space Ambient Occlusion ](../examples/3d/ssao.rs ) | A scene showcasing screen space ambient occlusion
2022-06-25 20:23:24 +00:00
[Shadow Biases ](../examples/3d/shadow_biases.rs ) | Demonstrates how shadow biases affect shadows in a 3d scene
[Shadow Caster and Receiver ](../examples/3d/shadow_caster_receiver.rs ) | Demonstrates how to prevent meshes from casting/receiving shadows in a 3d scene
Support array / cubemap / cubemap array textures in KTX2 (#5325)
# Objective
- Fix / support KTX2 array / cubemap / cubemap array textures
- Fixes #4495 . Supersedes #4514 .
## Solution
- Add `Option<TextureViewDescriptor>` to `Image` to enable configuration of the `TextureViewDimension` of a texture.
- This allows users to set `D2Array`, `D3`, `Cube`, `CubeArray` or whatever they need
- Automatically configure this when loading KTX2
- Transcode all layers and faces instead of just one
- Use the UASTC block size of 128 bits, and the number of blocks in x/y for a given mip level in order to determine the offset of the layer and face within the KTX2 mip level data
- `wgpu` wants data ordered as layer 0 mip 0..n, layer 1 mip 0..n, etc. See https://docs.rs/wgpu/latest/wgpu/util/trait.DeviceExt.html#tymethod.create_texture_with_data
- Reorder the data KTX2 mip X layer Y face Z to `wgpu` layer Y face Z mip X order
- Add a `skybox` example to demonstrate / test loading cubemaps from PNG and KTX2, including ASTC 4x4, BC7, and ETC2 compression for support everywhere. Note that you need to enable the `ktx2,zstd` features to be able to load the compressed textures.
---
## Changelog
- Fixed: KTX2 array / cubemap / cubemap array textures
- Fixes: Validation failure for compressed textures stored in KTX2 where the width/height are not a multiple of the block dimensions.
- Added: `Image` now has an `Option<TextureViewDescriptor>` field to enable configuration of the texture view. This is useful for configuring the `TextureViewDimension` when it is not just a plain 2D texture and the loader could/did not identify what it should be.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-07-30 07:02:58 +00:00
[Skybox ](../examples/3d/skybox.rs ) | Load a cubemap texture onto a cube like a skybox and cycle through different compressed texture formats.
2022-06-25 20:23:24 +00:00
[Spherical Area Lights ](../examples/3d/spherical_area_lights.rs ) | Demonstrates how point light radius values affect light behavior
[Split Screen ](../examples/3d/split_screen.rs ) | Demonstrates how to render two cameras to the same window to accomplish "split screen"
2022-07-08 19:57:43 +00:00
[Spotlight ](../examples/3d/spotlight.rs ) | Illustrates spot lights
2022-06-25 20:23:24 +00:00
[Texture ](../examples/3d/texture.rs ) | Shows configuration of texture materials
2023-02-19 20:38:13 +00:00
[Tonemapping ](../examples/3d/tonemapping.rs ) | Compares tonemapping options
`StandardMaterial` Light Transmission (#8015)
# Objective
<img width="1920" alt="Screenshot 2023-04-26 at 01 07 34"
src="https://user-images.githubusercontent.com/418473/234467578-0f34187b-5863-4ea1-88e9-7a6bb8ce8da3.png">
This PR adds both diffuse and specular light transmission capabilities
to the `StandardMaterial`, with support for screen space refractions.
This enables realistically representing a wide range of real-world
materials, such as:
- Glass; (Including frosted glass)
- Transparent and translucent plastics;
- Various liquids and gels;
- Gemstones;
- Marble;
- Wax;
- Paper;
- Leaves;
- Porcelain.
Unlike existing support for transparency, light transmission does not
rely on fixed function alpha blending, and therefore works with both
`AlphaMode::Opaque` and `AlphaMode::Mask` materials.
## Solution
- Introduces a number of transmission related fields in the
`StandardMaterial`;
- For specular transmission:
- Adds logic to take a view main texture snapshot after the opaque
phase; (in order to perform screen space refractions)
- Introduces a new `Transmissive3d` phase to the renderer, to which all
meshes with `transmission > 0.0` materials are sent.
- Calculates a light exit point (of the approximate mesh volume) using
`ior` and `thickness` properties
- Samples the snapshot texture with an adaptive number of taps across a
`roughness`-controlled radius enabling “blurry” refractions
- For diffuse transmission:
- Approximates transmitted diffuse light by using a second, flipped +
displaced, diffuse-only Lambertian lobe for each light source.
## To Do
- [x] Figure out where `fresnel_mix()` is taking place, if at all, and
where `dielectric_specular` is being calculated, if at all, and update
them to use the `ior` value (Not a blocker, just a nice-to-have for more
correct BSDF)
- To the _best of my knowledge, this is now taking place, after
964340cdd. The fresnel mix is actually "split" into two parts in our
implementation, one `(1 - fresnel(...))` in the transmission, and
`fresnel()` in the light implementations. A surface with more
reflectance now will produce slightly dimmer transmission towards the
grazing angle, as more of the light gets reflected.
- [x] Add `transmission_texture`
- [x] Add `diffuse_transmission_texture`
- [x] Add `thickness_texture`
- [x] Add `attenuation_distance` and `attenuation_color`
- [x] Connect values to glTF loader
- [x] `transmission` and `transmission_texture`
- [x] `thickness` and `thickness_texture`
- [x] `ior`
- [ ] `diffuse_transmission` and `diffuse_transmission_texture` (needs
upstream support in `gltf` crate, not a blocker)
- [x] Add support for multiple screen space refraction “steps”
- [x] Conditionally create no transmission snapshot texture at all if
`steps == 0`
- [x] Conditionally enable/disable screen space refraction transmission
snapshots
- [x] Read from depth pre-pass to prevent refracting pixels in front of
the light exit point
- [x] Use `interleaved_gradient_noise()` function for sampling blur in a
way that benefits from TAA
- [x] Drill down a TAA `#define`, tweak some aspects of the effect
conditionally based on it
- [x] Remove const array that's crashing under HLSL (unless a new `naga`
release with https://github.com/gfx-rs/naga/pull/2496 comes out before
we merge this)
- [ ] Look into alternatives to the `switch` hack for dynamically
indexing the const array (might not be needed, compilers seem to be
decent at expanding it)
- [ ] Add pipeline keys for gating transmission (do we really want/need
this?)
- [x] Tweak some material field/function names?
## A Note on Texture Packing
_This was originally added as a comment to the
`specular_transmission_texture`, `thickness_texture` and
`diffuse_transmission_texture` documentation, I removed it since it was
more confusing than helpful, and will likely be made redundant/will need
to be updated once we have a better infrastructure for preprocessing
assets_
Due to how channels are mapped, you can more efficiently use a single
shared texture image
for configuring the following:
- R - `specular_transmission_texture`
- G - `thickness_texture`
- B - _unused_
- A - `diffuse_transmission_texture`
The `KHR_materials_diffuse_transmission` glTF extension also defines a
`diffuseTransmissionColorTexture`,
that _we don't currently support_. One might choose to pack the
intensity and color textures together,
using RGB for the color and A for the intensity, in which case this
packing advice doesn't really apply.
---
## Changelog
- Added a new `Transmissive3d` render phase for rendering specular
transmissive materials with screen space refractions
- Added rendering support for transmitted environment map light on the
`StandardMaterial` as a fallback for screen space refractions
- Added `diffuse_transmission`, `specular_transmission`, `thickness`,
`ior`, `attenuation_distance` and `attenuation_color` to the
`StandardMaterial`
- Added `diffuse_transmission_texture`, `specular_transmission_texture`,
`thickness_texture` to the `StandardMaterial`, gated behind a new
`pbr_transmission_textures` cargo feature (off by default, for maximum
hardware compatibility)
- Added `Camera3d::screen_space_specular_transmission_steps` for
controlling the number of “layers of transparency” rendered for
transmissive objects
- Added a `TransmittedShadowReceiver` component for enabling shadows in
(diffusely) transmitted light. (disabled by default, as it requires
carefully setting up the `thickness` to avoid self-shadow artifacts)
- Added support for the `KHR_materials_transmission`,
`KHR_materials_ior` and `KHR_materials_volume` glTF extensions
- Renamed items related to temporal jitter for greater consistency
## Migration Guide
- `SsaoPipelineKey::temporal_noise` has been renamed to
`SsaoPipelineKey::temporal_jitter`
- The `TAA` shader def (controlled by the presence of the
`TemporalAntiAliasSettings` component in the camera) has been replaced
with the `TEMPORAL_JITTER` shader def (controlled by the presence of the
`TemporalJitter` component in the camera)
- `MeshPipelineKey::TAA` has been replaced by
`MeshPipelineKey::TEMPORAL_JITTER`
- The `TEMPORAL_NOISE` shader def has been consolidated with
`TEMPORAL_JITTER`
2023-10-31 20:59:02 +00:00
[Transmission ](../examples/3d/transmission.rs ) | Showcases light transmission in the PBR material
2022-06-25 20:23:24 +00:00
[Transparency in 3D ](../examples/3d/transparency_3d.rs ) | Demonstrates transparency in 3d
[Two Passes ](../examples/3d/two_passes.rs ) | Renders two 3d passes to the same window from different perspectives
[Update glTF Scene ](../examples/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
[Vertex Colors ](../examples/3d/vertex_colors.rs ) | Shows the use of vertex colors
[Wireframe ](../examples/3d/wireframe.rs ) | Showcases wireframe rendering
2020-08-17 23:02:59 +00:00
2022-03-29 18:31:13 +00:00
## Animation
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
[Animated Fox ](../examples/animation/animated_fox.rs ) | Plays an animation from a skinned glTF
[Animated Transform ](../examples/animation/animated_transform.rs ) | Create and play an animation defined by code that operates on the `Transform` component
2023-04-17 16:16:56 +00:00
[Cubic Curve ](../examples/animation/cubic_curve.rs ) | Bezier curve example showing a cube following a cubic curve
2022-06-25 20:23:24 +00:00
[Custom Skinned Mesh ](../examples/animation/custom_skinned_mesh.rs ) | Skinned mesh example with mesh and joints data defined in code
Add morph targets (#8158)
# Objective
- Add morph targets to `bevy_pbr` (closes #5756) & load them from glTF
- Supersedes #3722
- Fixes #6814
[Morph targets][1] (also known as shape interpolation, shape keys, or
blend shapes) allow animating individual vertices with fine grained
controls. This is typically used for facial expressions. By specifying
multiple poses as vertex offset, and providing a set of weight of each
pose, it is possible to define surprisingly realistic transitions
between poses. Blending between multiple poses also allow composition.
Morph targets are part of the [gltf standard][2] and are a feature of
Unity and Unreal, and babylone.js, it is only natural to implement them
in bevy.
## Solution
This implementation of morph targets uses a 3d texture where each pixel
is a component of an animated attribute. Each layer is a different
target. We use a 2d texture for each target, because the number of
attribute×components×animated vertices is expected to always exceed the
maximum pixel row size limit of webGL2. It copies fairly closely the way
skinning is implemented on the CPU side, while on the GPU side, the
shader morph target implementation is a relatively trivial detail.
We add an optional `morph_texture` to the `Mesh` struct. The
`morph_texture` is built through a method that accepts an iterator over
attribute buffers.
The `MorphWeights` component, user-accessible, controls the blend of
poses used by mesh instances (so that multiple copy of the same mesh may
have different weights), all the weights are uploaded to a uniform
buffer of 256 `f32`. We limit to 16 poses per mesh, and a total of 256
poses.
More literature:
* Old babylone.js implementation (vertex attribute-based):
https://www.eternalcoding.com/dev-log-1-morph-targets/
* Babylone.js implementation (similar to ours):
https://www.youtube.com/watch?v=LBPRmGgU0PE
* GPU gems 3:
https://developer.nvidia.com/gpugems/gpugems3/part-i-geometry/chapter-3-directx-10-blend-shapes-breaking-limits
* Development discord thread
https://discord.com/channels/691052431525675048/1083325980615114772
https://user-images.githubusercontent.com/26321040/231181046-3bca2ab2-d4d9-472e-8098-639f1871ce2e.mp4
https://github.com/bevyengine/bevy/assets/26321040/d2a0c544-0ef8-45cf-9f99-8c3792f5a258
## Acknowledgements
* Thanks to `storytold` for sponsoring the feature
* Thanks to `superdump` and `james7132` for guidance and help figuring
out stuff
## Future work
- Handling of less and more attributes (eg: animated uv, animated
arbitrary attributes)
- Dynamic pose allocation (so that zero-weighted poses aren't uploaded
to GPU for example, enables much more total poses)
- Better animation API, see #8357
----
## Changelog
- Add morph targets to bevy meshes
- Support up to 64 poses per mesh of individually up to 116508 vertices,
animation currently strictly limited to the position, normal and tangent
attributes.
- Load a morph target using `Mesh::set_morph_targets`
- Add `VisitMorphTargets` and `VisitMorphAttributes` traits to
`bevy_render`, this allows defining morph targets (a fairly complex and
nested data structure) through iterators (ie: single copy instead of
passing around buffers), see documentation of those traits for details
- Add `MorphWeights` component exported by `bevy_render`
- `MorphWeights` control mesh's morph target weights, blending between
various poses defined as morph targets.
- `MorphWeights` are directly inherited by direct children (single level
of hierarchy) of an entity. This allows controlling several mesh
primitives through a unique entity _as per GLTF spec_.
- Add `MorphTargetNames` component, naming each indices of loaded morph
targets.
- Load morph targets weights and buffers in `bevy_gltf`
- handle morph targets animations in `bevy_animation` (previously, it
was a `warn!` log)
- Add the `MorphStressTest.gltf` asset for morph targets testing, taken
from the glTF samples repo, CC0.
- Add morph target manipulation to `scene_viewer`
- Separate the animation code in `scene_viewer` from the rest of the
code, reducing `#[cfg(feature)]` noise
- Add the `morph_targets.rs` example to show off how to manipulate morph
targets, loading `MorpStressTest.gltf`
## Migration Guide
- (very specialized, unlikely to be touched by 3rd parties)
- `MeshPipeline` now has a single `mesh_layouts` field rather than
separate `mesh_layout` and `skinned_mesh_layout` fields. You should
handle all possible mesh bind group layouts in your implementation
- You should also handle properly the new `MORPH_TARGETS` shader def and
mesh pipeline key. A new function is exposed to make this easier:
`setup_moprh_and_skinning_defs`
- The `MeshBindGroup` is now `MeshBindGroups`, cached bind groups are
now accessed through the `get` method.
[1]: https://en.wikipedia.org/wiki/Morph_target_animation
[2]:
https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#morph-targets
---------
Co-authored-by: François <mockersf@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-06-22 20:00:01 +00:00
[Morph Targets ](../examples/animation/morph_targets.rs ) | Plays an animation from a glTF file with meshes with morph targets
2022-06-25 20:23:24 +00:00
[glTF Skinned Mesh ](../examples/animation/gltf_skinned_mesh.rs ) | Skinned mesh example with mesh and joints data loaded from a glTF file
2022-03-29 18:31:13 +00:00
2020-08-17 23:02:59 +00:00
## Application
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
[Custom Loop ](../examples/app/custom_loop.rs ) | Demonstrates how to create a custom runner (to update an app manually)
[Drag and Drop ](../examples/app/drag_and_drop.rs ) | An example that shows how to handle drag and drop in an app
[Empty ](../examples/app/empty.rs ) | An empty application (does nothing)
[Empty with Defaults ](../examples/app/empty_defaults.rs ) | An empty application with default plugins
[Headless ](../examples/app/headless.rs ) | An application that runs without default plugins
[Logs ](../examples/app/logs.rs ) | Illustrate how to use generate log output
2022-07-11 14:11:32 +00:00
[No Renderer ](../examples/app/no_renderer.rs ) | An application that runs with default plugins and displays an empty window, but without an actual renderer
2022-06-25 20:23:24 +00:00
[Plugin ](../examples/app/plugin.rs ) | Demonstrates the creation and registration of a custom plugin
[Plugin Group ](../examples/app/plugin_group.rs ) | Demonstrates the creation and registration of a custom plugin group
[Return after Run ](../examples/app/return_after_run.rs ) | Show how to return to main after the Bevy app has exited
[Thread Pool Resources ](../examples/app/thread_pool_resources.rs ) | Creates and customizes the internal thread pool
[Without Winit ](../examples/app/without_winit.rs ) | Create an application without winit (runs single time, no event loop)
2020-08-17 23:02:59 +00:00
## Assets
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
[Asset Loading ](../examples/asset/asset_loading.rs ) | Demonstrates various methods to load assets
2023-10-25 19:37:03 +00:00
[Asset Processing ](../examples/asset/processing/asset_processing.rs ) | Demonstrates how to process and load custom assets
2022-06-25 20:23:24 +00:00
[Custom Asset ](../examples/asset/custom_asset.rs ) | Implements a custom asset loader
Bevy Asset V2 (#8624)
# Bevy Asset V2 Proposal
## Why Does Bevy Need A New Asset System?
Asset pipelines are a central part of the gamedev process. Bevy's
current asset system is missing a number of features that make it
non-viable for many classes of gamedev. After plenty of discussions and
[a long community feedback
period](https://github.com/bevyengine/bevy/discussions/3972), we've
identified a number missing features:
* **Asset Preprocessing**: it should be possible to "preprocess" /
"compile" / "crunch" assets at "development time" rather than when the
game starts up. This enables offloading expensive work from deployed
apps, faster asset loading, less runtime memory usage, etc.
* **Per-Asset Loader Settings**: Individual assets cannot define their
own loaders that override the defaults. Additionally, they cannot
provide per-asset settings to their loaders. This is a huge limitation,
as many asset types don't provide all information necessary for Bevy
_inside_ the asset. For example, a raw PNG image says nothing about how
it should be sampled (ex: linear vs nearest).
* **Asset `.meta` files**: assets should have configuration files stored
adjacent to the asset in question, which allows the user to configure
asset-type-specific settings. These settings should be accessible during
the pre-processing phase. Modifying a `.meta` file should trigger a
re-processing / re-load of the asset. It should be possible to configure
asset loaders from the meta file.
* **Processed Asset Hot Reloading**: Changes to processed assets (or
their dependencies) should result in re-processing them and re-loading
the results in live Bevy Apps.
* **Asset Dependency Tracking**: The current bevy_asset has no good way
to wait for asset dependencies to load. It punts this as an exercise for
consumers of the loader apis, which is unreasonable and error prone.
There should be easy, ergonomic ways to wait for assets to load and
block some logic on an asset's entire dependency tree loading.
* **Runtime Asset Loading**: it should be (optionally) possible to load
arbitrary assets dynamically at runtime. This necessitates being able to
deploy and run the asset server alongside Bevy Apps on _all platforms_.
For example, we should be able to invoke the shader compiler at runtime,
stream scenes from sources like the internet, etc. To keep deployed
binaries (and startup times) small, the runtime asset server
configuration should be configurable with different settings compared to
the "pre processor asset server".
* **Multiple Backends**: It should be possible to load assets from
arbitrary sources (filesystems, the internet, remote asset serves, etc).
* **Asset Packing**: It should be possible to deploy assets in
compressed "packs", which makes it easier and more efficient to
distribute assets with Bevy Apps.
* **Asset Handoff**: It should be possible to hold a "live" asset
handle, which correlates to runtime data, without actually holding the
asset in memory. Ex: it must be possible to hold a reference to a GPU
mesh generated from a "mesh asset" without keeping the mesh data in CPU
memory
* **Per-Platform Processed Assets**: Different platforms and app
distributions have different capabilities and requirements. Some
platforms need lower asset resolutions or different asset formats to
operate within the hardware constraints of the platform. It should be
possible to define per-platform asset processing profiles. And it should
be possible to deploy only the assets required for a given platform.
These features have architectural implications that are significant
enough to require a full rewrite. The current Bevy Asset implementation
got us this far, but it can take us no farther. This PR defines a brand
new asset system that implements most of these features, while laying
the foundations for the remaining features to be built.
## Bevy Asset V2
Here is a quick overview of the features introduced in this PR.
* **Asset Preprocessing**: Preprocess assets at development time into
more efficient (and configurable) representations
* **Dependency Aware**: Dependencies required to process an asset are
tracked. If an asset's processed dependency changes, it will be
reprocessed
* **Hot Reprocessing/Reloading**: detect changes to asset source files,
reprocess them if they have changed, and then hot-reload them in Bevy
Apps.
* **Only Process Changes**: Assets are only re-processed when their
source file (or meta file) has changed. This uses hashing and timestamps
to avoid processing assets that haven't changed.
* **Transactional and Reliable**: Uses write-ahead logging (a technique
commonly used by databases) to recover from crashes / forced-exits.
Whenever possible it avoids full-reprocessing / only uncompleted
transactions will be reprocessed. When the processor is running in
parallel with a Bevy App, processor asset writes block Bevy App asset
reads. Reading metadata + asset bytes is guaranteed to be transactional
/ correctly paired.
* **Portable / Run anywhere / Database-free**: The processor does not
rely on an in-memory database (although it uses some database techniques
for reliability). This is important because pretty much all in-memory
databases have unsupported platforms or build complications.
* **Configure Processor Defaults Per File Type**: You can say "use this
processor for all files of this type".
* **Custom Processors**: The `Processor` trait is flexible and
unopinionated. It can be implemented by downstream plugins.
* **LoadAndSave Processors**: Most asset processing scenarios can be
expressed as "run AssetLoader A, save the results using AssetSaver X,
and then load the result using AssetLoader B". For example, load this
png image using `PngImageLoader`, which produces an `Image` asset and
then save it using `CompressedImageSaver` (which also produces an
`Image` asset, but in a compressed format), which takes an `Image` asset
as input. This means if you have an `AssetLoader` for an asset, you are
already half way there! It also means that you can share AssetSavers
across multiple loaders. Because `CompressedImageSaver` accepts Bevy's
generic Image asset as input, it means you can also use it with some
future `JpegImageLoader`.
* **Loader and Saver Settings**: Asset Loaders and Savers can now define
their own settings types, which are passed in as input when an asset is
loaded / saved. Each asset can define its own settings.
* **Asset `.meta` files**: configure asset loaders, their settings,
enable/disable processing, and configure processor settings
* **Runtime Asset Dependency Tracking** Runtime asset dependencies (ex:
if an asset contains a `Handle<Image>`) are tracked by the asset server.
An event is emitted when an asset and all of its dependencies have been
loaded
* **Unprocessed Asset Loading**: Assets do not require preprocessing.
They can be loaded directly. A processed asset is just a "normal" asset
with some extra metadata. Asset Loaders don't need to know or care about
whether or not an asset was processed.
* **Async Asset IO**: Asset readers/writers use async non-blocking
interfaces. Note that because Rust doesn't yet support async traits,
there is a bit of manual Boxing / Future boilerplate. This will
hopefully be removed in the near future when Rust gets async traits.
* **Pluggable Asset Readers and Writers**: Arbitrary asset source
readers/writers are supported, both by the processor and the asset
server.
* **Better Asset Handles**
* **Single Arc Tree**: Asset Handles now use a single arc tree that
represents the lifetime of the asset. This makes their implementation
simpler, more efficient, and allows us to cheaply attach metadata to
handles. Ex: the AssetPath of a handle is now directly accessible on the
handle itself!
* **Const Typed Handles**: typed handles can be constructed in a const
context. No more weird "const untyped converted to typed at runtime"
patterns!
* **Handles and Ids are Smaller / Faster To Hash / Compare**: Typed
`Handle<T>` is now much smaller in memory and `AssetId<T>` is even
smaller.
* **Weak Handle Usage Reduction**: In general Handles are now considered
to be "strong". Bevy features that previously used "weak `Handle<T>`"
have been ported to `AssetId<T>`, which makes it statically clear that
the features do not hold strong handles (while retaining strong type
information). Currently Handle::Weak still exists, but it is very
possible that we can remove that entirely.
* **Efficient / Dense Asset Ids**: Assets now have efficient dense
runtime asset ids, which means we can avoid expensive hash lookups.
Assets are stored in Vecs instead of HashMaps. There are now typed and
untyped ids, which means we no longer need to store dynamic type
information in the ID for typed handles. "AssetPathId" (which was a
nightmare from a performance and correctness standpoint) has been
entirely removed in favor of dense ids (which are retrieved for a path
on load)
* **Direct Asset Loading, with Dependency Tracking**: Assets that are
defined at runtime can still have their dependencies tracked by the
Asset Server (ex: if you create a material at runtime, you can still
wait for its textures to load). This is accomplished via the (currently
optional) "asset dependency visitor" trait. This system can also be used
to define a set of assets to load, then wait for those assets to load.
* **Async folder loading**: Folder loading also uses this system and
immediately returns a handle to the LoadedFolder asset, which means
folder loading no longer blocks on directory traversals.
* **Improved Loader Interface**: Loaders now have a specific "top level
asset type", which makes returning the top-level asset simpler and
statically typed.
* **Basic Image Settings and Processing**: Image assets can now be
processed into the gpu-friendly Basic Universal format. The ImageLoader
now has a setting to define what format the image should be loaded as.
Note that this is just a minimal MVP ... plenty of additional work to do
here. To demo this, enable the `basis-universal` feature and turn on
asset processing.
* **Simpler Audio Play / AudioSink API**: Asset handle providers are
cloneable, which means the Audio resource can mint its own handles. This
means you can now do `let sink_handle = audio.play(music)` instead of
`let sink_handle = audio_sinks.get_handle(audio.play(music))`. Note that
this might still be replaced by
https://github.com/bevyengine/bevy/pull/8424.
**Removed Handle Casting From Engine Features**: Ex: FontAtlases no
longer use casting between handle types
## Using The New Asset System
### Normal Unprocessed Asset Loading
By default the `AssetPlugin` does not use processing. It behaves pretty
much the same way as the old system.
If you are defining a custom asset, first derive `Asset`:
```rust
#[derive(Asset)]
struct Thing {
value: String,
}
```
Initialize the asset:
```rust
app.init_asset:<Thing>()
```
Implement a new `AssetLoader` for it:
```rust
#[derive(Default)]
struct ThingLoader;
#[derive(Serialize, Deserialize, Default)]
pub struct ThingSettings {
some_setting: bool,
}
impl AssetLoader for ThingLoader {
type Asset = Thing;
type Settings = ThingSettings;
fn load<'a>(
&'a self,
reader: &'a mut Reader,
settings: &'a ThingSettings,
load_context: &'a mut LoadContext,
) -> BoxedFuture<'a, Result<Thing, anyhow::Error>> {
Box::pin(async move {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
// convert bytes to value somehow
Ok(Thing {
value
})
})
}
fn extensions(&self) -> &[&str] {
&["thing"]
}
}
```
Note that this interface will get much cleaner once Rust gets support
for async traits. `Reader` is an async futures_io::AsyncRead. You can
stream bytes as they come in or read them all into a `Vec<u8>`,
depending on the context. You can use `let handle =
load_context.load(path)` to kick off a dependency load, retrieve a
handle, and register the dependency for the asset.
Then just register the loader in your Bevy app:
```rust
app.init_asset_loader::<ThingLoader>()
```
Now just add your `Thing` asset files into the `assets` folder and load
them like this:
```rust
fn system(asset_server: Res<AssetServer>) {
let handle = Handle<Thing> = asset_server.load("cool.thing");
}
```
You can check load states directly via the asset server:
```rust
if asset_server.load_state(&handle) == LoadState::Loaded { }
```
You can also listen for events:
```rust
fn system(mut events: EventReader<AssetEvent<Thing>>, handle: Res<SomeThingHandle>) {
for event in events.iter() {
if event.is_loaded_with_dependencies(&handle) {
}
}
}
```
Note the new `AssetEvent::LoadedWithDependencies`, which only fires when
the asset is loaded _and_ all dependencies (and their dependencies) have
loaded.
Unlike the old asset system, for a given asset path all `Handle<T>`
values point to the same underlying Arc. This means Handles can cheaply
hold more asset information, such as the AssetPath:
```rust
// prints the AssetPath of the handle
info!("{:?}", handle.path())
```
### Processed Assets
Asset processing can be enabled via the `AssetPlugin`. When developing
Bevy Apps with processed assets, do this:
```rust
app.add_plugins(DefaultPlugins.set(AssetPlugin::processed_dev()))
```
This runs the `AssetProcessor` in the background with hot-reloading. It
reads assets from the `assets` folder, processes them, and writes them
to the `.imported_assets` folder. Asset loads in the Bevy App will wait
for a processed version of the asset to become available. If an asset in
the `assets` folder changes, it will be reprocessed and hot-reloaded in
the Bevy App.
When deploying processed Bevy apps, do this:
```rust
app.add_plugins(DefaultPlugins.set(AssetPlugin::processed()))
```
This does not run the `AssetProcessor` in the background. It behaves
like `AssetPlugin::unprocessed()`, but reads assets from
`.imported_assets`.
When the `AssetProcessor` is running, it will populate sibling `.meta`
files for assets in the `assets` folder. Meta files for assets that do
not have a processor configured look like this:
```rust
(
meta_format_version: "1.0",
asset: Load(
loader: "bevy_render::texture::image_loader::ImageLoader",
settings: (
format: FromExtension,
),
),
)
```
This is metadata for an image asset. For example, if you have
`assets/my_sprite.png`, this could be the metadata stored at
`assets/my_sprite.png.meta`. Meta files are totally optional. If no
metadata exists, the default settings will be used.
In short, this file says "load this asset with the ImageLoader and use
the file extension to determine the image type". This type of meta file
is supported in all AssetPlugin modes. If in `Unprocessed` mode, the
asset (with the meta settings) will be loaded directly. If in
`ProcessedDev` mode, the asset file will be copied directly to the
`.imported_assets` folder. The meta will also be copied directly to the
`.imported_assets` folder, but with one addition:
```rust
(
meta_format_version: "1.0",
processed_info: Some((
hash: 12415480888597742505,
full_hash: 14344495437905856884,
process_dependencies: [],
)),
asset: Load(
loader: "bevy_render::texture::image_loader::ImageLoader",
settings: (
format: FromExtension,
),
),
)
```
`processed_info` contains `hash` (a direct hash of the asset and meta
bytes), `full_hash` (a hash of `hash` and the hashes of all
`process_dependencies`), and `process_dependencies` (the `path` and
`full_hash` of every process_dependency). A "process dependency" is an
asset dependency that is _directly_ used when processing the asset.
Images do not have process dependencies, so this is empty.
When the processor is enabled, you can use the `Process` metadata
config:
```rust
(
meta_format_version: "1.0",
asset: Process(
processor: "bevy_asset::processor::process::LoadAndSave<bevy_render::texture::image_loader::ImageLoader, bevy_render::texture::compressed_image_saver::CompressedImageSaver>",
settings: (
loader_settings: (
format: FromExtension,
),
saver_settings: (
generate_mipmaps: true,
),
),
),
)
```
This configures the asset to use the `LoadAndSave` processor, which runs
an AssetLoader and feeds the result into an AssetSaver (which saves the
given Asset and defines a loader to load it with). (for terseness
LoadAndSave will likely get a shorter/friendlier type name when [Stable
Type Paths](#7184) lands). `LoadAndSave` is likely to be the most common
processor type, but arbitrary processors are supported.
`CompressedImageSaver` saves an `Image` in the Basis Universal format
and configures the ImageLoader to load it as basis universal. The
`AssetProcessor` will read this meta, run it through the LoadAndSave
processor, and write the basis-universal version of the image to
`.imported_assets`. The final metadata will look like this:
```rust
(
meta_format_version: "1.0",
processed_info: Some((
hash: 905599590923828066,
full_hash: 9948823010183819117,
process_dependencies: [],
)),
asset: Load(
loader: "bevy_render::texture::image_loader::ImageLoader",
settings: (
format: Format(Basis),
),
),
)
```
To try basis-universal processing out in Bevy examples, (for example
`sprite.rs`), change `add_plugins(DefaultPlugins)` to
`add_plugins(DefaultPlugins.set(AssetPlugin::processed_dev()))` and run
with the `basis-universal` feature enabled: `cargo run
--features=basis-universal --example sprite`.
To create a custom processor, there are two main paths:
1. Use the `LoadAndSave` processor with an existing `AssetLoader`.
Implement the `AssetSaver` trait, register the processor using
`asset_processor.register_processor::<LoadAndSave<ImageLoader,
CompressedImageSaver>>(image_saver.into())`.
2. Implement the `Process` trait directly and register it using:
`asset_processor.register_processor(thing_processor)`.
You can configure default processors for file extensions like this:
```rust
asset_processor.set_default_processor::<ThingProcessor>("thing")
```
There is one more metadata type to be aware of:
```rust
(
meta_format_version: "1.0",
asset: Ignore,
)
```
This will ignore the asset during processing / prevent it from being
written to `.imported_assets`.
The AssetProcessor stores a transaction log at `.imported_assets/log`
and uses it to gracefully recover from unexpected stops. This means you
can force-quit the processor (and Bevy Apps running the processor in
parallel) at arbitrary times!
`.imported_assets` is "local state". It should _not_ be checked into
source control. It should also be considered "read only". In practice,
you _can_ modify processed assets and processed metadata if you really
need to test something. But those modifications will not be represented
in the hashes of the assets, so the processed state will be "out of
sync" with the source assets. The processor _will not_ fix this for you.
Either revert the change after you have tested it, or delete the
processed files so they can be re-populated.
## Open Questions
There are a number of open questions to be discussed. We should decide
if they need to be addressed in this PR and if so, how we will address
them:
### Implied Dependencies vs Dependency Enumeration
There are currently two ways to populate asset dependencies:
* **Implied via AssetLoaders**: if an AssetLoader loads an asset (and
retrieves a handle), a dependency is added to the list.
* **Explicit via the optional Asset::visit_dependencies**: if
`server.load_asset(my_asset)` is called, it will call
`my_asset.visit_dependencies`, which will grab dependencies that have
been manually defined for the asset via the Asset trait impl (which can
be derived).
This means that defining explicit dependencies is optional for "loaded
assets". And the list of dependencies is always accurate because loaders
can only produce Handles if they register dependencies. If an asset was
loaded with an AssetLoader, it only uses the implied dependencies. If an
asset was created at runtime and added with
`asset_server.load_asset(MyAsset)`, it will use
`Asset::visit_dependencies`.
However this can create a behavior mismatch between loaded assets and
equivalent "created at runtime" assets if `Assets::visit_dependencies`
doesn't exactly match the dependencies produced by the AssetLoader. This
behavior mismatch can be resolved by completely removing "implied loader
dependencies" and requiring `Asset::visit_dependencies` to supply
dependency data. But this creates two problems:
* It makes defining loaded assets harder and more error prone: Devs must
remember to manually annotate asset dependencies with `#[dependency]`
when deriving `Asset`. For more complicated assets (such as scenes), the
derive likely wouldn't be sufficient and a manual `visit_dependencies`
impl would be required.
* Removes the ability to immediately kick off dependency loads: When
AssetLoaders retrieve a Handle, they also immediately kick off an asset
load for the handle, which means it can start loading in parallel
_before_ the asset finishes loading. For large assets, this could be
significant. (although this could be mitigated for processed assets if
we store dependencies in the processed meta file and load them ahead of
time)
### Eager ProcessorDev Asset Loading
I made a controversial call in the interest of fast startup times ("time
to first pixel") for the "processor dev mode configuration". When
initializing the AssetProcessor, current processed versions of unchanged
assets are yielded immediately, even if their dependencies haven't been
checked yet for reprocessing. This means that
non-current-state-of-filesystem-but-previously-valid assets might be
returned to the App first, then hot-reloaded if/when their dependencies
change and the asset is reprocessed.
Is this behavior desirable? There is largely one alternative: do not
yield an asset from the processor to the app until all of its
dependencies have been checked for changes. In some common cases (load
dependency has not changed since last run) this will increase startup
time. The main question is "by how much" and is that slower startup time
worth it in the interest of only yielding assets that are true to the
current state of the filesystem. Should this be configurable? I'm
starting to think we should only yield an asset after its (historical)
dependencies have been checked for changes + processed as necessary, but
I'm curious what you all think.
### Paths Are Currently The Only Canonical ID / Do We Want Asset UUIDs?
In this implementation AssetPaths are the only canonical asset
identifier (just like the previous Bevy Asset system and Godot). Moving
assets will result in re-scans (and currently reprocessing, although
reprocessing can easily be avoided with some changes). Asset
renames/moves will break code and assets that rely on specific paths,
unless those paths are fixed up.
Do we want / need "stable asset uuids"? Introducing them is very
possible:
1. Generate a UUID and include it in .meta files
2. Support UUID in AssetPath
3. Generate "asset indices" which are loaded on startup and map UUIDs to
paths.
4 (maybe). Consider only supporting UUIDs for processed assets so we can
generate quick-to-load indices instead of scanning meta files.
The main "pro" is that assets referencing UUIDs don't need to be
migrated when a path changes. The main "con" is that UUIDs cannot be
"lazily resolved" like paths. They need a full view of all assets to
answer the question "does this UUID exist". Which means UUIDs require
the AssetProcessor to fully finish startup scans before saying an asset
doesnt exist. And they essentially require asset pre-processing to use
in apps, because scanning all asset metadata files at runtime to resolve
a UUID is not viable for medium-to-large apps. It really requires a
pre-generated UUID index, which must be loaded before querying for
assets.
I personally think this should be investigated in a separate PR. Paths
aren't going anywhere ... _everyone_ uses filesystems (and
filesystem-like apis) to manage their asset source files. I consider
them permanent canonical asset information. Additionally, they behave
well for both processed and unprocessed asset modes. Given that Bevy is
supporting both, this feels like the right canonical ID to start with.
UUIDS (and maybe even other indexed-identifier types) can be added later
as necessary.
### Folder / File Naming Conventions
All asset processing config currently lives in the `.imported_assets`
folder. The processor transaction log is in `.imported_assets/log`.
Processed assets are added to `.imported_assets/Default`, which will
make migrating to processed asset profiles (ex: a
`.imported_assets/Mobile` profile) a non-breaking change. It also allows
us to create top-level files like `.imported_assets/log` without it
being interpreted as an asset. Meta files currently have a `.meta`
suffix. Do we like these names and conventions?
### Should the `AssetPlugin::processed_dev` configuration enable
`watch_for_changes` automatically?
Currently it does (which I think makes sense), but it does make it the
only configuration that enables watch_for_changes by default.
### Discuss on_loaded High Level Interface:
This PR includes a very rough "proof of concept" `on_loaded` system
adapter that uses the `LoadedWithDependencies` event in combination with
`asset_server.load_asset` dependency tracking to support this pattern
```rust
fn main() {
App::new()
.init_asset::<MyAssets>()
.add_systems(Update, on_loaded(create_array_texture))
.run();
}
#[derive(Asset, Clone)]
struct MyAssets {
#[dependency]
picture_of_my_cat: Handle<Image>,
#[dependency]
picture_of_my_other_cat: Handle<Image>,
}
impl FromWorld for ArrayTexture {
fn from_world(world: &mut World) -> Self {
picture_of_my_cat: server.load("meow.png"),
picture_of_my_other_cat: server.load("meeeeeeeow.png"),
}
}
fn spawn_cat(In(my_assets): In<MyAssets>, mut commands: Commands) {
commands.spawn(SpriteBundle {
texture: my_assets.picture_of_my_cat.clone(),
..default()
});
commands.spawn(SpriteBundle {
texture: my_assets.picture_of_my_other_cat.clone(),
..default()
});
}
```
The implementation is _very_ rough. And it is currently unsafe because
`bevy_ecs` doesn't expose some internals to do this safely from inside
`bevy_asset`. There are plenty of unanswered questions like:
* "do we add a Loadable" derive? (effectively automate the FromWorld
implementation above)
* Should `MyAssets` even be an Asset? (largely implemented this way
because it elegantly builds on `server.load_asset(MyAsset { .. })`
dependency tracking).
We should think hard about what our ideal API looks like (and if this is
a pattern we want to support). Not necessarily something we need to
solve in this PR. The current `on_loaded` impl should probably be
removed from this PR before merging.
## Clarifying Questions
### What about Assets as Entities?
This Bevy Asset V2 proposal implementation initially stored Assets as
ECS Entities. Instead of `AssetId<T>` + the `Assets<T>` resource it used
`Entity` as the asset id and Asset values were just ECS components.
There are plenty of compelling reasons to do this:
1. Easier to inline assets in Bevy Scenes (as they are "just" normal
entities + components)
2. More flexible queries: use the power of the ECS to filter assets (ex:
`Query<Mesh, With<Tree>>`).
3. Extensible. Users can add arbitrary component data to assets.
4. Things like "component visualization tools" work out of the box to
visualize asset data.
However Assets as Entities has a ton of caveats right now:
* We need to be able to allocate entity ids without a direct World
reference (aka rework id allocator in Entities ... i worked around this
in my prototypes by just pre allocating big chunks of entities)
* We want asset change events in addition to ECS change tracking ... how
do we populate them when mutations can come from anywhere? Do we use
Changed queries? This would require iterating over the change data for
all assets every frame. Is this acceptable or should we implement a new
"event based" component change detection option?
* Reconciling manually created assets with asset-system managed assets
has some nuance (ex: are they "loaded" / do they also have that
component metadata?)
* "how do we handle "static" / default entity handles" (ties in to the
Entity Indices discussion:
https://github.com/bevyengine/bevy/discussions/8319). This is necessary
for things like "built in" assets and default handles in things like
SpriteBundle.
* Storing asset information as a component makes it easy to "invalidate"
asset state by removing the component (or forcing modifications).
Ideally we have ways to lock this down (some combination of Rust type
privacy and ECS validation)
In practice, how we store and identify assets is a reasonably
superficial change (porting off of Assets as Entities and implementing
dedicated storage + ids took less than a day). So once we sort out the
remaining challenges the flip should be straightforward. Additionally, I
do still have "Assets as Entities" in my commit history, so we can reuse
that work. I personally think "assets as entities" is a good endgame,
but it also doesn't provide _significant_ value at the moment and it
certainly isn't ready yet with the current state of things.
### Why not Distill?
[Distill](https://github.com/amethyst/distill) is a high quality fully
featured asset system built in Rust. It is very natural to ask "why not
just use Distill?".
It is also worth calling out that for awhile, [we planned on adopting
Distill / I signed off on
it](https://github.com/bevyengine/bevy/issues/708).
However I think Bevy has a number of constraints that make Distill
adoption suboptimal:
* **Architectural Simplicity:**
* Distill's processor requires an in-memory database (lmdb) and RPC
networked API (using Cap'n Proto). Each of these introduces API
complexity that increases maintenance burden and "code grokability".
Ignoring tests, documentation, and examples, Distill has 24,237 lines of
Rust code (including generated code for RPC + database interactions). If
you ignore generated code, it has 11,499 lines.
* Bevy builds the AssetProcessor and AssetServer using pluggable
AssetReader/AssetWriter Rust traits with simple io interfaces. They do
not necessitate databases or RPC interfaces (although Readers/Writers
could use them if that is desired). Bevy Asset V2 (at the time of
writing this PR) is 5,384 lines of Rust code (ignoring tests,
documentation, and examples). Grain of salt: Distill does have more
features currently (ex: Asset Packing, GUIDS, remote-out-of-process
asset processor). I do plan to implement these features in Bevy Asset V2
and I personally highly doubt they will meaningfully close the 6115
lines-of-code gap.
* This complexity gap (which while illustrated by lines of code, is much
bigger than just that) is noteworthy to me. Bevy should be hackable and
there are pillars of Distill that are very hard to understand and
extend. This is a matter of opinion (and Bevy Asset V2 also has
complicated areas), but I think Bevy Asset V2 is much more approachable
for the average developer.
* Necessary disclaimer: counting lines of code is an extremely rough
complexity metric. Read the code and form your own opinions.
* **Optional Asset Processing:** Not all Bevy Apps (or Bevy App
developers) need / want asset preprocessing. Processing increases the
complexity of the development environment by introducing things like
meta files, imported asset storage, running processors in the
background, waiting for processing to finish, etc. Distill _requires_
preprocessing to work. With Bevy Asset V2 processing is fully opt-in.
The AssetServer isn't directly aware of asset processors at all.
AssetLoaders only care about converting bytes to runtime Assets ... they
don't know or care if the bytes were pre-processed or not. Processing is
"elegantly" (forgive my self-congratulatory phrasing) layered on top and
builds on the existing Asset system primitives.
* **Direct Filesystem Access to Processed Asset State:** Distill stores
processed assets in a database. This makes debugging / inspecting the
processed outputs harder (either requires special tooling to query the
database or they need to be "deployed" to be inspected). Bevy Asset V2,
on the other hand, stores processed assets in the filesystem (by default
... this is configurable). This makes interacting with the processed
state more natural. Note that both Godot and Unity's new asset system
store processed assets in the filesystem.
* **Portability**: Because Distill's processor uses lmdb and RPC
networking, it cannot be run on certain platforms (ex: lmdb is a
non-rust dependency that cannot run on the web, some platforms don't
support running network servers). Bevy should be able to process assets
everywhere (ex: run the Bevy Editor on the web, compile + process
shaders on mobile, etc). Distill does partially mitigate this problem by
supporting "streaming" assets via the RPC protocol, but this is not a
full solve from my perspective. And Bevy Asset V2 can (in theory) also
stream assets (without requiring RPC, although this isn't implemented
yet)
Note that I _do_ still think Distill would be a solid asset system for
Bevy. But I think the approach in this PR is a better solve for Bevy's
specific "asset system requirements".
### Doesn't async-fs just shim requests to "sync" `std::fs`? What is the
point?
"True async file io" has limited / spotty platform support. async-fs
(and the rust async ecosystem generally ... ex Tokio) currently use
async wrappers over std::fs that offload blocking requests to separate
threads. This may feel unsatisfying, but it _does_ still provide value
because it prevents our task pools from blocking on file system
operations (which would prevent progress when there are many tasks to
do, but all threads in a pool are currently blocking on file system
ops).
Additionally, using async APIs for our AssetReaders and AssetWriters
also provides value because we can later add support for "true async
file io" for platforms that support it. _And_ we can implement other
"true async io" asset backends (such as networked asset io).
## Draft TODO
- [x] Fill in missing filesystem event APIs: file removed event (which
is expressed as dangling RenameFrom events in some cases), file/folder
renamed event
- [x] Assets without loaders are not moved to the processed folder. This
breaks things like referenced `.bin` files for GLTFs. This should be
configurable per-non-asset-type.
- [x] Initial implementation of Reflect and FromReflect for Handle. The
"deserialization" parity bar is low here as this only worked with static
UUIDs in the old impl ... this is a non-trivial problem. Either we add a
Handle::AssetPath variant that gets "upgraded" to a strong handle on
scene load or we use a separate AssetRef type for Bevy scenes (which is
converted to a runtime Handle on load). This deserves its own discussion
in a different pr.
- [x] Populate read_asset_bytes hash when run by the processor (a bit of
a special case .. when run by the processor the processed meta will
contain the hash so we don't need to compute it on the spot, but we
don't want/need to read the meta when run by the main AssetServer)
- [x] Delay hot reloading: currently filesystem events are handled
immediately, which creates timing issues in some cases. For example hot
reloading images can sometimes break because the image isn't finished
writing. We should add a delay, likely similar to the [implementation in
this PR](https://github.com/bevyengine/bevy/pull/8503).
- [x] Port old platform-specific AssetIo implementations to the new
AssetReader interface (currently missing Android and web)
- [x] Resolve on_loaded unsafety (either by removing the API entirely or
removing the unsafe)
- [x] Runtime loader setting overrides
- [x] Remove remaining unwraps that should be error-handled. There are
number of TODOs here
- [x] Pretty AssetPath Display impl
- [x] Document more APIs
- [x] Resolve spurious "reloading because it has changed" events (to
repro run load_gltf with `processed_dev()`)
- [x] load_dependency hot reloading currently only works for processed
assets. If processing is disabled, load_dependency changes are not hot
reloaded.
- [x] Replace AssetInfo dependency load/fail counters with
`loading_dependencies: HashSet<UntypedAssetId>` to prevent reloads from
(potentially) breaking counters. Storing this will also enable
"dependency reloaded" events (see [Next Steps](#next-steps))
- [x] Re-add filesystem watcher cargo feature gate (currently it is not
optional)
- [ ] Migration Guide
- [ ] Changelog
## Followup TODO
- [ ] Replace "eager unchanged processed asset loading" behavior with
"don't returned unchanged processed asset until dependencies have been
checked".
- [ ] Add true `Ignore` AssetAction that does not copy the asset to the
imported_assets folder.
- [ ] Finish "live asset unloading" (ex: free up CPU asset memory after
uploading an image to the GPU), rethink RenderAssets, and port renderer
features. The `Assets` collection uses `Option<T>` for asset storage to
support its removal. (1) the Option might not actually be necessary ...
might be able to just remove from the collection entirely (2) need to
finalize removal apis
- [ ] Try replacing the "channel based" asset id recycling with
something a bit more efficient (ex: we might be able to use raw atomic
ints with some cleverness)
- [ ] Consider adding UUIDs to processed assets (scoped just to helping
identify moved assets ... not exposed to load queries ... see [Next
Steps](#next-steps))
- [ ] Store "last modified" source asset and meta timestamps in
processed meta files to enable skipping expensive hashing when the file
wasn't changed
- [ ] Fix "slow loop" handle drop fix
- [ ] Migrate to TypeName
- [x] Handle "loader preregistration". See #9429
## Next Steps
* **Configurable per-type defaults for AssetMeta**: It should be
possible to add configuration like "all png image meta should default to
using nearest sampling" (currently this hard-coded per-loader/processor
Settings::default() impls). Also see the "Folder Meta" bullet point.
* **Avoid Reprocessing on Asset Renames / Moves**: See the "canonical
asset ids" discussion in [Open Questions](#open-questions) and the
relevant bullet point in [Draft TODO](#draft-todo). Even without
canonical ids, folder renames could avoid reprocessing in some cases.
* **Multiple Asset Sources**: Expand AssetPath to support "asset source
names" and support multiple AssetReaders in the asset server (ex:
`webserver://some_path/image.png` backed by an Http webserver
AssetReader). The "default" asset reader would use normal
`some_path/image.png` paths. Ideally this works in combination with
multiple AssetWatchers for hot-reloading
* **Stable Type Names**: this pr removes the TypeUuid requirement from
assets in favor of `std::any::type_name`. This makes defining assets
easier (no need to generate a new uuid / use weird proc macro syntax).
It also makes reading meta files easier (because things have "friendly
names"). We also use type names for components in scene files. If they
are good enough for components, they are good enough for assets. And
consistency across Bevy pillars is desirable. However,
`std::any::type_name` is not guaranteed to be stable (although in
practice it is). We've developed a [stable type
path](https://github.com/bevyengine/bevy/pull/7184) to resolve this,
which should be adopted when it is ready.
* **Command Line Interface**: It should be possible to run the asset
processor in a separate process from the command line. This will also
require building a network-server-backed AssetReader to communicate
between the app and the processor. We've been planning to build a "bevy
cli" for awhile. This seems like a good excuse to build it.
* **Asset Packing**: This is largely an additive feature, so it made
sense to me to punt this until we've laid the foundations in this PR.
* **Per-Platform Processed Assets**: It should be possible to generate
assets for multiple platforms by supporting multiple "processor
profiles" per asset (ex: compress with format X on PC and Y on iOS). I
think there should probably be arbitrary "profiles" (which can be
separate from actual platforms), which are then assigned to a given
platform when generating the final asset distribution for that platform.
Ex: maybe devs want a "Mobile" profile that is shared between iOS and
Android. Or a "LowEnd" profile shared between web and mobile.
* **Versioning and Migrations**: Assets, Loaders, Savers, and Processors
need to have versions to determine if their schema is valid. If an asset
/ loader version is incompatible with the current version expected at
runtime, the processor should be able to migrate them. I think we should
try using Bevy Reflect for this, as it would allow us to load the old
version as a dynamic Reflect type without actually having the old Rust
type. It would also allow us to define "patches" to migrate between
versions (Bevy Reflect devs are currently working on patching). The
`.meta` file already has its own format version. Migrating that to new
versions should also be possible.
* **Real Copy-on-write AssetPaths**: Rust's actual Cow (clone-on-write
type) currently used by AssetPath can still result in String clones that
aren't actually necessary (cloning an Owned Cow clones the contents).
Bevy's asset system requires cloning AssetPaths in a number of places,
which result in actual clones of the internal Strings. This is not
efficient. AssetPath internals should be reworked to exhibit truer
cow-like-behavior that reduces String clones to the absolute minimum.
* **Consider processor-less processing**: In theory the AssetServer
could run processors "inline" even if the background AssetProcessor is
disabled. If we decide this is actually desirable, we could add this.
But I don't think its a priority in the short or medium term.
* **Pre-emptive dependency loading**: We could encode dependencies in
processed meta files, which could then be used by the Asset Server to
kick of dependency loads as early as possible (prior to starting the
actual asset load). Is this desirable? How much time would this save in
practice?
* **Optimize Processor With UntypedAssetIds**: The processor exclusively
uses AssetPath to identify assets currently. It might be possible to
swap these out for UntypedAssetIds in some places, which are smaller /
cheaper to hash and compare.
* **One to Many Asset Processing**: An asset source file that produces
many assets currently must be processed into a single "processed" asset
source. If labeled assets can be written separately they can each have
their own configured savers _and_ they could be loaded more granularly.
Definitely worth exploring!
* **Automatically Track "Runtime-only" Asset Dependencies**: Right now,
tracking "created at runtime" asset dependencies requires adding them
via `asset_server.load_asset(StandardMaterial::default())`. I think with
some cleverness we could also do this for
`materials.add(StandardMaterial::default())`, making tracking work
"everywhere". There are challenges here relating to change detection /
ensuring the server is made aware of dependency changes. This could be
expensive in some cases.
* **"Dependency Changed" events**: Some assets have runtime artifacts
that need to be re-generated when one of their dependencies change (ex:
regenerate a material's bind group when a Texture needs to change). We
are generating the dependency graph so we can definitely produce these
events. Buuuuut generating these events will have a cost / they could be
high frequency for some assets, so we might want this to be opt-in for
specific cases.
* **Investigate Storing More Information In Handles**: Handles can now
store arbitrary information, which makes it cheaper and easier to
access. How much should we move into them? Canonical asset load states
(via atomics)? (`handle.is_loaded()` would be very cool). Should we
store the entire asset and remove the `Assets<T>` collection?
(`Arc<RwLock<Option<Image>>>`?)
* **Support processing and loading files without extensions**: This is a
pretty arbitrary restriction and could be supported with very minimal
changes.
* **Folder Meta**: It would be nice if we could define per folder
processor configuration defaults (likely in a `.meta` or `.folder_meta`
file). Things like "default to linear filtering for all Images in this
folder".
* **Replace async_broadcast with event-listener?** This might be
approximately drop-in for some uses and it feels more light weight
* **Support Running the AssetProcessor on the Web**: Most of the hard
work is done here, but there are some easy straggling TODOs (make the
transaction log an interface instead of a direct file writer so we can
write a web storage backend, implement an AssetReader/AssetWriter that
reads/writes to something like LocalStorage).
* **Consider identifying and preventing circular dependencies**: This is
especially important for "processor dependencies", as processing will
silently never finish in these cases.
* **Built-in/Inlined Asset Hot Reloading**: This PR regresses
"built-in/inlined" asset hot reloading (previously provided by the
DebugAssetServer). I'm intentionally punting this because I think it can
be cleanly implemented with "multiple asset sources" by registering a
"debug asset source" (ex: `debug://bevy_pbr/src/render/pbr.wgsl` asset
paths) in combination with an AssetWatcher for that asset source and
support for "manually loading pats with asset bytes instead of
AssetReaders". The old DebugAssetServer was quite nasty and I'd love to
avoid that hackery going forward.
* **Investigate ways to remove double-parsing meta files**: Parsing meta
files currently involves parsing once with "minimal" versions of the
meta file to extract the type name of the loader/processor config, then
parsing again to parse the "full" meta. This is suboptimal. We should be
able to define custom deserializers that (1) assume the loader/processor
type name comes first (2) dynamically looks up the loader/processor
registrations to deserialize settings in-line (similar to components in
the bevy scene format). Another alternative: deserialize as dynamic
Reflect objects and then convert.
* **More runtime loading configuration**: Support using the Handle type
as a hint to select an asset loader (instead of relying on AssetPath
extensions)
* **More high level Processor trait implementations**: For example, it
might be worth adding support for arbitrary chains of "asset transforms"
that modify an in-memory asset representation between loading and
saving. (ex: load a Mesh, run a `subdivide_mesh` transform, followed by
a `flip_normals` transform, then save the mesh to an efficient
compressed format).
* **Bevy Scene Handle Deserialization**: (see the relevant [Draft TODO
item](#draft-todo) for context)
* **Explore High Level Load Interfaces**: See [this
discussion](#discuss-on_loaded-high-level-interface) for one prototype.
* **Asset Streaming**: It would be great if we could stream Assets (ex:
stream a long video file piece by piece)
* **ID Exchanging**: In this PR Asset Handles/AssetIds are bigger than
they need to be because they have a Uuid enum variant. If we implement
an "id exchanging" system that trades Uuids for "efficient runtime ids",
we can cut down on the size of AssetIds, making them more efficient.
This has some open design questions, such as how to spawn entities with
"default" handle values (as these wouldn't have access to the exchange
api in the current system).
* **Asset Path Fixup Tooling**: Assets that inline asset paths inside
them will break when an asset moves. The asset system provides the
functionality to detect when paths break. We should build a framework
that enables formats to define "path migrations". This is especially
important for scene files. For editor-generated files, we should also
consider using UUIDs (see other bullet point) to avoid the need to
migrate in these cases.
---------
Co-authored-by: BeastLe9enD <beastle9end@outlook.de>
Co-authored-by: Mike <mike.hsu@gmail.com>
Co-authored-by: Nicola Papale <nicopap@users.noreply.github.com>
2023-09-07 02:07:27 +00:00
[Custom Asset IO ](../examples/asset/custom_asset_reader.rs ) | Implements a custom AssetReader
2022-06-25 20:23:24 +00:00
[Hot Reloading of Assets ](../examples/asset/hot_asset_reloading.rs ) | Demonstrates automatic reloading of assets when modified on disk
2020-08-17 23:02:59 +00:00
2021-05-23 20:13:55 +00:00
## Async Tasks
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
[Async Compute ](../examples/async_tasks/async_compute.rs ) | How to use `AsyncComputeTaskPool` to complete longer running tasks
[External Source of Data on an External Thread ](../examples/async_tasks/external_source_external_thread.rs ) | How to use an external thread to run an infinite task and communicate with a channel
2021-05-23 20:13:55 +00:00
2020-08-17 23:02:59 +00:00
## Audio
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
[Audio ](../examples/audio/audio.rs ) | Shows how to load and play an audio file
[Audio Control ](../examples/audio/audio_control.rs ) | Shows how to load and play an audio file, and control how it's played
2023-01-17 22:42:00 +00:00
[Decodable ](../examples/audio/decodable.rs ) | Shows how to create and register a custom audio source by implementing the `Decodable` type.
2023-07-29 22:29:41 +00:00
[Pitch ](../examples/audio/pitch.rs ) | Shows how to directly play a simple pitch
2023-02-20 15:31:07 +00:00
[Spatial Audio 2D ](../examples/audio/spatial_audio_2d.rs ) | Shows how to play spatial audio, and moving the emitter in 2D
[Spatial Audio 3D ](../examples/audio/spatial_audio_3d.rs ) | Shows how to play spatial audio, and moving the emitter in 3D
2020-08-17 23:02:59 +00:00
## Diagnostics
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
[Custom Diagnostic ](../examples/diagnostics/custom_diagnostic.rs ) | Shows how to create a custom diagnostic
[Log Diagnostics ](../examples/diagnostics/log_diagnostics.rs ) | Add a plugin that logs diagnostics, like frames per second (FPS), to the console
2020-08-17 23:02:59 +00:00
## ECS (Entity Component System)
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
2023-06-02 14:04:13 +00:00
[Apply System Buffers ](../examples/ecs/apply_deferred.rs ) | Show how to use `apply_deferred` system
2022-06-25 20:23:24 +00:00
[Component Change Detection ](../examples/ecs/component_change_detection.rs ) | Change detection on components
[Custom Query Parameters ](../examples/ecs/custom_query_param.rs ) | Groups commonly used compound queries and query filters into a single type
[ECS Guide ](../examples/ecs/ecs_guide.rs ) | Full guide to Bevy's ECS
[Event ](../examples/ecs/event.rs ) | Illustrates event creation, activation, and reception
[Fixed Timestep ](../examples/ecs/fixed_timestep.rs ) | Shows how to create systems that run every fixed timestep, rather than every tick
[Generic System ](../examples/ecs/generic_system.rs ) | Shows how to create systems that can be reused with different types
[Hierarchy ](../examples/ecs/hierarchy.rs ) | Creates a hierarchy of parents and children entities
[Iter Combinations ](../examples/ecs/iter_combinations.rs ) | Shows how to iterate over combinations of query results
2023-04-16 16:55:47 +00:00
[Nondeterministic System Order ](../examples/ecs/nondeterministic_system_order.rs ) | Systems run in parallel, but their order isn't always deterministic. Here's how to detect and fix this.
2023-09-19 20:17:05 +00:00
[One Shot Systems ](../examples/ecs/one_shot_systems.rs ) | Shows how to flexibly run systems without scheduling them
2022-06-25 20:23:24 +00:00
[Parallel Query ](../examples/ecs/parallel_query.rs ) | Illustrates parallel queries with `ParallelIterator`
Migrate engine to Schedule v3 (#7267)
Huge thanks to @maniwani, @devil-ira, @hymm, @cart, @superdump and @jakobhellermann for the help with this PR.
# Objective
- Followup #6587.
- Minimal integration for the Stageless Scheduling RFC: https://github.com/bevyengine/rfcs/pull/45
## Solution
- [x] Remove old scheduling module
- [x] Migrate new methods to no longer use extension methods
- [x] Fix compiler errors
- [x] Fix benchmarks
- [x] Fix examples
- [x] Fix docs
- [x] Fix tests
## Changelog
### Added
- a large number of methods on `App` to work with schedules ergonomically
- the `CoreSchedule` enum
- `App::add_extract_system` via the `RenderingAppExtension` trait extension method
- the private `prepare_view_uniforms` system now has a public system set for scheduling purposes, called `ViewSet::PrepareUniforms`
### Removed
- stages, and all code that mentions stages
- states have been dramatically simplified, and no longer use a stack
- `RunCriteriaLabel`
- `AsSystemLabel` trait
- `on_hierarchy_reports_enabled` run criteria (now just uses an ad hoc resource checking run condition)
- systems in `RenderSet/Stage::Extract` no longer warn when they do not read data from the main world
- `RunCriteriaLabel`
- `transform_propagate_system_set`: this was a nonstandard pattern that didn't actually provide enough control. The systems are already `pub`: the docs have been updated to ensure that the third-party usage is clear.
### Changed
- `System::default_labels` is now `System::default_system_sets`.
- `App::add_default_labels` is now `App::add_default_sets`
- `CoreStage` and `StartupStage` enums are now `CoreSet` and `StartupSet`
- `App::add_system_set` was renamed to `App::add_systems`
- The `StartupSchedule` label is now defined as part of the `CoreSchedules` enum
- `.label(SystemLabel)` is now referred to as `.in_set(SystemSet)`
- `SystemLabel` trait was replaced by `SystemSet`
- `SystemTypeIdLabel<T>` was replaced by `SystemSetType<T>`
- The `ReportHierarchyIssue` resource now has a public constructor (`new`), and implements `PartialEq`
- Fixed time steps now use a schedule (`CoreSchedule::FixedTimeStep`) rather than a run criteria.
- Adding rendering extraction systems now panics rather than silently failing if no subapp with the `RenderApp` label is found.
- the `calculate_bounds` system, with the `CalculateBounds` label, is now in `CoreSet::Update`, rather than in `CoreSet::PostUpdate` before commands are applied.
- `SceneSpawnerSystem` now runs under `CoreSet::Update`, rather than `CoreStage::PreUpdate.at_end()`.
- `bevy_pbr::add_clusters` is no longer an exclusive system
- the top level `bevy_ecs::schedule` module was replaced with `bevy_ecs::scheduling`
- `tick_global_task_pools_on_main_thread` is no longer run as an exclusive system. Instead, it has been replaced by `tick_global_task_pools`, which uses a `NonSend` resource to force running on the main thread.
## Migration Guide
- Calls to `.label(MyLabel)` should be replaced with `.in_set(MySet)`
- Stages have been removed. Replace these with system sets, and then add command flushes using the `apply_system_buffers` exclusive system where needed.
- The `CoreStage`, `StartupStage, `RenderStage` and `AssetStage` enums have been replaced with `CoreSet`, `StartupSet, `RenderSet` and `AssetSet`. The same scheduling guarantees have been preserved.
- Systems are no longer added to `CoreSet::Update` by default. Add systems manually if this behavior is needed, although you should consider adding your game logic systems to `CoreSchedule::FixedTimestep` instead for more reliable framerate-independent behavior.
- Similarly, startup systems are no longer part of `StartupSet::Startup` by default. In most cases, this won't matter to you.
- For example, `add_system_to_stage(CoreStage::PostUpdate, my_system)` should be replaced with
- `add_system(my_system.in_set(CoreSet::PostUpdate)`
- When testing systems or otherwise running them in a headless fashion, simply construct and run a schedule using `Schedule::new()` and `World::run_schedule` rather than constructing stages
- Run criteria have been renamed to run conditions. These can now be combined with each other and with states.
- Looping run criteria and state stacks have been removed. Use an exclusive system that runs a schedule if you need this level of control over system control flow.
- For app-level control flow over which schedules get run when (such as for rollback networking), create your own schedule and insert it under the `CoreSchedule::Outer` label.
- Fixed timesteps are now evaluated in a schedule, rather than controlled via run criteria. The `run_fixed_timestep` system runs this schedule between `CoreSet::First` and `CoreSet::PreUpdate` by default.
- Command flush points introduced by `AssetStage` have been removed. If you were relying on these, add them back manually.
- Adding extract systems is now typically done directly on the main app. Make sure the `RenderingAppExtension` trait is in scope, then call `app.add_extract_system(my_system)`.
- the `calculate_bounds` system, with the `CalculateBounds` label, is now in `CoreSet::Update`, rather than in `CoreSet::PostUpdate` before commands are applied. You may need to order your movement systems to occur before this system in order to avoid system order ambiguities in culling behavior.
- the `RenderLabel` `AppLabel` was renamed to `RenderApp` for clarity
- `App::add_state` now takes 0 arguments: the starting state is set based on the `Default` impl.
- Instead of creating `SystemSet` containers for systems that run in stages, simply use `.on_enter::<State::Variant>()` or its `on_exit` or `on_update` siblings.
- `SystemLabel` derives should be replaced with `SystemSet`. You will also need to add the `Debug`, `PartialEq`, `Eq`, and `Hash` traits to satisfy the new trait bounds.
- `with_run_criteria` has been renamed to `run_if`. Run criteria have been renamed to run conditions for clarity, and should now simply return a bool.
- States have been dramatically simplified: there is no longer a "state stack". To queue a transition to the next state, call `NextState::set`
## TODO
- [x] remove dead methods on App and World
- [x] add `App::add_system_to_schedule` and `App::add_systems_to_schedule`
- [x] avoid adding the default system set at inappropriate times
- [x] remove any accidental cycles in the default plugins schedule
- [x] migrate benchmarks
- [x] expose explicit labels for the built-in command flush points
- [x] migrate engine code
- [x] remove all mentions of stages from the docs
- [x] verify docs for States
- [x] fix uses of exclusive systems that use .end / .at_start / .before_commands
- [x] migrate RenderStage and AssetStage
- [x] migrate examples
- [x] ensure that transform propagation is exported in a sufficiently public way (the systems are already pub)
- [x] ensure that on_enter schedules are run at least once before the main app
- [x] re-enable opt-in to execution order ambiguities
- [x] revert change to `update_bounds` to ensure it runs in `PostUpdate`
- [x] test all examples
- [x] unbreak directional lights
- [x] unbreak shadows (see 3d_scene, 3d_shape, lighting, transparaency_3d examples)
- [x] game menu example shows loading screen and menu simultaneously
- [x] display settings menu is a blank screen
- [x] `without_winit` example panics
- [x] ensure all tests pass
- [x] SubApp doc test fails
- [x] runs_spawn_local tasks fails
- [x] [Fix panic_when_hierachy_cycle test hanging](https://github.com/alice-i-cecile/bevy/pull/120)
## Points of Difficulty and Controversy
**Reviewers, please give feedback on these and look closely**
1. Default sets, from the RFC, have been removed. These added a tremendous amount of implicit complexity and result in hard to debug scheduling errors. They're going to be tackled in the form of "base sets" by @cart in a followup.
2. The outer schedule controls which schedule is run when `App::update` is called.
3. I implemented `Label for `Box<dyn Label>` for our label types. This enables us to store schedule labels in concrete form, and then later run them. I ran into the same set of problems when working with one-shot systems. We've previously investigated this pattern in depth, and it does not appear to lead to extra indirection with nested boxes.
4. `SubApp::update` simply runs the default schedule once. This sucks, but this whole API is incomplete and this was the minimal changeset.
5. `time_system` and `tick_global_task_pools_on_main_thread` no longer use exclusive systems to attempt to force scheduling order
6. Implemetnation strategy for fixed timesteps
7. `AssetStage` was migrated to `AssetSet` without reintroducing command flush points. These did not appear to be used, and it's nice to remove these bottlenecks.
8. Migration of `bevy_render/lib.rs` and pipelined rendering. The logic here is unusually tricky, as we have complex scheduling requirements.
## Future Work (ideally before 0.10)
- Rename schedule_v3 module to schedule or scheduling
- Add a derive macro to states, and likely a `EnumIter` trait of some form
- Figure out what exactly to do with the "systems added should basically work by default" problem
- Improve ergonomics for working with fixed timesteps and states
- Polish FixedTime API to match Time
- Rebase and merge #7415
- Resolve all internal ambiguities (blocked on better tools, especially #7442)
- Add "base sets" to replace the removed default sets.
2023-02-06 02:04:50 +00:00
[Removal Detection ](../examples/ecs/removal_detection.rs ) | Query for entities that had a specific component removed earlier in the current frame
2023-02-18 05:32:59 +00:00
[Run Conditions ](../examples/ecs/run_conditions.rs ) | Run systems only when one or multiple conditions are met
2022-06-25 20:23:24 +00:00
[Startup System ](../examples/ecs/startup_system.rs ) | Demonstrates a startup system (one that runs once when the app starts up)
[State ](../examples/ecs/state.rs ) | Illustrates how to use States to control transitioning from a Menu state to an InGame state
[System Closure ](../examples/ecs/system_closure.rs ) | Show how to use closures as systems, and how to configure `Local` variables by capturing external state
[System Parameter ](../examples/ecs/system_param.rs ) | Illustrates creating custom system parameters with `SystemParam`
2022-10-11 15:21:12 +00:00
[System Piping ](../examples/ecs/system_piping.rs ) | Pipe the output of one system into a second, allowing you to handle any errors gracefully
2020-08-17 23:02:59 +00:00
## Games
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
[Alien Cake Addict ](../examples/games/alien_cake_addict.rs ) | Eat the cakes. Eat them all. An example 3D game
[Breakout ](../examples/games/breakout.rs ) | An implementation of the classic game "Breakout"
[Contributors ](../examples/games/contributors.rs ) | Displays each contributor as a bouncy bevy-ball!
[Game Menu ](../examples/games/game_menu.rs ) | A simple game menu
2020-08-17 23:02:59 +00:00
## Input
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
[Char Input Events ](../examples/input/char_input_events.rs ) | Prints out all chars as they are inputted
[Gamepad Input ](../examples/input/gamepad_input.rs ) | Shows handling of gamepad input, connections, and disconnections
[Gamepad Input Events ](../examples/input/gamepad_input_events.rs ) | Iterates and prints gamepad input and connection events
2023-04-24 15:28:53 +00:00
[Gamepad Rumble ](../examples/input/gamepad_rumble.rs ) | Shows how to rumble a gamepad using force feedback
2022-06-25 20:23:24 +00:00
[Keyboard Input ](../examples/input/keyboard_input.rs ) | Demonstrates handling a key press/release
[Keyboard Input Events ](../examples/input/keyboard_input_events.rs ) | Prints out all keyboard events
[Keyboard Modifiers ](../examples/input/keyboard_modifiers.rs ) | Demonstrates using key modifiers (ctrl, shift)
[Mouse Grab ](../examples/input/mouse_grab.rs ) | Demonstrates how to grab the mouse, locking the cursor to the app's screen
[Mouse Input ](../examples/input/mouse_input.rs ) | Demonstrates handling a mouse button press/release
[Mouse Input Events ](../examples/input/mouse_input_events.rs ) | Prints out all mouse events (buttons, movement, etc.)
2023-01-29 20:27:29 +00:00
[Text Input ](../examples/input/text_input.rs ) | Simple text input with IME support
2022-06-25 20:23:24 +00:00
[Touch Input ](../examples/input/touch_input.rs ) | Displays touch presses, releases, and cancels
[Touch Input Events ](../examples/input/touch_input_events.rs ) | Prints out all touch inputs
2020-08-17 23:02:59 +00:00
2020-12-02 22:35:27 +00:00
## Reflection
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
[Generic Reflection ](../examples/reflection/generic_reflection.rs ) | Registers concrete instances of generic types that may be used with reflection
[Reflection ](../examples/reflection/reflection.rs ) | Demonstrates how reflection in Bevy provides a way to dynamically interact with Rust types
[Reflection Types ](../examples/reflection/reflection_types.rs ) | Illustrates the various reflection types available
[Trait Reflection ](../examples/reflection/trait_reflection.rs ) | Allows reflection with trait objects
2020-12-02 22:35:27 +00:00
2020-08-17 23:02:59 +00:00
## Scene
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
[Scene ](../examples/scene/scene.rs ) | Demonstrates loading from and saving scenes to files
2020-08-17 23:02:59 +00:00
## Shaders
2022-05-30 15:57:25 +00:00
These examples demonstrate how to implement different shaders in user code.
2022-06-25 20:23:24 +00:00
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.
2022-05-30 15:57:25 +00:00
2022-06-25 20:23:24 +00:00
There are also compute shaders which are used for more general processing leveraging the GPU's parallelism.
2022-05-30 15:57:25 +00:00
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
[Animated ](../examples/shader/animate_shader.rs ) | A shader that uses dynamic data like the time since startup
2022-06-28 00:58:50 +00:00
[Array Texture ](../examples/shader/array_texture.rs ) | 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.
2022-06-25 20:23:24 +00:00
[Compute - Game of Life ](../examples/shader/compute_shader_game_of_life.rs ) | A compute shader that simulates Conway's Game of Life
[Custom Vertex Attribute ](../examples/shader/custom_vertex_attribute.rs ) | A shader that reads a mesh's custom vertex attribute
2023-10-17 21:28:08 +00:00
[Extended Material ](../examples/shader/extended_material.rs ) | A custom shader that builds on the standard material
2022-06-25 20:23:24 +00:00
[Instancing ](../examples/shader/shader_instancing.rs ) | A shader that renders a mesh multiple times in one draw call
[Material ](../examples/shader/shader_material.rs ) | A shader and a material that uses it
[Material - GLSL ](../examples/shader/shader_material_glsl.rs ) | A shader that uses the GLSL shading language
[Material - Screenspace Texture ](../examples/shader/shader_material_screenspace_texture.rs ) | A shader that samples a texture with view-independent UV coordinates
2023-03-02 02:23:06 +00:00
[Material Prepass ](../examples/shader/shader_prepass.rs ) | A shader that uses the various textures generated by the prepass
2023-04-15 21:48:31 +00:00
[Post Processing - Custom Render Pass ](../examples/shader/post_processing.rs ) | A custom post processing effect, using a custom render pass that runs after the main pass
2022-06-25 20:23:24 +00:00
[Shader Defs ](../examples/shader/shader_defs.rs ) | A shader that uses "shaders defs" (a bevy tool to selectively toggle parts of a shader)
2023-01-26 13:18:15 +00:00
[Texture Binding Array (Bindless Textures) ](../examples/shader/texture_binding_array.rs ) | A shader that shows how to bind and sample multiple textures as a binding array (a.k.a. bindless textures).
2020-08-17 23:02:59 +00:00
2022-04-10 02:05:21 +00:00
## 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:
```sh
cargo run --release --example < example name >
```
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
[Bevymark ](../examples/stress_tests/bevymark.rs ) | A heavy sprite rendering workload to benchmark your system with Bevy
2022-07-14 11:03:13 +00:00
[Many Animated Sprites ](../examples/stress_tests/many_animated_sprites.rs ) | Displays many animated sprites in a grid arrangement with slight offsets to their animation timers. Used for performance testing.
2022-07-21 14:39:03 +00:00
[Many Buttons ](../examples/stress_tests/many_buttons.rs ) | Test rendering of many UI elements
2022-06-25 20:23:24 +00:00
[Many Cubes ](../examples/stress_tests/many_cubes.rs ) | Simple benchmark to test per-entity draw overhead. Run with the `sphere` argument to test frustum culling
[Many Foxes ](../examples/stress_tests/many_foxes.rs ) | 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
2023-03-20 20:57:54 +00:00
[Many Gizmos ](../examples/stress_tests/many_gizmos.rs ) | Test rendering of many gizmos
2023-03-14 00:01:27 +00:00
[Many Glyphs ](../examples/stress_tests/many_glyphs.rs ) | Simple benchmark to test text rendering.
2022-06-25 20:23:24 +00:00
[Many Lights ](../examples/stress_tests/many_lights.rs ) | Simple benchmark to test rendering many point lights. Run with `WGPU_SETTINGS_PRIO=webgl2` to restrict to uniform buffers and max 256 lights
2022-07-14 11:03:13 +00:00
[Many Sprites ](../examples/stress_tests/many_sprites.rs ) | Displays many sprites in a grid arrangement! Used for performance testing. Use `--colored` to enable color tinted sprites.
2023-03-04 12:29:08 +00:00
[Text Pipeline ](../examples/stress_tests/text_pipeline.rs ) | Text Pipeline benchmark
2022-06-25 20:23:24 +00:00
[Transform Hierarchy ](../examples/stress_tests/transform_hierarchy.rs ) | Various test cases for hierarchy and transform propagation performance
2021-04-15 00:57:37 +00:00
2023-10-28 16:05:03 +00:00
## Time
Example | Description
--- | ---
[Time handling ](../examples/time/time.rs ) | Explains how Time is handled in ECS
[Timers ](../examples/time/timers.rs ) | Illustrates ticking `Timer` resources inside systems and handling their state
[Virtual time ](../examples/time/virtual_time.rs ) | Shows how `Time<Virtual>` can be used to pause, resume, slow down and speed up a game.
2020-11-15 19:24:18 +00:00
## Tools
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
2022-09-24 13:21:01 +00:00
[Gamepad Viewer ](../examples/tools/gamepad_viewer.rs ) | Shows a visualization of gamepad buttons, sticks, and triggers
2022-12-25 00:23:13 +00:00
[Scene Viewer ](../examples/tools/scene_viewer/main.rs ) | 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
2020-11-15 19:24:18 +00:00
2022-03-15 05:49:49 +00:00
## Transforms
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
[3D Rotation ](../examples/transforms/3d_rotation.rs ) | Illustrates how to (constantly) rotate an object around an axis
[Scale ](../examples/transforms/scale.rs ) | Illustrates how to scale an object in each direction
[Transform ](../examples/transforms/transform.rs ) | Shows multiple transformations of objects
[Translation ](../examples/transforms/translation.rs ) | Illustrates how to move an object along an axis
2022-03-15 05:49:49 +00:00
2020-08-17 23:02:59 +00:00
## UI (User Interface)
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
2023-06-14 22:43:38 +00:00
[Borders ](../examples/ui/borders.rs ) | Demonstrates how to create a node with a border
2022-06-25 20:23:24 +00:00
[Button ](../examples/ui/button.rs ) | Illustrates creating and updating a button
2023-04-17 16:21:38 +00:00
[CSS Grid ](../examples/ui/grid.rs ) | An example for CSS Grid layout
2023-06-19 23:19:34 +00:00
[Display and Visibility ](../examples/ui/display_and_visibility.rs ) | Demonstrates how Display and Visibility work in the UI.
2023-03-22 08:22:56 +00:00
[Flex Layout ](../examples/ui/flex_layout.rs ) | Demonstrates how the AlignItems and JustifyContent properties can be composed to layout nodes and position text
2022-06-25 20:23:24 +00:00
[Font Atlas Debug ](../examples/ui/font_atlas_debug.rs ) | Illustrates how FontAtlases are populated (used to optimize text rendering internally)
2023-04-17 22:23:52 +00:00
[Overflow ](../examples/ui/overflow.rs ) | Simple example demonstrating overflow behavior
2023-04-05 23:07:41 +00:00
[Overflow and Clipping Debug ](../examples/ui/overflow_debug.rs ) | An example to debug overflow and clipping behavior
2023-01-16 17:17:45 +00:00
[Relative Cursor Position ](../examples/ui/relative_cursor_position.rs ) | Showcases the RelativeCursorPosition component
2023-04-24 14:28:00 +00:00
[Size Constraints ](../examples/ui/size_constraints.rs ) | Demonstrates how the to use the size constraints to control the size of a UI node.
2022-06-25 20:23:24 +00:00
[Text ](../examples/ui/text.rs ) | Illustrates creating and updating text
[Text Debug ](../examples/ui/text_debug.rs ) | An example for debugging text layout
2023-04-24 14:22:31 +00:00
[Text Wrap Debug ](../examples/ui/text_wrap_debug.rs ) | Demonstrates text wrapping
2022-06-25 20:23:24 +00:00
[Transparency UI ](../examples/ui/transparency_ui.rs ) | Demonstrates transparency for UI
[UI ](../examples/ui/ui.rs ) | Illustrates various features of Bevy UI
2023-11-03 22:33:01 +00:00
[UI Material ](../examples/ui/ui_material.rs ) | Demonstrates creating and using custom Ui materials
2022-10-19 11:36:26 +00:00
[UI Scaling ](../examples/ui/ui_scaling.rs ) | Illustrates how to scale the UI
2023-06-19 21:52:02 +00:00
[UI Texture Atlas ](../examples/ui/ui_texture_atlas.rs ) | Illustrates how to use TextureAtlases in UI
Add z-index support with a predictable UI stack (#5877)
# Objective
Add consistent UI rendering and interaction where deep nodes inside two different hierarchies will never render on top of one-another by default and offer an escape hatch (z-index) for nodes to change their depth.
## The problem with current implementation
The current implementation of UI rendering is broken in that regard, mainly because [it sets the Z value of the `Transform` component based on a "global Z" space](https://github.com/bevyengine/bevy/blob/main/crates/bevy_ui/src/update.rs#L43) shared by all nodes in the UI. This doesn't account for the fact that each node's final `GlobalTransform` value will be relative to its parent. This effectively makes the depth unpredictable when two deep trees are rendered on top of one-another.
At the moment, it's also up to each part of the UI code to sort all of the UI nodes. The solution that's offered here does the full sorting of UI node entities once and offers the result through a resource so that all systems can use it.
## Solution
### New ZIndex component
This adds a new optional `ZIndex` enum component for nodes which offers two mechanism:
- `ZIndex::Local(i32)`: Overrides the depth of the node relative to its siblings.
- `ZIndex::Global(i32)`: Overrides the depth of the node relative to the UI root. This basically allows any node in the tree to "escape" the parent and be ordered relative to the entire UI.
Note that in the current implementation, omitting `ZIndex` on a node has the same result as adding `ZIndex::Local(0)`. Additionally, the "global" stacking context is essentially a way to add your node to the root stacking context, so using `ZIndex::Local(n)` on a root node (one without parent) will share that space with all nodes using `Index::Global(n)`.
### New UiStack resource
This adds a new `UiStack` resource which is calculated from both hierarchy and `ZIndex` during UI update and contains a vector of all node entities in the UI, ordered by depth (from farthest from camera to closest). This is exposed publicly by the bevy_ui crate with the hope that it can be used for consistent ordering and to reduce the amount of sorting that needs to be done by UI systems (i.e. instead of sorting everything by `global_transform.z` in every system, this array can be iterated over).
### New z_index example
This also adds a new z_index example that showcases the new `ZIndex` component. It's also a good general demo of the new UI stack system, because making this kind of UI was very broken with the old system (e.g. nodes would render on top of each other, not respecting hierarchy or insert order at all).
![image](https://user-images.githubusercontent.com/1060971/189015985-8ea8f989-0e9d-4601-a7e0-4a27a43a53f9.png)
---
## Changelog
- Added the `ZIndex` component to bevy_ui.
- Added the `UiStack` resource to bevy_ui, and added implementation in a new `stack.rs` module.
- Removed the previous Z updating system from bevy_ui, because it was replaced with the above.
- Changed bevy_ui rendering to use UiStack instead of z ordering.
- Changed bevy_ui focus/interaction system to use UiStack instead of z ordering.
- Added a new z_index example.
## ZIndex demo
Here's a demo I wrote to test these features
https://user-images.githubusercontent.com/1060971/188329295-d7beebd6-9aee-43ab-821e-d437df5dbe8a.mp4
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-11-02 22:06:04 +00:00
[UI Z-Index ](../examples/ui/z_index.rs ) | Demonstrates how to control the relative depth (z-position) of UI elements
2023-06-14 22:43:38 +00:00
[Viewport Debug ](../examples/ui/viewport_debug.rs ) | An example for debugging viewport coordinates
2022-11-21 12:59:10 +00:00
[Window Fallthrough ](../examples/ui/window_fallthrough.rs ) | Illustrates how to access `winit::window::Window` 's `hittest` functionality.
2020-08-17 23:02:59 +00:00
## Window
2022-06-25 20:23:24 +00:00
Example | Description
--- | ---
[Clear Color ](../examples/window/clear_color.rs ) | Creates a solid color window
[Low Power ](../examples/window/low_power.rs ) | Demonstrates settings to reduce power use for bevy applications
[Multiple Windows ](../examples/window/multiple_windows.rs ) | Demonstrates creating multiple windows, and rendering to them
2022-07-05 16:59:31 +00:00
[Scale Factor Override ](../examples/window/scale_factor_override.rs ) | Illustrates how to customize the default window settings
2023-04-19 21:28:42 +00:00
[Screenshot ](../examples/window/screenshot.rs ) | Shows how to save screenshots to disk
2022-06-25 20:23:24 +00:00
[Transparent Window ](../examples/window/transparent_window.rs ) | Illustrates making the window transparent and hiding the window decoration
2022-08-29 23:56:43 +00:00
[Window Resizing ](../examples/window/window_resizing.rs ) | Demonstrates resizing and responding to resizing a window
2022-06-25 20:23:24 +00:00
[Window Settings ](../examples/window/window_settings.rs ) | Demonstrates customizing default window settings
# Tests
Example | Description
--- | ---
[How to Test Systems ](../tests/how_to_test_systems.rs ) | How to test systems with commands, queries or resources
2020-09-16 01:05:31 +00:00
2020-11-15 19:24:18 +00:00
# Platform-Specific Examples
## Android
2020-09-16 01:05:31 +00:00
2021-02-22 04:50:05 +00:00
### Setup
2020-09-16 01:05:31 +00:00
2020-11-03 19:32:48 +00:00
```sh
2020-11-15 19:24:18 +00:00
rustup target add aarch64-linux-android armv7-linux-androideabi
cargo install cargo-apk
2020-11-03 19:32:48 +00:00
```
2020-09-16 01:05:31 +00:00
2020-11-15 19:24:18 +00:00
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]` .
2021-02-22 04:50:05 +00:00
### Build & Run
2020-09-16 01:05:31 +00:00
2020-11-15 19:24:18 +00:00
To run on a device setup for Android development, run:
2020-09-19 03:11:26 +00:00
2020-11-03 19:32:48 +00:00
```sh
2023-02-06 18:08:49 +00:00
cargo apk run -p bevy_mobile_example
2020-11-03 19:32:48 +00:00
```
2020-09-16 01:05:31 +00:00
2020-11-15 19:24:18 +00:00
When using Bevy as a library, the following fields must be added to `Cargo.toml` :
```toml
[package.metadata.android]
build_targets = ["aarch64-linux-android", "armv7-linux-androideabi"]
2022-06-30 19:42:45 +00:00
[package.metadata.android.sdk]
target_sdk_version = 31
2020-11-03 19:32:48 +00:00
```
2020-10-31 21:36:24 +00:00
2020-11-15 19:24:18 +00:00
Please reference `cargo-apk` [README ](https://crates.io/crates/cargo-apk ) for other Android Manifest fields.
2022-06-30 19:42:45 +00:00
### Debugging
You can view the logs with the following command:
```sh
adb logcat | grep 'RustStdoutStderr\|bevy\|wgpu'
```
2023-01-27 12:12:53 +00:00
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.
2022-06-30 19:42:45 +00:00
Sometimes, running the app complains about an unknown activity. This may be fixed by uninstalling the application:
```sh
adb uninstall org.bevyengine.example
```
2021-02-22 04:50:05 +00:00
### Old phones
2020-11-12 01:15:19 +00:00
2022-06-30 19:42:45 +00:00
Bevy by default targets Android API level 31 in its examples which is the <!-- markdown - link - check - disable -->
2021-05-02 20:22:32 +00:00
[Play Store's minimum API to upload or update apps ](https://developer.android.com/distribute/best-practices/develop/target-sdk ). <!-- markdown-link-check-enable -->
Users of older phones may want to use an older API when testing.
2020-11-15 19:24:18 +00:00
To use a different API, the following fields must be updated in Cargo.toml:
```toml
2022-06-30 19:42:45 +00:00
[package.metadata.android.sdk]
2020-11-15 19:24:18 +00:00
target_sdk_version = >>API< <
min_sdk_version = >>API or less< <
```
2020-11-12 01:15:19 +00:00
2021-01-28 21:58:20 +00:00
Example | File | Description
--- | --- | ---
2023-02-06 18:08:49 +00:00
`android` | [`mobile/src/lib.rs` ](./mobile/src/lib.rs ) | A 3d Scene with a button and playing sound
2021-01-28 21:58:20 +00:00
2020-10-31 21:36:24 +00:00
## iOS
2021-02-22 04:50:05 +00:00
### Setup
2020-10-31 21:36:24 +00:00
2021-11-29 23:25:22 +00:00
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
2020-11-03 19:32:48 +00:00
```sh
2021-11-29 23:25:22 +00:00
rustup target add aarch64-apple-ios x86_64-apple-ios aarch64-apple-ios-sim
2020-11-03 19:32:48 +00:00
```
2020-10-31 21:36:24 +00:00
2021-02-22 04:50:05 +00:00
### Build & Run
2020-10-31 21:36:24 +00:00
Using bash:
2020-11-03 06:54:08 +00:00
2020-11-03 19:32:48 +00:00
```sh
2023-02-06 18:08:49 +00:00
cd examples/mobile
2020-11-03 19:32:48 +00:00
make run
```
2020-10-31 21:36:24 +00:00
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:
2020-11-03 06:54:08 +00:00
2020-11-03 19:32:48 +00:00
```sh
DEVICE_ID=${YOUR_DEVICE_ID} make run
```
2020-10-31 21:36:24 +00:00
If you'd like to see xcode do stuff, you can run
2020-11-03 06:54:08 +00:00
2020-11-03 19:32:48 +00:00
```sh
2023-02-06 18:08:49 +00:00
open bevy_mobile_example.xcodeproj/
2020-11-03 19:32:48 +00:00
```
2020-10-31 21:36:24 +00:00
which will open xcode. You then must push the zoom zoom play button and wait
for the magic.
2021-01-28 21:58:20 +00:00
Example | File | Description
--- | --- | ---
2023-02-06 18:08:49 +00:00
`ios` | [`mobile/src/lib.rs` ](./mobile/src/lib.rs ) | A 3d Scene with a button and playing sound
2021-01-28 21:58:20 +00:00
2020-11-15 19:24:18 +00:00
## WASM
2020-11-03 06:54:08 +00:00
2021-02-22 04:50:05 +00:00
### Setup
2020-11-03 06:54:08 +00:00
2020-11-03 19:32:48 +00:00
```sh
2020-11-15 19:24:18 +00:00
rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli
2020-11-03 19:32:48 +00:00
```
2020-11-03 06:54:08 +00:00
2021-02-22 04:50:05 +00:00
### Build & Run
2020-11-03 06:54:08 +00:00
2022-01-17 22:38:05 +00:00
Following is an example for `lighting` . For other examples, change the `lighting` in the
2022-06-25 20:23:24 +00:00
following commands.
2020-11-03 06:54:08 +00:00
2020-11-03 19:32:48 +00:00
```sh
2023-08-12 21:05:36 +00:00
cargo build --release --example lighting --target wasm32-unknown-unknown
2022-07-25 15:48:13 +00:00
wasm-bindgen --out-name wasm_example \
--out-dir examples/wasm/target \
--target web target/wasm32-unknown-unknown/release/examples/lighting.wasm
2020-11-03 19:32:48 +00:00
```
2020-11-03 06:54:08 +00:00
2022-01-17 22:38:05 +00:00
The first command will build the example for the wasm target, creating a binary. Then,
[wasm-bindgen-cli ](https://rustwasm.github.io/wasm-bindgen/reference/cli.html ) is used to create
2023-08-12 21:05:36 +00:00
javascript bindings to this wasm file in the output file `examples/wasm/target/wasm_example.js` , which can be loaded using this
2022-01-17 22:38:05 +00:00
[example HTML file ](./wasm/index.html ).
Then serve `examples/wasm` directory to browser. i.e.
2020-11-03 06:54:08 +00:00
2020-11-15 19:24:18 +00:00
```sh
2022-01-17 22:38:05 +00:00
# cargo install basic-http-server
2020-11-15 19:24:18 +00:00
basic-http-server examples/wasm
2022-01-17 22:38:05 +00:00
# with python
python3 -m http.server --directory examples/wasm
# with ruby
ruby -run -ehttpd examples/wasm
2020-11-03 19:32:48 +00:00
```
2020-11-03 06:54:08 +00:00
Webgpu support (#8336)
# Objective
- Support WebGPU
- alternative to #5027 that doesn't need any async / await
- fixes #8315
- Surprise fix #7318
## Solution
### For async renderer initialisation
- Update the plugin lifecycle:
- app builds the plugin
- calls `plugin.build`
- registers the plugin
- app starts the event loop
- event loop waits for `ready` of all registered plugins in the same
order
- returns `true` by default
- then call all `finish` then all `cleanup` in the same order as
registered
- then execute the schedule
In the case of the renderer, to avoid anything async:
- building the renderer plugin creates a detached task that will send
back the initialised renderer through a mutex in a resource
- `ready` will wait for the renderer to be present in the resource
- `finish` will take that renderer and place it in the expected
resources by other plugins
- other plugins (that expect the renderer to be available) `finish` are
called and they are able to set up their pipelines
- `cleanup` is called, only custom one is still for pipeline rendering
### For WebGPU support
- update the `build-wasm-example` script to support passing `--api
webgpu` that will build the example with WebGPU support
- feature for webgl2 was always enabled when building for wasm. it's now
in the default feature list and enabled on all platforms, so check for
this feature must also check that the target_arch is `wasm32`
---
## Migration Guide
- `Plugin::setup` has been renamed `Plugin::cleanup`
- `Plugin::finish` has been added, and plugins adding pipelines should
do it in this function instead of `Plugin::build`
```rust
// Before
impl Plugin for MyPlugin {
fn build(&self, app: &mut App) {
app.insert_resource::<MyResource>
.add_systems(Update, my_system);
let render_app = match app.get_sub_app_mut(RenderApp) {
Ok(render_app) => render_app,
Err(_) => return,
};
render_app
.init_resource::<RenderResourceNeedingDevice>()
.init_resource::<OtherRenderResource>();
}
}
// After
impl Plugin for MyPlugin {
fn build(&self, app: &mut App) {
app.insert_resource::<MyResource>
.add_systems(Update, my_system);
let render_app = match app.get_sub_app_mut(RenderApp) {
Ok(render_app) => render_app,
Err(_) => return,
};
render_app
.init_resource::<OtherRenderResource>();
}
fn finish(&self, app: &mut App) {
let render_app = match app.get_sub_app_mut(RenderApp) {
Ok(render_app) => render_app,
Err(_) => return,
};
render_app
.init_resource::<RenderResourceNeedingDevice>();
}
}
```
2023-05-04 22:07:57 +00:00
#### 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.
2023-10-18 17:30:44 +00:00
WebGPU depends on unstable APIs so you will also need to pass the `web_sys_unstable_apis` flag to your builds. For example:
```sh
RUSTFLAGS=--cfg=web_sys_unstable_apis cargo build ...
```
Check `wasm-bindgen` [docs on Unstable APIs ](https://rustwasm.github.io/wasm-bindgen/web-sys/unstable-apis.html ) for more details.
Webgpu support (#8336)
# Objective
- Support WebGPU
- alternative to #5027 that doesn't need any async / await
- fixes #8315
- Surprise fix #7318
## Solution
### For async renderer initialisation
- Update the plugin lifecycle:
- app builds the plugin
- calls `plugin.build`
- registers the plugin
- app starts the event loop
- event loop waits for `ready` of all registered plugins in the same
order
- returns `true` by default
- then call all `finish` then all `cleanup` in the same order as
registered
- then execute the schedule
In the case of the renderer, to avoid anything async:
- building the renderer plugin creates a detached task that will send
back the initialised renderer through a mutex in a resource
- `ready` will wait for the renderer to be present in the resource
- `finish` will take that renderer and place it in the expected
resources by other plugins
- other plugins (that expect the renderer to be available) `finish` are
called and they are able to set up their pipelines
- `cleanup` is called, only custom one is still for pipeline rendering
### For WebGPU support
- update the `build-wasm-example` script to support passing `--api
webgpu` that will build the example with WebGPU support
- feature for webgl2 was always enabled when building for wasm. it's now
in the default feature list and enabled on all platforms, so check for
this feature must also check that the target_arch is `wasm32`
---
## Migration Guide
- `Plugin::setup` has been renamed `Plugin::cleanup`
- `Plugin::finish` has been added, and plugins adding pipelines should
do it in this function instead of `Plugin::build`
```rust
// Before
impl Plugin for MyPlugin {
fn build(&self, app: &mut App) {
app.insert_resource::<MyResource>
.add_systems(Update, my_system);
let render_app = match app.get_sub_app_mut(RenderApp) {
Ok(render_app) => render_app,
Err(_) => return,
};
render_app
.init_resource::<RenderResourceNeedingDevice>()
.init_resource::<OtherRenderResource>();
}
}
// After
impl Plugin for MyPlugin {
fn build(&self, app: &mut App) {
app.insert_resource::<MyResource>
.add_systems(Update, my_system);
let render_app = match app.get_sub_app_mut(RenderApp) {
Ok(render_app) => render_app,
Err(_) => return,
};
render_app
.init_resource::<OtherRenderResource>();
}
fn finish(&self, app: &mut App) {
let render_app = match app.get_sub_app_mut(RenderApp) {
Ok(render_app) => render_app,
Err(_) => return,
};
render_app
.init_resource::<RenderResourceNeedingDevice>();
}
}
```
2023-05-04 22:07:57 +00:00
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.
2023-05-17 23:54:35 +00:00
### 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 ](https://developer.chrome.com/blog/web-audio-autoplay/ ). This page also describes a JS workaround to resume audio as soon as the user interact with your game.
2022-07-25 15:48:13 +00:00
### 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 ](https://doc.rust-lang.org/cargo/reference/profiles.html )
to your `Cargo.toml` :
```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.
```sh
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.
```sh
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,
2023-09-26 19:46:24 +00:00
the generated file sizes are, as of July 2022, as follows:
2022-07-25 15:48:13 +00:00
|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:
- < https: // rustwasm . github . io / book / reference / code-size . html >
- < https: // rustwasm . github . io / docs / wasm-bindgen / reference / optimize-size . html >
- < https: // rustwasm . github . io / book / game-of-life / code-size . html >
2022-01-17 22:38:05 +00:00
### 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.