From 2e99d84cdce0fd4ce77de274a01e9c621c9eb423 Mon Sep 17 00:00:00 2001 From: Carter Anderson Date: Mon, 26 Jul 2021 23:44:23 +0000 Subject: [PATCH 01/30] remove .system from pipelined code (#2538) Now that we have main features, lets use them! --- .github/bors.toml | 5 ++- .github/workflows/ci.yml | 42 +++++++++---------- crates/bevy_app/src/app.rs | 2 +- .../bevy_ecs/src/system/exclusive_system.rs | 2 +- crates/bevy_ecs/src/system/system_param.rs | 8 +++- crates/crevice/CHANGELOG.md | 39 ----------------- crates/crevice/Cargo.toml | 3 -- crates/crevice/README.md | 9 ++-- crates/crevice/crevice-derive/Cargo.toml | 5 --- crates/crevice/crevice-derive/src/lib.rs | 5 --- crates/crevice/src/lib.rs | 4 +- crates/crevice/src/std140/traits.rs | 2 +- examples/3d/3d_scene_pipelined.rs | 6 +-- examples/3d/cornell_box_pipelined.rs | 2 +- examples/3d/shadow_biases_pipelined.rs | 12 +++--- examples/3d/texture_pipelined.rs | 2 +- examples/README.md | 6 +++ examples/tools/bevymark_pipelined.rs | 10 ++--- pipelined/bevy_pbr2/Cargo.toml | 2 +- pipelined/bevy_pbr2/src/lib.rs | 13 +++--- pipelined/bevy_render2/Cargo.toml | 6 +-- pipelined/bevy_render2/src/camera/mod.rs | 11 ++--- .../bevy_render2/src/core_pipeline/mod.rs | 11 ++--- .../bevy_render2/src/mesh/mesh/conversions.rs | 6 +-- pipelined/bevy_render2/src/mesh/mesh/mod.rs | 4 +- pipelined/bevy_render2/src/render_asset.rs | 4 +- pipelined/bevy_render2/src/shader/shader.rs | 2 +- pipelined/bevy_render2/src/texture/mod.rs | 3 +- pipelined/bevy_render2/src/view/mod.rs | 2 +- pipelined/bevy_render2/src/view/window.rs | 4 +- pipelined/bevy_sprite2/src/lib.rs | 7 ++-- pipelined/changes.md | 10 ----- 32 files changed, 94 insertions(+), 155 deletions(-) delete mode 100644 crates/crevice/CHANGELOG.md delete mode 100644 pipelined/changes.md diff --git a/.github/bors.toml b/.github/bors.toml index 15d17706b39b8..45c784f105520 100644 --- a/.github/bors.toml +++ b/.github/bors.toml @@ -3,8 +3,9 @@ status = [ "build (stable, ubuntu-latest)", "build (stable, macos-latest)", "build (nightly, ubuntu-latest)", - "build-wasm (stable, ubuntu-latest)", - "build-wasm (nightly, ubuntu-latest)", + # TODO: re-enable after wasm works on pipelined-rendering + # "build-wasm (stable, ubuntu-latest)", + # "build-wasm (nightly, ubuntu-latest)", "markdownlint", "check-markdown-links", "run-examples", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index af23b4c778af9..78deb9dcead54 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -45,27 +45,27 @@ jobs: env: CARGO_INCREMENTAL: 0 RUSTFLAGS: "-C debuginfo=0 -D warnings" - - build-wasm: - strategy: - matrix: - toolchain: [stable, nightly] - os: [ubuntu-latest] - runs-on: ${{ matrix.os }} - steps: - - uses: actions/checkout@v2 - - - uses: actions-rs/toolchain@v1 - with: - toolchain: ${{ matrix.toolchain }} - target: wasm32-unknown-unknown - override: true - - - name: Check wasm - uses: actions-rs/cargo@v1 - with: - command: check - args: --target wasm32-unknown-unknown --no-default-features --features bevy_winit,x11,hdr,bevy_gltf + # NOTE: temporarily disabled while we sort out pipelined-rendering support + # build-wasm: + # strategy: + # matrix: + # toolchain: [stable, nightly] + # os: [ubuntu-latest] + # runs-on: ${{ matrix.os }} + # steps: + # - uses: actions/checkout@v2 + + # - uses: actions-rs/toolchain@v1 + # with: + # toolchain: ${{ matrix.toolchain }} + # target: wasm32-unknown-unknown + # override: true + + # - name: Check wasm + # uses: actions-rs/cargo@v1 + # with: + # command: check + # args: --target wasm32-unknown-unknown --no-default-features --features bevy_winit,x11,hdr,bevy_gltf build-android: runs-on: ubuntu-latest diff --git a/crates/bevy_app/src/app.rs b/crates/bevy_app/src/app.rs index f27f60699ff16..65ecd7217b5ab 100644 --- a/crates/bevy_app/src/app.rs +++ b/crates/bevy_app/src/app.rs @@ -544,7 +544,7 @@ impl App { /// # /// # struct MyOwnPlugin; /// # impl Plugin for MyOwnPlugin { - /// # fn build(&self, app: &mut AppBuilder){;} + /// # fn build(&self, app: &mut App) { } /// # } /// # /// App::new() diff --git a/crates/bevy_ecs/src/system/exclusive_system.rs b/crates/bevy_ecs/src/system/exclusive_system.rs index f5af6cbbfcc45..8ea5064167b4b 100644 --- a/crates/bevy_ecs/src/system/exclusive_system.rs +++ b/crates/bevy_ecs/src/system/exclusive_system.rs @@ -1,6 +1,6 @@ use crate::{ archetype::ArchetypeGeneration, - system::{check_system_change_tick, BoxedSystem, IntoSystem, System, SystemId}, + system::{check_system_change_tick, BoxedSystem, IntoSystem, SystemId}, world::World, }; use std::borrow::Cow; diff --git a/crates/bevy_ecs/src/system/system_param.rs b/crates/bevy_ecs/src/system/system_param.rs index 6194b0f3dcc58..385ec8af41095 100644 --- a/crates/bevy_ecs/src/system/system_param.rs +++ b/crates/bevy_ecs/src/system/system_param.rs @@ -27,11 +27,15 @@ use std::{ /// /// ``` /// # use bevy_ecs::prelude::*; +/// # use std::marker::PhantomData; /// use bevy_ecs::system::SystemParam; /// /// #[derive(SystemParam)] -/// struct MyParam<'a> { -/// foo: Res<'a, usize>, +/// struct MyParam<'s, 'w> { +/// foo: Res<'w, usize>, +/// // TODO: this isn't ideal ... maybe the SystemParam derive can be smarter about world and state lifetimes? +/// #[system_param(ignore)] +/// marker: PhantomData<&'s usize>, /// } /// /// fn my_system(param: MyParam) { diff --git a/crates/crevice/CHANGELOG.md b/crates/crevice/CHANGELOG.md deleted file mode 100644 index 4400505fb88c1..0000000000000 --- a/crates/crevice/CHANGELOG.md +++ /dev/null @@ -1,39 +0,0 @@ -# Crevice Changelog - -## Unreleased Changes - -## [0.6.0][0.6.0] (2021-02-24) -* Added `std430` support. Most APIs between `std140` and `std430` are the same! -* Added the `WriteStd140` trait. This trait is more general than `AsStd140` and is automatically implemented for all existing `AsStd140` implementers. -* Added `Writer::write_std140` to write a type that implements `Std140`. -* Added `AsStd140::std140_size_static`. This is similar to the old size method, `std140_size`, but no longer requires a value to be passed. For size measurements that depend on a value, use `WriteStd140::std140_size` instead. -* Deprecated `Writer::write_slice`, as `Writer::write` now accepts slices. -* Changed bounds of some functions, like `Writer::write` to use `WriteStd140` instead of `AsStd140`. This should affect no existing consumers. -* Moved `std140_size` from `AsStd140` to `WriteStd140`. Some existing consumers may need to import the other trait to access this m ethod. - -[0.6.0]: https://github.com/LPGhatguy/crevice/releases/tag/v0.6.0 - -## 0.5.0 (2020-10-18) -* Added f64-based std140 types: `DVec2`, `DVec3`, `DVec4`, `DMat2`, `DMat3`, and `DMat4`. -* Added support for std140 structs with alignment greater than 16. -* Fixed padding for std140 matrices; they were previously missing trailing padding. - -## 0.4.0 (2020-10-01) -* Added `AsStd140::std140_size` for easily pre-sizing buffers. -* `Writer::write` and `Sizer::add` now return the offset the value is or would be written to. -* Added `std140::DynamicUniform` for aligning dynamic uniform members. -* Added `Writer::write_slice` for writing multiple values in a row. - -## 0.3.0 (2020-09-22) -* Added `Std140::as_bytes`, reducing the need to work with bytemuck directly. -* Removed public re-export of bytemuck. - -## 0.2.0 (2020-09-22) -* Added documentation for everything in the crate. -* Removed `type_layout` being exposed except for internal tests. -* Fixed alignment offset not taking into account previously added alignment. -* Added `std140::Writer`, for writing dynamically laid out types to buffers. -* Added `std140::Sizer`, for pre-calculating buffer sizes. - -## 0.1.0 (2020-09-18) -* Initial MVP release diff --git a/crates/crevice/Cargo.toml b/crates/crevice/Cargo.toml index 93a77d7da89cb..f37325432f745 100644 --- a/crates/crevice/Cargo.toml +++ b/crates/crevice/Cargo.toml @@ -25,7 +25,4 @@ mint = "0.5.5" glam = "0.15.1" [dev-dependencies] -cgmath = { version = "0.17.0", features = ["mint"] } -insta = "0.16.1" -type-layout = { version = "0.2.0", features = ["serde1"] } crevice-derive = { version = "0.6.0", path = "crevice-derive" } diff --git a/crates/crevice/README.md b/crates/crevice/README.md index d8a700e6a9e3d..c8306125026a7 100644 --- a/crates/crevice/README.md +++ b/crates/crevice/README.md @@ -18,9 +18,9 @@ Examples in this crate use cgmath, but any math crate that works with the mint crate will also work. Some other crates include nalgebra, ultraviolet, glam, and vek. -### Examples +## Examples -#### Single Value +### Single Value Uploading many types can be done by deriving `AsStd140` and using [`as_std140`][std140::AsStd140::as_std140] and @@ -126,10 +126,11 @@ Crevice supports Rust 1.46.0 and newer due to use of new `const fn` features. Licensed under either of - * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) - * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) +* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)) +* MIT license ([LICENSE-MIT](LICENSE-MIT) or [http://opensource.org/licenses/MIT](http://opensource.org/licenses/MIT)) at your option. ### Contribution + Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. diff --git a/crates/crevice/crevice-derive/Cargo.toml b/crates/crevice/crevice-derive/Cargo.toml index a84a1d462565e..25d0726c4ceb8 100644 --- a/crates/crevice/crevice-derive/Cargo.toml +++ b/crates/crevice/crevice-derive/Cargo.toml @@ -9,11 +9,6 @@ homepage = "https://github.com/LPGhatguy/crevice" repository = "https://github.com/LPGhatguy/crevice" license = "MIT OR Apache-2.0" -[features] -# Feature used for testing; enables type_layout derive on types. -# Requires crate using derive to depend on type_layout as well. -test_type_layout = [] - [lib] proc-macro = true diff --git a/crates/crevice/crevice-derive/src/lib.rs b/crates/crevice/crevice-derive/src/lib.rs index a4fbac11ae8e4..01d7376c4b321 100644 --- a/crates/crevice/crevice-derive/src/lib.rs +++ b/crates/crevice/crevice-derive/src/lib.rs @@ -244,10 +244,6 @@ impl EmitOptions { }, ); - // For testing purposes, we can optionally generate type layout - // information using the type-layout crate. - let type_layout_derive = quote!(); - quote! { #[allow(non_snake_case)] mod #alignment_mod_name { @@ -257,7 +253,6 @@ impl EmitOptions { } #[derive(Debug, Clone, Copy)] - #type_layout_derive #[repr(C)] #visibility struct #generated_name #ty_generics #where_clause { #( #generated_fields )* diff --git a/crates/crevice/src/lib.rs b/crates/crevice/src/lib.rs index 076f2c7ce4d78..16f0994474dfb 100644 --- a/crates/crevice/src/lib.rs +++ b/crates/crevice/src/lib.rs @@ -35,7 +35,7 @@ uniform MAIN { } main; ``` -```rust +```skip use crevice::std140::{AsStd140, Std140}; use cgmath::prelude::*; use cgmath::{Matrix3, Vector3}; @@ -76,7 +76,7 @@ buffer POINT_LIGHTS { } point_lights; ``` -```rust +```skip use crevice::std140::{self, AsStd140}; #[derive(AsStd140)] diff --git a/crates/crevice/src/std140/traits.rs b/crates/crevice/src/std140/traits.rs index 55eec47463aab..6e0cf172fb8da 100644 --- a/crates/crevice/src/std140/traits.rs +++ b/crates/crevice/src/std140/traits.rs @@ -87,7 +87,7 @@ uniform CAMERA { } camera; ``` -``` +```skip use cgmath::prelude::*; use cgmath::{Matrix4, Deg, perspective}; use crevice::std140::{AsStd140, Std140}; diff --git a/examples/3d/3d_scene_pipelined.rs b/examples/3d/3d_scene_pipelined.rs index 58cdcedd01fee..711a5b0bc0ce3 100644 --- a/examples/3d/3d_scene_pipelined.rs +++ b/examples/3d/3d_scene_pipelined.rs @@ -22,9 +22,9 @@ fn main() { .add_plugins(PipelinedDefaultPlugins) .add_plugin(FrameTimeDiagnosticsPlugin::default()) .add_plugin(LogDiagnosticsPlugin::default()) - .add_startup_system(setup.system()) - .add_system(movement.system()) - .add_system(animate_light_direction.system()) + .add_startup_system(setup) + .add_system(movement) + .add_system(animate_light_direction) .run(); } diff --git a/examples/3d/cornell_box_pipelined.rs b/examples/3d/cornell_box_pipelined.rs index 9dbce9a8b0e57..161b268fb7703 100644 --- a/examples/3d/cornell_box_pipelined.rs +++ b/examples/3d/cornell_box_pipelined.rs @@ -20,7 +20,7 @@ fn main() { .add_plugins(PipelinedDefaultPlugins) .add_plugin(FrameTimeDiagnosticsPlugin::default()) .add_plugin(LogDiagnosticsPlugin::default()) - .add_startup_system(setup.system()) + .add_startup_system(setup) .run(); } diff --git a/examples/3d/shadow_biases_pipelined.rs b/examples/3d/shadow_biases_pipelined.rs index ad56596ebc764..3036021c006a7 100644 --- a/examples/3d/shadow_biases_pipelined.rs +++ b/examples/3d/shadow_biases_pipelined.rs @@ -31,11 +31,11 @@ fn main() { ); App::new() .add_plugins(PipelinedDefaultPlugins) - .add_startup_system(setup.system()) - .add_system(adjust_point_light_biases.system()) - .add_system(toggle_light.system()) - .add_system(adjust_directional_light_biases.system()) - .add_system(camera_controller.system()) + .add_startup_system(setup) + .add_system(adjust_point_light_biases) + .add_system(toggle_light) + .add_system(adjust_directional_light_biases) + .add_system(camera_controller) .run(); } @@ -119,7 +119,7 @@ fn setup( mesh: meshes.add(Mesh::from(shape::Plane { size: 2.0 * spawn_plane_depth, })), - material: white_handle.clone(), + material: white_handle, ..Default::default() }); } diff --git a/examples/3d/texture_pipelined.rs b/examples/3d/texture_pipelined.rs index a5f07f16bbdf9..f37fa182c7b57 100644 --- a/examples/3d/texture_pipelined.rs +++ b/examples/3d/texture_pipelined.rs @@ -15,7 +15,7 @@ use bevy::{ fn main() { App::new() .add_plugins(PipelinedDefaultPlugins) - .add_startup_system(setup.system()) + .add_startup_system(setup) .run(); } diff --git a/examples/README.md b/examples/README.md index 37b76a3a34830..12856903adae3 100644 --- a/examples/README.md +++ b/examples/README.md @@ -96,14 +96,19 @@ Example | File | Description Example | File | Description --- | --- | --- `3d_scene` | [`3d/3d_scene.rs`](./3d/3d_scene.rs) | Simple 3D scene with basic shapes and lighting +`3d_scene_pipelined` | [`3d/3d_scene_pipelined.rs`](./3d/3d_scene_pipelined.rs) | Simple 3D scene with basic shapes and lighting +`cornell_box_pipelined` | [`3d/cornell_box_pipelined.rs`](./3d/cornell_box_pipelined.rs) | Re-production of the cornell box `load_gltf` | [`3d/load_gltf.rs`](./3d/load_gltf.rs) | Loads and renders a gltf file as a scene `msaa` | [`3d/msaa.rs`](./3d/msaa.rs) | Configures MSAA (Multi-Sample Anti-Aliasing) for smoother edges `orthographic` | [`3d/orthographic.rs`](./3d/orthographic.rs) | Shows how to create a 3D orthographic view (for isometric-look games or CAD applications) `parenting` | [`3d/parenting.rs`](./3d/parenting.rs) | Demonstrates parent->child relationships and relative transformations `pbr` | [`3d/pbr.rs`](./3d/pbr.rs) | Demonstrates use of Physically Based Rendering (PBR) properties +`pbr_pipelined` | [`3d/pbr_pipelined.rs`](./3d/pbr_pipelined.rs) | Demonstrates use of Physically Based Rendering (PBR) properties `render_to_texture` | [`3d/render_to_texture.rs`](./3d/render_to_texture.rs) | Shows how to render to texture +`shadow_biases_pipelined` | [`3d/shadow_biases_pipelined.rs`](./3d/shadow_biases_pipelined.rs) | Demonstrates how shadow biases affect shadows in a 3d scene `spawner` | [`3d/spawner.rs`](./3d/spawner.rs) | Renders a large number of cubes with changing position and material `texture` | [`3d/texture.rs`](./3d/texture.rs) | Shows configuration of texture materials +`texture_pipelined` | [`3d/texture_pipelined.rs`](./3d/texture_pipelined.rs) | Shows configuration of texture materials `update_gltf_scene` | [`3d/update_gltf_scene.rs`](./3d/update_gltf_scene.rs) | Update a scene from a gltf file, either by spawning the scene as a child of another entity, or by accessing the entities of the scene `wireframe` | [`3d/wireframe.rs`](./3d/wireframe.rs) | Showcases wireframe rendering `z_sort_debug` | [`3d/z_sort_debug.rs`](./3d/z_sort_debug.rs) | Visualizes camera Z-ordering @@ -230,6 +235,7 @@ Example | File | Description Example | File | Description --- | --- | --- `bevymark` | [`tools/bevymark.rs`](./tools/bevymark.rs) | A heavy workload to benchmark your system with Bevy +`bevymark_pipelined` | [`tools/bevymark_pipelined.rs`](./tools/bevymark_pipelined.rs) | A heavy workload to benchmark your system with Bevy ## UI (User Interface) diff --git a/examples/tools/bevymark_pipelined.rs b/examples/tools/bevymark_pipelined.rs index b2e80850e381e..2178ced79c973 100644 --- a/examples/tools/bevymark_pipelined.rs +++ b/examples/tools/bevymark_pipelined.rs @@ -54,11 +54,11 @@ fn main() { // .add_plugin(WgpuResourceDiagnosticsPlugin::default()) .insert_resource(BevyCounter { count: 0 }) // .init_resource::() - .add_startup_system(setup.system()) - .add_system(mouse_handler.system()) - .add_system(movement_system.system()) - .add_system(collision_system.system()) - .add_system(counter_system.system()) + .add_startup_system(setup) + .add_system(mouse_handler) + .add_system(movement_system) + .add_system(collision_system) + .add_system(counter_system) .run(); } diff --git a/pipelined/bevy_pbr2/Cargo.toml b/pipelined/bevy_pbr2/Cargo.toml index 613b36a298b2e..263089a07b91c 100644 --- a/pipelined/bevy_pbr2/Cargo.toml +++ b/pipelined/bevy_pbr2/Cargo.toml @@ -28,5 +28,5 @@ bevy_utils = { path = "../../crates/bevy_utils", version = "0.5.0" } bitflags = "1.2" # direct dependency required for derive macro bytemuck = { version = "1", features = ["derive"] } -crevice = { path = "../../crates/crevice" } +crevice = { path = "../../crates/crevice", version = "0.6.0" } wgpu = "0.9" diff --git a/pipelined/bevy_pbr2/src/lib.rs b/pipelined/bevy_pbr2/src/lib.rs index 290643ad0dbb3..02ecb7ae37b38 100644 --- a/pipelined/bevy_pbr2/src/lib.rs +++ b/pipelined/bevy_pbr2/src/lib.rs @@ -33,20 +33,17 @@ impl Plugin for PbrPlugin { let render_app = app.sub_app_mut(0); render_app - .add_system_to_stage(RenderStage::Extract, render::extract_meshes.system()) - .add_system_to_stage(RenderStage::Extract, render::extract_lights.system()) - .add_system_to_stage(RenderStage::Prepare, render::prepare_meshes.system()) + .add_system_to_stage(RenderStage::Extract, render::extract_meshes) + .add_system_to_stage(RenderStage::Extract, render::extract_lights) + .add_system_to_stage(RenderStage::Prepare, render::prepare_meshes) .add_system_to_stage( RenderStage::Prepare, // this is added as an exclusive system because it contributes new views. it must run (and have Commands applied) // _before_ the `prepare_views()` system is run. ideally this becomes a normal system when "stageless" features come out render::prepare_lights.exclusive_system(), ) - .add_system_to_stage(RenderStage::Queue, render::queue_meshes.system()) - .add_system_to_stage( - RenderStage::PhaseSort, - sort_phase_system::.system(), - ) + .add_system_to_stage(RenderStage::Queue, render::queue_meshes) + .add_system_to_stage(RenderStage::PhaseSort, sort_phase_system::) // FIXME: Hack to ensure RenderCommandQueue is initialized when PbrShaders is being initialized // .init_resource::() .init_resource::() diff --git a/pipelined/bevy_render2/Cargo.toml b/pipelined/bevy_render2/Cargo.toml index 35068605f0da8..6d19db11ca5da 100644 --- a/pipelined/bevy_render2/Cargo.toml +++ b/pipelined/bevy_render2/Cargo.toml @@ -30,7 +30,7 @@ image = { version = "0.23.12", default-features = false } # misc wgpu = "0.9" -naga = { git = "https://github.com/gfx-rs/naga", rev = "0cf5484bba530f1134badbd2a1c1a8e9daf2e9c3", features = ["glsl-in", "spv-in", "spv-out", "wgsl-in", "wgsl-out"] } +naga = { version = "0.5", features = ["glsl-in", "spv-in", "spv-out", "wgsl-in", "wgsl-out"] } serde = { version = "1", features = ["derive"] } bitflags = "1.2.1" smallvec = { version = "1.6", features = ["union", "const_generics"] } @@ -40,9 +40,9 @@ thiserror = "1.0" futures-lite = "1.4.0" anyhow = "1.0" hex = "0.4.2" -hexasphere = "3.4" +hexasphere = "4.0" parking_lot = "0.11.0" -crevice = { path = "../../crates/crevice" } +crevice = { path = "../../crates/crevice", version = "0.6.0" } [features] png = ["image/png"] diff --git a/pipelined/bevy_render2/src/camera/mod.rs b/pipelined/bevy_render2/src/camera/mod.rs index 23b31691d96e5..63ea8f66721f2 100644 --- a/pipelined/bevy_render2/src/camera/mod.rs +++ b/pipelined/bevy_render2/src/camera/mod.rs @@ -31,22 +31,19 @@ impl Plugin for CameraPlugin { active_cameras.add(Self::CAMERA_3D); app.register_type::() .insert_resource(active_cameras) + .add_system_to_stage(CoreStage::PostUpdate, crate::camera::active_cameras_system) .add_system_to_stage( CoreStage::PostUpdate, - crate::camera::active_cameras_system.system(), + crate::camera::camera_system::, ) .add_system_to_stage( CoreStage::PostUpdate, - crate::camera::camera_system::.system(), - ) - .add_system_to_stage( - CoreStage::PostUpdate, - crate::camera::camera_system::.system(), + crate::camera::camera_system::, ); let render_app = app.sub_app_mut(0); render_app .init_resource::() - .add_system_to_stage(RenderStage::Extract, extract_cameras.system()); + .add_system_to_stage(RenderStage::Extract, extract_cameras); } } diff --git a/pipelined/bevy_render2/src/core_pipeline/mod.rs b/pipelined/bevy_render2/src/core_pipeline/mod.rs index 36769ec92e243..45bb313b6f23a 100644 --- a/pipelined/bevy_render2/src/core_pipeline/mod.rs +++ b/pipelined/bevy_render2/src/core_pipeline/mod.rs @@ -61,18 +61,15 @@ impl Plugin for CorePipelinePlugin { fn build(&self, app: &mut App) { let render_app = app.sub_app_mut(0); render_app - .add_system_to_stage( - RenderStage::Extract, - extract_core_pipeline_camera_phases.system(), - ) - .add_system_to_stage(RenderStage::Prepare, prepare_core_views_system.system()) + .add_system_to_stage(RenderStage::Extract, extract_core_pipeline_camera_phases) + .add_system_to_stage(RenderStage::Prepare, prepare_core_views_system) .add_system_to_stage( RenderStage::PhaseSort, - sort_phase_system::.system(), + sort_phase_system::, ) .add_system_to_stage( RenderStage::PhaseSort, - sort_phase_system::.system(), + sort_phase_system::, ); let pass_node_2d = MainPass2dNode::new(&mut render_app.world); diff --git a/pipelined/bevy_render2/src/mesh/mesh/conversions.rs b/pipelined/bevy_render2/src/mesh/mesh/conversions.rs index 51170afc2b22e..79b88498a88c6 100644 --- a/pipelined/bevy_render2/src/mesh/mesh/conversions.rs +++ b/pipelined/bevy_render2/src/mesh/mesh/conversions.rs @@ -4,16 +4,16 @@ //! # Examples //! //! ```rust -//! use bevy_render::mesh::VertexAttributeValues; +//! use bevy_render2::mesh::VertexAttributeValues; //! use std::convert::{ TryInto, TryFrom }; //! //! // creating std::vec::Vec //! let buffer = vec![[0_u32; 4]; 10]; //! -//! // converting std::vec::Vec to bevy_render::mesh::VertexAttributeValues +//! // converting std::vec::Vec to bevy_render2::mesh::VertexAttributeValues //! let values = VertexAttributeValues::from(buffer.clone()); //! -//! // converting bevy_render::mesh::VertexAttributeValues to std::vec::Vec with two ways +//! // converting bevy_render2::mesh::VertexAttributeValues to std::vec::Vec with two ways //! let result_into: Vec<[u32; 4]> = values.clone().try_into().unwrap(); //! let result_from: Vec<[u32; 4]> = Vec::try_from(values.clone()).unwrap(); //! diff --git a/pipelined/bevy_render2/src/mesh/mesh/mod.rs b/pipelined/bevy_render2/src/mesh/mesh/mod.rs index 4f04b66a50413..57f5ed80d444b 100644 --- a/pipelined/bevy_render2/src/mesh/mesh/mod.rs +++ b/pipelined/bevy_render2/src/mesh/mesh/mod.rs @@ -36,8 +36,8 @@ pub struct Mesh { /// /// Example of constructing a mesh: /// ``` -/// # use bevy_render::mesh::{Mesh, Indices}; -/// # use bevy_render::pipeline::PrimitiveTopology; +/// # use bevy_render2::mesh::{Mesh, Indices}; +/// # use bevy_render2::render_resource::PrimitiveTopology; /// fn create_triangle() -> Mesh { /// let mut mesh = Mesh::new(PrimitiveTopology::TriangleList); /// mesh.set_attribute(Mesh::ATTRIBUTE_POSITION, vec![[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0]]); diff --git a/pipelined/bevy_render2/src/render_asset.rs b/pipelined/bevy_render2/src/render_asset.rs index be9489b5cb6e4..90533d2e5915c 100644 --- a/pipelined/bevy_render2/src/render_asset.rs +++ b/pipelined/bevy_render2/src/render_asset.rs @@ -35,8 +35,8 @@ impl Plugin for RenderAssetPlugin { render_app .init_resource::>() .init_resource::>() - .add_system_to_stage(RenderStage::Extract, extract_render_asset::.system()) - .add_system_to_stage(RenderStage::Prepare, prepare_render_asset::.system()); + .add_system_to_stage(RenderStage::Extract, extract_render_asset::) + .add_system_to_stage(RenderStage::Prepare, prepare_render_asset::); } } diff --git a/pipelined/bevy_render2/src/shader/shader.rs b/pipelined/bevy_render2/src/shader/shader.rs index 4fcf84d0f6b20..b27539dec9e2b 100644 --- a/pipelined/bevy_render2/src/shader/shader.rs +++ b/pipelined/bevy_render2/src/shader/shader.rs @@ -75,7 +75,7 @@ impl Shader { &source, &naga::front::glsl::Options { entry_points, - ..Default::default() + defines: Default::default(), }, )? } diff --git a/pipelined/bevy_render2/src/texture/mod.rs b/pipelined/bevy_render2/src/texture/mod.rs index 243c9fdc58d52..976b7c10592d5 100644 --- a/pipelined/bevy_render2/src/texture/mod.rs +++ b/pipelined/bevy_render2/src/texture/mod.rs @@ -16,7 +16,6 @@ pub use texture_cache::*; use crate::{render_asset::RenderAssetPlugin, RenderStage}; use bevy_app::{App, Plugin}; use bevy_asset::AddAsset; -use bevy_ecs::prelude::*; // TODO: replace Texture names with Image names? pub struct ImagePlugin; @@ -34,7 +33,7 @@ impl Plugin for ImagePlugin { let render_app = app.sub_app_mut(0); render_app .init_resource::() - .add_system_to_stage(RenderStage::Cleanup, update_texture_cache_system.system()); + .add_system_to_stage(RenderStage::Cleanup, update_texture_cache_system); } } diff --git a/pipelined/bevy_render2/src/view/mod.rs b/pipelined/bevy_render2/src/view/mod.rs index 06d73fd80ce00..d95ae8834ada5 100644 --- a/pipelined/bevy_render2/src/view/mod.rs +++ b/pipelined/bevy_render2/src/view/mod.rs @@ -25,7 +25,7 @@ impl Plugin for ViewPlugin { let render_app = app.sub_app_mut(0); render_app .init_resource::() - .add_system_to_stage(RenderStage::Prepare, prepare_views.system()); + .add_system_to_stage(RenderStage::Prepare, prepare_views); let mut graph = render_app.world.get_resource_mut::().unwrap(); graph.add_node(ViewPlugin::VIEW_NODE, ViewNode); diff --git a/pipelined/bevy_render2/src/view/window.rs b/pipelined/bevy_render2/src/view/window.rs index ddae464da516c..5ec52bec0d49b 100644 --- a/pipelined/bevy_render2/src/view/window.rs +++ b/pipelined/bevy_render2/src/view/window.rs @@ -23,8 +23,8 @@ impl Plugin for WindowRenderPlugin { render_app .init_resource::() .init_resource::() - .add_system_to_stage(RenderStage::Extract, extract_windows.system()) - .add_system_to_stage(RenderStage::Prepare, prepare_windows.system()); + .add_system_to_stage(RenderStage::Extract, extract_windows) + .add_system_to_stage(RenderStage::Prepare, prepare_windows); } } diff --git a/pipelined/bevy_sprite2/src/lib.rs b/pipelined/bevy_sprite2/src/lib.rs index 4f0c14d8becd2..9aed799588077 100644 --- a/pipelined/bevy_sprite2/src/lib.rs +++ b/pipelined/bevy_sprite2/src/lib.rs @@ -9,7 +9,6 @@ pub use render::*; pub use sprite::*; use bevy_app::prelude::*; -use bevy_ecs::prelude::IntoSystem; use bevy_render2::{ core_pipeline, render_graph::RenderGraph, render_phase::DrawFunctions, RenderStage, }; @@ -22,9 +21,9 @@ impl Plugin for SpritePlugin { app.register_type::(); let render_app = app.sub_app_mut(0); render_app - .add_system_to_stage(RenderStage::Extract, render::extract_sprites.system()) - .add_system_to_stage(RenderStage::Prepare, render::prepare_sprites.system()) - .add_system_to_stage(RenderStage::Queue, queue_sprites.system()) + .add_system_to_stage(RenderStage::Extract, render::extract_sprites) + .add_system_to_stage(RenderStage::Prepare, render::prepare_sprites) + .add_system_to_stage(RenderStage::Queue, queue_sprites) .init_resource::() .init_resource::(); let draw_sprite = DrawSprite::new(&mut render_app.world); diff --git a/pipelined/changes.md b/pipelined/changes.md deleted file mode 100644 index bd374ca1254e7..0000000000000 --- a/pipelined/changes.md +++ /dev/null @@ -1,10 +0,0 @@ -* Remove AppBuilder -* Add SubApps -* `Res>` -> `Res` -* Removed RenderResourceBindings -* Made shaders and pipelines proper render resources (removes dependency on bevy_asset and is generally a cleaner api) -* Removed RenderResources / RenderResource traits -* Decoupled swap chain from Window in Renderer api -* Removed RenderResourceBindings -* Removed asset tracking from render resources -* Removed cruft from RenderResource api \ No newline at end of file From 0973d40a9f516b15340ccfd84ed28e5642515082 Mon Sep 17 00:00:00 2001 From: Carter Anderson Date: Wed, 28 Jul 2021 17:52:24 +0000 Subject: [PATCH 02/30] Add RenderWorld to Extract step (#2555) Makes the "Render App World" directly available to Extract step systems as a `RenderWorld` resource. Prior to this, there was no way to directly read / write render world state during the Extract step. The only way to make changes was through Commands (which were applied at the end of the stage). ```rust // `thing` is an "app world resource". fn extract_thing(thing: Res, mut render_world: ResMut) { render_world.insert_resource(ExtractedThing::from(thing)); } ``` RenderWorld makes a number of scenarios possible: * When an extract system does big allocations, it is now possible to reuse them across frames by retrieving old values from RenderWorld (at the cost of reduced parallelism from unique RenderWorld borrows). * Enables inserting into the same resource across multiple extract systems * Enables using past RenderWorld state to inform future extract state (this should generally be avoided) Ultimately this is just a subset of the functionality we want. In the future, it would be great to have "multi-world schedules" to enable fine grained parallelism on the render world during the extract step. But that is a research project that almost certainly won't make it into 0.6. This is a good interim solution that should easily port over to multi-world schedules if/when they land. --- pipelined/bevy_render2/src/lib.rs | 43 +++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/pipelined/bevy_render2/src/lib.rs b/pipelined/bevy_render2/src/lib.rs index 1500846112c3b..8083b12751458 100644 --- a/pipelined/bevy_render2/src/lib.rs +++ b/pipelined/bevy_render2/src/lib.rs @@ -11,6 +11,8 @@ pub mod shader; pub mod texture; pub mod view; +use std::ops::{Deref, DerefMut}; + pub use once_cell; use wgpu::BackendBit; @@ -54,6 +56,29 @@ pub enum RenderStage { Cleanup, } +/// The Render App World. This is only available as a resource during the Extract step. +#[derive(Default)] +pub struct RenderWorld(World); + +impl Deref for RenderWorld { + type Target = World; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for RenderWorld { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +/// A "scratch" world used to avoid allocating new worlds every frame when +// swapping out the Render World. +#[derive(Default)] +struct ScratchRenderWorld(World); + impl Plugin for RenderPlugin { fn build(&self, app: &mut App) { let (instance, device, queue) = @@ -66,7 +91,8 @@ impl Plugin for RenderPlugin { &wgpu::DeviceDescriptor::default(), )); app.insert_resource(device.clone()) - .insert_resource(queue.clone()); + .insert_resource(queue.clone()) + .init_resource::(); let mut render_app = App::empty(); let mut extract_stage = SystemStage::parallel(); @@ -89,7 +115,7 @@ impl Plugin for RenderPlugin { .init_resource::() .init_resource::(); - app.add_sub_app(render_app, |app_world, render_app| { + app.add_sub_app(render_app, move |app_world, render_app| { // reserve all existing app entities for use in render_app // they can only be spawned using `get_or_spawn()` let meta_len = app_world.entities().meta.len(); @@ -97,6 +123,7 @@ impl Plugin for RenderPlugin { .world .entities() .reserve_entities(meta_len as u32); + // flushing as "invalid" ensures that app world entities aren't added as "empty archetype" entities by default // these entities cannot be accessed without spawning directly onto them // this _only_ works as expected because clear_entities() is called at the end of every frame. @@ -156,6 +183,18 @@ fn extract(app_world: &mut World, render_app: &mut App) { .schedule .get_stage_mut::(&RenderStage::Extract) .unwrap(); + + // temporarily add the render world to the app world as a resource + let scratch_world = app_world.remove_resource::().unwrap(); + let render_world = std::mem::replace(&mut render_app.world, scratch_world.0); + app_world.insert_resource(RenderWorld(render_world)); + extract.run(app_world); + + // add the render world back to the render app + let render_world = app_world.remove_resource::().unwrap(); + let scratch_world = std::mem::replace(&mut render_app.world, render_world.0); + app_world.insert_resource(ScratchRenderWorld(scratch_world)); + extract.apply_buffers(&mut render_app.world); } From 3ec6b3f9a0b7814f170e8d3e80950e50d7e9e457 Mon Sep 17 00:00:00 2001 From: Carter Anderson Date: Wed, 28 Jul 2021 21:29:32 +0000 Subject: [PATCH 03/30] move bevy_core_pipeline to its own plugin (#2552) This decouples the opinionated "core pipeline" from the new (less opinionated) bevy_render crate. The "core pipeline" is intended to be used by crates like bevy_sprites, bevy_pbr, bevy_ui, and 3rd party crates that extends core rendering functionality. --- Cargo.toml | 2 ++ crates/bevy_internal/Cargo.toml | 1 + crates/bevy_internal/src/default_plugins.rs | 18 ++++++++++------- crates/bevy_internal/src/lib.rs | 6 ++++++ pipelined/bevy_core_pipeline/Cargo.toml | 20 +++++++++++++++++++ .../mod.rs => bevy_core_pipeline/src/lib.rs} | 12 ++++++----- .../src}/main_pass_2d.rs | 8 ++++---- .../src}/main_pass_3d.rs | 14 ++++++------- .../src}/main_pass_driver.rs | 10 +++++----- pipelined/bevy_pbr2/Cargo.toml | 1 + pipelined/bevy_pbr2/src/lib.rs | 9 ++++----- pipelined/bevy_pbr2/src/render/light.rs | 2 +- pipelined/bevy_pbr2/src/render/mod.rs | 5 ++--- pipelined/bevy_render2/src/lib.rs | 1 - pipelined/bevy_sprite2/Cargo.toml | 1 + pipelined/bevy_sprite2/src/lib.rs | 6 ++---- pipelined/bevy_sprite2/src/render/mod.rs | 2 +- 17 files changed, 75 insertions(+), 43 deletions(-) create mode 100644 pipelined/bevy_core_pipeline/Cargo.toml rename pipelined/{bevy_render2/src/core_pipeline/mod.rs => bevy_core_pipeline/src/lib.rs} (97%) rename pipelined/{bevy_render2/src/core_pipeline => bevy_core_pipeline/src}/main_pass_2d.rs (94%) rename pipelined/{bevy_render2/src/core_pipeline => bevy_core_pipeline/src}/main_pass_3d.rs (93%) rename pipelined/{bevy_render2/src/core_pipeline => bevy_core_pipeline/src}/main_pass_driver.rs (92%) diff --git a/Cargo.toml b/Cargo.toml index 476fa13047cc5..84b9e1d5455e9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,7 @@ members = ["crates/*", "pipelined/*", "examples/ios", "tools/ci"] [features] default = [ "bevy_audio", + "bevy_core_pipeline", "bevy_dynamic_plugin", "bevy_gilrs", "bevy_gltf", @@ -51,6 +52,7 @@ bevy_gltf = ["bevy_internal/bevy_gltf"] bevy_wgpu = ["bevy_internal/bevy_wgpu"] bevy_winit = ["bevy_internal/bevy_winit"] +bevy_core_pipeline = ["bevy_internal/bevy_core_pipeline"] bevy_render2 = ["bevy_internal/bevy_render2"] bevy_sprite2 = ["bevy_internal/bevy_sprite2"] bevy_pbr2 = ["bevy_internal/bevy_pbr2"] diff --git a/crates/bevy_internal/Cargo.toml b/crates/bevy_internal/Cargo.toml index b745c40f34fa5..036a053df4bee 100644 --- a/crates/bevy_internal/Cargo.toml +++ b/crates/bevy_internal/Cargo.toml @@ -66,6 +66,7 @@ bevy_window = { path = "../bevy_window", version = "0.5.0" } bevy_tasks = { path = "../bevy_tasks", version = "0.5.0" } # bevy (optional) bevy_audio = { path = "../bevy_audio", optional = true, version = "0.5.0" } +bevy_core_pipeline = { path = "../../pipelined/bevy_core_pipeline", optional = true, version = "0.5.0" } bevy_gltf = { path = "../bevy_gltf", optional = true, version = "0.5.0" } bevy_pbr = { path = "../bevy_pbr", optional = true, version = "0.5.0" } bevy_pbr2 = { path = "../../pipelined/bevy_pbr2", optional = true, version = "0.5.0" } diff --git a/crates/bevy_internal/src/default_plugins.rs b/crates/bevy_internal/src/default_plugins.rs index 19dac798b0210..6d506e5651b27 100644 --- a/crates/bevy_internal/src/default_plugins.rs +++ b/crates/bevy_internal/src/default_plugins.rs @@ -121,16 +121,20 @@ impl PluginGroup for PipelinedDefaultPlugins { #[cfg(feature = "bevy_render2")] { group.add(bevy_render2::RenderPlugin::default()); - group.add(bevy_render2::core_pipeline::CorePipelinePlugin::default()); } - #[cfg(feature = "bevy_winit")] - group.add(bevy_winit::WinitPlugin::default()); + #[cfg(feature = "bevy_core_pipeline")] + { + group.add(bevy_core_pipeline::CorePipelinePlugin::default()); - #[cfg(feature = "bevy_sprite2")] - group.add(bevy_sprite2::SpritePlugin::default()); + #[cfg(feature = "bevy_sprite2")] + group.add(bevy_sprite2::SpritePlugin::default()); - #[cfg(feature = "bevy_pbr2")] - group.add(bevy_pbr2::PbrPlugin::default()); + #[cfg(feature = "bevy_pbr2")] + group.add(bevy_pbr2::PbrPlugin::default()); + } + + #[cfg(feature = "bevy_winit")] + group.add(bevy_winit::WinitPlugin::default()); } } diff --git a/crates/bevy_internal/src/lib.rs b/crates/bevy_internal/src/lib.rs index 081ef2879defc..a47ee1984062a 100644 --- a/crates/bevy_internal/src/lib.rs +++ b/crates/bevy_internal/src/lib.rs @@ -82,6 +82,12 @@ pub mod audio { pub use bevy_audio::*; } +#[cfg(feature = "bevy_core_pipeline")] +pub mod core_pipeline { + //! Core render pipeline. + pub use bevy_core_pipeline::*; +} + #[cfg(feature = "bevy_gilrs")] pub mod gilrs { pub use bevy_gilrs::*; diff --git a/pipelined/bevy_core_pipeline/Cargo.toml b/pipelined/bevy_core_pipeline/Cargo.toml new file mode 100644 index 0000000000000..539816e466b03 --- /dev/null +++ b/pipelined/bevy_core_pipeline/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "bevy_core_pipeline" +version = "0.5.0" +edition = "2018" +authors = [ + "Bevy Contributors ", + "Carter Anderson ", +] +description = "Provides a core render pipeline for Bevy Engine." +homepage = "https://bevyengine.org" +repository = "https://github.com/bevyengine/bevy" +license = "MIT OR Apache-2.0" +keywords = ["bevy"] + +[dependencies] +# bevy +bevy_app = { path = "../../crates/bevy_app", version = "0.5.0" } +bevy_ecs = { path = "../../crates/bevy_ecs", version = "0.5.0" } +bevy_render2 = { path = "../bevy_render2", version = "0.5.0" } + diff --git a/pipelined/bevy_render2/src/core_pipeline/mod.rs b/pipelined/bevy_core_pipeline/src/lib.rs similarity index 97% rename from pipelined/bevy_render2/src/core_pipeline/mod.rs rename to pipelined/bevy_core_pipeline/src/lib.rs index 45bb313b6f23a..51012767332da 100644 --- a/pipelined/bevy_render2/src/core_pipeline/mod.rs +++ b/pipelined/bevy_core_pipeline/src/lib.rs @@ -6,19 +6,21 @@ pub use main_pass_2d::*; pub use main_pass_3d::*; pub use main_pass_driver::*; -use crate::{ +use bevy_app::{App, Plugin}; +use bevy_ecs::prelude::*; +use bevy_render2::{ camera::{ActiveCameras, CameraPlugin}, render_graph::{EmptyNode, RenderGraph, SlotInfo, SlotType}, render_phase::{sort_phase_system, RenderPhase}, - render_resource::{Texture, TextureView}, + render_resource::{ + Extent3d, Texture, TextureDescriptor, TextureDimension, TextureFormat, TextureUsage, + TextureView, + }, renderer::RenderDevice, texture::TextureCache, view::{ExtractedView, ViewPlugin}, RenderStage, }; -use bevy_app::{App, Plugin}; -use bevy_ecs::prelude::*; -use wgpu::{Extent3d, TextureDescriptor, TextureDimension, TextureFormat, TextureUsage}; // Plugins that contribute to the RenderGraph should use the following label conventions: // 1. Graph modules should have a NAME, input module, and node module (where relevant) diff --git a/pipelined/bevy_render2/src/core_pipeline/main_pass_2d.rs b/pipelined/bevy_core_pipeline/src/main_pass_2d.rs similarity index 94% rename from pipelined/bevy_render2/src/core_pipeline/main_pass_2d.rs rename to pipelined/bevy_core_pipeline/src/main_pass_2d.rs index 969f0c7663200..50f91bdb9785f 100644 --- a/pipelined/bevy_render2/src/core_pipeline/main_pass_2d.rs +++ b/pipelined/bevy_core_pipeline/src/main_pass_2d.rs @@ -1,13 +1,13 @@ -use crate::{ +use crate::Transparent2dPhase; +use bevy_ecs::prelude::*; +use bevy_render2::{ color::Color, - core_pipeline::Transparent2dPhase, render_graph::{Node, NodeRunError, RenderGraphContext, SlotInfo, SlotType}, render_phase::{DrawFunctions, RenderPhase, TrackedRenderPass}, + render_resource::{LoadOp, Operations, RenderPassColorAttachment, RenderPassDescriptor}, renderer::RenderContext, view::ExtractedView, }; -use bevy_ecs::prelude::*; -use wgpu::{LoadOp, Operations, RenderPassColorAttachment, RenderPassDescriptor}; pub struct MainPass2dNode { query: QueryState<&'static RenderPhase, With>, diff --git a/pipelined/bevy_render2/src/core_pipeline/main_pass_3d.rs b/pipelined/bevy_core_pipeline/src/main_pass_3d.rs similarity index 93% rename from pipelined/bevy_render2/src/core_pipeline/main_pass_3d.rs rename to pipelined/bevy_core_pipeline/src/main_pass_3d.rs index c772fb654786e..c561bac2f3981 100644 --- a/pipelined/bevy_render2/src/core_pipeline/main_pass_3d.rs +++ b/pipelined/bevy_core_pipeline/src/main_pass_3d.rs @@ -1,16 +1,16 @@ -use crate::{ +use crate::Transparent3dPhase; +use bevy_ecs::prelude::*; +use bevy_render2::{ color::Color, - core_pipeline::Transparent3dPhase, render_graph::{Node, NodeRunError, RenderGraphContext, SlotInfo, SlotType}, render_phase::{DrawFunctions, RenderPhase, TrackedRenderPass}, + render_resource::{ + LoadOp, Operations, RenderPassColorAttachment, RenderPassDepthStencilAttachment, + RenderPassDescriptor, + }, renderer::RenderContext, view::ExtractedView, }; -use bevy_ecs::prelude::*; -use wgpu::{ - LoadOp, Operations, RenderPassColorAttachment, RenderPassDepthStencilAttachment, - RenderPassDescriptor, -}; pub struct MainPass3dNode { query: QueryState<&'static RenderPhase, With>, diff --git a/pipelined/bevy_render2/src/core_pipeline/main_pass_driver.rs b/pipelined/bevy_core_pipeline/src/main_pass_driver.rs similarity index 92% rename from pipelined/bevy_render2/src/core_pipeline/main_pass_driver.rs rename to pipelined/bevy_core_pipeline/src/main_pass_driver.rs index c4066fd1ed4c1..2e0736c3febb5 100644 --- a/pipelined/bevy_render2/src/core_pipeline/main_pass_driver.rs +++ b/pipelined/bevy_core_pipeline/src/main_pass_driver.rs @@ -1,11 +1,11 @@ -use crate::{ +use crate::ViewDepthTexture; +use bevy_ecs::world::World; +use bevy_render2::{ camera::{CameraPlugin, ExtractedCamera, ExtractedCameraNames}, - core_pipeline::{self, ViewDepthTexture}, render_graph::{Node, NodeRunError, RenderGraphContext, SlotValue}, renderer::RenderContext, view::ExtractedWindows, }; -use bevy_ecs::world::World; pub struct MainPassDriverNode; @@ -24,7 +24,7 @@ impl Node for MainPassDriverNode { let extracted_window = extracted_windows.get(&extracted_camera.window_id).unwrap(); let swap_chain_texture = extracted_window.swap_chain_frame.as_ref().unwrap().clone(); graph.run_sub_graph( - core_pipeline::draw_2d_graph::NAME, + crate::draw_2d_graph::NAME, vec![ SlotValue::Entity(*camera_2d), SlotValue::TextureView(swap_chain_texture), @@ -38,7 +38,7 @@ impl Node for MainPassDriverNode { let extracted_window = extracted_windows.get(&extracted_camera.window_id).unwrap(); let swap_chain_texture = extracted_window.swap_chain_frame.as_ref().unwrap().clone(); graph.run_sub_graph( - core_pipeline::draw_3d_graph::NAME, + crate::draw_3d_graph::NAME, vec![ SlotValue::Entity(*camera_3d), SlotValue::TextureView(swap_chain_texture), diff --git a/pipelined/bevy_pbr2/Cargo.toml b/pipelined/bevy_pbr2/Cargo.toml index 263089a07b91c..5f7f4e47b2dce 100644 --- a/pipelined/bevy_pbr2/Cargo.toml +++ b/pipelined/bevy_pbr2/Cargo.toml @@ -17,6 +17,7 @@ keywords = ["bevy"] bevy_app = { path = "../../crates/bevy_app", version = "0.5.0" } bevy_asset = { path = "../../crates/bevy_asset", version = "0.5.0" } bevy_core = { path = "../../crates/bevy_core", version = "0.5.0" } +bevy_core_pipeline = { path = "../bevy_core_pipeline", version = "0.5.0" } bevy_ecs = { path = "../../crates/bevy_ecs", version = "0.5.0" } bevy_math = { path = "../../crates/bevy_math", version = "0.5.0" } bevy_reflect = { path = "../../crates/bevy_reflect", version = "0.5.0", features = ["bevy"] } diff --git a/pipelined/bevy_pbr2/src/lib.rs b/pipelined/bevy_pbr2/src/lib.rs index 02ecb7ae37b38..75561835d9a64 100644 --- a/pipelined/bevy_pbr2/src/lib.rs +++ b/pipelined/bevy_pbr2/src/lib.rs @@ -11,7 +11,6 @@ pub use render::*; use bevy_app::prelude::*; use bevy_ecs::prelude::*; use bevy_render2::{ - core_pipeline, render_graph::RenderGraph, render_phase::{sort_phase_system, DrawFunctions}, RenderStage, @@ -61,23 +60,23 @@ impl Plugin for PbrPlugin { let mut graph = render_world.get_resource_mut::().unwrap(); graph.add_node("pbr", PbrNode); graph - .add_node_edge("pbr", core_pipeline::node::MAIN_PASS_DEPENDENCIES) + .add_node_edge("pbr", bevy_core_pipeline::node::MAIN_PASS_DEPENDENCIES) .unwrap(); let draw_3d_graph = graph - .get_sub_graph_mut(core_pipeline::draw_3d_graph::NAME) + .get_sub_graph_mut(bevy_core_pipeline::draw_3d_graph::NAME) .unwrap(); draw_3d_graph.add_node(draw_3d_graph::node::SHADOW_PASS, shadow_pass_node); draw_3d_graph .add_node_edge( draw_3d_graph::node::SHADOW_PASS, - core_pipeline::draw_3d_graph::node::MAIN_PASS, + bevy_core_pipeline::draw_3d_graph::node::MAIN_PASS, ) .unwrap(); draw_3d_graph .add_slot_edge( draw_3d_graph.input_node().unwrap().id, - core_pipeline::draw_3d_graph::input::VIEW_ENTITY, + bevy_core_pipeline::draw_3d_graph::input::VIEW_ENTITY, draw_3d_graph::node::SHADOW_PASS, ShadowPassNode::IN_VIEW, ) diff --git a/pipelined/bevy_pbr2/src/render/light.rs b/pipelined/bevy_pbr2/src/render/light.rs index 12e229e1f372d..45ab08a3a8fb0 100644 --- a/pipelined/bevy_pbr2/src/render/light.rs +++ b/pipelined/bevy_pbr2/src/render/light.rs @@ -1,10 +1,10 @@ use crate::{AmbientLight, DirectionalLight, ExtractedMeshes, MeshMeta, PbrShaders, PointLight}; +use bevy_core_pipeline::Transparent3dPhase; use bevy_ecs::{prelude::*, system::SystemState}; use bevy_math::{const_vec3, Mat4, Vec3, Vec4}; use bevy_render2::{ camera::CameraProjection, color::Color, - core_pipeline::Transparent3dPhase, mesh::Mesh, render_asset::RenderAssets, render_graph::{Node, NodeRunError, RenderGraphContext, SlotInfo, SlotType}, diff --git a/pipelined/bevy_pbr2/src/render/mod.rs b/pipelined/bevy_pbr2/src/render/mod.rs index 94d9f1507554d..8c54071eb136c 100644 --- a/pipelined/bevy_pbr2/src/render/mod.rs +++ b/pipelined/bevy_pbr2/src/render/mod.rs @@ -1,11 +1,12 @@ mod light; pub use light::*; +use crate::{StandardMaterial, StandardMaterialUniformData}; use bevy_asset::{Assets, Handle}; +use bevy_core_pipeline::Transparent3dPhase; use bevy_ecs::{prelude::*, system::SystemState}; use bevy_math::Mat4; use bevy_render2::{ - core_pipeline::Transparent3dPhase, mesh::Mesh, render_asset::RenderAssets, render_graph::{Node, NodeRunError, RenderGraphContext}, @@ -24,8 +25,6 @@ use wgpu::{ TextureViewDescriptor, }; -use crate::{StandardMaterial, StandardMaterialUniformData}; - pub struct PbrShaders { pipeline: RenderPipeline, shader_module: ShaderModule, diff --git a/pipelined/bevy_render2/src/lib.rs b/pipelined/bevy_render2/src/lib.rs index 8083b12751458..580e0d0a6caa2 100644 --- a/pipelined/bevy_render2/src/lib.rs +++ b/pipelined/bevy_render2/src/lib.rs @@ -1,6 +1,5 @@ pub mod camera; pub mod color; -pub mod core_pipeline; pub mod mesh; pub mod render_asset; pub mod render_graph; diff --git a/pipelined/bevy_sprite2/Cargo.toml b/pipelined/bevy_sprite2/Cargo.toml index 1cebd3ef06dfd..28f7e64843a56 100644 --- a/pipelined/bevy_sprite2/Cargo.toml +++ b/pipelined/bevy_sprite2/Cargo.toml @@ -17,6 +17,7 @@ keywords = ["bevy"] bevy_app = { path = "../../crates/bevy_app", version = "0.5.0" } bevy_asset = { path = "../../crates/bevy_asset", version = "0.5.0" } bevy_core = { path = "../../crates/bevy_core", version = "0.5.0" } +bevy_core_pipeline = { path = "../bevy_core_pipeline", version = "0.5.0" } bevy_ecs = { path = "../../crates/bevy_ecs", version = "0.5.0" } bevy_log = { path = "../../crates/bevy_log", version = "0.5.0" } bevy_math = { path = "../../crates/bevy_math", version = "0.5.0" } diff --git a/pipelined/bevy_sprite2/src/lib.rs b/pipelined/bevy_sprite2/src/lib.rs index 9aed799588077..9e5767b8f8c10 100644 --- a/pipelined/bevy_sprite2/src/lib.rs +++ b/pipelined/bevy_sprite2/src/lib.rs @@ -9,9 +9,7 @@ pub use render::*; pub use sprite::*; use bevy_app::prelude::*; -use bevy_render2::{ - core_pipeline, render_graph::RenderGraph, render_phase::DrawFunctions, RenderStage, -}; +use bevy_render2::{render_graph::RenderGraph, render_phase::DrawFunctions, RenderStage}; #[derive(Default)] pub struct SpritePlugin; @@ -37,7 +35,7 @@ impl Plugin for SpritePlugin { let mut graph = render_world.get_resource_mut::().unwrap(); graph.add_node("sprite", SpriteNode); graph - .add_node_edge("sprite", core_pipeline::node::MAIN_PASS_DEPENDENCIES) + .add_node_edge("sprite", bevy_core_pipeline::node::MAIN_PASS_DEPENDENCIES) .unwrap(); } } diff --git a/pipelined/bevy_sprite2/src/render/mod.rs b/pipelined/bevy_sprite2/src/render/mod.rs index 9f55cca8afa27..8e83f8c7113bc 100644 --- a/pipelined/bevy_sprite2/src/render/mod.rs +++ b/pipelined/bevy_sprite2/src/render/mod.rs @@ -1,9 +1,9 @@ use crate::Sprite; use bevy_asset::{Assets, Handle}; +use bevy_core_pipeline::Transparent2dPhase; use bevy_ecs::{prelude::*, system::SystemState}; use bevy_math::{Mat4, Vec2, Vec3, Vec4Swizzles}; use bevy_render2::{ - core_pipeline::Transparent2dPhase, mesh::{shape::Quad, Indices, Mesh, VertexAttributeValues}, render_asset::RenderAssets, render_graph::{Node, NodeRunError, RenderGraphContext}, From 6944d38a142bccb4d11f6610d2433f91829cd2d7 Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Thu, 29 Jul 2021 00:02:10 +0000 Subject: [PATCH 04/30] bevy_render2: Log adapter info on initialization (#2542) It is useful to see which adapter is being used and which wgpu backend. --- pipelined/bevy_render2/src/renderer/mod.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pipelined/bevy_render2/src/renderer/mod.rs b/pipelined/bevy_render2/src/renderer/mod.rs index fd1562659dbbf..b53a76e92bdcb 100644 --- a/pipelined/bevy_render2/src/renderer/mod.rs +++ b/pipelined/bevy_render2/src/renderer/mod.rs @@ -1,6 +1,7 @@ mod graph_runner; mod render_device; +use bevy_utils::tracing::info; pub use graph_runner::*; pub use render_device::*; @@ -40,6 +41,9 @@ pub async fn initialize_renderer( .await .expect("Unable to find a GPU! Make sure you have installed required drivers!"); + #[cfg(not(target_arch = "wasm32"))] + info!("{:?}", adapter.get_info()); + #[cfg(feature = "trace")] let trace_path = { let path = std::path::Path::new("wgpu_trace"); From 0b800e547bdee35a56590ad2e3f3ae1aaa280b8f Mon Sep 17 00:00:00 2001 From: Boxy Date: Thu, 29 Jul 2021 20:52:15 +0000 Subject: [PATCH 05/30] Fix some nightly clippy lints (#2522) on nightly these two clippy lints fail: - [needless_borrow](https://rust-lang.github.io/rust-clippy/master/#needless_borrow) - [unused_unit](https://rust-lang.github.io/rust-clippy/master/#unused_unit) --- crates/bevy_asset/src/asset_server.rs | 2 +- crates/bevy_asset/src/loader.rs | 2 +- crates/bevy_audio/src/audio_output.rs | 2 +- crates/bevy_core/src/label.rs | 2 +- crates/bevy_ecs/src/bundle.rs | 1 + crates/bevy_ecs/src/lib.rs | 6 +- crates/bevy_ecs/src/query/access.rs | 2 +- crates/bevy_ecs/src/query/fetch.rs | 4 ++ crates/bevy_ecs/src/query/iter.rs | 8 +-- crates/bevy_ecs/src/schedule/graph_utils.rs | 2 +- crates/bevy_ecs/src/system/function_system.rs | 2 +- crates/bevy_ecs/src/system/system_param.rs | 2 + crates/bevy_gltf/src/loader.rs | 2 +- .../bevy_pbr/src/render_graph/lights_node.rs | 6 +- .../bevy_reflect_derive/src/lib.rs | 12 ++-- crates/bevy_render/src/mesh/mesh.rs | 60 +++++++++---------- .../src/pipeline/pipeline_compiler.rs | 4 +- .../src/pipeline/vertex_buffer_descriptor.rs | 2 +- .../src/render_graph/nodes/pass_node.rs | 2 +- .../nodes/render_resources_node.rs | 16 ++--- .../render_graph/nodes/texture_copy_node.rs | 2 +- .../nodes/window_swapchain_node.rs | 6 +- .../render_graph/nodes/window_texture_node.rs | 4 +- crates/bevy_render/src/shader/shader.rs | 4 +- crates/bevy_render/src/texture/texture.rs | 2 +- crates/bevy_scene/src/dynamic_scene.rs | 2 +- crates/bevy_scene/src/scene_loader.rs | 2 +- crates/bevy_scene/src/scene_spawner.rs | 4 +- crates/bevy_ui/src/flex/mod.rs | 8 +-- .../src/renderer/wgpu_render_context.rs | 8 +-- .../renderer/wgpu_render_resource_context.rs | 14 ++--- crates/bevy_wgpu/src/wgpu_resources.rs | 2 +- crates/bevy_winit/src/winit_windows.rs | 4 +- examples/scene/scene.rs | 4 +- 34 files changed, 104 insertions(+), 101 deletions(-) diff --git a/crates/bevy_asset/src/asset_server.rs b/crates/bevy_asset/src/asset_server.rs index d5a331909de34..f46b96ed7bf8f 100644 --- a/crates/bevy_asset/src/asset_server.rs +++ b/crates/bevy_asset/src/asset_server.rs @@ -478,7 +478,7 @@ impl AssetServer { .expect("Asset should exist at this point."); if let Some(asset_lifecycle) = asset_lifecycles.get(&asset_value.type_uuid()) { let asset_path = - AssetPath::new_ref(&load_context.path, label.as_ref().map(|l| l.as_str())); + AssetPath::new_ref(load_context.path, label.as_ref().map(|l| l.as_str())); asset_lifecycle.create_asset(asset_path.into(), asset_value, load_context.version); } else { panic!( diff --git a/crates/bevy_asset/src/loader.rs b/crates/bevy_asset/src/loader.rs index 825eab38a459e..0ca85fa74738e 100644 --- a/crates/bevy_asset/src/loader.rs +++ b/crates/bevy_asset/src/loader.rs @@ -101,7 +101,7 @@ impl<'a> LoadContext<'a> { } pub fn path(&self) -> &Path { - &self.path + self.path } pub fn has_labeled_asset(&self, label: &str) -> bool { diff --git a/crates/bevy_audio/src/audio_output.rs b/crates/bevy_audio/src/audio_output.rs index 9d3fb481154d7..7b4aa1d24bee0 100644 --- a/crates/bevy_audio/src/audio_output.rs +++ b/crates/bevy_audio/src/audio_output.rs @@ -45,7 +45,7 @@ where { fn play_source(&self, audio_source: &P) { if let Some(stream_handle) = &self.stream_handle { - let sink = Sink::try_new(&stream_handle).unwrap(); + let sink = Sink::try_new(stream_handle).unwrap(); sink.append(audio_source.decoder()); sink.detach(); } diff --git a/crates/bevy_core/src/label.rs b/crates/bevy_core/src/label.rs index ce7b676eb641b..7a2689caff197 100644 --- a/crates/bevy_core/src/label.rs +++ b/crates/bevy_core/src/label.rs @@ -107,7 +107,7 @@ pub(crate) fn entity_labels_system( } } - for added_label in labels.labels.difference(¤t_labels) { + for added_label in labels.labels.difference(current_labels) { entity_labels .label_entities .entry(added_label.clone()) diff --git a/crates/bevy_ecs/src/bundle.rs b/crates/bevy_ecs/src/bundle.rs index 00f3bac9e527e..8a9f2f15e461d 100644 --- a/crates/bevy_ecs/src/bundle.rs +++ b/crates/bevy_ecs/src/bundle.rs @@ -71,6 +71,7 @@ macro_rules! tuple_impl { } #[allow(unused_variables, unused_mut)] + #[allow(clippy::unused_unit)] unsafe fn from_components(mut func: impl FnMut() -> *mut u8) -> Self { #[allow(non_snake_case)] let ($(mut $name,)*) = ( diff --git a/crates/bevy_ecs/src/lib.rs b/crates/bevy_ecs/src/lib.rs index dd2d3e23c03fb..8a4cc5eac659c 100644 --- a/crates/bevy_ecs/src/lib.rs +++ b/crates/bevy_ecs/src/lib.rs @@ -732,7 +732,7 @@ mod tests { fn get_added(world: &mut World) -> Vec { world .query_filtered::>() - .iter(&world) + .iter(world) .collect::>() } @@ -776,7 +776,7 @@ mod tests { { world .query_filtered::() - .iter(&world) + .iter(world) .collect::>() } @@ -863,7 +863,7 @@ mod tests { fn get_changed(world: &mut World) -> Vec { world .query_filtered::>() - .iter(&world) + .iter(world) .collect::>() } assert_eq!(get_changed(&mut world), vec![e1]); diff --git a/crates/bevy_ecs/src/query/access.rs b/crates/bevy_ecs/src/query/access.rs index dcf5c691c0f09..f735f36580f32 100644 --- a/crates/bevy_ecs/src/query/access.rs +++ b/crates/bevy_ecs/src/query/access.rs @@ -197,7 +197,7 @@ impl FilteredAccessSet { // compatibility if !filtered_access.access.is_compatible(&self.combined_access) { for current_filtered_access in self.filtered_accesses.iter() { - if !current_filtered_access.is_compatible(&filtered_access) { + if !current_filtered_access.is_compatible(filtered_access) { return current_filtered_access .access .get_conflicts(&filtered_access.access); diff --git a/crates/bevy_ecs/src/query/fetch.rs b/crates/bevy_ecs/src/query/fetch.rs index 19aacc3028421..97bdda0462c45 100644 --- a/crates/bevy_ecs/src/query/fetch.rs +++ b/crates/bevy_ecs/src/query/fetch.rs @@ -917,6 +917,7 @@ macro_rules! impl_tuple_fetch { type Item = ($($name::Item,)*); type State = ($($name::State,)*); + #[allow(clippy::unused_unit)] unsafe fn init(_world: &World, state: &Self::State, _last_change_tick: u32, _change_tick: u32) -> Self { let ($($name,)*) = state; ($($name::init(_world, $name, _last_change_tick, _change_tick),)*) @@ -944,12 +945,14 @@ macro_rules! impl_tuple_fetch { } #[inline] + #[allow(clippy::unused_unit)] unsafe fn table_fetch(&mut self, _table_row: usize) -> Self::Item { let ($($name,)*) = self; ($($name.table_fetch(_table_row),)*) } #[inline] + #[allow(clippy::unused_unit)] unsafe fn archetype_fetch(&mut self, _archetype_index: usize) -> Self::Item { let ($($name,)*) = self; ($($name.archetype_fetch(_archetype_index),)*) @@ -958,6 +961,7 @@ macro_rules! impl_tuple_fetch { // SAFETY: update_component_access and update_archetype_component_access are called for each item in the tuple #[allow(non_snake_case)] + #[allow(clippy::unused_unit)] unsafe impl<$($name: FetchState),*> FetchState for ($($name,)*) { fn init(_world: &mut World) -> Self { ($($name::init(_world),)*) diff --git a/crates/bevy_ecs/src/query/iter.rs b/crates/bevy_ecs/src/query/iter.rs index d2cadf2f0ea58..4ad402ccfe7d8 100644 --- a/crates/bevy_ecs/src/query/iter.rs +++ b/crates/bevy_ecs/src/query/iter.rs @@ -290,16 +290,12 @@ where // first, iterate from last to first until next item is found 'outer: for i in (0..K).rev() { - match self.cursors[i].next(&self.tables, &self.archetypes, &self.query_state) { + match self.cursors[i].next(self.tables, self.archetypes, self.query_state) { Some(_) => { // walk forward up to last element, propagating cursor state forward for j in (i + 1)..K { self.cursors[j] = self.cursors[j - 1].clone(); - match self.cursors[j].next( - &self.tables, - &self.archetypes, - &self.query_state, - ) { + match self.cursors[j].next(self.tables, self.archetypes, self.query_state) { Some(_) => {} None if i > 0 => continue 'outer, None => return None, diff --git a/crates/bevy_ecs/src/schedule/graph_utils.rs b/crates/bevy_ecs/src/schedule/graph_utils.rs index 2707f6997aad0..88cda8e2042dd 100644 --- a/crates/bevy_ecs/src/schedule/graph_utils.rs +++ b/crates/bevy_ecs/src/schedule/graph_utils.rs @@ -97,7 +97,7 @@ pub fn topological_order( } current.push(*node); for dependency in graph.get(node).unwrap().keys() { - if check_if_cycles_and_visit(dependency, &graph, sorted, unvisited, current) { + if check_if_cycles_and_visit(dependency, graph, sorted, unvisited, current) { return true; } } diff --git a/crates/bevy_ecs/src/system/function_system.rs b/crates/bevy_ecs/src/system/function_system.rs index b1b0670e10404..9a4b531362ac3 100644 --- a/crates/bevy_ecs/src/system/function_system.rs +++ b/crates/bevy_ecs/src/system/function_system.rs @@ -353,7 +353,7 @@ where #[inline] fn component_access(&self) -> &Access { - &self.system_meta.component_access_set.combined_access() + self.system_meta.component_access_set.combined_access() } #[inline] diff --git a/crates/bevy_ecs/src/system/system_param.rs b/crates/bevy_ecs/src/system/system_param.rs index 385ec8af41095..900017e9cbd1d 100644 --- a/crates/bevy_ecs/src/system/system_param.rs +++ b/crates/bevy_ecs/src/system/system_param.rs @@ -1167,6 +1167,7 @@ macro_rules! impl_system_param_tuple { type Item = ($($param::Item,)*); #[inline] + #[allow(clippy::unused_unit)] unsafe fn get_param( state: &'s mut Self, system_meta: &SystemMeta, @@ -1201,6 +1202,7 @@ macro_rules! impl_system_param_tuple { $($param.apply(_world);)* } + #[allow(clippy::unused_unit)] fn default_config() -> ($(<$param as SystemParamState>::Config,)*) { ($(<$param as SystemParamState>::default_config(),)*) } diff --git a/crates/bevy_gltf/src/loader.rs b/crates/bevy_gltf/src/loader.rs index efc41b6378333..9c68cd996230f 100644 --- a/crates/bevy_gltf/src/loader.rs +++ b/crates/bevy_gltf/src/loader.rs @@ -369,7 +369,7 @@ async fn load_texture<'a>( } fn load_material(material: &Material, load_context: &mut LoadContext) -> Handle { - let material_label = material_label(&material); + let material_label = material_label(material); let pbr = material.pbr_metallic_roughness(); diff --git a/crates/bevy_pbr/src/render_graph/lights_node.rs b/crates/bevy_pbr/src/render_graph/lights_node.rs index 6c7f0bbc96028..665f4b1f12f23 100644 --- a/crates/bevy_pbr/src/render_graph/lights_node.rs +++ b/crates/bevy_pbr/src/render_graph/lights_node.rs @@ -174,8 +174,8 @@ pub fn lights_node_system( .chunks_exact_mut(point_light_size), ) { slot.copy_from_slice(bytes_of(&PointLightUniform::new( - &point_light, - &global_transform, + point_light, + global_transform, ))); } @@ -184,7 +184,7 @@ pub fn lights_node_system( data[dir_light_uniform_start..dir_light_uniform_end] .chunks_exact_mut(dir_light_size), ) { - slot.copy_from_slice(bytes_of(&DirectionalLightUniform::new(&dir_light))); + slot.copy_from_slice(bytes_of(&DirectionalLightUniform::new(dir_light))); } }, ); diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index b393622fb8806..0066f5a10d52e 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -191,8 +191,8 @@ fn impl_struct( let field_count = active_fields.len(); let field_indices = (0..field_count).collect::>(); - let hash_fn = reflect_attrs.get_hash_impl(&bevy_reflect_path); - let serialize_fn = reflect_attrs.get_serialize_impl(&bevy_reflect_path); + let hash_fn = reflect_attrs.get_hash_impl(bevy_reflect_path); + let serialize_fn = reflect_attrs.get_serialize_impl(bevy_reflect_path); let partial_eq_fn = match reflect_attrs.reflect_partial_eq { TraitImpl::NotImplemented => quote! { use #bevy_reflect_path::Struct; @@ -335,8 +335,8 @@ fn impl_tuple_struct( let field_count = active_fields.len(); let field_indices = (0..field_count).collect::>(); - let hash_fn = reflect_attrs.get_hash_impl(&bevy_reflect_path); - let serialize_fn = reflect_attrs.get_serialize_impl(&bevy_reflect_path); + let hash_fn = reflect_attrs.get_hash_impl(bevy_reflect_path); + let serialize_fn = reflect_attrs.get_serialize_impl(bevy_reflect_path); let partial_eq_fn = match reflect_attrs.reflect_partial_eq { TraitImpl::NotImplemented => quote! { use #bevy_reflect_path::TupleStruct; @@ -448,9 +448,9 @@ fn impl_value( bevy_reflect_path: &Path, reflect_attrs: &ReflectAttrs, ) -> TokenStream { - let hash_fn = reflect_attrs.get_hash_impl(&bevy_reflect_path); + let hash_fn = reflect_attrs.get_hash_impl(bevy_reflect_path); let partial_eq_fn = reflect_attrs.get_partial_eq_impl(); - let serialize_fn = reflect_attrs.get_serialize_impl(&bevy_reflect_path); + let serialize_fn = reflect_attrs.get_serialize_impl(bevy_reflect_path); let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); TokenStream::from(quote! { diff --git a/crates/bevy_render/src/mesh/mesh.rs b/crates/bevy_render/src/mesh/mesh.rs index bbaf5fa5c6a88..29d2cdf19d4c4 100644 --- a/crates/bevy_render/src/mesh/mesh.rs +++ b/crates/bevy_render/src/mesh/mesh.rs @@ -413,34 +413,34 @@ impl Mesh { for (_, attributes) in self.attributes.iter_mut() { let indices = indices.iter(); match attributes { - VertexAttributeValues::Float32(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Sint32(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Uint32(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Float32x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Sint32x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Uint32x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Float32x3(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Sint32x3(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Uint32x3(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Sint32x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Uint32x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Float32x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Sint16x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Snorm16x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Uint16x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Unorm16x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Sint16x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Snorm16x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Uint16x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Unorm16x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Sint8x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Snorm8x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Uint8x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Unorm8x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Sint8x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Snorm8x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Uint8x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Unorm8x4(vec) => *vec = duplicate(&vec, indices), + VertexAttributeValues::Float32(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Sint32(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Uint32(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Float32x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Sint32x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Uint32x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Float32x3(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Sint32x3(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Uint32x3(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Sint32x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Uint32x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Float32x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Sint16x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Snorm16x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Uint16x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Unorm16x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Sint16x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Snorm16x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Uint16x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Unorm16x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Sint8x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Snorm8x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Uint8x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Unorm8x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Sint8x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Snorm8x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Uint8x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Unorm8x4(vec) => *vec = duplicate(vec, indices), } } } @@ -481,7 +481,7 @@ fn remove_resource_save( index: u64, ) { if let Some(RenderResourceId::Buffer(buffer)) = - render_resource_context.get_asset_resource(&handle, index) + render_resource_context.get_asset_resource(handle, index) { render_resource_context.remove_buffer(buffer); render_resource_context.remove_asset_resource(handle, index); @@ -546,7 +546,7 @@ pub fn mesh_resource_provider_system( buffer_usage: BufferUsage::INDEX, ..Default::default() }, - &data, + data, ); render_resource_context.set_asset_resource( diff --git a/crates/bevy_render/src/pipeline/pipeline_compiler.rs b/crates/bevy_render/src/pipeline/pipeline_compiler.rs index 84753b0291025..1272551773403 100644 --- a/crates/bevy_render/src/pipeline/pipeline_compiler.rs +++ b/crates/bevy_render/src/pipeline/pipeline_compiler.rs @@ -164,7 +164,7 @@ impl PipelineCompiler { }); let mut layout = render_resource_context.reflect_pipeline_layout( - &shaders, + shaders, &specialized_descriptor.shader_stages, true, ); @@ -252,7 +252,7 @@ impl PipelineCompiler { render_resource_context.create_render_pipeline( specialized_pipeline_handle.clone_weak(), pipelines.get(&specialized_pipeline_handle).unwrap(), - &shaders, + shaders, ); // track specialized shader pipelines diff --git a/crates/bevy_render/src/pipeline/vertex_buffer_descriptor.rs b/crates/bevy_render/src/pipeline/vertex_buffer_descriptor.rs index a891cb3720f36..14ad026720346 100644 --- a/crates/bevy_render/src/pipeline/vertex_buffer_descriptor.rs +++ b/crates/bevy_render/src/pipeline/vertex_buffer_descriptor.rs @@ -51,6 +51,6 @@ pub struct VertexAttribute { /// Internally, `bevy_render` uses hashes to identify vertex attribute names. pub fn get_vertex_attribute_name_id(name: &str) -> u64 { let mut hasher = bevy_utils::AHasher::default(); - hasher.write(&name.as_bytes()); + hasher.write(name.as_bytes()); hasher.finish() } diff --git a/crates/bevy_render/src/render_graph/nodes/pass_node.rs b/crates/bevy_render/src/render_graph/nodes/pass_node.rs index cf0962a13aadf..73cf62e8f113a 100644 --- a/crates/bevy_render/src/render_graph/nodes/pass_node.rs +++ b/crates/bevy_render/src/render_graph/nodes/pass_node.rs @@ -237,7 +237,7 @@ where let commands = &mut self.commands; render_context.begin_pass( &self.descriptor, - &render_resource_bindings, + render_resource_bindings, &mut |render_pass| { for render_command in commands.drain(..) { match render_command { diff --git a/crates/bevy_render/src/render_graph/nodes/render_resources_node.rs b/crates/bevy_render/src/render_graph/nodes/render_resources_node.rs index 0901a7782d9db..2b46a9a6b715d 100644 --- a/crates/bevy_render/src/render_graph/nodes/render_resources_node.rs +++ b/crates/bevy_render/src/render_graph/nodes/render_resources_node.rs @@ -458,7 +458,7 @@ fn render_resources_node_system( queries.q1_mut().get_mut(entity) { if !setup_uniform_texture_resources::( - &uniforms, + uniforms, render_resource_context, &mut render_pipelines.bindings, ) { @@ -473,7 +473,7 @@ fn render_resources_node_system( } uniform_buffer_arrays.prepare_uniform_buffers(entity, uniforms); if !setup_uniform_texture_resources::( - &uniforms, + uniforms, render_resource_context, &mut render_pipelines.bindings, ) { @@ -505,7 +505,7 @@ fn render_resources_node_system( state.uniform_buffer_arrays.write_uniform_buffers( entity, - &uniforms, + uniforms, state.dynamic_uniforms, render_resource_context, &mut render_pipelines.bindings, @@ -522,7 +522,7 @@ fn render_resources_node_system( state.uniform_buffer_arrays.write_uniform_buffers( entity, - &uniforms, + uniforms, state.dynamic_uniforms, render_resource_context, &mut render_pipelines.bindings, @@ -656,7 +656,7 @@ fn asset_render_resources_node_system( if let Some(asset) = assets.get(asset_handle) { let mut bindings = asset_render_resource_bindings.get_or_insert_mut(&Handle::::weak(asset_handle)); - if !setup_uniform_texture_resources::(&asset, render_resource_context, &mut bindings) + if !setup_uniform_texture_resources::(asset, render_resource_context, &mut bindings) { asset_state.assets_waiting_for_textures.push(asset_handle); } @@ -689,7 +689,7 @@ fn asset_render_resources_node_system( uniform_buffer_arrays.prepare_uniform_buffers(*asset_handle, asset); let mut bindings = asset_render_resource_bindings.get_or_insert_mut(&Handle::::weak(*asset_handle)); - if !setup_uniform_texture_resources::(&asset, render_resource_context, &mut bindings) { + if !setup_uniform_texture_resources::(asset, render_resource_context, &mut bindings) { asset_state.assets_waiting_for_textures.push(*asset_handle); } } @@ -719,7 +719,7 @@ fn asset_render_resources_node_system( // TODO: only setup buffer if we haven't seen this handle before state.uniform_buffer_arrays.write_uniform_buffers( asset_handle, - &asset, + asset, state.dynamic_uniforms, render_resource_context, &mut render_resource_bindings, @@ -733,7 +733,7 @@ fn asset_render_resources_node_system( // TODO: only setup buffer if we haven't seen this handle before state.uniform_buffer_arrays.write_uniform_buffers( *asset_handle, - &asset, + asset, state.dynamic_uniforms, render_resource_context, &mut render_resource_bindings, diff --git a/crates/bevy_render/src/render_graph/nodes/texture_copy_node.rs b/crates/bevy_render/src/render_graph/nodes/texture_copy_node.rs index 93dbc45edf6ae..ff37812800cb9 100644 --- a/crates/bevy_render/src/render_graph/nodes/texture_copy_node.rs +++ b/crates/bevy_render/src/render_graph/nodes/texture_copy_node.rs @@ -24,7 +24,7 @@ impl Node for TextureCopyNode { let texture_events = world.get_resource::>>().unwrap(); let textures = world.get_resource::>().unwrap(); let mut copied_textures = HashSet::default(); - for event in self.texture_event_reader.iter(&texture_events) { + for event in self.texture_event_reader.iter(texture_events) { match event { AssetEvent::Created { handle } | AssetEvent::Modified { handle } => { if let Some(texture) = textures.get(handle) { diff --git a/crates/bevy_render/src/render_graph/nodes/window_swapchain_node.rs b/crates/bevy_render/src/render_graph/nodes/window_swapchain_node.rs index 959f39b4a14a3..50df2ea88359d 100644 --- a/crates/bevy_render/src/render_graph/nodes/window_swapchain_node.rs +++ b/crates/bevy_render/src/render_graph/nodes/window_swapchain_node.rs @@ -55,17 +55,17 @@ impl Node for WindowSwapChainNode { // create window swapchain when window is resized or created if self .window_created_event_reader - .iter(&window_created_events) + .iter(window_created_events) .any(|e| e.id == window.id()) || self .window_resized_event_reader - .iter(&window_resized_events) + .iter(window_resized_events) .any(|e| e.id == window.id()) { render_resource_context.create_swap_chain(window); } - let swap_chain_texture = render_resource_context.next_swap_chain_texture(&window); + let swap_chain_texture = render_resource_context.next_swap_chain_texture(window); output.set( WINDOW_TEXTURE, RenderResourceId::Texture(swap_chain_texture), diff --git a/crates/bevy_render/src/render_graph/nodes/window_texture_node.rs b/crates/bevy_render/src/render_graph/nodes/window_texture_node.rs index 234b5ee1621ea..92fc94da769cf 100644 --- a/crates/bevy_render/src/render_graph/nodes/window_texture_node.rs +++ b/crates/bevy_render/src/render_graph/nodes/window_texture_node.rs @@ -55,11 +55,11 @@ impl Node for WindowTextureNode { if self .window_created_event_reader - .iter(&window_created_events) + .iter(window_created_events) .any(|e| e.id == window.id()) || self .window_resized_event_reader - .iter(&window_resized_events) + .iter(window_resized_events) .any(|e| e.id == window.id()) { let render_resource_context = render_context.resources_mut(); diff --git a/crates/bevy_render/src/shader/shader.rs b/crates/bevy_render/src/shader/shader.rs index 6ce291f670064..b8ea268546fb8 100644 --- a/crates/bevy_render/src/shader/shader.rs +++ b/crates/bevy_render/src/shader/shader.rs @@ -213,7 +213,7 @@ impl Shader { pub fn get_spirv(&self, macros: Option<&[String]>) -> Result, ShaderError> { match self.source { ShaderSource::Spirv(ref bytes) => Ok(bytes.clone()), - ShaderSource::Glsl(ref source) => glsl_to_spirv(&source, self.stage, macros), + ShaderSource::Glsl(ref source) => glsl_to_spirv(source, self.stage, macros), } } @@ -288,7 +288,7 @@ impl ShaderStages { pub fn iter(&self) -> ShaderStagesIterator { ShaderStagesIterator { - shader_stages: &self, + shader_stages: self, state: 0, } } diff --git a/crates/bevy_render/src/texture/texture.rs b/crates/bevy_render/src/texture/texture.rs index 980441852295f..2a349a0fd0770 100644 --- a/crates/bevy_render/src/texture/texture.rs +++ b/crates/bevy_render/src/texture/texture.rs @@ -84,7 +84,7 @@ impl Texture { ); for current_pixel in value.data.chunks_exact_mut(pixel.len()) { - current_pixel.copy_from_slice(&pixel); + current_pixel.copy_from_slice(pixel); } value } diff --git a/crates/bevy_scene/src/dynamic_scene.rs b/crates/bevy_scene/src/dynamic_scene.rs index 6e4651eba15fe..82d015ec3e3bc 100644 --- a/crates/bevy_scene/src/dynamic_scene.rs +++ b/crates/bevy_scene/src/dynamic_scene.rs @@ -95,7 +95,7 @@ impl DynamicScene { for registration in type_registry.iter() { if let Some(map_entities_reflect) = registration.data::() { map_entities_reflect - .map_entities(world, &entity_map) + .map_entities(world, entity_map) .unwrap(); } } diff --git a/crates/bevy_scene/src/scene_loader.rs b/crates/bevy_scene/src/scene_loader.rs index 72e5741cc113b..06c7fb9192cf0 100644 --- a/crates/bevy_scene/src/scene_loader.rs +++ b/crates/bevy_scene/src/scene_loader.rs @@ -27,7 +27,7 @@ impl AssetLoader for SceneLoader { load_context: &'a mut LoadContext, ) -> BoxedFuture<'a, Result<()>> { Box::pin(async move { - let mut deserializer = ron::de::Deserializer::from_bytes(&bytes)?; + let mut deserializer = ron::de::Deserializer::from_bytes(bytes)?; let scene_deserializer = SceneDeserializer { type_registry: &*self.type_registry.read(), }; diff --git a/crates/bevy_scene/src/scene_spawner.rs b/crates/bevy_scene/src/scene_spawner.rs index b62015c5095e1..e6570a20f9ed2 100644 --- a/crates/bevy_scene/src/scene_spawner.rs +++ b/crates/bevy_scene/src/scene_spawner.rs @@ -79,7 +79,7 @@ impl SceneSpawner { ) -> Result<(), SceneSpawnError> { if let Some(instance_ids) = self.spawned_dynamic_scenes.get(&scene_handle) { for instance_id in instance_ids { - if let Some(instance) = self.spawned_instances.get(&instance_id) { + if let Some(instance) = self.spawned_instances.get(instance_id) { for entity in instance.entity_map.values() { let _ = world.despawn(entity); // Ignore the result, despawn only cares if // it exists. @@ -305,7 +305,7 @@ pub fn scene_spawner_system(world: &mut World) { let mut updated_spawned_scenes = Vec::new(); for event in scene_spawner .scene_asset_event_reader - .iter(&scene_asset_events) + .iter(scene_asset_events) { if let AssetEvent::Modified { handle } = event { if scene_spawner.spawned_dynamic_scenes.contains_key(handle) { diff --git a/crates/bevy_ui/src/flex/mod.rs b/crates/bevy_ui/src/flex/mod.rs index 2e1c205b1a674..0bb7a573d302a 100644 --- a/crates/bevy_ui/src/flex/mod.rs +++ b/crates/bevy_ui/src/flex/mod.rs @@ -243,15 +243,15 @@ pub fn flex_node_system( for (entity, style, calculated_size) in query.iter() { // TODO: remove node from old hierarchy if its root has changed if let Some(calculated_size) = calculated_size { - flex_surface.upsert_leaf(entity, &style, *calculated_size, scaling_factor); + flex_surface.upsert_leaf(entity, style, *calculated_size, scaling_factor); } else { - flex_surface.upsert_node(entity, &style, scaling_factor); + flex_surface.upsert_node(entity, style, scaling_factor); } } } for (entity, style, calculated_size) in changed_size_query.iter() { - flex_surface.upsert_leaf(entity, &style, *calculated_size, logical_to_physical_factor); + flex_surface.upsert_leaf(entity, style, *calculated_size, logical_to_physical_factor); } // TODO: handle removed nodes @@ -263,7 +263,7 @@ pub fn flex_node_system( // update children for (entity, children) in children_query.iter() { - flex_surface.update_children(entity, &children); + flex_surface.update_children(entity, children); } // compute layouts diff --git a/crates/bevy_wgpu/src/renderer/wgpu_render_context.rs b/crates/bevy_wgpu/src/renderer/wgpu_render_context.rs index 4ed78f2eba145..d2aba29fa7cbf 100644 --- a/crates/bevy_wgpu/src/renderer/wgpu_render_context.rs +++ b/crates/bevy_wgpu/src/renderer/wgpu_render_context.rs @@ -225,13 +225,13 @@ fn get_texture_view<'a>( attachment: &TextureAttachment, ) -> &'a wgpu::TextureView { match attachment { - TextureAttachment::Name(name) => match global_render_resource_bindings.get(&name) { - Some(RenderResourceBinding::Texture(resource)) => refs.textures.get(&resource).unwrap(), + TextureAttachment::Name(name) => match global_render_resource_bindings.get(name) { + Some(RenderResourceBinding::Texture(resource)) => refs.textures.get(resource).unwrap(), _ => { panic!("Color attachment {} does not exist.", name); } }, - TextureAttachment::Id(render_resource) => refs.textures.get(&render_resource).unwrap_or_else(|| &refs.swap_chain_frames.get(&render_resource).unwrap().output.view), + TextureAttachment::Id(render_resource) => refs.textures.get(render_resource).unwrap_or_else(|| &refs.swap_chain_frames.get(render_resource).unwrap().output.view), TextureAttachment::Input(_) => panic!("Encountered unset `TextureAttachment::Input`. The `RenderGraph` executor should always set `TextureAttachment::Inputs` to `TextureAttachment::RenderResource` before running. This is a bug, please report it!"), } } @@ -250,7 +250,7 @@ fn create_wgpu_color_attachment<'a>( let resolve_target = color_attachment .resolve_target .as_ref() - .map(|target| get_texture_view(global_render_resource_bindings, refs, &target)); + .map(|target| get_texture_view(global_render_resource_bindings, refs, target)); wgpu::RenderPassColorAttachment { ops: (&color_attachment.ops).wgpu_into(), diff --git a/crates/bevy_wgpu/src/renderer/wgpu_render_resource_context.rs b/crates/bevy_wgpu/src/renderer/wgpu_render_resource_context.rs index 346bfe062fe34..8e53d3c292a96 100644 --- a/crates/bevy_wgpu/src/renderer/wgpu_render_resource_context.rs +++ b/crates/bevy_wgpu/src/renderer/wgpu_render_resource_context.rs @@ -349,7 +349,7 @@ impl RenderResourceContext for WgpuRenderResourceContext { .resources .shader_modules .read() - .get(&shader_handle) + .get(shader_handle) .is_some() { return; @@ -439,7 +439,7 @@ impl RenderResourceContext for WgpuRenderResourceContext { let layout = pipeline_descriptor.get_layout().unwrap(); for bind_group_descriptor in layout.bind_groups.iter() { - self.create_bind_group_layout(&bind_group_descriptor); + self.create_bind_group_layout(bind_group_descriptor); } let bind_group_layouts = self.resources.bind_group_layouts.read(); @@ -490,7 +490,7 @@ impl RenderResourceContext for WgpuRenderResourceContext { label: None, layout: Some(&pipeline_layout), vertex: wgpu::VertexState { - module: &vertex_shader_module, + module: vertex_shader_module, entry_point: "main", buffers: &owned_vertex_buffer_descriptors .iter() @@ -555,16 +555,16 @@ impl RenderResourceContext for WgpuRenderResourceContext { let wgpu_resource = match &indexed_binding.entry { RenderResourceBinding::Texture(resource) => { let texture_view = texture_views - .get(&resource) + .get(resource) .unwrap_or_else(|| panic!("{:?}", resource)); wgpu::BindingResource::TextureView(texture_view) } RenderResourceBinding::Sampler(resource) => { - let sampler = samplers.get(&resource).unwrap(); + let sampler = samplers.get(resource).unwrap(); wgpu::BindingResource::Sampler(sampler) } RenderResourceBinding::Buffer { buffer, range, .. } => { - let wgpu_buffer = buffers.get(&buffer).unwrap(); + let wgpu_buffer = buffers.get(buffer).unwrap(); let size = NonZeroU64::new(range.end - range.start) .expect("Size of the buffer needs to be greater than 0!"); wgpu::BindingResource::Buffer(wgpu::BufferBinding { @@ -684,7 +684,7 @@ impl RenderResourceContext for WgpuRenderResourceContext { ) -> Result { let spirv_data = match shader.source { ShaderSource::Spirv(ref bytes) => bytes.clone(), - ShaderSource::Glsl(ref source) => glsl_to_spirv(&source, shader.stage, macros)?, + ShaderSource::Glsl(ref source) => glsl_to_spirv(source, shader.stage, macros)?, }; Ok(Shader { source: ShaderSource::Spirv(spirv_data), diff --git a/crates/bevy_wgpu/src/wgpu_resources.rs b/crates/bevy_wgpu/src/wgpu_resources.rs index b3cb93c9fdc84..e3e918a97a6e2 100644 --- a/crates/bevy_wgpu/src/wgpu_resources.rs +++ b/crates/bevy_wgpu/src/wgpu_resources.rs @@ -163,7 +163,7 @@ impl BindGroupCounter { *count > 0 }; if !retain { - bind_group_usage_counts.remove(&id); + bind_group_usage_counts.remove(id); } retain diff --git a/crates/bevy_winit/src/winit_windows.rs b/crates/bevy_winit/src/winit_windows.rs index 1874a9a02debe..04196c615d61c 100644 --- a/crates/bevy_winit/src/winit_windows.rs +++ b/crates/bevy_winit/src/winit_windows.rs @@ -103,7 +103,7 @@ impl WinitWindows { } } - let winit_window = winit_window_builder.build(&event_loop).unwrap(); + let winit_window = winit_window_builder.build(event_loop).unwrap(); match winit_window.set_cursor_grab(window_descriptor.cursor_locked) { Ok(_) => {} @@ -142,7 +142,7 @@ impl WinitWindows { self.windows.insert(winit_window.id(), winit_window); Window::new( window_id, - &window_descriptor, + window_descriptor, inner_size.width, inner_size.height, scale_factor, diff --git a/examples/scene/scene.rs b/examples/scene/scene.rs index 188dddcb6af96..ba5fdecc6ef9d 100644 --- a/examples/scene/scene.rs +++ b/examples/scene/scene.rs @@ -92,10 +92,10 @@ fn save_scene_system(world: &mut World) { // The TypeRegistry resource contains information about all registered types (including // components). This is used to construct scenes. let type_registry = world.get_resource::().unwrap(); - let scene = DynamicScene::from_world(&scene_world, &type_registry); + let scene = DynamicScene::from_world(&scene_world, type_registry); // Scenes can be serialized like this: - info!("{}", scene.serialize_ron(&type_registry).unwrap()); + info!("{}", scene.serialize_ron(type_registry).unwrap()); // TODO: save scene } From 7b336fd779d8c016e79b063bc282e3495b071b84 Mon Sep 17 00:00:00 2001 From: Carter Anderson Date: Fri, 30 Jul 2021 03:17:27 +0000 Subject: [PATCH 06/30] fix nightly clippy lints (#2568) Fix new nightly clippy lints on `pipelined-rendering` --- crates/bevy_asset/src/asset_server.rs | 11 ++-- pipelined/bevy_pbr2/src/render/mod.rs | 18 +++---- pipelined/bevy_render2/src/mesh/mesh/mod.rs | 58 ++++++++++----------- pipelined/bevy_render2/src/renderer/mod.rs | 4 +- pipelined/bevy_render2/src/shader/shader.rs | 6 +-- pipelined/bevy_render2/src/texture/image.rs | 2 +- 6 files changed, 47 insertions(+), 52 deletions(-) diff --git a/crates/bevy_asset/src/asset_server.rs b/crates/bevy_asset/src/asset_server.rs index f46b96ed7bf8f..9847e242541d9 100644 --- a/crates/bevy_asset/src/asset_server.rs +++ b/crates/bevy_asset/src/asset_server.rs @@ -53,7 +53,7 @@ pub struct AssetServerInternal { pub(crate) asset_ref_counter: AssetRefCounter, pub(crate) asset_sources: Arc>>, pub(crate) asset_lifecycles: Arc>>>, - loaders: RwLock>>>, + loaders: RwLock>>, extension_to_loader_index: RwLock>, handle_to_path: Arc>>>, task_pool: TaskPool, @@ -112,7 +112,7 @@ impl AssetServer { .write() .insert(extension.to_string(), loader_index); } - loaders.push(Arc::new(Box::new(loader))); + loaders.push(Arc::new(loader)); } pub fn watch_for_changes(&self) -> Result<(), AssetServerError> { @@ -130,10 +130,7 @@ impl AssetServer { HandleUntyped::strong(id.into(), sender) } - fn get_asset_loader( - &self, - extension: &str, - ) -> Result>, AssetServerError> { + fn get_asset_loader(&self, extension: &str) -> Result, AssetServerError> { let index = { // scope map to drop lock as soon as possible let map = self.server.extension_to_loader_index.read(); @@ -149,7 +146,7 @@ impl AssetServer { fn get_path_asset_loader>( &self, path: P, - ) -> Result>, AssetServerError> { + ) -> Result, AssetServerError> { let s = path .as_ref() .file_name() diff --git a/pipelined/bevy_pbr2/src/render/mod.rs b/pipelined/bevy_pbr2/src/render/mod.rs index 8c54071eb136c..31e160d83549d 100644 --- a/pipelined/bevy_pbr2/src/render/mod.rs +++ b/pipelined/bevy_pbr2/src/render/mod.rs @@ -631,39 +631,37 @@ pub fn queue_meshes( }, BindGroupEntry { binding: 1, - resource: BindingResource::TextureView( - &base_color_texture_view, - ), + resource: BindingResource::TextureView(base_color_texture_view), }, BindGroupEntry { binding: 2, - resource: BindingResource::Sampler(&base_color_sampler), + resource: BindingResource::Sampler(base_color_sampler), }, BindGroupEntry { binding: 3, - resource: BindingResource::TextureView(&emissive_texture_view), + resource: BindingResource::TextureView(emissive_texture_view), }, BindGroupEntry { binding: 4, - resource: BindingResource::Sampler(&emissive_sampler), + resource: BindingResource::Sampler(emissive_sampler), }, BindGroupEntry { binding: 5, resource: BindingResource::TextureView( - &metallic_roughness_texture_view, + metallic_roughness_texture_view, ), }, BindGroupEntry { binding: 6, - resource: BindingResource::Sampler(&metallic_roughness_sampler), + resource: BindingResource::Sampler(metallic_roughness_sampler), }, BindGroupEntry { binding: 7, - resource: BindingResource::TextureView(&occlusion_texture_view), + resource: BindingResource::TextureView(occlusion_texture_view), }, BindGroupEntry { binding: 8, - resource: BindingResource::Sampler(&occlusion_sampler), + resource: BindingResource::Sampler(occlusion_sampler), }, ], label: None, diff --git a/pipelined/bevy_render2/src/mesh/mesh/mod.rs b/pipelined/bevy_render2/src/mesh/mesh/mod.rs index 57f5ed80d444b..18e22ab08d166 100644 --- a/pipelined/bevy_render2/src/mesh/mesh/mod.rs +++ b/pipelined/bevy_render2/src/mesh/mesh/mod.rs @@ -210,34 +210,34 @@ impl Mesh { for (_, attributes) in self.attributes.iter_mut() { let indices = indices.iter(); match attributes { - VertexAttributeValues::Float32(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Sint32(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Uint32(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Float32x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Sint32x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Uint32x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Float32x3(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Sint32x3(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Uint32x3(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Sint32x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Uint32x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Float32x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Sint16x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Snorm16x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Uint16x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Unorm16x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Sint16x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Snorm16x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Uint16x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Unorm16x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Sint8x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Snorm8x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Uint8x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Unorm8x2(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Sint8x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Snorm8x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Uint8x4(vec) => *vec = duplicate(&vec, indices), - VertexAttributeValues::Unorm8x4(vec) => *vec = duplicate(&vec, indices), + VertexAttributeValues::Float32(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Sint32(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Uint32(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Float32x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Sint32x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Uint32x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Float32x3(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Sint32x3(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Uint32x3(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Sint32x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Uint32x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Float32x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Sint16x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Snorm16x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Uint16x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Unorm16x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Sint16x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Snorm16x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Uint16x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Unorm16x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Sint8x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Snorm8x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Uint8x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Unorm8x2(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Sint8x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Snorm8x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Uint8x4(vec) => *vec = duplicate(vec, indices), + VertexAttributeValues::Unorm8x4(vec) => *vec = duplicate(vec, indices), } } } @@ -560,7 +560,7 @@ impl RenderAsset for Mesh { let index_info = mesh.get_index_buffer_bytes().map(|data| GpuIndexInfo { buffer: render_device.create_buffer_with_data(&BufferInitDescriptor { usage: BufferUsage::INDEX, - contents: &data, + contents: data, label: None, }), count: mesh.indices().unwrap().len() as u32, diff --git a/pipelined/bevy_render2/src/renderer/mod.rs b/pipelined/bevy_render2/src/renderer/mod.rs index b53a76e92bdcb..91bb42a08b5a1 100644 --- a/pipelined/bevy_render2/src/renderer/mod.rs +++ b/pipelined/bevy_render2/src/renderer/mod.rs @@ -37,7 +37,7 @@ pub async fn initialize_renderer( let instance = wgpu::Instance::new(backends); let adapter = instance - .request_adapter(&request_adapter_options) + .request_adapter(request_adapter_options) .await .expect("Unable to find a GPU! Make sure you have installed required drivers!"); @@ -55,7 +55,7 @@ pub async fn initialize_renderer( let trace_path = None; let (device, queue) = adapter - .request_device(&device_descriptor, trace_path) + .request_device(device_descriptor, trace_path) .await .unwrap(); let device = Arc::new(device); diff --git a/pipelined/bevy_render2/src/shader/shader.rs b/pipelined/bevy_render2/src/shader/shader.rs index b27539dec9e2b..ace300da63a0d 100644 --- a/pipelined/bevy_render2/src/shader/shader.rs +++ b/pipelined/bevy_render2/src/shader/shader.rs @@ -66,13 +66,13 @@ impl Shader { pub fn reflect(&self) -> Result { let module = match &self { // TODO: process macros here - Shader::Wgsl(source) => naga::front::wgsl::parse_str(&source)?, + Shader::Wgsl(source) => naga::front::wgsl::parse_str(source)?, Shader::Glsl(source) => { let mut entry_points = HashMap::default(); entry_points.insert("vertex".to_string(), ShaderStage::Vertex); entry_points.insert("fragment".to_string(), ShaderStage::Fragment); naga::front::glsl::parse_str( - &source, + source, &naga::front::glsl::Options { entry_points, defines: Default::default(), @@ -80,7 +80,7 @@ impl Shader { )? } Shader::SpirV(source) => naga::front::spv::parse_u8_slice( - &source, + source, &naga::front::spv::Options { adjust_coordinate_space: false, ..naga::front::spv::Options::default() diff --git a/pipelined/bevy_render2/src/texture/image.rs b/pipelined/bevy_render2/src/texture/image.rs index 196185ddfa53f..61416694727a1 100644 --- a/pipelined/bevy_render2/src/texture/image.rs +++ b/pipelined/bevy_render2/src/texture/image.rs @@ -89,7 +89,7 @@ impl Image { ); for current_pixel in value.data.chunks_exact_mut(pixel.len()) { - current_pixel.copy_from_slice(&pixel); + current_pixel.copy_from_slice(pixel); } value } From ae4f809a529af988cd0e0218e8e1a9190c9bfa80 Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Fri, 30 Jul 2021 03:37:34 +0000 Subject: [PATCH 07/30] Port bevy_gltf to pipelined-rendering (#2537) # Objective Port bevy_gltf to the pipelined-rendering branch. ## Solution crates/bevy_gltf has been copied and pasted into pipelined/bevy_gltf2 and modifications were made to work with the pipelined-rendering branch. Notably vertex tangents and vertex colours are not supported. Co-authored-by: Carter Anderson --- Cargo.toml | 7 +- crates/bevy_internal/Cargo.toml | 1 + crates/bevy_internal/src/default_plugins.rs | 4 + crates/bevy_internal/src/lib.rs | 6 + examples/3d/load_gltf_pipelined.rs | 62 ++ examples/README.md | 1 + pipelined/bevy_gltf2/Cargo.toml | 35 + pipelined/bevy_gltf2/src/lib.rs | 60 ++ pipelined/bevy_gltf2/src/loader.rs | 868 ++++++++++++++++++++ 9 files changed, 1043 insertions(+), 1 deletion(-) create mode 100644 examples/3d/load_gltf_pipelined.rs create mode 100644 pipelined/bevy_gltf2/Cargo.toml create mode 100644 pipelined/bevy_gltf2/src/lib.rs create mode 100644 pipelined/bevy_gltf2/src/loader.rs diff --git a/Cargo.toml b/Cargo.toml index 84b9e1d5455e9..920153c08a953 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,7 +25,7 @@ default = [ "bevy_core_pipeline", "bevy_dynamic_plugin", "bevy_gilrs", - "bevy_gltf", + "bevy_gltf2", "bevy_wgpu", "bevy_sprite2", "bevy_render2", @@ -56,6 +56,7 @@ bevy_core_pipeline = ["bevy_internal/bevy_core_pipeline"] bevy_render2 = ["bevy_internal/bevy_render2"] bevy_sprite2 = ["bevy_internal/bevy_sprite2"] bevy_pbr2 = ["bevy_internal/bevy_pbr2"] +bevy_gltf2 = ["bevy_internal/bevy_gltf2"] trace_chrome = ["bevy_internal/trace_chrome"] trace = ["bevy_internal/trace"] @@ -156,6 +157,10 @@ path = "examples/3d/cornell_box_pipelined.rs" name = "load_gltf" path = "examples/3d/load_gltf.rs" +[[example]] +name = "load_gltf_pipelined" +path = "examples/3d/load_gltf_pipelined.rs" + [[example]] name = "msaa" path = "examples/3d/msaa.rs" diff --git a/crates/bevy_internal/Cargo.toml b/crates/bevy_internal/Cargo.toml index 036a053df4bee..8f7a1d2c2dd9e 100644 --- a/crates/bevy_internal/Cargo.toml +++ b/crates/bevy_internal/Cargo.toml @@ -68,6 +68,7 @@ bevy_tasks = { path = "../bevy_tasks", version = "0.5.0" } bevy_audio = { path = "../bevy_audio", optional = true, version = "0.5.0" } bevy_core_pipeline = { path = "../../pipelined/bevy_core_pipeline", optional = true, version = "0.5.0" } bevy_gltf = { path = "../bevy_gltf", optional = true, version = "0.5.0" } +bevy_gltf2 = { path = "../../pipelined/bevy_gltf2", optional = true, version = "0.5.0" } bevy_pbr = { path = "../bevy_pbr", optional = true, version = "0.5.0" } bevy_pbr2 = { path = "../../pipelined/bevy_pbr2", optional = true, version = "0.5.0" } bevy_render = { path = "../bevy_render", optional = true, version = "0.5.0" } diff --git a/crates/bevy_internal/src/default_plugins.rs b/crates/bevy_internal/src/default_plugins.rs index 6d506e5651b27..27e206d657af8 100644 --- a/crates/bevy_internal/src/default_plugins.rs +++ b/crates/bevy_internal/src/default_plugins.rs @@ -117,6 +117,7 @@ impl PluginGroup for PipelinedDefaultPlugins { group.add(bevy_input::InputPlugin::default()); group.add(bevy_window::WindowPlugin::default()); group.add(bevy_asset::AssetPlugin::default()); + group.add(bevy_scene::ScenePlugin::default()); #[cfg(feature = "bevy_render2")] { @@ -132,6 +133,9 @@ impl PluginGroup for PipelinedDefaultPlugins { #[cfg(feature = "bevy_pbr2")] group.add(bevy_pbr2::PbrPlugin::default()); + + #[cfg(feature = "bevy_gltf2")] + group.add(bevy_gltf2::GltfPlugin::default()); } #[cfg(feature = "bevy_winit")] diff --git a/crates/bevy_internal/src/lib.rs b/crates/bevy_internal/src/lib.rs index a47ee1984062a..932971b6f1046 100644 --- a/crates/bevy_internal/src/lib.rs +++ b/crates/bevy_internal/src/lib.rs @@ -99,6 +99,12 @@ pub mod gltf { pub use bevy_gltf::*; } +#[cfg(feature = "bevy_gltf2")] +pub mod gltf2 { + //! Support for GLTF file loading. + pub use bevy_gltf2::*; +} + #[cfg(feature = "bevy_pbr")] pub mod pbr { //! Physically based rendering. diff --git a/examples/3d/load_gltf_pipelined.rs b/examples/3d/load_gltf_pipelined.rs new file mode 100644 index 0000000000000..8b842095e92b5 --- /dev/null +++ b/examples/3d/load_gltf_pipelined.rs @@ -0,0 +1,62 @@ +use bevy::{ + core::Time, + ecs::prelude::*, + math::{EulerRot, Quat, Vec3}, + pbr2::{AmbientLight, DirectionalLight, DirectionalLightBundle}, + prelude::{App, AssetServer, SpawnSceneCommands, Transform}, + render2::{ + camera::{OrthographicProjection, PerspectiveCameraBundle}, + color::Color, + }, + PipelinedDefaultPlugins, +}; + +fn main() { + App::new() + .insert_resource(AmbientLight { + color: Color::WHITE, + brightness: 1.0 / 5.0f32, + }) + .add_plugins(PipelinedDefaultPlugins) + .add_startup_system(setup.system()) + .add_system(animate_light_direction.system()) + .run(); +} + +fn setup(mut commands: Commands, asset_server: Res) { + commands.spawn_scene(asset_server.load("models/FlightHelmet/FlightHelmet.gltf#Scene0")); + commands.spawn_bundle(PerspectiveCameraBundle { + transform: Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y), + ..Default::default() + }); + const HALF_SIZE: f32 = 1.0; + commands.spawn_bundle(DirectionalLightBundle { + directional_light: DirectionalLight { + shadow_projection: OrthographicProjection { + left: -HALF_SIZE, + right: HALF_SIZE, + bottom: -HALF_SIZE, + top: HALF_SIZE, + near: -10.0 * HALF_SIZE, + far: 10.0 * HALF_SIZE, + ..Default::default() + }, + ..Default::default() + }, + ..Default::default() + }); +} + +fn animate_light_direction( + time: Res { impl Plugin for RenderAssetPlugin { fn build(&self, app: &mut App) { - let render_app = app.sub_app_mut(0); + let render_app = app.sub_app_mut(RenderSubApp).unwrap(); render_app .init_resource::>() .init_resource::>() diff --git a/pipelined/bevy_render2/src/texture/mod.rs b/pipelined/bevy_render2/src/texture/mod.rs index 976b7c10592d5..efe05dc5616f4 100644 --- a/pipelined/bevy_render2/src/texture/mod.rs +++ b/pipelined/bevy_render2/src/texture/mod.rs @@ -13,7 +13,7 @@ pub use hdr_texture_loader::*; pub use image_texture_loader::*; pub use texture_cache::*; -use crate::{render_asset::RenderAssetPlugin, RenderStage}; +use crate::{render_asset::RenderAssetPlugin, RenderStage, RenderSubApp}; use bevy_app::{App, Plugin}; use bevy_asset::AddAsset; @@ -30,7 +30,7 @@ impl Plugin for ImagePlugin { app.add_plugin(RenderAssetPlugin::::default()) .add_asset::(); - let render_app = app.sub_app_mut(0); + let render_app = app.sub_app_mut(RenderSubApp).unwrap(); render_app .init_resource::() .add_system_to_stage(RenderStage::Cleanup, update_texture_cache_system); diff --git a/pipelined/bevy_render2/src/view/mod.rs b/pipelined/bevy_render2/src/view/mod.rs index d95ae8834ada5..911148116b3c7 100644 --- a/pipelined/bevy_render2/src/view/mod.rs +++ b/pipelined/bevy_render2/src/view/mod.rs @@ -7,7 +7,7 @@ use crate::{ render_graph::{Node, NodeRunError, RenderGraph, RenderGraphContext}, render_resource::DynamicUniformVec, renderer::{RenderContext, RenderDevice}, - RenderStage, + RenderStage, RenderSubApp, }; use bevy_app::{App, Plugin}; use bevy_ecs::prelude::*; @@ -22,7 +22,7 @@ impl ViewPlugin { impl Plugin for ViewPlugin { fn build(&self, app: &mut App) { - let render_app = app.sub_app_mut(0); + let render_app = app.sub_app_mut(RenderSubApp).unwrap(); render_app .init_resource::() .add_system_to_stage(RenderStage::Prepare, prepare_views); diff --git a/pipelined/bevy_render2/src/view/window.rs b/pipelined/bevy_render2/src/view/window.rs index 5ec52bec0d49b..dbcf46f4c3010 100644 --- a/pipelined/bevy_render2/src/view/window.rs +++ b/pipelined/bevy_render2/src/view/window.rs @@ -2,7 +2,7 @@ use crate::{ render_resource::TextureView, renderer::{RenderDevice, RenderInstance}, texture::BevyDefault, - RenderStage, + RenderStage, RenderSubApp, }; use bevy_app::{App, Plugin}; use bevy_ecs::prelude::*; @@ -19,7 +19,7 @@ pub struct WindowRenderPlugin; impl Plugin for WindowRenderPlugin { fn build(&self, app: &mut App) { - let render_app = app.sub_app_mut(0); + let render_app = app.sub_app_mut(RenderSubApp).unwrap(); render_app .init_resource::() .init_resource::() diff --git a/pipelined/bevy_sprite2/src/lib.rs b/pipelined/bevy_sprite2/src/lib.rs index 484252a0989d0..a1a7643ea69d3 100644 --- a/pipelined/bevy_sprite2/src/lib.rs +++ b/pipelined/bevy_sprite2/src/lib.rs @@ -16,7 +16,9 @@ pub use texture_atlas::*; pub use texture_atlas_builder::*; use bevy_app::prelude::*; -use bevy_render2::{render_graph::RenderGraph, render_phase::DrawFunctions, RenderStage}; +use bevy_render2::{ + render_graph::RenderGraph, render_phase::DrawFunctions, RenderStage, RenderSubApp, +}; #[derive(Default)] pub struct SpritePlugin; @@ -26,7 +28,7 @@ impl Plugin for SpritePlugin { app.add_asset::() .register_type::() .add_system_to_stage(CoreStage::PostUpdate, sprite_auto_resize_system); - let render_app = app.sub_app_mut(0); + let render_app = app.sub_app_mut(RenderSubApp).unwrap(); render_app .init_resource::() .add_system_to_stage(RenderStage::Extract, render::extract_atlases) @@ -42,7 +44,7 @@ impl Plugin for SpritePlugin { .unwrap() .write() .add(draw_sprite); - let render_world = app.sub_app_mut(0).world.cell(); + let render_world = app.sub_app_mut(RenderSubApp).unwrap().world.cell(); let mut graph = render_world.get_resource_mut::().unwrap(); graph.add_node("sprite", SpriteNode); graph diff --git a/tools/publish.sh b/tools/publish.sh index 85008c6247912..62b7181c9014a 100644 --- a/tools/publish.sh +++ b/tools/publish.sh @@ -7,6 +7,7 @@ crates=( bevy_tasks bevy_ecs/macros bevy_ecs + bevy_app/macros bevy_app bevy_log bevy_dynamic_plugin @@ -42,4 +43,4 @@ do done cd .. -cargo publish \ No newline at end of file +cargo publish From 9898469e9e9399763bec226816d04b27840c56bf Mon Sep 17 00:00:00 2001 From: Carter Anderson Date: Tue, 24 Aug 2021 06:37:28 +0000 Subject: [PATCH 17/30] Sub app label changes (#2717) Makes some tweaks to the SubApp labeling introduced in #2695: * Ergonomics improvements * Removes unnecessary allocation when retrieving subapp label * Removes the newly added "app macros" crate in favor of bevy_derive * renamed RenderSubApp to RenderApp @zicklag (for reference) --- crates/bevy_app/Cargo.toml | 1 - crates/bevy_app/macros/Cargo.toml | 16 ------------- crates/bevy_app/macros/src/lib.rs | 19 --------------- crates/bevy_app/src/app.rs | 27 ++++++++++++++-------- crates/bevy_derive/src/lib.rs | 10 ++++++++ pipelined/bevy_core_pipeline/src/lib.rs | 4 ++-- pipelined/bevy_pbr2/src/lib.rs | 4 ++-- pipelined/bevy_render2/src/camera/mod.rs | 5 ++-- pipelined/bevy_render2/src/lib.rs | 8 +++---- pipelined/bevy_render2/src/render_asset.rs | 5 ++-- pipelined/bevy_render2/src/texture/mod.rs | 5 ++-- pipelined/bevy_render2/src/view/mod.rs | 4 ++-- pipelined/bevy_render2/src/view/window.rs | 5 ++-- pipelined/bevy_sprite2/src/lib.rs | 7 +++--- tools/publish.sh | 1 - 15 files changed, 49 insertions(+), 72 deletions(-) delete mode 100644 crates/bevy_app/macros/Cargo.toml delete mode 100644 crates/bevy_app/macros/src/lib.rs diff --git a/crates/bevy_app/Cargo.toml b/crates/bevy_app/Cargo.toml index f73f333392e1e..58e8ac243e79c 100644 --- a/crates/bevy_app/Cargo.toml +++ b/crates/bevy_app/Cargo.toml @@ -23,7 +23,6 @@ bevy_derive = { path = "../bevy_derive", version = "0.5.0" } bevy_ecs = { path = "../bevy_ecs", version = "0.5.0" } bevy_reflect = { path = "../bevy_reflect", version = "0.5.0", optional = true } bevy_utils = { path = "../bevy_utils", version = "0.5.0" } -bevy_app_macros = { path = "./macros", version = "0.5.0" } # other serde = { version = "1.0", features = ["derive"], optional = true } diff --git a/crates/bevy_app/macros/Cargo.toml b/crates/bevy_app/macros/Cargo.toml deleted file mode 100644 index 505c27068b690..0000000000000 --- a/crates/bevy_app/macros/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "bevy_app_macros" -version = "0.5.0" -description = "Bevy App Macros" -edition = "2018" -license = "MIT OR Apache-2.0" - -[lib] -proc-macro = true - -[dependencies] -bevy_macro_utils = { path = "../../bevy_macro_utils", version = "0.5.0" } - -syn = "1.0" -quote = "1.0" -proc-macro2 = "1.0" diff --git a/crates/bevy_app/macros/src/lib.rs b/crates/bevy_app/macros/src/lib.rs deleted file mode 100644 index eafa3dde55cda..0000000000000 --- a/crates/bevy_app/macros/src/lib.rs +++ /dev/null @@ -1,19 +0,0 @@ -extern crate proc_macro; - -use bevy_macro_utils::{derive_label, BevyManifest}; -use proc_macro::TokenStream; -use quote::format_ident; - -#[proc_macro_derive(SubAppLabel)] -pub fn derive_sub_app_label(input: TokenStream) -> TokenStream { - let input = syn::parse_macro_input!(input as syn::DeriveInput); - let mut trait_path = bevy_app_path(); - trait_path - .segments - .push(format_ident!("SubAppLabel").into()); - derive_label(input, trait_path) -} - -fn bevy_app_path() -> syn::Path { - BevyManifest::default().get_path("bevy_app") -} diff --git a/crates/bevy_app/src/app.rs b/crates/bevy_app/src/app.rs index faf7a4cc1590c..c7f28970a5e98 100644 --- a/crates/bevy_app/src/app.rs +++ b/crates/bevy_app/src/app.rs @@ -1,3 +1,5 @@ +pub use bevy_derive::AppLabel; + use crate::{CoreStage, Events, Plugin, PluginGroup, PluginGroupBuilder, StartupStage}; use bevy_ecs::{ component::{Component, ComponentDescriptor}, @@ -10,13 +12,10 @@ use bevy_ecs::{ use bevy_utils::{tracing::debug, HashMap}; use std::{fmt::Debug, hash::Hash}; -pub use bevy_app_macros::SubAppLabel; - #[cfg(feature = "trace")] use bevy_utils::tracing::info_span; -bevy_utils::define_label!(SubAppLabel); -type BoxedSubAppLabel = Box; +bevy_utils::define_label!(AppLabel); #[allow(clippy::needless_doctest_main)] /// Containers of app logic and data @@ -45,7 +44,7 @@ pub struct App { pub world: World, pub runner: Box, pub schedule: Schedule, - sub_apps: HashMap, + sub_apps: HashMap, SubApp>, } struct SubApp { @@ -594,7 +593,7 @@ impl App { pub fn add_sub_app( &mut self, - label: impl SubAppLabel, + label: impl AppLabel, app: App, f: impl Fn(&mut World, &mut App) + 'static, ) -> &mut Self { @@ -608,11 +607,21 @@ impl App { self } - pub fn sub_app_mut(&mut self, label: impl SubAppLabel) -> Option<&mut App> { - let label = Box::new(label) as BoxedSubAppLabel; + /// Retrieves a "sub app" stored inside this [App]. This will panic if the sub app does not exist. + pub fn sub_app(&mut self, label: impl AppLabel) -> &mut App { + match self.get_sub_app(label) { + Ok(app) => app, + Err(label) => panic!("Sub-App with label '{:?}' does not exist", label), + } + } + + /// Retrieves a "sub app" inside this [App] with the given label, if it exists. Otherwise returns + /// an [Err] containing the given label. + pub fn get_sub_app(&mut self, label: impl AppLabel) -> Result<&mut App, impl AppLabel> { self.sub_apps - .get_mut(&label) + .get_mut((&label) as &dyn AppLabel) .map(|sub_app| &mut sub_app.app) + .ok_or(label) } } diff --git a/crates/bevy_derive/src/lib.rs b/crates/bevy_derive/src/lib.rs index a73093ed2aa7e..7f21428fc2a7a 100644 --- a/crates/bevy_derive/src/lib.rs +++ b/crates/bevy_derive/src/lib.rs @@ -10,7 +10,9 @@ mod render_resources; mod resource; mod shader_defs; +use bevy_macro_utils::{derive_label, BevyManifest}; use proc_macro::TokenStream; +use quote::format_ident; /// Derives the FromResources trait. Each field must also implement the FromResources trait or this /// will fail. FromResources is automatically implemented for types that implement Default. @@ -60,3 +62,11 @@ pub fn bevy_main(attr: TokenStream, item: TokenStream) -> TokenStream { pub fn derive_enum_variant_meta(input: TokenStream) -> TokenStream { enum_variant_meta::derive_enum_variant_meta(input) } + +#[proc_macro_derive(AppLabel)] +pub fn derive_app_label(input: TokenStream) -> TokenStream { + let input = syn::parse_macro_input!(input as syn::DeriveInput); + let mut trait_path = BevyManifest::default().get_path("bevy_app"); + trait_path.segments.push(format_ident!("AppLabel").into()); + derive_label(input, trait_path) +} diff --git a/pipelined/bevy_core_pipeline/src/lib.rs b/pipelined/bevy_core_pipeline/src/lib.rs index 6f7d447ac5fb7..c9187adf39daa 100644 --- a/pipelined/bevy_core_pipeline/src/lib.rs +++ b/pipelined/bevy_core_pipeline/src/lib.rs @@ -20,7 +20,7 @@ use bevy_render2::{ renderer::RenderDevice, texture::TextureCache, view::{ExtractedView, ViewPlugin}, - RenderStage, RenderSubApp, RenderWorld, + RenderApp, RenderStage, RenderWorld, }; /// Resource that configures the clear color @@ -74,7 +74,7 @@ impl Plugin for CorePipelinePlugin { fn build(&self, app: &mut App) { app.init_resource::(); - let render_app = app.sub_app_mut(RenderSubApp).unwrap(); + let render_app = app.sub_app(RenderApp); render_app .add_system_to_stage(RenderStage::Extract, extract_clear_color) .add_system_to_stage(RenderStage::Extract, extract_core_pipeline_camera_phases) diff --git a/pipelined/bevy_pbr2/src/lib.rs b/pipelined/bevy_pbr2/src/lib.rs index 4490e660b6514..8e1a0dc8f5b48 100644 --- a/pipelined/bevy_pbr2/src/lib.rs +++ b/pipelined/bevy_pbr2/src/lib.rs @@ -13,7 +13,7 @@ use bevy_ecs::prelude::*; use bevy_render2::{ render_graph::RenderGraph, render_phase::{sort_phase_system, DrawFunctions}, - RenderStage, RenderSubApp, + RenderApp, RenderStage, }; pub mod draw_3d_graph { @@ -30,7 +30,7 @@ impl Plugin for PbrPlugin { app.add_plugin(StandardMaterialPlugin) .init_resource::(); - let render_app = app.sub_app_mut(RenderSubApp).unwrap(); + let render_app = app.sub_app(RenderApp); render_app .add_system_to_stage(RenderStage::Extract, render::extract_meshes) .add_system_to_stage(RenderStage::Extract, render::extract_lights) diff --git a/pipelined/bevy_render2/src/camera/mod.rs b/pipelined/bevy_render2/src/camera/mod.rs index cade9c514962b..597e54c98c26d 100644 --- a/pipelined/bevy_render2/src/camera/mod.rs +++ b/pipelined/bevy_render2/src/camera/mod.rs @@ -12,7 +12,7 @@ pub use bundle::*; pub use camera::*; pub use projection::*; -use crate::{view::ExtractedView, RenderStage, RenderSubApp}; +use crate::{view::ExtractedView, RenderApp, RenderStage}; use bevy_app::{App, CoreStage, Plugin}; use bevy_ecs::prelude::*; @@ -40,8 +40,7 @@ impl Plugin for CameraPlugin { CoreStage::PostUpdate, crate::camera::camera_system::, ); - let render_app = app.sub_app_mut(RenderSubApp).unwrap(); - render_app + app.sub_app(RenderApp) .init_resource::() .add_system_to_stage(RenderStage::Extract, extract_cameras); } diff --git a/pipelined/bevy_render2/src/lib.rs b/pipelined/bevy_render2/src/lib.rs index 49d73e97e43a8..b4f8467fce75c 100644 --- a/pipelined/bevy_render2/src/lib.rs +++ b/pipelined/bevy_render2/src/lib.rs @@ -24,7 +24,7 @@ use crate::{ texture::ImagePlugin, view::{ViewPlugin, WindowRenderPlugin}, }; -use bevy_app::{App, Plugin, SubAppLabel}; +use bevy_app::{App, AppLabel, Plugin}; use bevy_ecs::prelude::*; #[derive(Default)] @@ -74,8 +74,8 @@ impl DerefMut for RenderWorld { } /// Label for the rendering sub-app -#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, SubAppLabel)] -pub struct RenderSubApp; +#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, AppLabel)] +pub struct RenderApp; /// A "scratch" world used to avoid allocating new worlds every frame when // swapping out the Render World. @@ -118,7 +118,7 @@ impl Plugin for RenderPlugin { .init_resource::() .init_resource::(); - app.add_sub_app(RenderSubApp, render_app, move |app_world, render_app| { + app.add_sub_app(RenderApp, render_app, move |app_world, render_app| { // reserve all existing app entities for use in render_app // they can only be spawned using `get_or_spawn()` let meta_len = app_world.entities().meta.len(); diff --git a/pipelined/bevy_render2/src/render_asset.rs b/pipelined/bevy_render2/src/render_asset.rs index 66fd9f2dabdbc..4185c93cc09c2 100644 --- a/pipelined/bevy_render2/src/render_asset.rs +++ b/pipelined/bevy_render2/src/render_asset.rs @@ -2,7 +2,7 @@ use std::marker::PhantomData; use crate::{ renderer::{RenderDevice, RenderQueue}, - RenderStage, RenderSubApp, + RenderApp, RenderStage, }; use bevy_app::{App, Plugin}; use bevy_asset::{Asset, AssetEvent, Assets, Handle}; @@ -31,8 +31,7 @@ impl Default for RenderAssetPlugin { impl Plugin for RenderAssetPlugin { fn build(&self, app: &mut App) { - let render_app = app.sub_app_mut(RenderSubApp).unwrap(); - render_app + app.sub_app(RenderApp) .init_resource::>() .init_resource::>() .add_system_to_stage(RenderStage::Extract, extract_render_asset::) diff --git a/pipelined/bevy_render2/src/texture/mod.rs b/pipelined/bevy_render2/src/texture/mod.rs index efe05dc5616f4..cd25dd57387ae 100644 --- a/pipelined/bevy_render2/src/texture/mod.rs +++ b/pipelined/bevy_render2/src/texture/mod.rs @@ -13,7 +13,7 @@ pub use hdr_texture_loader::*; pub use image_texture_loader::*; pub use texture_cache::*; -use crate::{render_asset::RenderAssetPlugin, RenderStage, RenderSubApp}; +use crate::{render_asset::RenderAssetPlugin, RenderApp, RenderStage}; use bevy_app::{App, Plugin}; use bevy_asset::AddAsset; @@ -30,8 +30,7 @@ impl Plugin for ImagePlugin { app.add_plugin(RenderAssetPlugin::::default()) .add_asset::(); - let render_app = app.sub_app_mut(RenderSubApp).unwrap(); - render_app + app.sub_app(RenderApp) .init_resource::() .add_system_to_stage(RenderStage::Cleanup, update_texture_cache_system); } diff --git a/pipelined/bevy_render2/src/view/mod.rs b/pipelined/bevy_render2/src/view/mod.rs index 911148116b3c7..e00a3bdcdc5bc 100644 --- a/pipelined/bevy_render2/src/view/mod.rs +++ b/pipelined/bevy_render2/src/view/mod.rs @@ -7,7 +7,7 @@ use crate::{ render_graph::{Node, NodeRunError, RenderGraph, RenderGraphContext}, render_resource::DynamicUniformVec, renderer::{RenderContext, RenderDevice}, - RenderStage, RenderSubApp, + RenderApp, RenderStage, }; use bevy_app::{App, Plugin}; use bevy_ecs::prelude::*; @@ -22,7 +22,7 @@ impl ViewPlugin { impl Plugin for ViewPlugin { fn build(&self, app: &mut App) { - let render_app = app.sub_app_mut(RenderSubApp).unwrap(); + let render_app = app.sub_app(RenderApp); render_app .init_resource::() .add_system_to_stage(RenderStage::Prepare, prepare_views); diff --git a/pipelined/bevy_render2/src/view/window.rs b/pipelined/bevy_render2/src/view/window.rs index dbcf46f4c3010..cb71008f572b3 100644 --- a/pipelined/bevy_render2/src/view/window.rs +++ b/pipelined/bevy_render2/src/view/window.rs @@ -2,7 +2,7 @@ use crate::{ render_resource::TextureView, renderer::{RenderDevice, RenderInstance}, texture::BevyDefault, - RenderStage, RenderSubApp, + RenderApp, RenderStage, }; use bevy_app::{App, Plugin}; use bevy_ecs::prelude::*; @@ -19,8 +19,7 @@ pub struct WindowRenderPlugin; impl Plugin for WindowRenderPlugin { fn build(&self, app: &mut App) { - let render_app = app.sub_app_mut(RenderSubApp).unwrap(); - render_app + app.sub_app(RenderApp) .init_resource::() .init_resource::() .add_system_to_stage(RenderStage::Extract, extract_windows) diff --git a/pipelined/bevy_sprite2/src/lib.rs b/pipelined/bevy_sprite2/src/lib.rs index a1a7643ea69d3..5c77bf0714765 100644 --- a/pipelined/bevy_sprite2/src/lib.rs +++ b/pipelined/bevy_sprite2/src/lib.rs @@ -17,7 +17,7 @@ pub use texture_atlas_builder::*; use bevy_app::prelude::*; use bevy_render2::{ - render_graph::RenderGraph, render_phase::DrawFunctions, RenderStage, RenderSubApp, + render_graph::RenderGraph, render_phase::DrawFunctions, RenderApp, RenderStage, }; #[derive(Default)] @@ -28,7 +28,7 @@ impl Plugin for SpritePlugin { app.add_asset::() .register_type::() .add_system_to_stage(CoreStage::PostUpdate, sprite_auto_resize_system); - let render_app = app.sub_app_mut(RenderSubApp).unwrap(); + let render_app = app.sub_app(RenderApp); render_app .init_resource::() .add_system_to_stage(RenderStage::Extract, render::extract_atlases) @@ -44,8 +44,7 @@ impl Plugin for SpritePlugin { .unwrap() .write() .add(draw_sprite); - let render_world = app.sub_app_mut(RenderSubApp).unwrap().world.cell(); - let mut graph = render_world.get_resource_mut::().unwrap(); + let mut graph = render_app.world.get_resource_mut::().unwrap(); graph.add_node("sprite", SpriteNode); graph .add_node_edge("sprite", bevy_core_pipeline::node::MAIN_PASS_DEPENDENCIES) diff --git a/tools/publish.sh b/tools/publish.sh index 62b7181c9014a..ca35a3e327c09 100644 --- a/tools/publish.sh +++ b/tools/publish.sh @@ -7,7 +7,6 @@ crates=( bevy_tasks bevy_ecs/macros bevy_ecs - bevy_app/macros bevy_app bevy_log bevy_dynamic_plugin From f368bf7fc78f8eef10d2fa52d33c7d983375f8f5 Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Wed, 25 Aug 2021 05:57:57 +0000 Subject: [PATCH 18/30] bevy_pbr2: Add support for configurable shadow map sizes (#2700) # Objective Add support for configurable shadow map sizes ## Solution - Add `DirectionalLightShadowMap` and `PointLightShadowMap` resources, which just have size members, to the app world, and add `Extracted*` counterparts to the render world - Use the configured sizes when rendering shadow maps - Default sizes remain the same - 4096 for directional light shadow maps, 1024 for point light shadow maps (which are cube maps so 6 faces at 1024x1024 per light) --- pipelined/bevy_pbr2/src/lib.rs | 4 +- pipelined/bevy_pbr2/src/light.rs | 22 ++++++++++ pipelined/bevy_pbr2/src/render/light.rs | 54 ++++++++++++++++--------- 3 files changed, 60 insertions(+), 20 deletions(-) diff --git a/pipelined/bevy_pbr2/src/lib.rs b/pipelined/bevy_pbr2/src/lib.rs index 8e1a0dc8f5b48..9b0b535245a30 100644 --- a/pipelined/bevy_pbr2/src/lib.rs +++ b/pipelined/bevy_pbr2/src/lib.rs @@ -28,7 +28,9 @@ pub struct PbrPlugin; impl Plugin for PbrPlugin { fn build(&self, app: &mut App) { app.add_plugin(StandardMaterialPlugin) - .init_resource::(); + .init_resource::() + .init_resource::() + .init_resource::(); let render_app = app.sub_app(RenderApp); render_app diff --git a/pipelined/bevy_pbr2/src/light.rs b/pipelined/bevy_pbr2/src/light.rs index 06bf06b24eef6..571a9048bc590 100644 --- a/pipelined/bevy_pbr2/src/light.rs +++ b/pipelined/bevy_pbr2/src/light.rs @@ -49,6 +49,17 @@ impl PointLight { pub const DEFAULT_SHADOW_NORMAL_BIAS: f32 = 0.5; } +#[derive(Clone, Debug)] +pub struct PointLightShadowMap { + pub size: usize, +} + +impl Default for PointLightShadowMap { + fn default() -> Self { + Self { size: 1024 } + } +} + /// A Directional light. /// /// Directional lights don't exist in reality but they are a good @@ -113,6 +124,17 @@ impl DirectionalLight { pub const DEFAULT_SHADOW_NORMAL_BIAS: f32 = 0.6; } +#[derive(Clone, Debug)] +pub struct DirectionalLightShadowMap { + pub size: usize, +} + +impl Default for DirectionalLightShadowMap { + fn default() -> Self { + Self { size: 4096 } + } +} + /// Ambient light. #[derive(Debug)] pub struct AmbientLight { diff --git a/pipelined/bevy_pbr2/src/render/light.rs b/pipelined/bevy_pbr2/src/render/light.rs index 20756a84f9bb7..c77e021aeb6ff 100644 --- a/pipelined/bevy_pbr2/src/render/light.rs +++ b/pipelined/bevy_pbr2/src/render/light.rs @@ -1,4 +1,7 @@ -use crate::{AmbientLight, DirectionalLight, ExtractedMeshes, MeshMeta, PbrShaders, PointLight}; +use crate::{ + AmbientLight, DirectionalLight, DirectionalLightShadowMap, ExtractedMeshes, MeshMeta, + PbrShaders, PointLight, PointLightShadowMap, +}; use bevy_core_pipeline::Transparent3dPhase; use bevy_ecs::{prelude::*, system::SystemState}; use bevy_math::{const_vec3, Mat4, Vec3, Vec4}; @@ -34,6 +37,8 @@ pub struct ExtractedPointLight { shadow_normal_bias: f32, } +pub type ExtractedPointLightShadowMap = PointLightShadowMap; + pub struct ExtractedDirectionalLight { color: Color, illuminance: f32, @@ -43,6 +48,8 @@ pub struct ExtractedDirectionalLight { shadow_normal_bias: f32, } +pub type ExtractedDirectionalLightShadowMap = DirectionalLightShadowMap; + #[repr(C)] #[derive(Copy, Clone, AsStd140, Default, Debug)] pub struct GpuPointLight { @@ -81,16 +88,8 @@ pub struct GpuLights { // NOTE: this must be kept in sync with the same constants in pbr.frag pub const MAX_POINT_LIGHTS: usize = 10; pub const MAX_DIRECTIONAL_LIGHTS: usize = 1; -pub const POINT_SHADOW_SIZE: Extent3d = Extent3d { - width: 1024, - height: 1024, - depth_or_array_layers: (6 * MAX_POINT_LIGHTS) as u32, -}; -pub const DIRECTIONAL_SHADOW_SIZE: Extent3d = Extent3d { - width: 4096, - height: 4096, - depth_or_array_layers: MAX_DIRECTIONAL_LIGHTS as u32, -}; +pub const POINT_SHADOW_LAYERS: u32 = (6 * MAX_POINT_LIGHTS) as u32; +pub const DIRECTIONAL_SHADOW_LAYERS: u32 = MAX_DIRECTIONAL_LIGHTS as u32; pub const SHADOW_FORMAT: TextureFormat = TextureFormat::Depth32Float; pub struct ShadowShaders { @@ -222,6 +221,8 @@ impl FromWorld for ShadowShaders { pub fn extract_lights( mut commands: Commands, ambient_light: Res, + point_light_shadow_map: Res, + directional_light_shadow_map: Res, point_lights: Query<(Entity, &PointLight, &GlobalTransform)>, directional_lights: Query<(Entity, &DirectionalLight, &GlobalTransform)>, ) { @@ -229,6 +230,10 @@ pub fn extract_lights( color: ambient_light.color, brightness: ambient_light.brightness, }); + commands.insert_resource::(point_light_shadow_map.clone()); + commands.insert_resource::( + directional_light_shadow_map.clone(), + ); // This is the point light shadow map texel size for one face of the cube as a distance of 1.0 // world unit from the light. // point_light_texel_size = 2.0 * 1.0 * tan(PI / 4.0) / cube face width in texels @@ -236,7 +241,7 @@ pub fn extract_lights( // point_light_texel_size = 2.0 / cube face width in texels // NOTE: When using various PCF kernel sizes, this will need to be adjusted, according to: // https://catlikecoding.com/unity/tutorials/custom-srp/point-and-spot-shadows/ - let point_light_texel_size = 2.0 / POINT_SHADOW_SIZE.width as f32; + let point_light_texel_size = 2.0 / point_light_shadow_map.size as f32; for (entity, point_light, transform) in point_lights.iter() { commands.get_or_spawn(entity).insert(ExtractedPointLight { color: point_light.color, @@ -265,7 +270,8 @@ pub fn extract_lights( directional_light.shadow_projection.top - directional_light.shadow_projection.bottom, ); - let directional_light_texel_size = largest_dimension / DIRECTIONAL_SHADOW_SIZE.width as f32; + let directional_light_texel_size = + largest_dimension / directional_light_shadow_map.size as f32; commands .get_or_spawn(entity) .insert(ExtractedDirectionalLight { @@ -366,6 +372,8 @@ pub fn prepare_lights( mut light_meta: ResMut, views: Query>>, ambient_light: Res, + point_light_shadow_map: Res, + directional_light_shadow_map: Res, point_lights: Query<&ExtractedPointLight>, directional_lights: Query<&ExtractedDirectionalLight>, ) { @@ -380,7 +388,11 @@ pub fn prepare_lights( let point_light_depth_texture = texture_cache.get( &render_device, TextureDescriptor { - size: POINT_SHADOW_SIZE, + size: Extent3d { + width: point_light_shadow_map.size as u32, + height: point_light_shadow_map.size as u32, + depth_or_array_layers: POINT_SHADOW_LAYERS, + }, mip_level_count: 1, sample_count: 1, dimension: TextureDimension::D2, @@ -392,7 +404,11 @@ pub fn prepare_lights( let directional_light_depth_texture = texture_cache.get( &render_device, TextureDescriptor { - size: DIRECTIONAL_SHADOW_SIZE, + size: Extent3d { + width: directional_light_shadow_map.size as u32, + height: directional_light_shadow_map.size as u32, + depth_or_array_layers: DIRECTIONAL_SHADOW_LAYERS, + }, mip_level_count: 1, sample_count: 1, dimension: TextureDimension::D2, @@ -451,8 +467,8 @@ pub fn prepare_lights( ), }, ExtractedView { - width: POINT_SHADOW_SIZE.width, - height: POINT_SHADOW_SIZE.height, + width: point_light_shadow_map.size as u32, + height: point_light_shadow_map.size as u32, transform: view_translation * view_rotation, projection, }, @@ -537,8 +553,8 @@ pub fn prepare_lights( pass_name: format!("shadow pass directional light {}", i), }, ExtractedView { - width: DIRECTIONAL_SHADOW_SIZE.width, - height: DIRECTIONAL_SHADOW_SIZE.height, + width: directional_light_shadow_map.size as u32, + height: directional_light_shadow_map.size as u32, transform: GlobalTransform::from_matrix(view.inverse()), projection, }, From f4aa3284a8bc4be46583ab0a7efe6727c926854e Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Wed, 25 Aug 2021 19:44:20 +0000 Subject: [PATCH 19/30] bevy_pbr2: Add support for not casting/receiving shadows (#2726) # Objective Allow marking meshes as not casting / receiving shadows. ## Solution - Added `NotShadowCaster` and `NotShadowReceiver` zero-sized type components. - Extract these components into `bool`s in `ExtractedMesh` - Only generate `DrawShadowMesh` `Drawable`s for meshes _without_ `NotShadowCaster` - Add a `u32` bit `flags` member to `MeshUniform` with one flag indicating whether the mesh is a shadow receiver - If a mesh does _not_ have the `NotShadowReceiver` component, then it is a shadow receiver, and so the bit in the `MeshUniform` is set, otherwise it is not set. - Added an example illustrating the functionality. NOTE: I wanted to have the default state of a mesh as being a shadow caster and shadow receiver, hence the `Not*` components. However, I am on the fence about this. I don't want to have a negative performance impact, nor have people wondering why their custom meshes don't have shadows because they forgot to add `ShadowCaster` and `ShadowReceiver` components, but I also really don't like the double negatives the `Not*` approach incurs. What do you think? Co-authored-by: Carter Anderson --- Cargo.toml | 4 + .../3d/shadow_caster_receiver_pipelined.rs | 182 ++++++++++++++++++ examples/README.md | 1 + pipelined/bevy_pbr2/src/light.rs | 5 + pipelined/bevy_pbr2/src/render/mod.rs | 72 +++++-- pipelined/bevy_pbr2/src/render/pbr.wgsl | 57 ++++-- 6 files changed, 286 insertions(+), 35 deletions(-) create mode 100644 examples/3d/shadow_caster_receiver_pipelined.rs diff --git a/Cargo.toml b/Cargo.toml index d38ff3375fa4a..0fccee6aac6be 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -199,6 +199,10 @@ path = "examples/3d/render_to_texture.rs" name = "shadow_biases_pipelined" path = "examples/3d/shadow_biases_pipelined.rs" +[[example]] +name = "shadow_caster_receiver_pipelined" +path = "examples/3d/shadow_caster_receiver_pipelined.rs" + [[example]] name = "spawner" path = "examples/3d/spawner.rs" diff --git a/examples/3d/shadow_caster_receiver_pipelined.rs b/examples/3d/shadow_caster_receiver_pipelined.rs new file mode 100644 index 0000000000000..c3a68d0378d1b --- /dev/null +++ b/examples/3d/shadow_caster_receiver_pipelined.rs @@ -0,0 +1,182 @@ +use bevy::{ + ecs::prelude::*, + input::Input, + math::{EulerRot, Mat4, Vec3}, + pbr2::{ + DirectionalLight, DirectionalLightBundle, NotShadowCaster, NotShadowReceiver, PbrBundle, + PointLight, PointLightBundle, StandardMaterial, + }, + prelude::{App, Assets, Handle, KeyCode, Transform}, + render2::{ + camera::{OrthographicProjection, PerspectiveCameraBundle}, + color::Color, + mesh::{shape, Mesh}, + }, + PipelinedDefaultPlugins, +}; + +fn main() { + println!( + "Controls: + C - toggle shadow casters (i.e. casters become not, and not casters become casters) + R - toggle shadow receivers (i.e. receivers become not, and not receivers become receivers) + L - switch between directional and point lights" + ); + App::new() + .add_plugins(PipelinedDefaultPlugins) + .add_startup_system(setup) + .add_system(toggle_light) + .add_system(toggle_shadows) + .run(); +} + +/// set up a 3D scene to test shadow biases and perspective projections +fn setup( + mut commands: Commands, + mut meshes: ResMut>, + mut materials: ResMut>, +) { + let spawn_plane_depth = 500.0f32; + let spawn_height = 2.0; + let sphere_radius = 0.25; + + let white_handle = materials.add(StandardMaterial { + base_color: Color::WHITE, + perceptual_roughness: 1.0, + ..Default::default() + }); + let sphere_handle = meshes.add(Mesh::from(shape::Icosphere { + radius: sphere_radius, + ..Default::default() + })); + + // sphere - initially a caster + commands.spawn_bundle(PbrBundle { + mesh: sphere_handle.clone(), + material: materials.add(Color::RED.into()), + transform: Transform::from_xyz(-1.0, spawn_height, 0.0), + ..Default::default() + }); + + // sphere - initially not a caster + commands + .spawn_bundle(PbrBundle { + mesh: sphere_handle, + material: materials.add(Color::BLUE.into()), + transform: Transform::from_xyz(1.0, spawn_height, 0.0), + ..Default::default() + }) + .insert(NotShadowCaster); + + // floating plane - initially not a shadow receiver and not a caster + commands + .spawn_bundle(PbrBundle { + mesh: meshes.add(Mesh::from(shape::Plane { size: 20.0 })), + material: materials.add(Color::GREEN.into()), + transform: Transform::from_xyz(0.0, 1.0, -10.0), + ..Default::default() + }) + .insert_bundle((NotShadowCaster, NotShadowReceiver)); + + // lower ground plane - initially a shadow receiver + commands.spawn_bundle(PbrBundle { + mesh: meshes.add(Mesh::from(shape::Plane { size: 20.0 })), + material: white_handle, + ..Default::default() + }); + + println!("Using DirectionalLight"); + + commands.spawn_bundle(PointLightBundle { + transform: Transform::from_xyz(5.0, 5.0, 0.0), + point_light: PointLight { + intensity: 0.0, + range: spawn_plane_depth, + color: Color::WHITE, + ..Default::default() + }, + ..Default::default() + }); + + let theta = std::f32::consts::FRAC_PI_4; + let light_transform = Mat4::from_euler(EulerRot::ZYX, 0.0, std::f32::consts::FRAC_PI_2, -theta); + commands.spawn_bundle(DirectionalLightBundle { + directional_light: DirectionalLight { + illuminance: 100000.0, + shadow_projection: OrthographicProjection { + left: -10.0, + right: 10.0, + bottom: -10.0, + top: 10.0, + near: -50.0, + far: 50.0, + ..Default::default() + }, + ..Default::default() + }, + transform: Transform::from_matrix(light_transform), + ..Default::default() + }); + + // camera + commands.spawn_bundle(PerspectiveCameraBundle { + transform: Transform::from_xyz(-5.0, 5.0, 5.0) + .looking_at(Vec3::new(-1.0, 1.0, 0.0), Vec3::Y), + ..Default::default() + }); +} + +fn toggle_light( + input: Res>, + mut point_lights: Query<&mut PointLight>, + mut directional_lights: Query<&mut DirectionalLight>, +) { + if input.just_pressed(KeyCode::L) { + for mut light in point_lights.iter_mut() { + light.intensity = if light.intensity == 0.0 { + println!("Using PointLight"); + 100000000.0 + } else { + 0.0 + }; + } + for mut light in directional_lights.iter_mut() { + light.illuminance = if light.illuminance == 0.0 { + println!("Using DirectionalLight"); + 100000.0 + } else { + 0.0 + }; + } + } +} + +fn toggle_shadows( + mut commands: Commands, + input: Res>, + queries: QuerySet<( + Query>, With)>, + Query>, With)>, + Query>, Without)>, + Query>, Without)>, + )>, +) { + if input.just_pressed(KeyCode::C) { + println!("Toggling casters"); + for entity in queries.q0().iter() { + commands.entity(entity).remove::(); + } + for entity in queries.q2().iter() { + commands.entity(entity).insert(NotShadowCaster); + } + } + if input.just_pressed(KeyCode::R) { + println!("Toggling receivers"); + for entity in queries.q1().iter() { + commands.entity(entity).remove::(); + } + for entity in queries.q3().iter() { + commands.entity(entity).insert(NotShadowReceiver); + } + } +} diff --git a/examples/README.md b/examples/README.md index 40e82fb112c2c..c0343a9016db7 100644 --- a/examples/README.md +++ b/examples/README.md @@ -107,6 +107,7 @@ Example | File | Description `pbr` | [`3d/pbr.rs`](./3d/pbr.rs) | Demonstrates use of Physically Based Rendering (PBR) properties `pbr_pipelined` | [`3d/pbr_pipelined.rs`](./3d/pbr_pipelined.rs) | Demonstrates use of Physically Based Rendering (PBR) properties `render_to_texture` | [`3d/render_to_texture.rs`](./3d/render_to_texture.rs) | Shows how to render to texture +`shadow_caster_receiver_pipelined` | [`3d/shadow_caster_receiver_pipelined.rs`](./3d/shadow_caster_receiver_pipelined.rs) | Demonstrates how to prevent meshes from casting/receiving shadows in a 3d scene `shadow_biases_pipelined` | [`3d/shadow_biases_pipelined.rs`](./3d/shadow_biases_pipelined.rs) | Demonstrates how shadow biases affect shadows in a 3d scene `spawner` | [`3d/spawner.rs`](./3d/spawner.rs) | Renders a large number of cubes with changing position and material `texture` | [`3d/texture.rs`](./3d/texture.rs) | Shows configuration of texture materials diff --git a/pipelined/bevy_pbr2/src/light.rs b/pipelined/bevy_pbr2/src/light.rs index 571a9048bc590..dab8eee43ab07 100644 --- a/pipelined/bevy_pbr2/src/light.rs +++ b/pipelined/bevy_pbr2/src/light.rs @@ -151,3 +151,8 @@ impl Default for AmbientLight { } } } + +/// Add this component to make a `Mesh` not cast shadows +pub struct NotShadowCaster; +/// Add this component to make a `Mesh` not receive shadows +pub struct NotShadowReceiver; diff --git a/pipelined/bevy_pbr2/src/render/mod.rs b/pipelined/bevy_pbr2/src/render/mod.rs index 31e160d83549d..915657d60d5b7 100644 --- a/pipelined/bevy_pbr2/src/render/mod.rs +++ b/pipelined/bevy_pbr2/src/render/mod.rs @@ -1,7 +1,7 @@ mod light; pub use light::*; -use crate::{StandardMaterial, StandardMaterialUniformData}; +use crate::{NotShadowCaster, NotShadowReceiver, StandardMaterial, StandardMaterialUniformData}; use bevy_asset::{Assets, Handle}; use bevy_core_pipeline::Transparent3dPhase; use bevy_ecs::{prelude::*, system::SystemState}; @@ -120,11 +120,11 @@ impl FromWorld for PbrShaders { let mesh_layout = render_device.create_bind_group_layout(&BindGroupLayoutDescriptor { entries: &[BindGroupLayoutEntry { binding: 0, - visibility: ShaderStage::VERTEX, + visibility: ShaderStage::VERTEX | ShaderStage::FRAGMENT, ty: BindingType::Buffer { ty: BufferBindingType::Uniform, has_dynamic_offset: true, - min_binding_size: BufferSize::new(Mat4::std140_size_static() as u64), + min_binding_size: BufferSize::new(80), }, count: None, }], @@ -374,6 +374,8 @@ struct ExtractedMesh { mesh: Handle, transform_binding_offset: u32, material_handle: Handle, + casts_shadows: bool, + receives_shadows: bool, } pub struct ExtractedMeshes { @@ -385,10 +387,23 @@ pub fn extract_meshes( meshes: Res>, materials: Res>, images: Res>, - query: Query<(&GlobalTransform, &Handle, &Handle)>, + query: Query<( + &GlobalTransform, + &Handle, + &Handle, + Option<&NotShadowCaster>, + Option<&NotShadowReceiver>, + )>, ) { let mut extracted_meshes = Vec::new(); - for (transform, mesh_handle, material_handle) in query.iter() { + for ( + transform, + mesh_handle, + material_handle, + maybe_not_shadow_caster, + maybe_not_shadow_receiver, + ) in query.iter() + { if !meshes.contains(mesh_handle) { continue; } @@ -419,6 +434,10 @@ pub fn extract_meshes( mesh: mesh_handle.clone_weak(), transform_binding_offset: 0, material_handle: material_handle.clone_weak(), + // NOTE: Double-negative is so that meshes cast and receive shadows by default + // Not not shadow caster means that this mesh is a shadow caster + casts_shadows: maybe_not_shadow_caster.is_none(), + receives_shadows: maybe_not_shadow_receiver.is_none(), }); } else { continue; @@ -435,9 +454,25 @@ struct MeshDrawInfo { material_bind_group_key: FrameSlabMapKey, } +#[derive(Debug, AsStd140)] +pub struct MeshUniform { + model: Mat4, + flags: u32, +} + +// NOTE: These must match the bit flags in bevy_pbr2/src/render/pbr.wgsl! +bitflags::bitflags! { + #[repr(transparent)] + struct MeshFlags: u32 { + const SHADOW_RECEIVER = (1 << 0); + const NONE = 0; + const UNINITIALIZED = 0xFFFF; + } +} + #[derive(Default)] pub struct MeshMeta { - transform_uniforms: DynamicUniformVec, + transform_uniforms: DynamicUniformVec, material_bind_groups: FrameSlabMap, mesh_transform_bind_group: FrameSlabMap, mesh_transform_bind_group_key: Option>, @@ -453,8 +488,15 @@ pub fn prepare_meshes( .transform_uniforms .reserve_and_clear(extracted_meshes.meshes.len(), &render_device); for extracted_mesh in extracted_meshes.meshes.iter_mut() { - extracted_mesh.transform_binding_offset = - mesh_meta.transform_uniforms.push(extracted_mesh.transform); + let flags = if extracted_mesh.receives_shadows { + MeshFlags::SHADOW_RECEIVER + } else { + MeshFlags::NONE + }; + extracted_mesh.transform_binding_offset = mesh_meta.transform_uniforms.push(MeshUniform { + model: extracted_mesh.transform, + flags: flags.bits, + }); } mesh_meta @@ -694,12 +736,14 @@ pub fn queue_meshes( for view_light_entity in view_lights.lights.iter().copied() { let mut shadow_phase = view_light_shadow_phases.get_mut(view_light_entity).unwrap(); // TODO: this should only queue up meshes that are actually visible by each "light view" - for i in 0..extracted_meshes.meshes.len() { - shadow_phase.add(Drawable { - draw_function: draw_shadow_mesh, - draw_key: i, - sort_key: 0, // TODO: sort back-to-front - }) + for (i, mesh) in extracted_meshes.meshes.iter().enumerate() { + if mesh.casts_shadows { + shadow_phase.add(Drawable { + draw_function: draw_shadow_mesh, + draw_key: i, + sort_key: 0, // TODO: sort back-to-front + }); + } } } } diff --git a/pipelined/bevy_pbr2/src/render/pbr.wgsl b/pipelined/bevy_pbr2/src/render/pbr.wgsl index 6e866689fa044..81be4e8241a33 100644 --- a/pipelined/bevy_pbr2/src/render/pbr.wgsl +++ b/pipelined/bevy_pbr2/src/render/pbr.wgsl @@ -4,14 +4,19 @@ struct View { view_proj: mat4x4; world_position: vec3; }; -[[group(0), binding(0)]] -var view: View; [[block]] struct Mesh { - transform: mat4x4; + model: mat4x4; + // 'flags' is a bit field indicating various options. u32 is 32 bits so we have up to 32 options. + flags: u32; }; + +let MESH_FLAGS_SHADOW_RECEIVER_BIT: u32 = 1u; + +[[group(0), binding(0)]] +var view: View; [[group(1), binding(0)]] var mesh: Mesh; @@ -30,7 +35,7 @@ struct VertexOutput { [[stage(vertex)]] fn vertex(vertex: Vertex) -> VertexOutput { - let world_position = mesh.transform * vec4(vertex.position, 1.0); + let world_position = mesh.model * vec4(vertex.position, 1.0); var out: VertexOutput; out.uv = vertex.uv; @@ -38,7 +43,7 @@ fn vertex(vertex: Vertex) -> VertexOutput { out.clip_position = view.view_proj * world_position; // FIXME: The inverse transpose of the model matrix should be used to correctly handle scaling // of normals - out.world_normal = mat3x3(mesh.transform.x.xyz, mesh.transform.y.xyz, mesh.transform.z.xyz) * vertex.normal; + out.world_normal = mat3x3(mesh.model.x.xyz, mesh.model.y.xyz, mesh.model.z.xyz) * vertex.normal; return out; } @@ -83,10 +88,17 @@ struct StandardMaterial { perceptual_roughness: f32; metallic: f32; reflectance: f32; - // 'flags' is a bit field indicating various option. uint is 32 bits so we have up to 32 options. + // 'flags' is a bit field indicating various options. u32 is 32 bits so we have up to 32 options. flags: u32; }; +let STANDARD_MATERIAL_FLAGS_BASE_COLOR_TEXTURE_BIT: u32 = 1u; +let STANDARD_MATERIAL_FLAGS_EMISSIVE_TEXTURE_BIT: u32 = 2u; +let STANDARD_MATERIAL_FLAGS_METALLIC_ROUGHNESS_TEXTURE_BIT: u32 = 4u; +let STANDARD_MATERIAL_FLAGS_OCCLUSION_TEXTURE_BIT: u32 = 8u; +let STANDARD_MATERIAL_FLAGS_DOUBLE_SIDED_BIT: u32 = 16u; +let STANDARD_MATERIAL_FLAGS_UNLIT_BIT: u32 = 32u; + struct PointLight { color: vec4; // projection: mat4x4; @@ -118,13 +130,6 @@ struct Lights { n_directional_lights: u32; }; -let FLAGS_BASE_COLOR_TEXTURE_BIT: u32 = 1u; -let FLAGS_EMISSIVE_TEXTURE_BIT: u32 = 2u; -let FLAGS_METALLIC_ROUGHNESS_TEXTURE_BIT: u32 = 4u; -let FLAGS_OCCLUSION_TEXTURE_BIT: u32 = 8u; -let FLAGS_DOUBLE_SIDED_BIT: u32 = 16u; -let FLAGS_UNLIT_BIT: u32 = 32u; - [[group(0), binding(1)]] var lights: Lights; @@ -463,22 +468,22 @@ struct FragmentInput { [[stage(fragment)]] fn fragment(in: FragmentInput) -> [[location(0)]] vec4 { var output_color: vec4 = material.base_color; - if ((material.flags & FLAGS_BASE_COLOR_TEXTURE_BIT) != 0u) { + if ((material.flags & STANDARD_MATERIAL_FLAGS_BASE_COLOR_TEXTURE_BIT) != 0u) { output_color = output_color * textureSample(base_color_texture, base_color_sampler, in.uv); } // // NOTE: Unlit bit not set means == 0 is true, so the true case is if lit - if ((material.flags & FLAGS_UNLIT_BIT) == 0u) { + if ((material.flags & STANDARD_MATERIAL_FLAGS_UNLIT_BIT) == 0u) { // TODO use .a for exposure compensation in HDR var emissive: vec4 = material.emissive; - if ((material.flags & FLAGS_EMISSIVE_TEXTURE_BIT) != 0u) { + if ((material.flags & STANDARD_MATERIAL_FLAGS_EMISSIVE_TEXTURE_BIT) != 0u) { emissive = vec4(emissive.rgb * textureSample(emissive_texture, emissive_sampler, in.uv).rgb, 1.0); } // calculate non-linear roughness from linear perceptualRoughness var metallic: f32 = material.metallic; var perceptual_roughness: f32 = material.perceptual_roughness; - if ((material.flags & FLAGS_METALLIC_ROUGHNESS_TEXTURE_BIT) != 0u) { + if ((material.flags & STANDARD_MATERIAL_FLAGS_METALLIC_ROUGHNESS_TEXTURE_BIT) != 0u) { let metallic_roughness = textureSample(metallic_roughness_texture, metallic_roughness_sampler, in.uv); // Sampling from GLTF standard channels for now metallic = metallic * metallic_roughness.b; @@ -487,7 +492,7 @@ fn fragment(in: FragmentInput) -> [[location(0)]] vec4 { let roughness = perceptualRoughnessToRoughness(perceptual_roughness); var occlusion: f32 = 1.0; - if ((material.flags & FLAGS_OCCLUSION_TEXTURE_BIT) != 0u) { + if ((material.flags & STANDARD_MATERIAL_FLAGS_OCCLUSION_TEXTURE_BIT) != 0u) { occlusion = textureSample(occlusion_texture, occlusion_sampler, in.uv).r; } @@ -500,7 +505,7 @@ fn fragment(in: FragmentInput) -> [[location(0)]] vec4 { // vec3 B = cross(N, T) * v_WorldTangent.w; // # endif - if ((material.flags & FLAGS_DOUBLE_SIDED_BIT) != 0u) { + if ((material.flags & STANDARD_MATERIAL_FLAGS_DOUBLE_SIDED_BIT) != 0u) { if (!in.is_front) { N = -N; } @@ -543,13 +548,23 @@ fn fragment(in: FragmentInput) -> [[location(0)]] vec4 { let n_directional_lights = i32(lights.n_directional_lights); for (var i: i32 = 0; i < n_point_lights; i = i + 1) { let light = lights.point_lights[i]; - let shadow = fetch_point_shadow(i, in.world_position, in.world_normal); + var shadow: f32; + if ((mesh.flags & MESH_FLAGS_SHADOW_RECEIVER_BIT) != 0u) { + shadow = fetch_point_shadow(i, in.world_position, in.world_normal); + } else { + shadow = 1.0; + } let light_contrib = point_light(in.world_position.xyz, light, roughness, NdotV, N, V, R, F0, diffuse_color); light_accum = light_accum + light_contrib * shadow; } for (var i: i32 = 0; i < n_directional_lights; i = i + 1) { let light = lights.directional_lights[i]; - let shadow = fetch_directional_shadow(i, in.world_position, in.world_normal); + var shadow: f32; + if ((mesh.flags & MESH_FLAGS_SHADOW_RECEIVER_BIT) != 0u) { + shadow = fetch_directional_shadow(i, in.world_position, in.world_normal); + } else { + shadow = 1.0; + } let light_contrib = directional_light(light, roughness, NdotV, N, V, R, F0, diffuse_color); light_accum = light_accum + light_contrib * shadow; } From dd32cd029d404783b24f0318546236cfce8ac448 Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Wed, 25 Aug 2021 20:10:43 +0000 Subject: [PATCH 20/30] Pipelined separate shadow vertex shader (#2727) # Objective - Avoid unnecessary work in the vertex shader of the numerous shadow passes - Have the natural order of bind groups in the pbr shader: view, material, mesh ## Solution - Separate out the vertex stage of pbr.wgsl into depth.wgsl - Remove the unnecessary calculation of uv and normal, as well as removing the unnecessary vertex inputs and outputs - Use the depth.wgsl for shadow passes - Reorder the bind groups in pbr.wgsl and PbrShaders to be 0 - view, 1 - material, 2 - mesh in decreasing order of rebind frequency --- pipelined/bevy_pbr2/src/render/depth.wgsl | 30 +++++++++++++++ pipelined/bevy_pbr2/src/render/light.rs | 7 +++- pipelined/bevy_pbr2/src/render/mod.rs | 46 +++++++++++------------ pipelined/bevy_pbr2/src/render/pbr.wgsl | 20 +++++----- 4 files changed, 68 insertions(+), 35 deletions(-) create mode 100644 pipelined/bevy_pbr2/src/render/depth.wgsl diff --git a/pipelined/bevy_pbr2/src/render/depth.wgsl b/pipelined/bevy_pbr2/src/render/depth.wgsl new file mode 100644 index 0000000000000..9313118d16f1d --- /dev/null +++ b/pipelined/bevy_pbr2/src/render/depth.wgsl @@ -0,0 +1,30 @@ +[[block]] +struct View { + view_proj: mat4x4; + world_position: vec3; +}; +[[group(0), binding(0)]] +var view: View; + + +[[block]] +struct Mesh { + transform: mat4x4; +}; +[[group(1), binding(0)]] +var mesh: Mesh; + +struct Vertex { + [[location(0)]] position: vec3; +}; + +struct VertexOutput { + [[builtin(position)]] clip_position: vec4; +}; + +[[stage(vertex)]] +fn vertex(vertex: Vertex) -> VertexOutput { + var out: VertexOutput; + out.clip_position = view.view_proj * mesh.transform * vec4(vertex.position, 1.0); + return out; +} diff --git a/pipelined/bevy_pbr2/src/render/light.rs b/pipelined/bevy_pbr2/src/render/light.rs index c77e021aeb6ff..c26a4b754ed5e 100644 --- a/pipelined/bevy_pbr2/src/render/light.rs +++ b/pipelined/bevy_pbr2/src/render/light.rs @@ -14,6 +14,7 @@ use bevy_render2::{ render_phase::{Draw, DrawFunctions, RenderPhase, TrackedRenderPass}, render_resource::*, renderer::{RenderContext, RenderDevice}, + shader::Shader, texture::*, view::{ExtractedView, ViewUniformOffset}, }; @@ -93,6 +94,7 @@ pub const DIRECTIONAL_SHADOW_LAYERS: u32 = MAX_DIRECTIONAL_LIGHTS as u32; pub const SHADOW_FORMAT: TextureFormat = TextureFormat::Depth32Float; pub struct ShadowShaders { + pub shader_module: ShaderModule, pub pipeline: RenderPipeline, pub view_layout: BindGroupLayout, pub point_light_sampler: Sampler, @@ -104,6 +106,8 @@ impl FromWorld for ShadowShaders { fn from_world(world: &mut World) -> Self { let render_device = world.get_resource::().unwrap(); let pbr_shaders = world.get_resource::().unwrap(); + let shader = Shader::from_wgsl(include_str!("depth.wgsl")); + let shader_module = render_device.create_shader_module(&shader); let view_layout = render_device.create_bind_group_layout(&BindGroupLayoutDescriptor { entries: &[ @@ -157,7 +161,7 @@ impl FromWorld for ShadowShaders { }, ], }], - module: &pbr_shaders.shader_module, + module: &shader_module, entry_point: "vertex", }, fragment: None, @@ -191,6 +195,7 @@ impl FromWorld for ShadowShaders { }); ShadowShaders { + shader_module, pipeline, view_layout, point_light_sampler: render_device.create_sampler(&SamplerDescriptor { diff --git a/pipelined/bevy_pbr2/src/render/mod.rs b/pipelined/bevy_pbr2/src/render/mod.rs index 915657d60d5b7..683ad9b5db21c 100644 --- a/pipelined/bevy_pbr2/src/render/mod.rs +++ b/pipelined/bevy_pbr2/src/render/mod.rs @@ -27,7 +27,6 @@ use wgpu::{ pub struct PbrShaders { pipeline: RenderPipeline, - shader_module: ShaderModule, view_layout: BindGroupLayout, material_layout: BindGroupLayout, mesh_layout: BindGroupLayout, @@ -117,20 +116,6 @@ impl FromWorld for PbrShaders { label: None, }); - let mesh_layout = render_device.create_bind_group_layout(&BindGroupLayoutDescriptor { - entries: &[BindGroupLayoutEntry { - binding: 0, - visibility: ShaderStage::VERTEX | ShaderStage::FRAGMENT, - ty: BindingType::Buffer { - ty: BufferBindingType::Uniform, - has_dynamic_offset: true, - min_binding_size: BufferSize::new(80), - }, - count: None, - }], - label: None, - }); - let material_layout = render_device.create_bind_group_layout(&BindGroupLayoutDescriptor { entries: &[ BindGroupLayoutEntry { @@ -233,10 +218,24 @@ impl FromWorld for PbrShaders { label: None, }); + let mesh_layout = render_device.create_bind_group_layout(&BindGroupLayoutDescriptor { + entries: &[BindGroupLayoutEntry { + binding: 0, + visibility: ShaderStage::VERTEX | ShaderStage::FRAGMENT, + ty: BindingType::Buffer { + ty: BufferBindingType::Uniform, + has_dynamic_offset: true, + min_binding_size: BufferSize::new(80), + }, + count: None, + }], + label: None, + }); + let pipeline_layout = render_device.create_pipeline_layout(&PipelineLayoutDescriptor { label: None, push_constant_ranges: &[], - bind_group_layouts: &[&view_layout, &mesh_layout, &material_layout], + bind_group_layouts: &[&view_layout, &material_layout, &mesh_layout], }); let pipeline = render_device.create_render_pipeline(&RenderPipelineDescriptor { @@ -360,7 +359,6 @@ impl FromWorld for PbrShaders { }; PbrShaders { pipeline, - shader_module, view_layout, material_layout, mesh_layout, @@ -818,21 +816,21 @@ impl Draw for DrawPbr { &mesh_view_bind_groups.view, &[view_uniforms.offset, view_lights.gpu_light_binding_index], ); + let mesh_draw_info = &mesh_meta.mesh_draw_info[draw_key]; pass.set_bind_group( 1, + // &mesh_meta.material_bind_groups[sort_key & ((1 << 10) - 1)], + &mesh_meta.material_bind_groups[mesh_draw_info.material_bind_group_key], + &[], + ); + pass.set_bind_group( + 2, mesh_meta .mesh_transform_bind_group .get_value(mesh_meta.mesh_transform_bind_group_key.unwrap()) .unwrap(), &[extracted_mesh.transform_binding_offset], ); - let mesh_draw_info = &mesh_meta.mesh_draw_info[draw_key]; - pass.set_bind_group( - 2, - // &mesh_meta.material_bind_groups[sort_key & ((1 << 10) - 1)], - &mesh_meta.material_bind_groups[mesh_draw_info.material_bind_group_key], - &[], - ); let gpu_mesh = meshes.into_inner().get(&extracted_mesh.mesh).unwrap(); pass.set_vertex_buffer(0, gpu_mesh.vertex_buffer.slice(..)); diff --git a/pipelined/bevy_pbr2/src/render/pbr.wgsl b/pipelined/bevy_pbr2/src/render/pbr.wgsl index 81be4e8241a33..de9c856be9e53 100644 --- a/pipelined/bevy_pbr2/src/render/pbr.wgsl +++ b/pipelined/bevy_pbr2/src/render/pbr.wgsl @@ -17,7 +17,7 @@ let MESH_FLAGS_SHADOW_RECEIVER_BIT: u32 = 1u; [[group(0), binding(0)]] var view: View; -[[group(1), binding(0)]] +[[group(2), binding(0)]] var mesh: Mesh; struct Vertex { @@ -142,23 +142,23 @@ var directional_shadow_textures: texture_depth_2d_array; [[group(0), binding(5)]] var directional_shadow_textures_sampler: sampler_comparison; -[[group(2), binding(0)]] +[[group(1), binding(0)]] var material: StandardMaterial; -[[group(2), binding(1)]] +[[group(1), binding(1)]] var base_color_texture: texture_2d; -[[group(2), binding(2)]] +[[group(1), binding(2)]] var base_color_sampler: sampler; -[[group(2), binding(3)]] +[[group(1), binding(3)]] var emissive_texture: texture_2d; -[[group(2), binding(4)]] +[[group(1), binding(4)]] var emissive_sampler: sampler; -[[group(2), binding(5)]] +[[group(1), binding(5)]] var metallic_roughness_texture: texture_2d; -[[group(2), binding(6)]] +[[group(1), binding(6)]] var metallic_roughness_sampler: sampler; -[[group(2), binding(7)]] +[[group(1), binding(7)]] var occlusion_texture: texture_2d; -[[group(2), binding(8)]] +[[group(1), binding(8)]] var occlusion_sampler: sampler; let PI: f32 = 3.141592653589793; From ec62a8056404311a8f096d19c24e14fc75168f20 Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Sun, 25 Jul 2021 13:32:56 +0200 Subject: [PATCH 21/30] 3d_scene_pipelined: Minor cleanup --- examples/3d/3d_scene_pipelined.rs | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/examples/3d/3d_scene_pipelined.rs b/examples/3d/3d_scene_pipelined.rs index f3bef825b1a8f..d3c25432568fa 100644 --- a/examples/3d/3d_scene_pipelined.rs +++ b/examples/3d/3d_scene_pipelined.rs @@ -36,11 +36,7 @@ fn setup( mut meshes: ResMut>, mut materials: ResMut>, ) { - commands.insert_resource(AmbientLight { - color: Color::ORANGE_RED, - brightness: 0.02, - }); - // plane + // ground plane commands.spawn_bundle(PbrBundle { mesh: meshes.add(Mesh::from(shape::Plane { size: 10.0 })), material: materials.add(StandardMaterial { @@ -51,6 +47,7 @@ fn setup( ..Default::default() }); + // left wall let mut transform = Transform::from_xyz(2.5, 2.5, 0.0); transform.rotate(Quat::from_rotation_z(std::f32::consts::FRAC_PI_2)); commands.spawn_bundle(PbrBundle { @@ -63,7 +60,7 @@ fn setup( }), ..Default::default() }); - + // back (right) wall let mut transform = Transform::from_xyz(0.0, 2.5, -2.5); transform.rotate(Quat::from_rotation_x(std::f32::consts::FRAC_PI_2)); commands.spawn_bundle(PbrBundle { @@ -76,6 +73,7 @@ fn setup( }), ..Default::default() }); + // cube commands .spawn_bundle(PbrBundle { @@ -104,7 +102,13 @@ fn setup( }) .insert(Movable); - // light + // ambient light + commands.insert_resource(AmbientLight { + color: Color::ORANGE_RED, + brightness: 0.02, + }); + + // red point light commands .spawn_bundle(PointLightBundle { // transform: Transform::from_xyz(5.0, 8.0, 2.0), @@ -131,7 +135,7 @@ fn setup( }); }); - // light + // green point light commands .spawn_bundle(PointLightBundle { // transform: Transform::from_xyz(5.0, 8.0, 2.0), @@ -158,7 +162,7 @@ fn setup( }); }); - // light + // blue point light commands .spawn_bundle(PointLightBundle { // transform: Transform::from_xyz(5.0, 8.0, 2.0), @@ -185,6 +189,7 @@ fn setup( }); }); + // directional 'sun' light const HALF_SIZE: f32 = 10.0; commands.spawn_bundle(DirectionalLightBundle { directional_light: DirectionalLight { From ace8a66e2700e1ae8561e2e6820108eec2e8aace Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Sun, 25 Jul 2021 13:35:22 +0200 Subject: [PATCH 22/30] bevy_render2/bevy_pbr2: Use the infinite reverse rh perspective projection This projection is industry standard and offers better precision distribution over the depth range than forward projections. --- .../bevy_core_pipeline/src/main_pass_3d.rs | 2 +- pipelined/bevy_pbr2/src/light.rs | 2 +- pipelined/bevy_pbr2/src/render/light.rs | 14 ++++----- pipelined/bevy_pbr2/src/render/mod.rs | 4 +-- pipelined/bevy_pbr2/src/render/pbr.wgsl | 29 +++++++++++++------ .../bevy_render2/src/camera/projection.rs | 6 ++-- 6 files changed, 35 insertions(+), 22 deletions(-) diff --git a/pipelined/bevy_core_pipeline/src/main_pass_3d.rs b/pipelined/bevy_core_pipeline/src/main_pass_3d.rs index a3d0438d7690b..b2a1ab644bd8d 100644 --- a/pipelined/bevy_core_pipeline/src/main_pass_3d.rs +++ b/pipelined/bevy_core_pipeline/src/main_pass_3d.rs @@ -62,7 +62,7 @@ impl Node for MainPass3dNode { depth_stencil_attachment: Some(RenderPassDepthStencilAttachment { view: depth_texture, depth_ops: Some(Operations { - load: LoadOp::Clear(1.0), + load: LoadOp::Clear(0.0), store: true, }), stencil_ops: None, diff --git a/pipelined/bevy_pbr2/src/light.rs b/pipelined/bevy_pbr2/src/light.rs index dab8eee43ab07..c5b2f60f56fe0 100644 --- a/pipelined/bevy_pbr2/src/light.rs +++ b/pipelined/bevy_pbr2/src/light.rs @@ -46,7 +46,7 @@ impl Default for PointLight { impl PointLight { pub const DEFAULT_SHADOW_DEPTH_BIAS: f32 = 0.02; - pub const DEFAULT_SHADOW_NORMAL_BIAS: f32 = 0.5; + pub const DEFAULT_SHADOW_NORMAL_BIAS: f32 = 0.6; } #[derive(Clone, Debug)] diff --git a/pipelined/bevy_pbr2/src/render/light.rs b/pipelined/bevy_pbr2/src/render/light.rs index c26a4b754ed5e..04a81acfe1d1e 100644 --- a/pipelined/bevy_pbr2/src/render/light.rs +++ b/pipelined/bevy_pbr2/src/render/light.rs @@ -54,8 +54,8 @@ pub type ExtractedDirectionalLightShadowMap = DirectionalLightShadowMap; #[repr(C)] #[derive(Copy, Clone, AsStd140, Default, Debug)] pub struct GpuPointLight { + projection: Mat4, color: Vec4, - // proj: Mat4, position: Vec3, inverse_square_range: f32, radius: f32, @@ -168,7 +168,7 @@ impl FromWorld for ShadowShaders { depth_stencil: Some(DepthStencilState { format: SHADOW_FORMAT, depth_write_enabled: true, - depth_compare: CompareFunction::LessEqual, + depth_compare: CompareFunction::GreaterEqual, stencil: StencilState { front: StencilFaceState::IGNORE, back: StencilFaceState::IGNORE, @@ -205,7 +205,7 @@ impl FromWorld for ShadowShaders { mag_filter: FilterMode::Linear, min_filter: FilterMode::Linear, mipmap_filter: FilterMode::Nearest, - compare: Some(CompareFunction::LessEqual), + compare: Some(CompareFunction::GreaterEqual), ..Default::default() }), directional_light_sampler: render_device.create_sampler(&SamplerDescriptor { @@ -215,7 +215,7 @@ impl FromWorld for ShadowShaders { mag_filter: FilterMode::Linear, min_filter: FilterMode::Linear, mipmap_filter: FilterMode::Nearest, - compare: Some(CompareFunction::LessEqual), + compare: Some(CompareFunction::GreaterEqual), ..Default::default() }), } @@ -435,7 +435,7 @@ pub fn prepare_lights( // TODO: this should select lights based on relevance to the view instead of the first ones that show up in a query for (light_index, light) in point_lights.iter().enumerate().take(MAX_POINT_LIGHTS) { let projection = - Mat4::perspective_rh(std::f32::consts::FRAC_PI_2, 1.0, 0.1, light.range); + Mat4::perspective_infinite_reverse_rh(std::f32::consts::FRAC_PI_2, 1.0, 0.1); // ignore scale because we don't want to effectively scale light radius and range // by applying those as a view transform to shadow map rendering of objects @@ -484,6 +484,7 @@ pub fn prepare_lights( } gpu_lights.point_lights[light_index] = GpuPointLight { + projection, // premultiply color by intensity // we don't use the alpha at all, so no reason to multiply only [0..3] color: (light.color.as_rgba_linear() * light.intensity).into(), @@ -492,7 +493,6 @@ pub fn prepare_lights( inverse_square_range: 1.0 / (light.range * light.range), near: 0.1, far: light.range, - // proj: projection, shadow_depth_bias: light.shadow_depth_bias, shadow_normal_bias: light.shadow_normal_bias, }; @@ -656,7 +656,7 @@ impl Node for ShadowPassNode { depth_stencil_attachment: Some(RenderPassDepthStencilAttachment { view: &view_light.depth_texture_view, depth_ops: Some(Operations { - load: LoadOp::Clear(1.0), + load: LoadOp::Clear(0.0), store: true, }), stencil_ops: None, diff --git a/pipelined/bevy_pbr2/src/render/mod.rs b/pipelined/bevy_pbr2/src/render/mod.rs index 683ad9b5db21c..f5dd75c304ca0 100644 --- a/pipelined/bevy_pbr2/src/render/mod.rs +++ b/pipelined/bevy_pbr2/src/render/mod.rs @@ -66,7 +66,7 @@ impl FromWorld for PbrShaders { has_dynamic_offset: true, // TODO: change this to GpuLights::std140_size_static once crevice fixes this! // Context: https://github.com/LPGhatguy/crevice/issues/29 - min_binding_size: BufferSize::new(1024), + min_binding_size: BufferSize::new(1424), }, count: None, }, @@ -291,7 +291,7 @@ impl FromWorld for PbrShaders { depth_stencil: Some(DepthStencilState { format: TextureFormat::Depth32Float, depth_write_enabled: true, - depth_compare: CompareFunction::Less, + depth_compare: CompareFunction::Greater, stencil: StencilState { front: StencilFaceState::IGNORE, back: StencilFaceState::IGNORE, diff --git a/pipelined/bevy_pbr2/src/render/pbr.wgsl b/pipelined/bevy_pbr2/src/render/pbr.wgsl index de9c856be9e53..df0da250c546a 100644 --- a/pipelined/bevy_pbr2/src/render/pbr.wgsl +++ b/pipelined/bevy_pbr2/src/render/pbr.wgsl @@ -100,8 +100,8 @@ let STANDARD_MATERIAL_FLAGS_DOUBLE_SIDED_BIT: u32 = 16u; let STANDARD_MATERIAL_FLAGS_UNLIT_BIT: u32 = 32u; struct PointLight { + projection: mat4x4; color: vec4; - // projection: mat4x4; position: vec3; inverse_square_range: f32; radius: f32; @@ -408,14 +408,25 @@ fn fetch_point_shadow(light_id: i32, frag_position: vec4, surface_normal: v let abs_position_ls = abs(frag_ls); let major_axis_magnitude = max(abs_position_ls.x, max(abs_position_ls.y, abs_position_ls.z)); - // do a full projection - // vec4 clip = light.projection * vec4(0.0, 0.0, -major_axis_magnitude, 1.0); - // float depth = (clip.z / clip.w); + // NOTE: These simplifications come from multiplying: + // projection * vec4(0, 0, -major_axis_magnitude, 1.0) + // and keeping only the terms that have any impact on the depth. + // Projection-agnostic approach: + let projection_cols23_row2 = vec2(light.projection[2][2], light.projection[3][2]); + let projection_cols23_row3 = vec2(light.projection[2][3], light.projection[3][3]); + let frag_zw = vec2(-major_axis_magnitude, 1.0); + let z = dot(projection_cols23_row2, frag_zw); + let w = dot(projection_cols23_row3, frag_zw); + + // For perspective_rh: + // let proj_r = light.far / (light.near - light.far); + // let z = -major_axis_magnitude * proj_r + light.near * proj_r; + // let w = major_axis_magnitude; + + // For perspective_infinite_reverse_rh: + // let z = light.near; + // let w = major_axis_magnitude; - // alternatively do only the necessary multiplications using near/far - let proj_r = light.far / (light.near - light.far); - let z = -major_axis_magnitude * proj_r + light.near * proj_r; - let w = major_axis_magnitude; let depth = z / w; // do the lookup, using HW PCF and comparison @@ -526,7 +537,7 @@ fn fragment(in: FragmentInput) -> [[location(0)]] vec4 { V = normalize(view.world_position.xyz - in.world_position.xyz); } else { // Ortho view vec - V = normalize(vec3(-view.view_proj.x.z, -view.view_proj.y.z, -view.view_proj.z.z)); + V = normalize(vec3(view.view_proj.x.z, view.view_proj.y.z, view.view_proj.z.z)); } // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886" diff --git a/pipelined/bevy_render2/src/camera/projection.rs b/pipelined/bevy_render2/src/camera/projection.rs index 61a0870458c6e..fabfd2134ecaf 100644 --- a/pipelined/bevy_render2/src/camera/projection.rs +++ b/pipelined/bevy_render2/src/camera/projection.rs @@ -21,7 +21,7 @@ pub struct PerspectiveProjection { impl CameraProjection for PerspectiveProjection { fn get_projection_matrix(&self) -> Mat4 { - Mat4::perspective_rh(self.fov, self.aspect_ratio, self.near, self.far) + Mat4::perspective_infinite_reverse_rh(self.fov, self.aspect_ratio, self.near) } fn update(&mut self, width: f32, height: f32) { @@ -88,8 +88,10 @@ impl CameraProjection for OrthographicProjection { self.right * self.scale, self.bottom * self.scale, self.top * self.scale, - self.near, + // NOTE: near and far are swapped to invert the depth range from [0,1] to [1,0] + // This is for interoperability with pipelines using infinite reverse perspective projections. self.far, + self.near, ) } From b4d4defe11ff55512e323c50fbd95faffaf0bf28 Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Sun, 25 Jul 2021 13:35:52 +0200 Subject: [PATCH 23/30] Add the orthographic_pipelined example --- Cargo.toml | 4 ++ examples/3d/orthographic_pipelined.rs | 71 +++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 examples/3d/orthographic_pipelined.rs diff --git a/Cargo.toml b/Cargo.toml index 0fccee6aac6be..93d0f69c90778 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -179,6 +179,10 @@ path = "examples/3d/msaa.rs" name = "orthographic" path = "examples/3d/orthographic.rs" +[[example]] +name = "orthographic_pipelined" +path = "examples/3d/orthographic_pipelined.rs" + [[example]] name = "parenting" path = "examples/3d/parenting.rs" diff --git a/examples/3d/orthographic_pipelined.rs b/examples/3d/orthographic_pipelined.rs new file mode 100644 index 0000000000000..31f80170bb4b0 --- /dev/null +++ b/examples/3d/orthographic_pipelined.rs @@ -0,0 +1,71 @@ +use bevy::{ + ecs::prelude::*, + math::Vec3, + pbr2::{PbrBundle, PointLightBundle, StandardMaterial}, + prelude::{App, Assets, Transform}, + render2::{ + camera::OrthographicCameraBundle, + color::Color, + mesh::{shape, Mesh}, + }, + PipelinedDefaultPlugins, +}; + +fn main() { + App::new() + .add_plugins(PipelinedDefaultPlugins) + .add_startup_system(setup.system()) + .run(); +} + +/// set up a simple 3D scene +fn setup( + mut commands: Commands, + mut meshes: ResMut>, + mut materials: ResMut>, +) { + // set up the camera + let mut camera = OrthographicCameraBundle::new_3d(); + camera.orthographic_projection.scale = 3.0; + camera.transform = Transform::from_xyz(5.0, 5.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y); + + // camera + commands.spawn_bundle(camera); + + // plane + commands.spawn_bundle(PbrBundle { + mesh: meshes.add(Mesh::from(shape::Plane { size: 5.0 })), + material: materials.add(Color::rgb(0.3, 0.5, 0.3).into()), + ..Default::default() + }); + // cubes + commands.spawn_bundle(PbrBundle { + mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })), + material: materials.add(Color::rgb(0.8, 0.7, 0.6).into()), + transform: Transform::from_xyz(1.5, 0.5, 1.5), + ..Default::default() + }); + commands.spawn_bundle(PbrBundle { + mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })), + material: materials.add(Color::rgb(0.8, 0.7, 0.6).into()), + transform: Transform::from_xyz(1.5, 0.5, -1.5), + ..Default::default() + }); + commands.spawn_bundle(PbrBundle { + mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })), + material: materials.add(Color::rgb(0.8, 0.7, 0.6).into()), + transform: Transform::from_xyz(-1.5, 0.5, 1.5), + ..Default::default() + }); + commands.spawn_bundle(PbrBundle { + mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })), + material: materials.add(Color::rgb(0.8, 0.7, 0.6).into()), + transform: Transform::from_xyz(-1.5, 0.5, -1.5), + ..Default::default() + }); + // light + commands.spawn_bundle(PointLightBundle { + transform: Transform::from_xyz(3.0, 8.0, 5.0), + ..Default::default() + }); +} From a41cc5fecb72a1fc901ecf7941131a7b263a8959 Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Mon, 23 Aug 2021 06:54:25 +0200 Subject: [PATCH 24/30] bevy_render2/_pbr2/_sprite2: Add useful matrices to view and mesh uniforms view, inverse view, projection, and inverse projection are commonly-used matrices from the view. model and inverse transpose model are commonly-used matrices for meshes. --- pipelined/bevy_pbr2/src/render/light.rs | 2 +- pipelined/bevy_pbr2/src/render/mod.rs | 10 +++++++--- pipelined/bevy_pbr2/src/render/pbr.wgsl | 5 +++++ pipelined/bevy_render2/src/view/mod.rs | 14 +++++++++++++- pipelined/bevy_sprite2/src/render/mod.rs | 4 +++- 5 files changed, 29 insertions(+), 6 deletions(-) diff --git a/pipelined/bevy_pbr2/src/render/light.rs b/pipelined/bevy_pbr2/src/render/light.rs index 04a81acfe1d1e..2d30d1a9bb8a4 100644 --- a/pipelined/bevy_pbr2/src/render/light.rs +++ b/pipelined/bevy_pbr2/src/render/light.rs @@ -120,7 +120,7 @@ impl FromWorld for ShadowShaders { has_dynamic_offset: true, // TODO: change this to ViewUniform::std140_size_static once crevice fixes this! // Context: https://github.com/LPGhatguy/crevice/issues/29 - min_binding_size: BufferSize::new(80), + min_binding_size: BufferSize::new(336), }, count: None, }, diff --git a/pipelined/bevy_pbr2/src/render/mod.rs b/pipelined/bevy_pbr2/src/render/mod.rs index f5dd75c304ca0..d52031c054b7f 100644 --- a/pipelined/bevy_pbr2/src/render/mod.rs +++ b/pipelined/bevy_pbr2/src/render/mod.rs @@ -53,7 +53,7 @@ impl FromWorld for PbrShaders { has_dynamic_offset: true, // TODO: change this to ViewUniform::std140_size_static once crevice fixes this! // Context: https://github.com/LPGhatguy/crevice/issues/29 - min_binding_size: BufferSize::new(80), + min_binding_size: BufferSize::new(336), }, count: None, }, @@ -225,7 +225,7 @@ impl FromWorld for PbrShaders { ty: BindingType::Buffer { ty: BufferBindingType::Uniform, has_dynamic_offset: true, - min_binding_size: BufferSize::new(80), + min_binding_size: BufferSize::new(144), }, count: None, }], @@ -455,6 +455,7 @@ struct MeshDrawInfo { #[derive(Debug, AsStd140)] pub struct MeshUniform { model: Mat4, + inverse_transpose_model: Mat4, flags: u32, } @@ -486,13 +487,16 @@ pub fn prepare_meshes( .transform_uniforms .reserve_and_clear(extracted_meshes.meshes.len(), &render_device); for extracted_mesh in extracted_meshes.meshes.iter_mut() { + let model = extracted_mesh.transform; + let inverse_transpose_model = model.inverse().transpose(); let flags = if extracted_mesh.receives_shadows { MeshFlags::SHADOW_RECEIVER } else { MeshFlags::NONE }; extracted_mesh.transform_binding_offset = mesh_meta.transform_uniforms.push(MeshUniform { - model: extracted_mesh.transform, + model, + inverse_transpose_model, flags: flags.bits, }); } diff --git a/pipelined/bevy_pbr2/src/render/pbr.wgsl b/pipelined/bevy_pbr2/src/render/pbr.wgsl index df0da250c546a..53ea8891e4d30 100644 --- a/pipelined/bevy_pbr2/src/render/pbr.wgsl +++ b/pipelined/bevy_pbr2/src/render/pbr.wgsl @@ -2,6 +2,10 @@ [[block]] struct View { view_proj: mat4x4; + view: mat4x4; + inverse_view: mat4x4; + projection: mat4x4; + inverse_projection: mat4x4; world_position: vec3; }; @@ -9,6 +13,7 @@ struct View { [[block]] struct Mesh { model: mat4x4; + inverse_transpose_model: mat4x4; // 'flags' is a bit field indicating various options. u32 is 32 bits so we have up to 32 options. flags: u32; }; diff --git a/pipelined/bevy_render2/src/view/mod.rs b/pipelined/bevy_render2/src/view/mod.rs index e00a3bdcdc5bc..bba907fdbb8e7 100644 --- a/pipelined/bevy_render2/src/view/mod.rs +++ b/pipelined/bevy_render2/src/view/mod.rs @@ -42,6 +42,10 @@ pub struct ExtractedView { #[derive(Clone, AsStd140)] pub struct ViewUniform { view_proj: Mat4, + view: Mat4, + inverse_view: Mat4, + projection: Mat4, + inverse_projection: Mat4, world_position: Vec3, } @@ -64,9 +68,17 @@ fn prepare_views( .uniforms .reserve_and_clear(extracted_views.iter_mut().len(), &render_resources); for (entity, camera) in extracted_views.iter() { + let view = camera.transform.compute_matrix(); + let inverse_view = view.inverse(); + let projection = camera.projection; + let inverse_projection = projection.inverse(); let view_uniforms = ViewUniformOffset { offset: view_meta.uniforms.push(ViewUniform { - view_proj: camera.projection * camera.transform.compute_matrix().inverse(), + view_proj: projection * inverse_view, + view, + inverse_view, + projection, + inverse_projection, world_position: camera.transform.translation, }), }; diff --git a/pipelined/bevy_sprite2/src/render/mod.rs b/pipelined/bevy_sprite2/src/render/mod.rs index 31a9d0cd66bc4..50569f3eb8dc2 100644 --- a/pipelined/bevy_sprite2/src/render/mod.rs +++ b/pipelined/bevy_sprite2/src/render/mod.rs @@ -42,7 +42,9 @@ impl FromWorld for SpriteShaders { ty: BindingType::Buffer { ty: BufferBindingType::Uniform, has_dynamic_offset: true, - min_binding_size: BufferSize::new(std::mem::size_of::() as u64), + // TODO: change this to ViewUniform::std140_size_static once crevice fixes this! + // Context: https://github.com/LPGhatguy/crevice/issues/29 + min_binding_size: BufferSize::new(336), }, count: None, }], From 17a7f99896c6ef5893771d144b917efb6fe6b816 Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Mon, 23 Aug 2021 06:55:37 +0200 Subject: [PATCH 25/30] bevy_pbr2: Fix transformation of normals Normals should be transformed by the inverse transpose of the model matrix to correctly transform their scale. --- pipelined/bevy_pbr2/src/render/pbr.wgsl | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/pipelined/bevy_pbr2/src/render/pbr.wgsl b/pipelined/bevy_pbr2/src/render/pbr.wgsl index 53ea8891e4d30..8cd284b06901a 100644 --- a/pipelined/bevy_pbr2/src/render/pbr.wgsl +++ b/pipelined/bevy_pbr2/src/render/pbr.wgsl @@ -46,9 +46,11 @@ fn vertex(vertex: Vertex) -> VertexOutput { out.uv = vertex.uv; out.world_position = world_position; out.clip_position = view.view_proj * world_position; - // FIXME: The inverse transpose of the model matrix should be used to correctly handle scaling - // of normals - out.world_normal = mat3x3(mesh.model.x.xyz, mesh.model.y.xyz, mesh.model.z.xyz) * vertex.normal; + out.world_normal = mat3x3( + mesh.inverse_transpose_model.x.xyz, + mesh.inverse_transpose_model.y.xyz, + mesh.inverse_transpose_model.z.xyz + ) * vertex.normal; return out; } From 546d7b9a7d0b36f2e66aa9bd6cbb156c4d7c49cf Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Mon, 23 Aug 2021 06:57:13 +0200 Subject: [PATCH 26/30] bevy_pbr2: Correct detection of an orthographic projection A projection is not orthographic if the view projection matrix bottom-right element is 1.0, rather if the projection matrix bottom-right value is 1.0. Now the projection matrix is bound, this fix is possible. --- pipelined/bevy_pbr2/src/render/pbr.wgsl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pipelined/bevy_pbr2/src/render/pbr.wgsl b/pipelined/bevy_pbr2/src/render/pbr.wgsl index 8cd284b06901a..c111ce24984cd 100644 --- a/pipelined/bevy_pbr2/src/render/pbr.wgsl +++ b/pipelined/bevy_pbr2/src/render/pbr.wgsl @@ -539,7 +539,7 @@ fn fragment(in: FragmentInput) -> [[location(0)]] vec4 { // # endif var V: vec3; - if (view.view_proj.w.w != 1.0) { // If the projection is not orthographic + if (view.projection.w.w != 1.0) { // If the projection is not orthographic // Only valid for a perpective projection V = normalize(view.world_position.xyz - in.world_position.xyz); } else { From dc9e5018fce5a8201a0a7570d7a7a654aedbbd8e Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Mon, 23 Aug 2021 06:59:49 +0200 Subject: [PATCH 27/30] examples/README.md: Add orthographic_pipelined --- examples/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/README.md b/examples/README.md index c0343a9016db7..c718f32547fd9 100644 --- a/examples/README.md +++ b/examples/README.md @@ -103,6 +103,7 @@ Example | File | Description `load_gltf_pipelined` | [`3d/load_gltf_pipelined.rs`](./3d/load_gltf_pipelined.rs) | Loads and renders a gltf file as a scene `msaa` | [`3d/msaa.rs`](./3d/msaa.rs) | Configures MSAA (Multi-Sample Anti-Aliasing) for smoother edges `orthographic` | [`3d/orthographic.rs`](./3d/orthographic.rs) | Shows how to create a 3D orthographic view (for isometric-look games or CAD applications) +`orthographic_pipelined` | [`3d/orthographic_pipelined.rs`](./3d/orthographic_pipelined.rs) | Shows how to create a 3D orthographic view (for isometric-look games or CAD applications) `parenting` | [`3d/parenting.rs`](./3d/parenting.rs) | Demonstrates parent->child relationships and relative transformations `pbr` | [`3d/pbr.rs`](./3d/pbr.rs) | Demonstrates use of Physically Based Rendering (PBR) properties `pbr_pipelined` | [`3d/pbr_pipelined.rs`](./3d/pbr_pipelined.rs) | Demonstrates use of Physically Based Rendering (PBR) properties From 0ab73d822d5cd040abe1fa139d860b7a91989618 Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Thu, 26 Aug 2021 11:34:03 +0200 Subject: [PATCH 28/30] bevy_pbr2: Minor simplification of the point light projection code --- pipelined/bevy_pbr2/src/render/pbr.wgsl | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/pipelined/bevy_pbr2/src/render/pbr.wgsl b/pipelined/bevy_pbr2/src/render/pbr.wgsl index c111ce24984cd..98edf0ce46d1b 100644 --- a/pipelined/bevy_pbr2/src/render/pbr.wgsl +++ b/pipelined/bevy_pbr2/src/render/pbr.wgsl @@ -419,11 +419,8 @@ fn fetch_point_shadow(light_id: i32, frag_position: vec4, surface_normal: v // projection * vec4(0, 0, -major_axis_magnitude, 1.0) // and keeping only the terms that have any impact on the depth. // Projection-agnostic approach: - let projection_cols23_row2 = vec2(light.projection[2][2], light.projection[3][2]); - let projection_cols23_row3 = vec2(light.projection[2][3], light.projection[3][3]); - let frag_zw = vec2(-major_axis_magnitude, 1.0); - let z = dot(projection_cols23_row2, frag_zw); - let w = dot(projection_cols23_row3, frag_zw); + let z = -major_axis_magnitude * light.projection[2][2] + light.projection[3][2]; + let w = -major_axis_magnitude * light.projection[2][3] + light.projection[3][3]; // For perspective_rh: // let proj_r = light.far / (light.near - light.far); From cf8a4ffc23bd750539d00741c71c15d08eb8ffd6 Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Thu, 26 Aug 2021 11:40:25 +0200 Subject: [PATCH 29/30] bevy_pbr2: Cleanup --- pipelined/bevy_pbr2/src/render/depth.wgsl | 4 ++-- pipelined/bevy_pbr2/src/render/mod.rs | 2 ++ pipelined/bevy_sprite2/src/render/mod.rs | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/pipelined/bevy_pbr2/src/render/depth.wgsl b/pipelined/bevy_pbr2/src/render/depth.wgsl index 9313118d16f1d..b8bb0eec23948 100644 --- a/pipelined/bevy_pbr2/src/render/depth.wgsl +++ b/pipelined/bevy_pbr2/src/render/depth.wgsl @@ -9,7 +9,7 @@ var view: View; [[block]] struct Mesh { - transform: mat4x4; + model: mat4x4; }; [[group(1), binding(0)]] var mesh: Mesh; @@ -25,6 +25,6 @@ struct VertexOutput { [[stage(vertex)]] fn vertex(vertex: Vertex) -> VertexOutput { var out: VertexOutput; - out.clip_position = view.view_proj * mesh.transform * vec4(vertex.position, 1.0); + out.clip_position = view.view_proj * mesh.model * vec4(vertex.position, 1.0); return out; } diff --git a/pipelined/bevy_pbr2/src/render/mod.rs b/pipelined/bevy_pbr2/src/render/mod.rs index d52031c054b7f..f2009b145a36a 100644 --- a/pipelined/bevy_pbr2/src/render/mod.rs +++ b/pipelined/bevy_pbr2/src/render/mod.rs @@ -225,6 +225,8 @@ impl FromWorld for PbrShaders { ty: BindingType::Buffer { ty: BufferBindingType::Uniform, has_dynamic_offset: true, + // TODO: change this to MeshUniform::std140_size_static once crevice fixes this! + // Context: https://github.com/LPGhatguy/crevice/issues/29 min_binding_size: BufferSize::new(144), }, count: None, diff --git a/pipelined/bevy_sprite2/src/render/mod.rs b/pipelined/bevy_sprite2/src/render/mod.rs index 50569f3eb8dc2..5455eb1bb57b7 100644 --- a/pipelined/bevy_sprite2/src/render/mod.rs +++ b/pipelined/bevy_sprite2/src/render/mod.rs @@ -15,7 +15,7 @@ use bevy_render2::{ renderer::{RenderContext, RenderDevice}, shader::Shader, texture::{BevyDefault, Image}, - view::{ViewMeta, ViewUniform, ViewUniformOffset}, + view::{ViewMeta, ViewUniformOffset}, RenderWorld, }; use bevy_transform::components::GlobalTransform; From 2ee8f3203c22f5f6b5eb8e67dc8ec2301abd5834 Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Thu, 26 Aug 2021 21:12:42 +0200 Subject: [PATCH 30/30] bevy_*2: Remove unnecessary ViewUniform members --- pipelined/bevy_pbr2/src/render/depth.wgsl | 2 ++ pipelined/bevy_pbr2/src/render/light.rs | 2 +- pipelined/bevy_pbr2/src/render/mod.rs | 2 +- pipelined/bevy_pbr2/src/render/pbr.wgsl | 4 +--- pipelined/bevy_render2/src/view/mod.rs | 11 +---------- pipelined/bevy_sprite2/src/render/mod.rs | 2 +- 6 files changed, 7 insertions(+), 16 deletions(-) diff --git a/pipelined/bevy_pbr2/src/render/depth.wgsl b/pipelined/bevy_pbr2/src/render/depth.wgsl index b8bb0eec23948..36367c1b9c23d 100644 --- a/pipelined/bevy_pbr2/src/render/depth.wgsl +++ b/pipelined/bevy_pbr2/src/render/depth.wgsl @@ -1,6 +1,8 @@ +// NOTE: Keep in sync with pbr.wgsl [[block]] struct View { view_proj: mat4x4; + projection: mat4x4; world_position: vec3; }; [[group(0), binding(0)]] diff --git a/pipelined/bevy_pbr2/src/render/light.rs b/pipelined/bevy_pbr2/src/render/light.rs index 2d30d1a9bb8a4..fb45a1f2b132a 100644 --- a/pipelined/bevy_pbr2/src/render/light.rs +++ b/pipelined/bevy_pbr2/src/render/light.rs @@ -120,7 +120,7 @@ impl FromWorld for ShadowShaders { has_dynamic_offset: true, // TODO: change this to ViewUniform::std140_size_static once crevice fixes this! // Context: https://github.com/LPGhatguy/crevice/issues/29 - min_binding_size: BufferSize::new(336), + min_binding_size: BufferSize::new(144), }, count: None, }, diff --git a/pipelined/bevy_pbr2/src/render/mod.rs b/pipelined/bevy_pbr2/src/render/mod.rs index f2009b145a36a..47d75c5ad6e15 100644 --- a/pipelined/bevy_pbr2/src/render/mod.rs +++ b/pipelined/bevy_pbr2/src/render/mod.rs @@ -53,7 +53,7 @@ impl FromWorld for PbrShaders { has_dynamic_offset: true, // TODO: change this to ViewUniform::std140_size_static once crevice fixes this! // Context: https://github.com/LPGhatguy/crevice/issues/29 - min_binding_size: BufferSize::new(336), + min_binding_size: BufferSize::new(144), }, count: None, }, diff --git a/pipelined/bevy_pbr2/src/render/pbr.wgsl b/pipelined/bevy_pbr2/src/render/pbr.wgsl index 98edf0ce46d1b..5532a5bb1fde3 100644 --- a/pipelined/bevy_pbr2/src/render/pbr.wgsl +++ b/pipelined/bevy_pbr2/src/render/pbr.wgsl @@ -1,11 +1,9 @@ // TODO: try merging this block with the binding? +// NOTE: Keep in sync with depth.wgsl [[block]] struct View { view_proj: mat4x4; - view: mat4x4; - inverse_view: mat4x4; projection: mat4x4; - inverse_projection: mat4x4; world_position: vec3; }; diff --git a/pipelined/bevy_render2/src/view/mod.rs b/pipelined/bevy_render2/src/view/mod.rs index bba907fdbb8e7..d4d02cf35ef06 100644 --- a/pipelined/bevy_render2/src/view/mod.rs +++ b/pipelined/bevy_render2/src/view/mod.rs @@ -42,10 +42,7 @@ pub struct ExtractedView { #[derive(Clone, AsStd140)] pub struct ViewUniform { view_proj: Mat4, - view: Mat4, - inverse_view: Mat4, projection: Mat4, - inverse_projection: Mat4, world_position: Vec3, } @@ -68,17 +65,11 @@ fn prepare_views( .uniforms .reserve_and_clear(extracted_views.iter_mut().len(), &render_resources); for (entity, camera) in extracted_views.iter() { - let view = camera.transform.compute_matrix(); - let inverse_view = view.inverse(); let projection = camera.projection; - let inverse_projection = projection.inverse(); let view_uniforms = ViewUniformOffset { offset: view_meta.uniforms.push(ViewUniform { - view_proj: projection * inverse_view, - view, - inverse_view, + view_proj: projection * camera.transform.compute_matrix().inverse(), projection, - inverse_projection, world_position: camera.transform.translation, }), }; diff --git a/pipelined/bevy_sprite2/src/render/mod.rs b/pipelined/bevy_sprite2/src/render/mod.rs index 5455eb1bb57b7..e99474d552ca6 100644 --- a/pipelined/bevy_sprite2/src/render/mod.rs +++ b/pipelined/bevy_sprite2/src/render/mod.rs @@ -44,7 +44,7 @@ impl FromWorld for SpriteShaders { has_dynamic_offset: true, // TODO: change this to ViewUniform::std140_size_static once crevice fixes this! // Context: https://github.com/LPGhatguy/crevice/issues/29 - min_binding_size: BufferSize::new(336), + min_binding_size: BufferSize::new(144), }, count: None, }],