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/Cargo.toml b/Cargo.toml index 476fa13047cc5..93d0f69c90778 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,9 +22,10 @@ members = ["crates/*", "pipelined/*", "examples/ios", "tools/ci"] [features] default = [ "bevy_audio", + "bevy_core_pipeline", "bevy_dynamic_plugin", "bevy_gilrs", - "bevy_gltf", + "bevy_gltf2", "bevy_wgpu", "bevy_sprite2", "bevy_render2", @@ -41,7 +42,13 @@ default = [ dynamic = ["bevy_dylib"] # Rendering support (Also needs the bevy_wgpu feature or a third-party rendering backend) -render = ["bevy_internal/bevy_pbr", "bevy_internal/bevy_render", "bevy_internal/bevy_sprite", "bevy_internal/bevy_text", "bevy_internal/bevy_ui"] +render = [ + "bevy_internal/bevy_pbr", + "bevy_internal/bevy_render", + "bevy_internal/bevy_sprite", + "bevy_internal/bevy_text", + "bevy_internal/bevy_ui", +] # Optional bevy crates bevy_audio = ["bevy_internal/bevy_audio"] @@ -51,9 +58,11 @@ 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"] +bevy_gltf2 = ["bevy_internal/bevy_gltf2"] trace_chrome = ["bevy_internal/trace_chrome"] trace = ["bevy_internal/trace"] @@ -89,14 +98,14 @@ subpixel_glyph_atlas = ["bevy_internal/subpixel_glyph_atlas"] bevy_ci_testing = ["bevy_internal/bevy_ci_testing"] [dependencies] -bevy_dylib = {path = "crates/bevy_dylib", version = "0.5.0", default-features = false, optional = true} -bevy_internal = {path = "crates/bevy_internal", version = "0.5.0", default-features = false} +bevy_dylib = { path = "crates/bevy_dylib", version = "0.5.0", default-features = false, optional = true } +bevy_internal = { path = "crates/bevy_internal", version = "0.5.0", default-features = false } [dev-dependencies] anyhow = "1.0.4" rand = "0.8.0" ron = "0.6.2" -serde = {version = "1", features = ["derive"]} +serde = { version = "1", features = ["derive"] } # Needed to poll Task examples futures-lite = "1.11.3" @@ -137,6 +146,10 @@ path = "examples/2d/text2d.rs" name = "texture_atlas" path = "examples/2d/texture_atlas.rs" +[[example]] +name = "pipelined_texture_atlas" +path = "examples/2d/pipelined_texture_atlas.rs" + # 3D Rendering [[example]] name = "3d_scene" @@ -154,6 +167,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" @@ -162,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" @@ -182,6 +203,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" @@ -476,6 +501,10 @@ path = "examples/ui/ui.rs" name = "clear_color" path = "examples/window/clear_color.rs" +[[example]] +name = "clear_color_pipelined" +path = "examples/window/clear_color_pipelined.rs" + [[example]] name = "multiple_windows" path = "examples/window/multiple_windows.rs" diff --git a/crates/bevy_app/src/app.rs b/crates/bevy_app/src/app.rs index f27f60699ff16..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}, @@ -7,12 +9,14 @@ use bevy_ecs::{ }, world::World, }; -use bevy_utils::tracing::debug; +use bevy_utils::{tracing::debug, HashMap}; use std::{fmt::Debug, hash::Hash}; #[cfg(feature = "trace")] use bevy_utils::tracing::info_span; +bevy_utils::define_label!(AppLabel); + #[allow(clippy::needless_doctest_main)] /// Containers of app logic and data /// @@ -40,7 +44,7 @@ pub struct App { pub world: World, pub runner: Box, pub schedule: Schedule, - sub_apps: Vec, + sub_apps: HashMap, SubApp>, } struct SubApp { @@ -77,7 +81,7 @@ impl App { world: Default::default(), schedule: Default::default(), runner: Box::new(run_once), - sub_apps: Vec::new(), + sub_apps: HashMap::default(), } } @@ -87,7 +91,7 @@ impl App { #[cfg(feature = "trace")] let _bevy_frame_update_guard = bevy_frame_update_span.enter(); self.schedule.run(&mut self.world); - for sub_app in self.sub_apps.iter_mut() { + for sub_app in self.sub_apps.values_mut() { (sub_app.runner)(&mut self.world, &mut sub_app.app); } } @@ -544,7 +548,7 @@ impl App { /// # /// # struct MyOwnPlugin; /// # impl Plugin for MyOwnPlugin { - /// # fn build(&self, app: &mut AppBuilder){;} + /// # fn build(&self, app: &mut App) { } /// # } /// # /// App::new() @@ -589,19 +593,35 @@ impl App { pub fn add_sub_app( &mut self, + label: impl AppLabel, app: App, f: impl Fn(&mut World, &mut App) + 'static, ) -> &mut Self { - self.sub_apps.push(SubApp { - app, - runner: Box::new(f), - }); + self.sub_apps.insert( + Box::new(label), + SubApp { + app, + runner: Box::new(f), + }, + ); self } - // TODO: use labels instead of indices - pub fn sub_app_mut(&mut self, index: usize) -> &mut App { - &mut self.sub_apps[index].app + /// 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) as &dyn AppLabel) + .map(|sub_app| &mut sub_app.app) + .ok_or(label) } } diff --git a/crates/bevy_asset/src/asset_server.rs b/crates/bevy_asset/src/asset_server.rs index d5a331909de34..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() @@ -478,7 +475,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_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/crates/bevy_ecs/macros/Cargo.toml b/crates/bevy_ecs/macros/Cargo.toml index b6617e54ee41c..78f882dead7d4 100644 --- a/crates/bevy_ecs/macros/Cargo.toml +++ b/crates/bevy_ecs/macros/Cargo.toml @@ -2,10 +2,6 @@ name = "bevy_ecs_macros" version = "0.5.0" description = "Bevy ECS Macros" -authors = [ - "Bevy Contributors ", - "Carter Anderson ", -] edition = "2018" license = "MIT OR Apache-2.0" diff --git a/crates/bevy_ecs/macros/src/lib.rs b/crates/bevy_ecs/macros/src/lib.rs index 21c2feabaa05f..cc88f89ddcf55 100644 --- a/crates/bevy_ecs/macros/src/lib.rs +++ b/crates/bevy_ecs/macros/src/lib.rs @@ -1,8 +1,8 @@ extern crate proc_macro; -use bevy_macro_utils::BevyManifest; +use bevy_macro_utils::{derive_label, BevyManifest}; use proc_macro::TokenStream; -use proc_macro2::{Span, TokenStream as TokenStream2}; +use proc_macro2::Span; use quote::{format_ident, quote}; use syn::{ parse::{Parse, ParseStream}, @@ -10,7 +10,7 @@ use syn::{ punctuated::Punctuated, token::Comma, Data, DataStruct, DeriveInput, Field, Fields, GenericParam, Ident, Index, Lifetime, LitInt, - Path, Result, Token, + Result, Token, }; struct AllTuples { @@ -436,46 +436,43 @@ pub fn derive_system_param(input: TokenStream) -> TokenStream { #[proc_macro_derive(SystemLabel)] pub fn derive_system_label(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); - - derive_label(input, Ident::new("SystemLabel", Span::call_site())).into() + let mut trait_path = bevy_ecs_path(); + trait_path.segments.push(format_ident!("schedule").into()); + trait_path + .segments + .push(format_ident!("SystemLabel").into()); + derive_label(input, trait_path) } #[proc_macro_derive(StageLabel)] pub fn derive_stage_label(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); - derive_label(input, Ident::new("StageLabel", Span::call_site())).into() + let mut trait_path = bevy_ecs_path(); + trait_path.segments.push(format_ident!("schedule").into()); + trait_path.segments.push(format_ident!("StageLabel").into()); + derive_label(input, trait_path) } #[proc_macro_derive(AmbiguitySetLabel)] pub fn derive_ambiguity_set_label(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); - derive_label(input, Ident::new("AmbiguitySetLabel", Span::call_site())).into() + let mut trait_path = bevy_ecs_path(); + trait_path.segments.push(format_ident!("schedule").into()); + trait_path + .segments + .push(format_ident!("AmbiguitySetLabel").into()); + derive_label(input, trait_path) } #[proc_macro_derive(RunCriteriaLabel)] pub fn derive_run_criteria_label(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); - derive_label(input, Ident::new("RunCriteriaLabel", Span::call_site())).into() -} - -fn derive_label(input: DeriveInput, label_type: Ident) -> TokenStream2 { - let ident = input.ident; - let ecs_path: Path = bevy_ecs_path(); - - let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); - let mut where_clause = where_clause.cloned().unwrap_or_else(|| syn::WhereClause { - where_token: Default::default(), - predicates: Default::default(), - }); - where_clause.predicates.push(syn::parse2(quote! { Self: Eq + ::std::fmt::Debug + ::std::hash::Hash + Clone + Send + Sync + 'static }).unwrap()); - - quote! { - impl #impl_generics #ecs_path::schedule::#label_type for #ident #ty_generics #where_clause { - fn dyn_clone(&self) -> Box { - Box::new(Clone::clone(self)) - } - } - } + let mut trait_path = bevy_ecs_path(); + trait_path.segments.push(format_ident!("schedule").into()); + trait_path + .segments + .push(format_ident!("RunCriteriaLabel").into()); + derive_label(input, trait_path) } fn bevy_ecs_path() -> syn::Path { 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/schedule/label.rs b/crates/bevy_ecs/src/schedule/label.rs index a7f3538741242..ed9398426e4f8 100644 --- a/crates/bevy_ecs/src/schedule/label.rs +++ b/crates/bevy_ecs/src/schedule/label.rs @@ -1,115 +1,15 @@ pub use bevy_ecs_macros::{AmbiguitySetLabel, RunCriteriaLabel, StageLabel, SystemLabel}; -use std::{ - any::Any, - borrow::Cow, - fmt::Debug, - hash::{Hash, Hasher}, -}; +use bevy_utils::define_label; -pub trait DynEq: Any { - fn as_any(&self) -> &dyn Any; - - fn dyn_eq(&self, other: &dyn DynEq) -> bool; -} - -impl DynEq for T -where - T: Any + Eq, -{ - fn as_any(&self) -> &dyn Any { - self - } - - fn dyn_eq(&self, other: &dyn DynEq) -> bool { - if let Some(other) = other.as_any().downcast_ref::() { - return self == other; - } - false - } -} - -pub trait DynHash: DynEq { - fn as_dyn_eq(&self) -> &dyn DynEq; - - fn dyn_hash(&self, state: &mut dyn Hasher); -} - -impl DynHash for T -where - T: DynEq + Hash, -{ - fn as_dyn_eq(&self) -> &dyn DynEq { - self - } - - fn dyn_hash(&self, mut state: &mut dyn Hasher) { - T::hash(self, &mut state); - self.type_id().hash(&mut state); - } -} - -pub trait StageLabel: DynHash + Debug + Send + Sync + 'static { - #[doc(hidden)] - fn dyn_clone(&self) -> Box; -} +define_label!(StageLabel); pub(crate) type BoxedStageLabel = Box; -pub trait SystemLabel: DynHash + Debug + Send + Sync + 'static { - #[doc(hidden)] - fn dyn_clone(&self) -> Box; -} +define_label!(SystemLabel); pub(crate) type BoxedSystemLabel = Box; -pub trait AmbiguitySetLabel: DynHash + Debug + Send + Sync + 'static { - #[doc(hidden)] - fn dyn_clone(&self) -> Box; -} +define_label!(AmbiguitySetLabel); pub(crate) type BoxedAmbiguitySetLabel = Box; -pub trait RunCriteriaLabel: DynHash + Debug + Send + Sync + 'static { - #[doc(hidden)] - fn dyn_clone(&self) -> Box; -} +define_label!(RunCriteriaLabel); pub(crate) type BoxedRunCriteriaLabel = Box; - -macro_rules! impl_label { - ($trait_name:ident) => { - impl PartialEq for dyn $trait_name { - fn eq(&self, other: &Self) -> bool { - self.dyn_eq(other.as_dyn_eq()) - } - } - - impl Eq for dyn $trait_name {} - - impl Hash for dyn $trait_name { - fn hash(&self, state: &mut H) { - self.dyn_hash(state); - } - } - - impl Clone for Box { - fn clone(&self) -> Self { - self.dyn_clone() - } - } - - impl $trait_name for Cow<'static, str> { - fn dyn_clone(&self) -> Box { - Box::new(self.clone()) - } - } - - impl $trait_name for &'static str { - fn dyn_clone(&self) -> Box { - Box::new(<&str>::clone(self)) - } - } - }; -} - -impl_label!(StageLabel); -impl_label!(SystemLabel); -impl_label!(AmbiguitySetLabel); -impl_label!(RunCriteriaLabel); 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/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 6194b0f3dcc58..900017e9cbd1d 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) { @@ -1163,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, @@ -1197,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_internal/Cargo.toml b/crates/bevy_internal/Cargo.toml index b745c40f34fa5..8f7a1d2c2dd9e 100644 --- a/crates/bevy_internal/Cargo.toml +++ b/crates/bevy_internal/Cargo.toml @@ -66,7 +66,9 @@ 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_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 19dac798b0210..27e206d657af8 100644 --- a/crates/bevy_internal/src/default_plugins.rs +++ b/crates/bevy_internal/src/default_plugins.rs @@ -117,20 +117,28 @@ 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")] { 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_gltf2")] + group.add(bevy_gltf2::GltfPlugin::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..932971b6f1046 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::*; @@ -93,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/crates/bevy_macro_utils/Cargo.toml b/crates/bevy_macro_utils/Cargo.toml index 46c8fac2ba468..b92056f642455 100644 --- a/crates/bevy_macro_utils/Cargo.toml +++ b/crates/bevy_macro_utils/Cargo.toml @@ -15,3 +15,4 @@ keywords = ["bevy"] [dependencies] cargo-manifest = "0.2.3" syn = "1.0" +quote = "1.0" diff --git a/crates/bevy_macro_utils/src/lib.rs b/crates/bevy_macro_utils/src/lib.rs index 2933d9d8000d9..2c23461bf8dc1 100644 --- a/crates/bevy_macro_utils/src/lib.rs +++ b/crates/bevy_macro_utils/src/lib.rs @@ -2,6 +2,7 @@ extern crate proc_macro; use cargo_manifest::{DepsSet, Manifest}; use proc_macro::TokenStream; +use quote::quote; use std::{env, path::PathBuf}; pub struct BevyManifest { @@ -59,3 +60,29 @@ fn get_path(path: &str) -> syn::Path { fn parse_str(path: &str) -> T { syn::parse(path.parse::().unwrap()).unwrap() } + +/// Derive a label trait +/// +/// # Args +/// +/// - `input`: The [`syn::DeriveInput`] for struct that is deriving the label trait +/// - `trait_path`: The path [`syn::Path`] to the label trait +pub fn derive_label(input: syn::DeriveInput, trait_path: syn::Path) -> TokenStream { + let ident = input.ident; + + let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); + let mut where_clause = where_clause.cloned().unwrap_or_else(|| syn::WhereClause { + where_token: Default::default(), + predicates: Default::default(), + }); + where_clause.predicates.push(syn::parse2(quote! { Self: Eq + ::std::fmt::Debug + ::std::hash::Hash + Clone + Send + Sync + 'static }).unwrap()); + + (quote! { + impl #impl_generics #trait_path for #ident #ty_generics #where_clause { + fn dyn_clone(&self) -> Box { + Box::new(Clone::clone(self)) + } + } + }) + .into() +} 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_utils/src/label.rs b/crates/bevy_utils/src/label.rs new file mode 100644 index 0000000000000..ed759f6a59886 --- /dev/null +++ b/crates/bevy_utils/src/label.rs @@ -0,0 +1,100 @@ +//! Traits used by label implementations + +use std::{ + any::Any, + hash::{Hash, Hasher}, +}; + +pub trait DynEq: Any { + fn as_any(&self) -> &dyn Any; + + fn dyn_eq(&self, other: &dyn DynEq) -> bool; +} + +impl DynEq for T +where + T: Any + Eq, +{ + fn as_any(&self) -> &dyn Any { + self + } + + fn dyn_eq(&self, other: &dyn DynEq) -> bool { + if let Some(other) = other.as_any().downcast_ref::() { + return self == other; + } + false + } +} + +pub trait DynHash: DynEq { + fn as_dyn_eq(&self) -> &dyn DynEq; + + fn dyn_hash(&self, state: &mut dyn Hasher); +} + +impl DynHash for T +where + T: DynEq + Hash, +{ + fn as_dyn_eq(&self) -> &dyn DynEq { + self + } + + fn dyn_hash(&self, mut state: &mut dyn Hasher) { + T::hash(self, &mut state); + self.type_id().hash(&mut state); + } +} + +/// Macro to define a new label trait +/// +/// # Example +/// +/// ``` +/// # use bevy_utils::define_label; +/// define_label!(MyNewLabelTrait); +/// ``` +#[macro_export] +macro_rules! define_label { + ($label_trait_name:ident) => { + pub trait $label_trait_name: + ::bevy_utils::label::DynHash + ::std::fmt::Debug + Send + Sync + 'static + { + #[doc(hidden)] + fn dyn_clone(&self) -> Box; + } + + impl PartialEq for dyn $label_trait_name { + fn eq(&self, other: &Self) -> bool { + self.dyn_eq(other.as_dyn_eq()) + } + } + + impl Eq for dyn $label_trait_name {} + + impl ::std::hash::Hash for dyn $label_trait_name { + fn hash(&self, state: &mut H) { + self.dyn_hash(state); + } + } + + impl Clone for Box { + fn clone(&self) -> Self { + self.dyn_clone() + } + } + + impl $label_trait_name for ::std::borrow::Cow<'static, str> { + fn dyn_clone(&self) -> Box { + Box::new(self.clone()) + } + } + + impl $label_trait_name for &'static str { + fn dyn_clone(&self) -> Box { + Box::new(<&str>::clone(self)) + } + } + }; +} diff --git a/crates/bevy_utils/src/lib.rs b/crates/bevy_utils/src/lib.rs index 57202de29bf4f..c6b5f25359052 100644 --- a/crates/bevy_utils/src/lib.rs +++ b/crates/bevy_utils/src/lib.rs @@ -1,4 +1,5 @@ mod enum_variant_meta; +pub mod label; pub mod slab; pub use ahash::AHasher; 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/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/2d/pipelined_texture_atlas.rs b/examples/2d/pipelined_texture_atlas.rs new file mode 100644 index 0000000000000..a11bad5e7e3ee --- /dev/null +++ b/examples/2d/pipelined_texture_atlas.rs @@ -0,0 +1,94 @@ +use bevy::{ + asset::LoadState, + math::Vec3, + prelude::{ + App, AssetServer, Assets, Commands, HandleUntyped, IntoSystem, Res, ResMut, State, + SystemSet, Transform, + }, + render2::{camera::OrthographicCameraBundle, texture::Image}, + sprite2::{ + PipelinedSpriteBundle, PipelinedSpriteSheetBundle, TextureAtlas, TextureAtlasBuilder, + TextureAtlasSprite, + }, + PipelinedDefaultPlugins, +}; + +/// In this example we generate a new texture atlas (sprite sheet) from a folder containing +/// individual sprites +fn main() { + App::new() + .init_resource::() + .add_plugins(PipelinedDefaultPlugins) + .add_state(AppState::Setup) + .add_system_set(SystemSet::on_enter(AppState::Setup).with_system(load_textures.system())) + .add_system_set(SystemSet::on_update(AppState::Setup).with_system(check_textures.system())) + .add_system_set(SystemSet::on_enter(AppState::Finished).with_system(setup.system())) + .run(); +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum AppState { + Setup, + Finished, +} + +#[derive(Default)] +struct RpgSpriteHandles { + handles: Vec, +} + +fn load_textures(mut rpg_sprite_handles: ResMut, asset_server: Res) { + rpg_sprite_handles.handles = asset_server.load_folder("textures/rpg").unwrap(); +} + +fn check_textures( + mut state: ResMut>, + rpg_sprite_handles: ResMut, + asset_server: Res, +) { + if let LoadState::Loaded = + asset_server.get_group_load_state(rpg_sprite_handles.handles.iter().map(|handle| handle.id)) + { + state.set(AppState::Finished).unwrap(); + } +} + +fn setup( + mut commands: Commands, + rpg_sprite_handles: Res, + asset_server: Res, + mut texture_atlases: ResMut>, + mut textures: ResMut>, +) { + let mut texture_atlas_builder = TextureAtlasBuilder::default(); + for handle in rpg_sprite_handles.handles.iter() { + let texture = textures.get(handle).unwrap(); + texture_atlas_builder.add_texture(handle.clone_weak().typed::(), texture); + } + + let texture_atlas = texture_atlas_builder.finish(&mut textures).unwrap(); + let texture_atlas_texture = texture_atlas.texture.clone(); + let vendor_handle = asset_server.get_handle("textures/rpg/chars/vendor/generic-rpg-vendor.png"); + let vendor_index = texture_atlas.get_texture_index(&vendor_handle).unwrap(); + let atlas_handle = texture_atlases.add(texture_atlas); + + // set up a scene to display our texture atlas + commands.spawn_bundle(OrthographicCameraBundle::new_2d()); + // draw a sprite from the atlas + commands.spawn_bundle(PipelinedSpriteSheetBundle { + transform: Transform { + translation: Vec3::new(150.0, 0.0, 0.0), + scale: Vec3::splat(4.0), + ..Default::default() + }, + sprite: TextureAtlasSprite::new(vendor_index as u32), + texture_atlas: atlas_handle, + ..Default::default() + }); + // draw the atlas itself + commands.spawn_bundle(PipelinedSpriteBundle { + texture: texture_atlas_texture, + transform: Transform::from_xyz(-300.0, 0.0, 0.0), + ..Default::default() + }); +} diff --git a/examples/3d/3d_scene_pipelined.rs b/examples/3d/3d_scene_pipelined.rs index 58cdcedd01fee..d3c25432568fa 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(); } @@ -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,12 +102,19 @@ 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), transform: Transform::from_xyz(1.0, 2.0, 0.0), point_light: PointLight { + intensity: 1600.0, // lumens - roughly a 100W non-halogen incandescent bulb color: Color::RED, ..Default::default() }, @@ -130,12 +135,13 @@ fn setup( }); }); - // light + // green point light commands .spawn_bundle(PointLightBundle { // transform: Transform::from_xyz(5.0, 8.0, 2.0), transform: Transform::from_xyz(-1.0, 2.0, 0.0), point_light: PointLight { + intensity: 1600.0, // lumens - roughly a 100W non-halogen incandescent bulb color: Color::GREEN, ..Default::default() }, @@ -156,12 +162,13 @@ fn setup( }); }); - // light + // blue point light commands .spawn_bundle(PointLightBundle { // transform: Transform::from_xyz(5.0, 8.0, 2.0), transform: Transform::from_xyz(0.0, 4.0, 0.0), point_light: PointLight { + intensity: 1600.0, // lumens - roughly a 100W non-halogen incandescent bulb color: Color::BLUE, ..Default::default() }, @@ -182,6 +189,7 @@ fn setup( }); }); + // directional 'sun' light const HALF_SIZE: f32 = 10.0; commands.spawn_bundle(DirectionalLightBundle { directional_light: DirectionalLight { 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/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