diff --git a/.github/workflows/ci-comment-failures.yml b/.github/workflows/ci-comment-failures.yml index d926390993e28..b631625aaa0c0 100644 --- a/.github/workflows/ci-comment-failures.yml +++ b/.github/workflows/ci-comment-failures.yml @@ -69,7 +69,7 @@ jobs: owner: context.repo.owner, repo: context.repo.repo, issue_number: issue_number, - body: 'The generated `examples/README.md` is out of sync with the example metadata in `Cargo.toml` or the example readme template. Please run `cargo run -p build-templated-pages -- update examples` to update it, and commit the file change.' + body: 'The generated `examples/README.md` is out of sync with the example metadata in `Cargo.toml` or the example readme template. Please run `cargo run -p build-templated-pages -- update examples` to update it. Then, commit and push the file change.' }); } @@ -127,7 +127,7 @@ jobs: owner: context.repo.owner, repo: context.repo.repo, issue_number: issue_number, - body: 'You added a new feature but didn\'t update the readme. Please run `cargo run -p build-templated-pages -- update features` to update it, and commit the file change.' + body: 'You added a new feature but didn\'t update the readme. Please run `cargo run -p build-templated-pages -- update features` to update it. Then, commit and push the file change.' }); } diff --git a/Cargo.toml b/Cargo.toml index 897e751449319..47ee86cda6f38 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1678,7 +1678,7 @@ path = "examples/asset/multi_asset_sync.rs" doc-scrape-examples = true [package.metadata.example.multi_asset_sync] -name = "Mult-asset synchronization" +name = "Multi-asset synchronization" description = "Demonstrates how to wait for multiple assets to be loaded." category = "Assets" wasm = true diff --git a/README.md b/README.md index a8018aa0daad2..645d90d06d3b4 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ If you'd like to help build Bevy, check out the **[Contributor's Guide](https:// For simple problems, feel free to [open an issue](https://github.com/bevyengine/bevy/issues) or [PR](https://github.com/bevyengine/bevy/pulls) and tackle it yourself! -For more complex architecture decisions and experimental mad science, please open an [RFC](https://github.com/bevyengine/rfcs) (Request For Comments) so we can brainstorm together effectively! +For more complex architecture decisions and experimental mad science, please open an [RFC](https://github.com/bevyengine/rfcs) (Request For Comments) so that we can brainstorm together effectively! ## Getting Started diff --git a/assets/shaders/custom_material.frag b/assets/shaders/custom_material.frag index a6bc9af0d2a7d..658e9ba98184e 100644 --- a/assets/shaders/custom_material.frag +++ b/assets/shaders/custom_material.frag @@ -10,9 +10,9 @@ layout(set = 2, binding = 2) uniform sampler CustomMaterial_sampler; // wgsl modules can be imported and used in glsl // FIXME - this doesn't work any more ... -// #import bevy_pbr::pbr_functions as PbrFuncs +// #import bevy_pbr::pbr_functions as PbrFunctions void main() { - // o_Target = PbrFuncs::tone_mapping(Color * texture(sampler2D(CustomMaterial_texture,CustomMaterial_sampler), v_Uv)); + // o_Target = PbrFunctions::tone_mapping(Color * texture(sampler2D(CustomMaterial_texture,CustomMaterial_sampler), v_Uv)); o_Target = CustomMaterial_color * texture(sampler2D(CustomMaterial_texture,CustomMaterial_sampler), v_Uv); } diff --git a/assets/shaders/specialized_mesh_pipeline.wgsl b/assets/shaders/specialized_mesh_pipeline.wgsl index 82b5cea911658..daf9b5d6015b5 100644 --- a/assets/shaders/specialized_mesh_pipeline.wgsl +++ b/assets/shaders/specialized_mesh_pipeline.wgsl @@ -2,7 +2,7 @@ //! between the vertex and fragment shader. Also shows the custom vertex layout. // First we import everything we need from bevy_pbr -// A 2d shader would be vevry similar but import from bevy_sprite instead +// A 2D shader would be very similar but import from bevy_sprite instead #import bevy_pbr::{ mesh_functions, view_transformations::position_world_to_clip @@ -10,7 +10,7 @@ struct Vertex { // This is needed if you are using batching and/or gpu preprocessing - // It's a built in so you don't need to define it in the vertex layout + // It's a built in, so you don't need to define it in the vertex layout @builtin(instance_index) instance_index: u32, // Like we defined for the vertex layout // position is at location 0 @@ -30,7 +30,7 @@ struct VertexOutput { fn vertex(vertex: Vertex) -> VertexOutput { var out: VertexOutput; // This is how bevy computes the world position - // The vertex.instance_index is very important. Esepecially if you are using batching and gpu preprocessing + // The vertex.instance_index is very important, especially if you are using batching and gpu preprocessing var world_from_local = mesh_functions::get_world_from_local(vertex.instance_index); out.world_position = mesh_functions::mesh_position_local_to_world(world_from_local, vec4(vertex.position, 1.0)); out.clip_position = position_world_to_clip(out.world_position.xyz); @@ -45,4 +45,4 @@ fn vertex(vertex: Vertex) -> VertexOutput { fn fragment(in: VertexOutput) -> @location(0) vec4 { // output the color directly return vec4(in.color, 1.0); -} \ No newline at end of file +} diff --git a/assets/shaders/tonemapping_test_patterns.wgsl b/assets/shaders/tonemapping_test_patterns.wgsl index 7fe88bf5485b3..9d545b9e3e325 100644 --- a/assets/shaders/tonemapping_test_patterns.wgsl +++ b/assets/shaders/tonemapping_test_patterns.wgsl @@ -3,25 +3,25 @@ forward_io::VertexOutput, } -#import bevy_render::maths::PI +#import bevy_render::math::PI #ifdef TONEMAP_IN_SHADER #import bevy_core_pipeline::tonemapping::tone_mapping #endif -// Sweep across hues on y axis with value from 0.0 to +15EV across x axis +// Sweep across hues on y axis with value from 0.0 to +15EV across x axis // quantized into 24 steps for both axis. fn color_sweep(uv_input: vec2) -> vec3 { var uv = uv_input; let steps = 24.0; uv.y = uv.y * (1.0 + 1.0 / steps); let ratio = 2.0; - + let h = PI * 2.0 * floor(1.0 + steps * uv.y) / steps; let L = floor(uv.x * steps * ratio) / (steps * ratio) - 0.5; - + var color = vec3(0.0); - if uv.y < 1.0 { + if uv.y < 1.0 { color = cos(h + vec3(0.0, 1.0, 2.0) * PI * 2.0 / 3.0); let maxRGB = max(color.r, max(color.g, color.b)); let minRGB = min(color.r, min(color.g, color.b)); diff --git a/benches/benches/bevy_ecs/scheduling/schedule.rs b/benches/benches/bevy_ecs/scheduling/schedule.rs index 4571899a9b7b5..87fad72e406ed 100644 --- a/benches/benches/bevy_ecs/scheduling/schedule.rs +++ b/benches/benches/bevy_ecs/scheduling/schedule.rs @@ -79,7 +79,7 @@ pub fn build_schedule(criterion: &mut Criterion) { // Benchmark graphs of different sizes. for graph_size in [100, 500, 1000] { // Basic benchmark without constraints. - group.bench_function(format!("{graph_size}_schedule_noconstraints"), |bencher| { + group.bench_function(format!("{graph_size}_schedule_no_constraints"), |bencher| { bencher.iter(|| { let mut app = App::new(); for _ in 0..graph_size { diff --git a/benches/benches/bevy_ecs/world/despawn.rs b/benches/benches/bevy_ecs/world/despawn.rs index ace88e744a482..c78970ead9add 100644 --- a/benches/benches/bevy_ecs/world/despawn.rs +++ b/benches/benches/bevy_ecs/world/despawn.rs @@ -18,10 +18,10 @@ pub fn world_despawn(criterion: &mut Criterion) { world.spawn((A(Mat4::default()), B(Vec4::default()))); } - let ents = world.iter_entities().map(|e| e.id()).collect::>(); + let entities = world.iter_entities().map(|e| e.id()).collect::>(); group.bench_function(format!("{}_entities", entity_count), |bencher| { bencher.iter(|| { - ents.iter().for_each(|e| { + entities.iter().for_each(|e| { world.despawn(*e); }); }); diff --git a/benches/benches/bevy_ecs/world/despawn_recursive.rs b/benches/benches/bevy_ecs/world/despawn_recursive.rs index 482086ab17444..2fef2d00084ec 100644 --- a/benches/benches/bevy_ecs/world/despawn_recursive.rs +++ b/benches/benches/bevy_ecs/world/despawn_recursive.rs @@ -25,10 +25,10 @@ pub fn world_despawn_recursive(criterion: &mut Criterion) { }); } - let ents = world.iter_entities().map(|e| e.id()).collect::>(); + let entities = world.iter_entities().map(|e| e.id()).collect::>(); group.bench_function(format!("{}_entities", entity_count), |bencher| { bencher.iter(|| { - ents.iter().for_each(|e| { + entities.iter().for_each(|e| { despawn_with_children_recursive(&mut world, *e, true); }); }); diff --git a/benches/benches/bevy_ecs/world/entity_hash.rs b/benches/benches/bevy_ecs/world/entity_hash.rs index 3bd148d90da63..37a8a1494fff8 100644 --- a/benches/benches/bevy_ecs/world/entity_hash.rs +++ b/benches/benches/bevy_ecs/world/entity_hash.rs @@ -19,7 +19,7 @@ fn make_entity(rng: &mut impl Rng, size: usize) -> Entity { let x: f64 = rng.gen(); let gen = 1.0 + -(1.0 - x).log2() * 2.0; - // this is not reliable, but we're internal so a hack is ok + // this is not reliable, but we're internal, so a hack is ok let bits = ((gen as u64) << 32) | (id as u64); let e = Entity::from_bits(bits); assert_eq!(e.index(), id as u32); diff --git a/benches/benches/bevy_picking/ray_mesh_intersection.rs b/benches/benches/bevy_picking/ray_mesh_intersection.rs index f451b790612c3..85f6502e64e09 100644 --- a/benches/benches/bevy_picking/ray_mesh_intersection.rs +++ b/benches/benches/bevy_picking/ray_mesh_intersection.rs @@ -2,7 +2,7 @@ use bevy_math::{Dir3, Mat4, Ray3d, Vec3}; use bevy_picking::mesh_picking::ray_cast; use criterion::{black_box, criterion_group, criterion_main, Criterion}; -fn ptoxznorm(p: u32, size: u32) -> (f32, f32) { +fn p_to_xz_norm(p: u32, size: u32) -> (f32, f32) { let ij = (p / (size), p % (size)); (ij.0 as f32 / size as f32, ij.1 as f32 / size as f32) } @@ -17,7 +17,7 @@ fn mesh_creation(vertices_per_side: u32) -> SimpleMesh { let mut positions = Vec::new(); let mut normals = Vec::new(); for p in 0..vertices_per_side.pow(2) { - let xz = ptoxznorm(p, vertices_per_side); + let xz = p_to_xz_norm(p, vertices_per_side); positions.push([xz.0 - 0.5, 0.0, xz.1 - 0.5]); normals.push([0.0, 1.0, 0.0]); } diff --git a/crates/bevy_animation/src/animatable.rs b/crates/bevy_animation/src/animatable.rs index 6af653d3077b4..12cce37de2339 100644 --- a/crates/bevy_animation/src/animatable.rs +++ b/crates/bevy_animation/src/animatable.rs @@ -18,7 +18,7 @@ pub struct BlendInput { /// An animatable value type. pub trait Animatable: Reflect + Sized + Send + Sync + 'static { - /// Interpolates between `a` and `b` with a interpolation factor of `time`. + /// Interpolates between `a` and `b` with an interpolation factor of `time`. /// /// The `time` parameter here may not be clamped to the range `[0.0, 1.0]`. fn interpolate(a: &Self, b: &Self, time: f32) -> Self; @@ -211,9 +211,9 @@ where // (additive) blending and linear interpolation. // // Evaluating a Bézier curve via repeated linear interpolation when the - // control points are known is straightforward via [de Casteljau - // subdivision]. So the only remaining problem is to get the two off-curve - // control points. The [derivative of the cubic Bézier curve] is: + // control points are known is straightforward via [de Casteljau subdivision]. + // The only remaining problem is to get the two off-curve control points. + // The [derivative of the cubic Bézier curve] is: // // B′(t) = 3(1 - t)²(P₁ - P₀) + 6(1 - t)t(P₂ - P₁) + 3t²(P₃ - P₂) // diff --git a/crates/bevy_animation/src/gltf_curves.rs b/crates/bevy_animation/src/gltf_curves.rs index 8d3b6cc248442..305e318cb2396 100644 --- a/crates/bevy_animation/src/gltf_curves.rs +++ b/crates/bevy_animation/src/gltf_curves.rs @@ -405,11 +405,11 @@ fn cubic_spline_interpolation( where T: VectorSpace, { - let coeffs = (vec4(2.0, 1.0, -2.0, 1.0) * lerp + vec4(-3.0, -2.0, 3.0, -1.0)) * lerp; - value_start * (coeffs.x * lerp + 1.0) - + tangent_out_start * step_duration * lerp * (coeffs.y + 1.0) - + value_end * lerp * coeffs.z - + tangent_in_end * step_duration * lerp * coeffs.w + let coefficients = (vec4(2.0, 1.0, -2.0, 1.0) * lerp + vec4(-3.0, -2.0, 3.0, -1.0)) * lerp; + value_start * (coefficients.x * lerp + 1.0) + + tangent_out_start * step_duration * lerp * (coefficients.y + 1.0) + + value_end * lerp * coefficients.z + + tangent_in_end * step_duration * lerp * coefficients.w } fn cubic_spline_interpolate_slices<'a, T: VectorSpace>( diff --git a/crates/bevy_animation/src/lib.rs b/crates/bevy_animation/src/lib.rs index 8d55cb7ea5c81..6a7c9233f557a 100644 --- a/crates/bevy_animation/src/lib.rs +++ b/crates/bevy_animation/src/lib.rs @@ -744,7 +744,7 @@ impl ActiveAnimation { /// /// Note that any events between the current time and `seek_time` /// will be triggered on the next update. - /// Use [`set_seek_time`](Self::set_seek_time) if this is undisered. + /// Use [`set_seek_time`](Self::set_seek_time) if this is undesired. pub fn seek_to(&mut self, seek_time: f32) -> &mut Self { self.last_seek_time = Some(self.seek_time); self.seek_time = seek_time; @@ -755,7 +755,7 @@ impl ActiveAnimation { /// /// Note that any events between the current time and `0.0` /// will be triggered on the next update. - /// Use [`set_seek_time`](Self::set_seek_time) if this is undisered. + /// Use [`set_seek_time`](Self::set_seek_time) if this is undesired. pub fn rewind(&mut self) -> &mut Self { self.last_seek_time = Some(self.seek_time); self.seek_time = 0.0; diff --git a/crates/bevy_app/src/app.rs b/crates/bevy_app/src/app.rs index 4cdc3a2473d55..238976c452d91 100644 --- a/crates/bevy_app/src/app.rs +++ b/crates/bevy_app/src/app.rs @@ -291,7 +291,7 @@ impl App { self } - /// Registers a system and returns a [`SystemId`] so it can later be called by [`World::run_system`]. + /// Registers a system and returns a [`SystemId`] so that it can later be called by [`World::run_system`]. /// /// It's possible to register the same systems more than once, they'll be stored separately. /// @@ -1320,7 +1320,7 @@ pub enum AppExit { } impl AppExit { - /// Creates a [`AppExit::Error`] with a error code of 1. + /// Creates a [`AppExit::Error`] with an error code of 1. #[must_use] pub const fn error() -> Self { Self::Error(NonZero::::MIN) @@ -1695,8 +1695,8 @@ mod tests { #[test] fn app_exit_size() { - // There wont be many of them so the size isn't a issue but - // it's nice they're so small let's keep it that way. + // There wont be many of them, so the size isn't an issue; + // however, it's nice they're so small let's keep it that way. assert_eq!(size_of::(), size_of::()); } diff --git a/crates/bevy_app/src/main_schedule.rs b/crates/bevy_app/src/main_schedule.rs index f2b549443769c..4b05589dbe2fa 100644 --- a/crates/bevy_app/src/main_schedule.rs +++ b/crates/bevy_app/src/main_schedule.rs @@ -414,7 +414,7 @@ pub enum RunFixedMainLoopSystem { /// [`Time`] and [`Time::overstep`]. /// /// Don't place systems here, use [`FixedUpdate`] and friends instead. - /// Use this system instead to order your systems to run specifically inbetween the fixed update logic and all + /// Use this system instead to order your systems to run specifically in-between the fixed update logic and all /// other systems that run in [`RunFixedMainLoopSystem::BeforeFixedMainLoop`] or [`RunFixedMainLoopSystem::AfterFixedMainLoop`]. /// /// [`Time`]: https://docs.rs/bevy/latest/bevy/prelude/struct.Virtual.html diff --git a/crates/bevy_asset/src/io/android.rs b/crates/bevy_asset/src/io/android.rs index b8b78a9681637..39b46c24347ce 100644 --- a/crates/bevy_asset/src/io/android.rs +++ b/crates/bevy_asset/src/io/android.rs @@ -88,10 +88,10 @@ impl AssetReader for AndroidAssetReader { // The solution here was to first use `open_dir` to eliminate the case // when the path does not exist at all, and then to use `open` to // see if that path is a file or a directory - let cpath = CString::new(path.to_str().unwrap()).unwrap(); + let c_path = CString::new(path.to_str().unwrap()).unwrap(); let _ = asset_manager - .open_dir(&cpath) + .open_dir(&c_path) .ok_or(AssetReaderError::NotFound(path.to_path_buf()))?; - Ok(asset_manager.open(&cpath).is_none()) + Ok(asset_manager.open(&c_path).is_none()) } } diff --git a/crates/bevy_asset/src/io/file/file_watcher.rs b/crates/bevy_asset/src/io/file/file_watcher.rs index bb4cf109c32c1..6909fd3d3bef4 100644 --- a/crates/bevy_asset/src/io/file/file_watcher.rs +++ b/crates/bevy_asset/src/io/file/file_watcher.rs @@ -188,7 +188,7 @@ pub(crate) fn new_asset_event_debouncer( } (true, false) => { error!( - "Asset metafile {old_path:?} was changed to asset file {new_path:?}, which is not supported. Try restarting your app to see if configuration is still valid" + "Asset meta file {old_path:?} was changed to asset file {new_path:?}, which is not supported. Try restarting your app to see if configuration is still valid" ); } (false, true) => { diff --git a/crates/bevy_asset/src/io/memory.rs b/crates/bevy_asset/src/io/memory.rs index 2fa2579c581a9..fc4a9e49dc72e 100644 --- a/crates/bevy_asset/src/io/memory.rs +++ b/crates/bevy_asset/src/io/memory.rs @@ -336,7 +336,7 @@ pub mod test { let dir = Dir::default(); let a_path = Path::new("a.txt"); let a_data = "a".as_bytes().to_vec(); - let a_meta = "ameta".as_bytes().to_vec(); + let a_meta = "a meta".as_bytes().to_vec(); dir.insert_asset(a_path, a_data.clone()); let asset = dir.get_asset(a_path).unwrap(); diff --git a/crates/bevy_asset/src/lib.rs b/crates/bevy_asset/src/lib.rs index 8937c8838c171..3a7c5067376d8 100644 --- a/crates/bevy_asset/src/lib.rs +++ b/crates/bevy_asset/src/lib.rs @@ -379,7 +379,7 @@ impl Plugin for AssetPlugin { .configure_sets(PreUpdate, TrackAssets.after(handle_internal_asset_events)) // `handle_internal_asset_events` requires the use of `&mut World`, // and as a result has ambiguous system ordering with all other systems in `PreUpdate`. - // This is virtually never a real problem: asset loading is async and so anything that interacts directly with it + // This is virtually never a real problem: asset loading is async, thus anything that interacts directly with it // needs to be robust to stochastic delays anyways. .add_systems(PreUpdate, handle_internal_asset_events.ambiguous_with_all()) .register_type::(); @@ -910,7 +910,7 @@ mod tests { } // Allow "a" to load ... wait for it to finish loading and validate results - // Dependencies are still gated so they should not be loaded yet + // Dependencies are still gated, so they should not be loaded yet gate_opener.open(a_path); run_app_until(&mut app, |world| { let a_text = get::(world, a_id)?; diff --git a/crates/bevy_asset/src/path.rs b/crates/bevy_asset/src/path.rs index c86a190fe1b01..82c2ba046ba24 100644 --- a/crates/bevy_asset/src/path.rs +++ b/crates/bevy_asset/src/path.rs @@ -411,7 +411,7 @@ impl<'a> AssetPath<'a> { // It's a label only Ok(self.clone_owned().with_label(label.to_owned())) } else { - let (source, rpath, rlabel) = AssetPath::parse_internal(path)?; + let (source, r_path, r_label) = AssetPath::parse_internal(path)?; let mut base_path = PathBuf::from(self.path()); if replace && !self.path.to_str().unwrap().ends_with('/') { // No error if base is empty (per RFC 1808). @@ -420,12 +420,12 @@ impl<'a> AssetPath<'a> { // Strip off leading slash let mut is_absolute = false; - let rpath = match rpath.strip_prefix("/") { + let r_path = match r_path.strip_prefix("/") { Ok(p) => { is_absolute = true; p } - _ => rpath, + _ => r_path, }; let mut result_path = if !is_absolute && source.is_none() { @@ -433,7 +433,7 @@ impl<'a> AssetPath<'a> { } else { PathBuf::new() }; - result_path.push(rpath); + result_path.push(r_path); result_path = normalize_path(result_path.as_path()); Ok(AssetPath { @@ -442,7 +442,7 @@ impl<'a> AssetPath<'a> { None => self.source.clone_owned(), }, path: CowArc::Owned(result_path.into()), - label: rlabel.map(|l| CowArc::Owned(l.into())), + label: r_label.map(|l| CowArc::Owned(l.into())), }) } } diff --git a/crates/bevy_asset/src/processor/mod.rs b/crates/bevy_asset/src/processor/mod.rs index a047cd7971032..0cc553d3bb8eb 100644 --- a/crates/bevy_asset/src/processor/mod.rs +++ b/crates/bevy_asset/src/processor/mod.rs @@ -88,7 +88,7 @@ use std::path::{Path, PathBuf}; /// A [`ProcessorTransactionLog`] is produced, which uses "write-ahead logging" to make the [`AssetProcessor`] crash and failure resistant. If a failed/unfinished /// transaction from a previous run is detected, the affected asset(s) will be re-processed. /// -/// [`AssetProcessor`] can be cloned. It is backed by an [`Arc`] so clones will share state. Clones can be freely used in parallel. +/// [`AssetProcessor`] can be cloned. It is backed by an [`Arc`], so clones will share state. Clones can be freely used in parallel. #[derive(Resource, Clone)] pub struct AssetProcessor { server: AssetServer, @@ -276,7 +276,7 @@ impl AssetProcessor { AssetSourceEvent::AddedFolder(path) => { self.handle_added_folder(source, path).await; } - // NOTE: As a heads up for future devs: this event shouldn't be run in parallel with other events that might + // NOTE: As a heads up for future developers: this event shouldn't be run in parallel with other events that might // touch this folder (ex: the folder might be re-created with new assets). Clean up the old state first. // Currently this event handler is not parallel, but it could be (and likely should be) in the future. AssetSourceEvent::RemovedFolder(path) => { @@ -698,7 +698,7 @@ impl AssetProcessor { async fn clean_empty_processed_ancestor_folders(&self, source: &AssetSource, path: &Path) { // As a safety precaution don't delete absolute paths to avoid deleting folders outside of the destination folder if path.is_absolute() { - error!("Attempted to clean up ancestor folders of an absolute path. This is unsafe so the operation was skipped."); + error!("Attempted to clean up ancestor folders of an absolute path. This is unsafe, so the operation was skipped."); return; } while let Some(parent) = path.parent() { @@ -924,11 +924,11 @@ impl AssetProcessor { if let Err(err) = ProcessorTransactionLog::validate().await { let state_is_valid = match err { ValidateLogError::ReadLogError(err) => { - error!("Failed to read processor log file. Processed assets cannot be validated so they must be re-generated {err}"); + error!("Failed to read processor log file. Processed assets cannot be validated, so they must be re-generated {err}"); false } ValidateLogError::UnrecoverableError => { - error!("Encountered an unrecoverable error in the last run. Processed assets cannot be validated so they must be re-generated"); + error!("Encountered an unrecoverable error in the last run. Processed assets cannot be validated, so they must be re-generated."); false } ValidateLogError::EntryErrors(entry_errors) => { diff --git a/crates/bevy_asset/src/reflect.rs b/crates/bevy_asset/src/reflect.rs index 3aaa1580bb110..f96f4059ca495 100644 --- a/crates/bevy_asset/src/reflect.rs +++ b/crates/bevy_asset/src/reflect.rs @@ -279,13 +279,13 @@ mod tests { let handle = reflect_asset.add(app.world_mut(), &value); // struct is a reserved keyword, so we can't use it here - let strukt = reflect_asset + let r#struct = reflect_asset .get_mut(app.world_mut(), handle) .unwrap() .reflect_mut() .as_struct() .unwrap(); - strukt + r#struct .field_mut("field") .unwrap() .apply(&String::from("edited")); diff --git a/crates/bevy_asset/src/server/mod.rs b/crates/bevy_asset/src/server/mod.rs index 297164062906e..312f9c937c6f7 100644 --- a/crates/bevy_asset/src/server/mod.rs +++ b/crates/bevy_asset/src/server/mod.rs @@ -45,7 +45,7 @@ use std::path::{Path, PathBuf}; /// 3. Add the asset to your asset folder (defaults to `assets`). /// 4. Call [`AssetServer::load`] with a path to your asset. /// -/// [`AssetServer`] can be cloned. It is backed by an [`Arc`] so clones will share state. Clones can be freely used in parallel. +/// [`AssetServer`] can be cloned. It is backed by an [`Arc`], so clones will share state. Clones can be freely used in parallel. /// /// [`AssetApp::init_asset`]: crate::AssetApp::init_asset /// [`AssetApp::init_asset_loader`]: crate::AssetApp::init_asset_loader @@ -574,7 +574,7 @@ impl AssetServer { if let Some(meta_transform) = input_handle.as_ref().and_then(|h| h.meta_transform()) { (*meta_transform)(&mut *meta); } - // downgrade the input handle so we don't keep the asset alive just because we're loading it + // downgrade the input handle so that we don't keep the asset alive just because we're loading it // note we can't just pass a weak handle in, as only strong handles contain the asset meta transform input_handle = input_handle.map(|h| h.clone_weak()); @@ -584,7 +584,7 @@ impl AssetServer { // 2. The asset has not been loaded yet, meaning there is no existing Handle for it // 3. The path has a label, meaning the AssetLoader's root asset type is not the path's asset type // - // In the None case, the only course of action is to wait for the asset to load so we can allocate the + // In the None case, the only course of action is to wait for the asset to load so that we can allocate the // handle for that type. // // TODO: Note that in the None case, multiple asset loads for the same path can happen at the same time @@ -1349,7 +1349,7 @@ impl AssetServer { /// or if the asset has not been queued up to be loaded. pub async fn wait_for_asset( &self, - // NOTE: We take a reference to a handle so we know it will outlive the future, + // NOTE: We take a reference to a handle so that we know it will outlive the future, // which ensures the handle won't be dropped while waiting for the asset. handle: &Handle, ) -> Result<(), WaitForAssetError> { @@ -1365,7 +1365,7 @@ impl AssetServer { /// or if the asset has not been queued up to be loaded. pub async fn wait_for_asset_untyped( &self, - // NOTE: We take a reference to a handle so we know it will outlive the future, + // NOTE: We take a reference to a handle so that we know it will outlive the future, // which ensures the handle won't be dropped while waiting for the asset. handle: &UntypedHandle, ) -> Result<(), WaitForAssetError> { @@ -1384,7 +1384,7 @@ impl AssetServer { /// asset from being dropped. /// If you have access to an asset's strong [`Handle`], you should prefer to call /// [`AssetServer::wait_for_asset`] - /// or [`wait_for_assest_untyped`](Self::wait_for_asset_untyped) to ensure the asset finishes + /// or [`wait_for_asset_untyped`](Self::wait_for_asset_untyped) to ensure the asset finishes /// loading. /// /// # Errors diff --git a/crates/bevy_color/src/color.rs b/crates/bevy_color/src/color.rs index d2e4cb792187c..758ebc60d9a00 100644 --- a/crates/bevy_color/src/color.rs +++ b/crates/bevy_color/src/color.rs @@ -174,7 +174,7 @@ impl Color { #[deprecated = "Use Color::linear_rgba instead."] /// Creates a new [`Color`] object storing a [`LinearRgba`] color. - pub const fn rbga_linear(red: f32, green: f32, blue: f32, alpha: f32) -> Self { + pub const fn rgba_linear(red: f32, green: f32, blue: f32, alpha: f32) -> Self { Self::linear_rgba(red, green, blue, alpha) } diff --git a/crates/bevy_color/src/color_range.rs b/crates/bevy_color/src/color_range.rs index 48afa5418225d..ff0bd90c935c9 100644 --- a/crates/bevy_color/src/color_range.rs +++ b/crates/bevy_color/src/color_range.rs @@ -33,14 +33,14 @@ mod tests { assert_eq!(range.at(1.0), basic::BLUE); assert_eq!(range.at(1.5), basic::BLUE); - let lred: LinearRgba = basic::RED.into(); - let lblue: LinearRgba = basic::BLUE.into(); + let linear_red: LinearRgba = basic::RED.into(); + let linear_blue: LinearRgba = basic::BLUE.into(); - let range = lred..lblue; - assert_eq!(range.at(-0.5), lred); - assert_eq!(range.at(0.0), lred); + let range = linear_red..linear_blue; + assert_eq!(range.at(-0.5), linear_red); + assert_eq!(range.at(0.0), linear_red); assert_eq!(range.at(0.5), LinearRgba::new(0.5, 0.0, 0.5, 1.0)); - assert_eq!(range.at(1.0), lblue); - assert_eq!(range.at(1.5), lblue); + assert_eq!(range.at(1.0), linear_blue); + assert_eq!(range.at(1.5), linear_blue); } } diff --git a/crates/bevy_color/src/linear_rgba.rs b/crates/bevy_color/src/linear_rgba.rs index 3a9a0fd5d2641..a917ae79b1cd0 100644 --- a/crates/bevy_color/src/linear_rgba.rs +++ b/crates/bevy_color/src/linear_rgba.rs @@ -330,8 +330,8 @@ impl From for wgpu_types::Color { } } -// [`LinearRgba`] is intended to be used with shaders -// So it's the only color type that implements [`ShaderType`] to make it easier to use inside shaders +// [`LinearRgba`] is intended to be used with shaders, which is why it's the only color +// type that implements [`ShaderType`] to make it easier to use inside shaders impl encase::ShaderType for LinearRgba { type ExtraMetadata = (); diff --git a/crates/bevy_color/src/srgba.rs b/crates/bevy_color/src/srgba.rs index 8fdecc19ad640..32b260bdba2a2 100644 --- a/crates/bevy_color/src/srgba.rs +++ b/crates/bevy_color/src/srgba.rs @@ -175,7 +175,7 @@ impl Srgba { } } - /// New `Srgba` from sRGB colorspace. + /// New `Srgba` from sRGB color space. /// /// # Arguments /// @@ -190,7 +190,7 @@ impl Srgba { // Float operations in const fn are not stable yet // see https://github.com/rust-lang/rust/issues/57241 - /// New `Srgba` from sRGB colorspace. + /// New `Srgba` from sRGB color space. /// /// # Arguments /// diff --git a/crates/bevy_core_pipeline/src/auto_exposure/settings.rs b/crates/bevy_core_pipeline/src/auto_exposure/settings.rs index 91bdf836eebee..4ca9d6d21e25f 100644 --- a/crates/bevy_core_pipeline/src/auto_exposure/settings.rs +++ b/crates/bevy_core_pipeline/src/auto_exposure/settings.rs @@ -35,8 +35,8 @@ pub struct AutoExposure { /// The portion of the histogram to consider when metering. /// - /// By default, the darkest 10% and the brightest 10% of samples are ignored, - /// so the default value is `0.10..=0.90`. + /// By default, the darkest 10% and the brightest 10% of samples are ignored; + /// therefore, the default value is `0.10..=0.90`. pub filter: RangeInclusive, /// The speed at which the exposure adapts from dark to bright scenes, in F-stops per second. diff --git a/crates/bevy_core_pipeline/src/bloom/mod.rs b/crates/bevy_core_pipeline/src/bloom/mod.rs index bfd7ee22dbd10..9d2f61745bf50 100644 --- a/crates/bevy_core_pipeline/src/bloom/mod.rs +++ b/crates/bevy_core_pipeline/src/bloom/mod.rs @@ -335,7 +335,7 @@ fn prepare_bloom_textures( y: height, }) = camera.physical_viewport_size { - // How many times we can halve the resolution minus one so we don't go unnecessarily low + // How many times we can halve the resolution minus one so that we don't go unnecessarily low let mip_count = bloom.max_mip_dimension.ilog2().max(2) - 1; let mip_height_ratio = if height != 0 { bloom.max_mip_dimension as f32 / height as f32 diff --git a/crates/bevy_core_pipeline/src/bloom/upsampling_pipeline.rs b/crates/bevy_core_pipeline/src/bloom/upsampling_pipeline.rs index b63a3eb633485..8091ca5f47c50 100644 --- a/crates/bevy_core_pipeline/src/bloom/upsampling_pipeline.rs +++ b/crates/bevy_core_pipeline/src/bloom/upsampling_pipeline.rs @@ -82,7 +82,7 @@ impl SpecializedRenderPipeline for BloomUpsamplingPipeline { // TODO: Use alpha instead of blend constants and move // compute_blend_factor to the shader. The shader // will likely need to know current mip number or - // mip "angle" (original texture is 0deg, max mip is 90deg) + // mip "angle" (original texture is 0deg, max mip is 90deg), // so make sure you give it that as a uniform. // That does have to be provided per each pass unlike other // uniforms that are set once. diff --git a/crates/bevy_core_pipeline/src/contrast_adaptive_sharpening/robust_contrast_adaptive_sharpening.wgsl b/crates/bevy_core_pipeline/src/contrast_adaptive_sharpening/robust_contrast_adaptive_sharpening.wgsl index 252d97c9d6c3e..0f7c5228a8c34 100644 --- a/crates/bevy_core_pipeline/src/contrast_adaptive_sharpening/robust_contrast_adaptive_sharpening.wgsl +++ b/crates/bevy_core_pipeline/src/contrast_adaptive_sharpening/robust_contrast_adaptive_sharpening.wgsl @@ -23,8 +23,8 @@ struct CASUniforms { sharpness: f32, }; -@group(0) @binding(0) var screenTexture: texture_2d; -@group(0) @binding(1) var samp: sampler; +@group(0) @binding(0) var screen_texture: texture_2d; +@group(0) @binding(1) var samplr: sampler; @group(0) @binding(2) var uniforms: CASUniforms; // This is set at the limit of providing unnatural results for sharpening. @@ -38,7 +38,7 @@ const peakC = vec2(10.0, -40.0); // RCAS is based on the following logic. // RCAS uses a 5 tap filter in a cross pattern (same as CAS), // W b -// W 1 W for taps d e f +// W 1 W for taps d e f // W h // Where 'W' is the negative lobe weight. // output = (W*(b+d+f+h)+e)/(4*W+1) @@ -50,7 +50,7 @@ const peakC = vec2(10.0, -40.0); // So RCAS uses 4x the maximum and 4x the minimum (depending on equation)in place of the individual taps. // As well as switching from 'e' to either the minimum or maximum (depending on side), to help in energy conservation. // This stabilizes RCAS. -// RCAS does a simple highpass which is normalized against the local contrast then shaped, +// RCAS does a simple high-pass which is normalized against the local contrast then shaped, // 0.25 // 0.25 -1 0.25 // 0.25 @@ -62,12 +62,12 @@ fn fragment(in: FullscreenVertexOutput) -> @location(0) vec4 { // b // d e f // h - let b = textureSample(screenTexture, samp, in.uv, vec2(0, -1)).rgb; - let d = textureSample(screenTexture, samp, in.uv, vec2(-1, 0)).rgb; + let b = textureSample(screen_texture, samplr, in.uv, vec2(0, -1)).rgb; + let d = textureSample(screen_texture, samplr, in.uv, vec2(-1, 0)).rgb; // We need the alpha value of the pixel we're working on for the output - let e = textureSample(screenTexture, samp, in.uv).rgbw; - let f = textureSample(screenTexture, samp, in.uv, vec2(1, 0)).rgb; - let h = textureSample(screenTexture, samp, in.uv, vec2(0, 1)).rgb; + let e = textureSample(screen_texture, samplr, in.uv).rgbw; + let f = textureSample(screen_texture, samplr, in.uv, vec2(1, 0)).rgb; + let h = textureSample(screen_texture, samplr, in.uv, vec2(0, 1)).rgb; // Min and max of ring. let mn4 = min(min(b, d), min(f, h)); let mx4 = max(max(b, d), max(f, h)); diff --git a/crates/bevy_core_pipeline/src/core_2d/main_transparent_pass_2d_node.rs b/crates/bevy_core_pipeline/src/core_2d/main_transparent_pass_2d_node.rs index e365be954775b..9c9b1b0f7c377 100644 --- a/crates/bevy_core_pipeline/src/core_2d/main_transparent_pass_2d_node.rs +++ b/crates/bevy_core_pipeline/src/core_2d/main_transparent_pass_2d_node.rs @@ -81,7 +81,7 @@ impl ViewNode for MainTransparentPass2dNode { } // WebGL2 quirk: if ending with a render pass with a custom viewport, the viewport isn't - // reset for the next render pass so add an empty render pass without a custom viewport + // reset for the next render pass, so add an empty render pass without a custom viewport #[cfg(all(feature = "webgl", target_arch = "wasm32", not(feature = "webgpu")))] if camera.viewport.is_some() { #[cfg(feature = "trace")] diff --git a/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs b/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs index 3b60d8fde6b06..2053b96882817 100644 --- a/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs +++ b/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs @@ -42,7 +42,7 @@ pub struct Camera3d { /// /// Roughly corresponds to how many “layers of transparency” are rendered for screen space /// specular transmissive objects. Each step requires making one additional - /// texture copy, so it's recommended to keep this number to a resonably low value. Defaults to `1`. + /// texture copy, so it's recommended to keep this number to a reasonably low value. Defaults to `1`. /// /// ### Notes /// diff --git a/crates/bevy_core_pipeline/src/core_3d/main_transparent_pass_3d_node.rs b/crates/bevy_core_pipeline/src/core_3d/main_transparent_pass_3d_node.rs index 4f0d3d0722f0e..379283d638bf7 100644 --- a/crates/bevy_core_pipeline/src/core_3d/main_transparent_pass_3d_node.rs +++ b/crates/bevy_core_pipeline/src/core_3d/main_transparent_pass_3d_node.rs @@ -79,7 +79,7 @@ impl ViewNode for MainTransparentPass3dNode { } // WebGL2 quirk: if ending with a render pass with a custom viewport, the viewport isn't - // reset for the next render pass so add an empty render pass without a custom viewport + // reset for the next render pass, so add an empty render pass without a custom viewport #[cfg(all(feature = "webgl", target_arch = "wasm32", not(feature = "webgpu")))] if camera.viewport.is_some() { #[cfg(feature = "trace")] diff --git a/crates/bevy_core_pipeline/src/fxaa/fxaa.wgsl b/crates/bevy_core_pipeline/src/fxaa/fxaa.wgsl index 2ff080de5e8e5..b686c5755c2a7 100644 --- a/crates/bevy_core_pipeline/src/fxaa/fxaa.wgsl +++ b/crates/bevy_core_pipeline/src/fxaa/fxaa.wgsl @@ -8,8 +8,8 @@ #import bevy_core_pipeline::fullscreen_vertex_shader::FullscreenVertexOutput -@group(0) @binding(0) var screenTexture: texture_2d; -@group(0) @binding(1) var samp: sampler; +@group(0) @binding(0) var screen_texture: texture_2d; +@group(0) @binding(1) var samplr: sampler; // Trims the algorithm from processing darks. #ifdef EDGE_THRESH_MIN_LOW @@ -74,21 +74,21 @@ fn rgb2luma(rgb: vec3) -> f32 { // Performs FXAA post-process anti-aliasing as described in the Nvidia FXAA white paper and the associated shader code. @fragment fn fragment(in: FullscreenVertexOutput) -> @location(0) vec4 { - let resolution = vec2(textureDimensions(screenTexture)); + let resolution = vec2(textureDimensions(screen_texture)); let inverseScreenSize = 1.0 / resolution.xy; let texCoord = in.position.xy * inverseScreenSize; - let centerSample = textureSampleLevel(screenTexture, samp, texCoord, 0.0); + let centerSample = textureSampleLevel(screen_texture, samplr, texCoord, 0.0); let colorCenter = centerSample.rgb; // Luma at the current fragment let lumaCenter = rgb2luma(colorCenter); // Luma at the four direct neighbors of the current fragment. - let lumaDown = rgb2luma(textureSampleLevel(screenTexture, samp, texCoord, 0.0, vec2(0, -1)).rgb); - let lumaUp = rgb2luma(textureSampleLevel(screenTexture, samp, texCoord, 0.0, vec2(0, 1)).rgb); - let lumaLeft = rgb2luma(textureSampleLevel(screenTexture, samp, texCoord, 0.0, vec2(-1, 0)).rgb); - let lumaRight = rgb2luma(textureSampleLevel(screenTexture, samp, texCoord, 0.0, vec2(1, 0)).rgb); + let lumaDown = rgb2luma(textureSampleLevel(screen_texture, samplr, texCoord, 0.0, vec2(0, -1)).rgb); + let lumaUp = rgb2luma(textureSampleLevel(screen_texture, samplr, texCoord, 0.0, vec2(0, 1)).rgb); + let lumaLeft = rgb2luma(textureSampleLevel(screen_texture, samplr, texCoord, 0.0, vec2(-1, 0)).rgb); + let lumaRight = rgb2luma(textureSampleLevel(screen_texture, samplr, texCoord, 0.0, vec2(1, 0)).rgb); // Find the maximum and minimum luma around the current fragment. let lumaMin = min(lumaCenter, min(min(lumaDown, lumaUp), min(lumaLeft, lumaRight))); @@ -103,10 +103,10 @@ fn fragment(in: FullscreenVertexOutput) -> @location(0) vec4 { } // Query the 4 remaining corners lumas. - let lumaDownLeft = rgb2luma(textureSampleLevel(screenTexture, samp, texCoord, 0.0, vec2(-1, -1)).rgb); - let lumaUpRight = rgb2luma(textureSampleLevel(screenTexture, samp, texCoord, 0.0, vec2(1, 1)).rgb); - let lumaUpLeft = rgb2luma(textureSampleLevel(screenTexture, samp, texCoord, 0.0, vec2(-1, 1)).rgb); - let lumaDownRight = rgb2luma(textureSampleLevel(screenTexture, samp, texCoord, 0.0, vec2(1, -1)).rgb); + let lumaDownLeft = rgb2luma(textureSampleLevel(screen_texture, samplr, texCoord, 0.0, vec2(-1, -1)).rgb); + let lumaUpRight = rgb2luma(textureSampleLevel(screen_texture, samplr, texCoord, 0.0, vec2(1, 1)).rgb); + let lumaUpLeft = rgb2luma(textureSampleLevel(screen_texture, samplr, texCoord, 0.0, vec2(-1, 1)).rgb); + let lumaDownRight = rgb2luma(textureSampleLevel(screen_texture, samplr, texCoord, 0.0, vec2(1, -1)).rgb); // Combine the four edges lumas (using intermediary variables for future computations with the same values). let lumaDownUp = lumaDown + lumaUp; @@ -119,12 +119,12 @@ fn fragment(in: FullscreenVertexOutput) -> @location(0) vec4 { let lumaUpCorners = lumaUpRight + lumaUpLeft; // Compute an estimation of the gradient along the horizontal and vertical axis. - let edgeHorizontal = abs(-2.0 * lumaLeft + lumaLeftCorners) + - abs(-2.0 * lumaCenter + lumaDownUp) * 2.0 + + let edgeHorizontal = abs(-2.0 * lumaLeft + lumaLeftCorners) + + abs(-2.0 * lumaCenter + lumaDownUp) * 2.0 + abs(-2.0 * lumaRight + lumaRightCorners); - let edgeVertical = abs(-2.0 * lumaUp + lumaUpCorners) + - abs(-2.0 * lumaCenter + lumaLeftRight) * 2.0 + + let edgeVertical = abs(-2.0 * lumaUp + lumaUpCorners) + + abs(-2.0 * lumaCenter + lumaLeftRight) * 2.0 + abs(-2.0 * lumaDown + lumaDownCorners); // Is the local edge horizontal or vertical ? @@ -174,8 +174,8 @@ fn fragment(in: FullscreenVertexOutput) -> @location(0) vec4 { var uv2 = currentUv + offset; // * QUALITY(0); // (quality 0 is 1.0) // Read the lumas at both current extremities of the exploration segment, and compute the delta wrt to the local average luma. - var lumaEnd1 = rgb2luma(textureSampleLevel(screenTexture, samp, uv1, 0.0).rgb); - var lumaEnd2 = rgb2luma(textureSampleLevel(screenTexture, samp, uv2, 0.0).rgb); + var lumaEnd1 = rgb2luma(textureSampleLevel(screen_texture, samplr, uv1, 0.0).rgb); + var lumaEnd2 = rgb2luma(textureSampleLevel(screen_texture, samplr, uv2, 0.0).rgb); lumaEnd1 = lumaEnd1 - lumaLocalAverage; lumaEnd2 = lumaEnd2 - lumaLocalAverage; @@ -192,13 +192,13 @@ fn fragment(in: FullscreenVertexOutput) -> @location(0) vec4 { if (!reachedBoth) { for (var i: i32 = 2; i < ITERATIONS; i = i + 1) { // If needed, read luma in 1st direction, compute delta. - if (!reached1) { - lumaEnd1 = rgb2luma(textureSampleLevel(screenTexture, samp, uv1, 0.0).rgb); + if (!reached1) { + lumaEnd1 = rgb2luma(textureSampleLevel(screen_texture, samplr, uv1, 0.0).rgb); lumaEnd1 = lumaEnd1 - lumaLocalAverage; } // If needed, read luma in opposite direction, compute delta. - if (!reached2) { - lumaEnd2 = rgb2luma(textureSampleLevel(screenTexture, samp, uv2, 0.0).rgb); + if (!reached2) { + lumaEnd2 = rgb2luma(textureSampleLevel(screen_texture, samplr, uv2, 0.0).rgb); lumaEnd2 = lumaEnd2 - lumaLocalAverage; } // If the luma deltas at the current extremities is larger than the local gradient, we have reached the side of the edge. @@ -215,8 +215,8 @@ fn fragment(in: FullscreenVertexOutput) -> @location(0) vec4 { } // If both sides have been reached, stop the exploration. - if (reachedBoth) { - break; + if (reachedBoth) { + break; } } } @@ -269,6 +269,6 @@ fn fragment(in: FullscreenVertexOutput) -> @location(0) vec4 { } // Read the color at the new UV coordinates, and use it. - var finalColor = textureSampleLevel(screenTexture, samp, finalUv, 0.0).rgb; + var finalColor = textureSampleLevel(screen_texture, samplr, finalUv, 0.0).rgb; return vec4(finalColor, centerSample.a); } diff --git a/crates/bevy_core_pipeline/src/oit/mod.rs b/crates/bevy_core_pipeline/src/oit/mod.rs index 45fbdf234472d..f5fcbbe8d54c7 100644 --- a/crates/bevy_core_pipeline/src/oit/mod.rs +++ b/crates/bevy_core_pipeline/src/oit/mod.rs @@ -31,7 +31,7 @@ use crate::core_3d::{ Camera3d, }; -/// Module that defines the necesasry systems to resolve the OIT buffer and render it to the screen. +/// Module that defines the necessary systems to resolve the OIT buffer and render it to the screen. pub mod resolve; /// Shader handle for the shader that draws the transparent meshes to the OIT layers buffer. @@ -39,7 +39,7 @@ pub const OIT_DRAW_SHADER_HANDLE: Handle = Handle::weak_from_u128(404252 /// Used to identify which camera will use OIT to render transparent meshes /// and to configure OIT. -// TODO consider supporting multiple OIT techniques like WBOIT, Moment Based OIT, +// TODO consider supporting multiple OIT techniques like Weighted Blended OIT, Moment Based OIT, // depth peeling, stochastic transparency, ray tracing etc. // This should probably be done by adding an enum to this component. // We use the same struct to pass on the settings to the drawing shader. @@ -147,7 +147,7 @@ impl Plugin for OrderIndependentTransparencyPlugin { // WARN This should only happen for cameras with the [`OrderIndependentTransparencySettings`] component // but when multiple cameras are present on the same window -// bevy reuses the same depth texture so we need to set this on all cameras with the same render target. +// bevy reuses the same depth texture, so we need to set this on all cameras with the same render target. fn configure_depth_texture_usages( p: Query>, cameras: Query<(&Camera, Has)>, @@ -185,8 +185,8 @@ fn check_msaa(cameras: Query<&Msaa, With>) } /// Holds the buffers that contain the data of all OIT layers. -/// We use one big buffer for the entire app. Each camaera will reuse it so it will -/// always be the size of the biggest OIT enabled camera. +/// We use one big buffer for the entire app. Each camera will reuse it, +/// so it will always be the size of the biggest OIT enabled camera. #[derive(Resource)] pub struct OitBuffers { /// The OIT layers containing depth and color for each fragments. @@ -203,7 +203,7 @@ impl FromWorld for OitBuffers { let render_device = world.resource::(); let render_queue = world.resource::(); - // initialize buffers with something so there's a valid binding + // initialize buffers with something so that there's a valid binding let mut layers = BufferVec::new(BufferUsages::COPY_DST | BufferUsages::STORAGE); layers.set_label(Some("oit_layers")); diff --git a/crates/bevy_core_pipeline/src/oit/resolve/mod.rs b/crates/bevy_core_pipeline/src/oit/resolve/mod.rs index 101f7b1ed941e..802150b746766 100644 --- a/crates/bevy_core_pipeline/src/oit/resolve/mod.rs +++ b/crates/bevy_core_pipeline/src/oit/resolve/mod.rs @@ -138,7 +138,8 @@ pub fn queue_oit_resolve_pipeline( With, >, // Store the key with the id to make the clean up logic easier. - // This also means it will always replace the entry if the key changes so nothing to clean up. + // This also means it will always replace the entry if the key + // changes, so there is nothing to clean up. mut cached_pipeline_id: Local>, ) { let mut current_view_entities = EntityHashSet::default(); diff --git a/crates/bevy_core_pipeline/src/oit/resolve/oit_resolve.wgsl b/crates/bevy_core_pipeline/src/oit/resolve/oit_resolve.wgsl index 41ebb457ad534..cb7eb2252d875 100644 --- a/crates/bevy_core_pipeline/src/oit/resolve/oit_resolve.wgsl +++ b/crates/bevy_core_pipeline/src/oit/resolve/oit_resolve.wgsl @@ -36,7 +36,7 @@ fn fragment(in: FullscreenVertexOutput) -> @location(0) vec4 { } else { // Load depth for manual depth testing. // This is necessary because early z doesn't seem to trigger in the transparent pass. - // This should be done during the draw pass so those fragments simply don't exist in the list, + // This should be done during the draw pass so that those fragments simply don't exist in the list, // but this requires a bigger refactor let d = textureLoad(depth, vec2(in.position.xy), 0); let result = sort(screen_index, buffer_size, d); diff --git a/crates/bevy_core_pipeline/src/skybox/skybox.wgsl b/crates/bevy_core_pipeline/src/skybox/skybox.wgsl index 41ac214050295..83ff5e27872f2 100644 --- a/crates/bevy_core_pipeline/src/skybox/skybox.wgsl +++ b/crates/bevy_core_pipeline/src/skybox/skybox.wgsl @@ -31,7 +31,7 @@ fn coords_to_ray_direction(position: vec2, viewport: vec4) -> vec3 VertexOutput { fn skybox_fragment(in: VertexOutput) -> @location(0) vec4 { let ray_direction = coords_to_ray_direction(in.position.xy, view.viewport); - // Cube maps are left-handed so we negate the z coordinate. + // Cube maps are left-handed, so we negate the z coordinate. let out = textureSample(skybox, skybox_sampler, ray_direction * vec3(1.0, 1.0, -1.0)); return vec4(out.rgb * uniforms.brightness, out.a); } diff --git a/crates/bevy_core_pipeline/src/smaa/smaa.wgsl b/crates/bevy_core_pipeline/src/smaa/smaa.wgsl index 5c95c18c2602f..3f75a014d3626 100644 --- a/crates/bevy_core_pipeline/src/smaa/smaa.wgsl +++ b/crates/bevy_core_pipeline/src/smaa/smaa.wgsl @@ -44,7 +44,7 @@ * Here you'll find instructions to get the shader up and running as fast as * possible. * - * IMPORTANTE NOTICE: when updating, remember to update both this file and the + * IMPORTANT NOTICE: when updating, remember to update both this file and the * precomputed textures! They may change from version to version. * * The shader has three passes, chained together as follows: @@ -64,7 +64,7 @@ * |output| * * Note that each [pass] has its own vertex and pixel shader. Remember to use - * oversized triangles instead of quads to avoid overshading along the + * oversized triangles instead of quads to avoid extra shading along the * diagonal. * * You've three edge detection methods to choose from: luma, color or depth. @@ -80,7 +80,7 @@ * - Color edge detection is usually the most expensive one but catches * chroma-only edges. * - * For quickstarters: just use luma edge detection. + * For quick-starters: just use luma edge detection. * * The general advice is to not rush the integration process and ensure each * step is done correctly (don't try to integrate SMAA T2x with predicated edge @@ -410,7 +410,7 @@ const SMAA_CORNER_ROUNDING: u32 = 25u; * * Range: [0, 20] * - * On high-end machines it is cheap (between a 0.8x and 0.9x slower for 16 + * On high-end machines it is cheap (between a 0.8x and 0.9x slower for 16 * steps), but it can have a significant impact on older machines. * * Define SMAA_DISABLE_DIAG_DETECTION to disable diagonal processing. @@ -444,7 +444,7 @@ const SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR: f32 = 2.0; const SMAA_AREATEX_MAX_DISTANCE: f32 = 16.0; const SMAA_AREATEX_MAX_DISTANCE_DIAG: f32 = 20.0; const SMAA_AREATEX_PIXEL_SIZE: vec2 = (1.0 / vec2(160.0, 560.0)); -const SMAA_AREATEX_SUBTEX_SIZE: f32 = (1.0 / 7.0); +const SMAA_AREATEX_SUBTEXTURE_SIZE: f32 = (1.0 / 7.0); const SMAA_SEARCHTEX_SIZE: vec2 = vec2(66.0, 33.0); const SMAA_SEARCHTEX_PACKED_SIZE: vec2 = vec2(64.0, 16.0); @@ -684,7 +684,7 @@ fn search_diag_2(tex_coord: vec2, dir: vec2, e: ptr, e: vec2, offset: f32) -> vec2 { tex_coord.x += 0.5; // Move to proper place, according to the subpixel offset: - tex_coord.y += SMAA_AREATEX_SUBTEX_SIZE * offset; + tex_coord.y += SMAA_AREATEX_SUBTEXTURE_SIZE * offset; // Do it! return textureSampleLevel(area_texture, edges_sampler, tex_coord, 0.0).rg; @@ -790,7 +790,7 @@ fn calculate_diag_weights(tex_coord: vec2, e: vec2, subsample_indices: /** * This allows to determine how much length should we add in the last step - * of the searches. It takes the bilinearly interpolated edge (see + * of the searches. It takes the bilinearly interpolated edge (see * @PSEUDO_GATHER4), and adds 0, 1 or 2, depending on which edges and * crossing edges are active. */ @@ -804,7 +804,7 @@ fn search_length(e: vec2, offset: f32) -> f32 { scale += vec2(-1.0, 1.0); bias += vec2( 0.5, -0.5); - // Convert from pixel coordinates to texcoords: + // Convert from pixel coordinates to texture coordinates: // (We use SMAA_SEARCHTEX_PACKED_SIZE because the texture is cropped) scale *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE; bias *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE; @@ -879,7 +879,7 @@ fn search_y_down(in_tex_coord: vec2, end: f32) -> f32 { return -smaa_info.rt_metrics.y * offset + tex_coord.y; } -/** +/** * Ok, we have the distance and both crossing edges. So, what are the areas * at each side of current edge? */ @@ -891,7 +891,7 @@ fn area(dist: vec2, e1: f32, e2: f32, offset: f32) -> vec2 { tex_coord = SMAA_AREATEX_PIXEL_SIZE * tex_coord + 0.5 * SMAA_AREATEX_PIXEL_SIZE; // Move to proper place, according to the subpixel offset: - tex_coord.y += SMAA_AREATEX_SUBTEX_SIZE * offset; + tex_coord.y += SMAA_AREATEX_SUBTEXTURE_SIZE * offset; // Do it! return textureSample(area_texture, edges_sampler, tex_coord).rg; @@ -966,7 +966,7 @@ fn blending_weight_calculation_fragment_main(in: BlendingWeightCalculationVaryin // one of the boundaries is enough. weights = vec4(calculate_diag_weights(in.tex_coord, e, subsample_indices), weights.ba); - // We give priority to diagonals, so if we find a diagonal we skip + // We give priority to diagonals, so if we find a diagonal we skip // horizontal/vertical processing. if (weights.r + weights.g != 0.0) { return weights; diff --git a/crates/bevy_core_pipeline/src/tonemapping/mod.rs b/crates/bevy_core_pipeline/src/tonemapping/mod.rs index c6fb3217253f9..e9e8a4f537403 100644 --- a/crates/bevy_core_pipeline/src/tonemapping/mod.rs +++ b/crates/bevy_core_pipeline/src/tonemapping/mod.rs @@ -431,8 +431,10 @@ pub fn get_lut_bind_group_layout_entries() -> [BindGroupLayoutEntryBuilder; 2] { ] } -// allow(dead_code) so it doesn't complain when the tonemapping_luts feature is disabled -#[allow(dead_code)] +#[allow( + dead_code, + reason = "So that it doesn't complain when the tonemapping_luts feature is disabled" +)] fn setup_tonemapping_lut_image(bytes: &[u8], image_type: ImageType) -> Image { let image_sampler = ImageSampler::Descriptor(bevy_image::ImageSamplerDescriptor { label: Some("Tonemapping LUT sampler".to_string()), diff --git a/crates/bevy_core_pipeline/src/tonemapping/tonemapping.wgsl b/crates/bevy_core_pipeline/src/tonemapping/tonemapping.wgsl index 015cd48c695eb..be54a025973c4 100644 --- a/crates/bevy_core_pipeline/src/tonemapping/tonemapping.wgsl +++ b/crates/bevy_core_pipeline/src/tonemapping/tonemapping.wgsl @@ -2,7 +2,7 @@ #import bevy_render::{ view::View, - maths::powsafe, + math::powsafe, } #import bevy_core_pipeline::{ fullscreen_vertex_shader::FullscreenVertexOutput, diff --git a/crates/bevy_core_pipeline/src/tonemapping/tonemapping_shared.wgsl b/crates/bevy_core_pipeline/src/tonemapping/tonemapping_shared.wgsl index 52d1ddcb6f167..edb4b26657e38 100644 --- a/crates/bevy_core_pipeline/src/tonemapping/tonemapping_shared.wgsl +++ b/crates/bevy_core_pipeline/src/tonemapping/tonemapping_shared.wgsl @@ -3,7 +3,7 @@ #import bevy_render::{ view::ColorGrading, color_operations::{hsv_to_rgb, rgb_to_hsv}, - maths::{PI_2, powsafe}, + math::{PI_2, powsafe}, } #import bevy_core_pipeline::tonemapping_lut_bindings::{ @@ -76,19 +76,19 @@ fn somewhat_boring_display_transform(col: vec3) -> vec3 { let ycbcr = rgb_to_ycbcr(boring_color); let bt = tonemap_curve(length(ycbcr.yz) * 2.4); - var desat = max((bt - 0.7) * 0.8, 0.0); - desat *= desat; + var desaturation = max((bt - 0.7) * 0.8, 0.0); + desaturation *= desaturation; - let desat_col = mix(boring_color.rgb, ycbcr.xxx, desat); + let desaturated_color = mix(boring_color.rgb, ycbcr.xxx, desaturation); let tm_luma = tonemap_curve(ycbcr.x); let tm0 = boring_color.rgb * max(0.0, tm_luma / max(1e-5, tonemapping_luminance(boring_color.rgb))); - let final_mult = 0.97; - let tm1 = tonemap_curve3_(desat_col); + let final_multiplier = 0.97; + let tm1 = tonemap_curve3_(desaturated_color); boring_color = mix(tm0, tm1, bt * bt); - return boring_color * final_mult; + return boring_color * final_multiplier; } // ------------------------------------------ @@ -175,14 +175,14 @@ fn saturation(color: vec3, saturationAmount: f32) -> vec3 { ref[0] */ fn convertOpenDomainToNormalizedLog2_(color: vec3, minimum_ev: f32, maximum_ev: f32) -> vec3 { - let in_midgray = 0.18; + let in_mid_gray = 0.18; // remove negative before log transform var normalized_color = max(vec3(0.0), color); // avoid infinite issue with log -- ref[1] normalized_color = select(normalized_color, 0.00001525878 + normalized_color, normalized_color < vec3(0.00003051757)); normalized_color = clamp( - log2(normalized_color / in_midgray), + log2(normalized_color / in_mid_gray), vec3(minimum_ev), vec3(maximum_ev) ); @@ -194,12 +194,12 @@ fn convertOpenDomainToNormalizedLog2_(color: vec3, minimum_ev: f32, maximum // Inverse of above fn convertNormalizedLog2ToOpenDomain(color: vec3, minimum_ev: f32, maximum_ev: f32) -> vec3 { var open_color = color; - let in_midgray = 0.18; + let in_mid_gray = 0.18; let total_exposure = maximum_ev - minimum_ev; open_color = (open_color * total_exposure) + minimum_ev; open_color = pow(vec3(2.0), open_color); - open_color = open_color * in_midgray; + open_color = open_color * in_mid_gray; return open_color; } diff --git a/crates/bevy_core_pipeline/src/upscaling/mod.rs b/crates/bevy_core_pipeline/src/upscaling/mod.rs index b686d4484931c..dad57731c56fa 100644 --- a/crates/bevy_core_pipeline/src/upscaling/mod.rs +++ b/crates/bevy_core_pipeline/src/upscaling/mod.rs @@ -55,7 +55,7 @@ fn prepare_view_upscaling_pipelines( match blend_state { None => { - // If we've already seen this output for a camera and it doesn't have a output blend + // If we've already seen this output for a camera and it doesn't have an output blend // mode configured, default to alpha blend so that we don't accidentally overwrite // the output texture if already_seen { diff --git a/crates/bevy_dev_tools/src/fps_overlay.rs b/crates/bevy_dev_tools/src/fps_overlay.rs index f970fc8f434c8..a00717cd99f58 100644 --- a/crates/bevy_dev_tools/src/fps_overlay.rs +++ b/crates/bevy_dev_tools/src/fps_overlay.rs @@ -23,8 +23,8 @@ use bevy_utils::default; /// [`GlobalZIndex`] used to render the fps overlay. /// -/// We use a number slightly under `i32::MAX` so you can render on top of it if you really need to. -pub const FPS_OVERLAY_ZINDEX: i32 = i32::MAX - 32; +/// We use a number slightly under `i32::MAX` so that you can render on top of it if you really need to. +pub const FPS_OVERLAY_Z_INDEX: i32 = i32::MAX - 32; /// A plugin that adds an FPS overlay to the Bevy application. /// @@ -94,7 +94,7 @@ fn setup(mut commands: Commands, overlay_config: Res) { ..default() }, // Render overlay on top of everything - GlobalZIndex(FPS_OVERLAY_ZINDEX), + GlobalZIndex(FPS_OVERLAY_Z_INDEX), )) .with_children(|p| { p.spawn(( diff --git a/crates/bevy_dev_tools/src/ui_debug_overlay/inset.rs b/crates/bevy_dev_tools/src/ui_debug_overlay/inset.rs index 92522f6fbe68f..5a45795d36584 100644 --- a/crates/bevy_dev_tools/src/ui_debug_overlay/inset.rs +++ b/crates/bevy_dev_tools/src/ui_debug_overlay/inset.rs @@ -7,7 +7,7 @@ use bevy_utils::HashMap; use super::{CameraQuery, LayoutRect}; -// Function used here so we don't need to redraw lines that are fairly close to each other. +// Redrawing lines that are fairly close to each other is unnecessary. fn approx_eq(compared: f32, other: f32) -> bool { (compared - other).abs() < 0.001 } diff --git a/crates/bevy_dev_tools/src/ui_debug_overlay/mod.rs b/crates/bevy_dev_tools/src/ui_debug_overlay/mod.rs index 4e72778f15543..cbc4b1a2fc26a 100644 --- a/crates/bevy_dev_tools/src/ui_debug_overlay/mod.rs +++ b/crates/bevy_dev_tools/src/ui_debug_overlay/mod.rs @@ -68,7 +68,7 @@ impl UiDebugOptions { fn update_debug_camera( mut gizmo_config: ResMut, mut options: ResMut, - mut cmds: Commands, + mut commands: Commands, mut debug_cams: Query<&mut Camera, With>, ) { if !options.is_changed() && !gizmo_config.is_changed() { @@ -87,23 +87,24 @@ fn update_debug_camera( } } else { let spawn_cam = || { - cmds.spawn(( - Camera2d, - OrthographicProjection { - far: 1000.0, - viewport_origin: Vec2::new(0.0, 0.0), - ..OrthographicProjection::default_3d() - }, - Camera { - order: LAYOUT_DEBUG_CAMERA_ORDER, - clear_color: ClearColorConfig::None, - ..default() - }, - LAYOUT_DEBUG_LAYERS.clone(), - DebugOverlayCamera, - Name::new("Layout Debug Camera"), - )) - .id() + commands + .spawn(( + Camera2d, + OrthographicProjection { + far: 1000.0, + viewport_origin: Vec2::new(0.0, 0.0), + ..OrthographicProjection::default_3d() + }, + Camera { + order: LAYOUT_DEBUG_CAMERA_ORDER, + clear_color: ClearColorConfig::None, + ..default() + }, + LAYOUT_DEBUG_LAYERS.clone(), + DebugOverlayCamera, + Name::new("Layout Debug Camera"), + )) + .id() }; if let Some((config, _)) = gizmo_config.get_config_mut_dyn(&TypeId::of::()) { config.enabled = true; @@ -269,7 +270,7 @@ impl Plugin for DebugUiPlugin { update_debug_camera, outline_roots .after(TransformSystem::TransformPropagate) - // This needs to run before VisibilityPropagate so it can relies on ViewVisibility + // This needs to run before VisibilityPropagate so that it can rely on ViewVisibility .before(VisibilitySystems::VisibilityPropagate), ) .chain(), diff --git a/crates/bevy_diagnostic/src/system_information_diagnostics_plugin.rs b/crates/bevy_diagnostic/src/system_information_diagnostics_plugin.rs index 975d0f04b745c..870733db8732b 100644 --- a/crates/bevy_diagnostic/src/system_information_diagnostics_plugin.rs +++ b/crates/bevy_diagnostic/src/system_information_diagnostics_plugin.rs @@ -183,7 +183,7 @@ pub mod internal { .physical_core_count() .map(|x| x.to_string()) .unwrap_or_else(|| String::from("not available")), - // Convert from Bytes to GibiBytes since it's probably what people expect most of the time + // Convert from Bytes to Gibibytes since it's probably what people expect most of the time memory: format!("{:.1} GiB", sys.total_memory() as f64 * BYTES_TO_GIB), }; diff --git a/crates/bevy_ecs/macros/src/lib.rs b/crates/bevy_ecs/macros/src/lib.rs index 10f794075466c..84ed5fe7c2e06 100644 --- a/crates/bevy_ecs/macros/src/lib.rs +++ b/crates/bevy_ecs/macros/src/lib.rs @@ -340,7 +340,7 @@ pub fn impl_param_set(_input: TokenStream) -> TokenStream { type State = (#(#param::State,)*); type Item<'w, 's> = ParamSet<'w, 's, (#(#param,)*)>; - // Note: We allow non snake case so the compiler don't complain about the creation of non_snake_case variables + // Note: We allow non snake case so that the compiler doesn't complain about the creation of non_snake_case variables #[allow(non_snake_case)] fn init_state(world: &mut World, system_meta: &mut SystemMeta) -> Self::State { #( diff --git a/crates/bevy_ecs/macros/src/query_filter.rs b/crates/bevy_ecs/macros/src/query_filter.rs index 378e26df101a7..6e83ba289167f 100644 --- a/crates/bevy_ecs/macros/src/query_filter.rs +++ b/crates/bevy_ecs/macros/src/query_filter.rs @@ -120,7 +120,7 @@ pub fn derive_query_filter_impl(input: TokenStream) -> TokenStream { ); let filter_impl = quote! { - // SAFETY: This only performs access that subqueries perform, and they impl `QueryFilter` and so perform no mutable access. + // SAFETY: This only performs access that subqueries perform. The subqueries implement `QueryFilter`, thus perform no mutable access. unsafe impl #user_impl_generics #path::query::QueryFilter for #struct_name #user_ty_generics #user_where_clauses { const IS_ARCHETYPAL: bool = true #(&& <#field_types>::IS_ARCHETYPAL)*; diff --git a/crates/bevy_ecs/src/bundle.rs b/crates/bevy_ecs/src/bundle.rs index 384b7517c77b2..a8b9092614c76 100644 --- a/crates/bevy_ecs/src/bundle.rs +++ b/crates/bevy_ecs/src/bundle.rs @@ -374,21 +374,21 @@ impl BundleInfo { mut component_ids: Vec, id: BundleId, ) -> BundleInfo { - let mut deduped = component_ids.clone(); - deduped.sort_unstable(); - deduped.dedup(); + let mut deduplicated = component_ids.clone(); + deduplicated.sort_unstable(); + deduplicated.dedup(); - if deduped.len() != component_ids.len() { + if deduplicated.len() != component_ids.len() { // TODO: Replace with `Vec::partition_dedup` once https://github.com/rust-lang/rust/issues/54279 is stabilized let mut seen = HashSet::new(); - let mut dups = Vec::new(); + let mut duplicates = Vec::new(); for id in component_ids { if !seen.insert(id) { - dups.push(id); + duplicates.push(id); } } - let names = dups + let names = duplicates .into_iter() .map(|id| { // SAFETY: the caller ensures component_id is valid. diff --git a/crates/bevy_ecs/src/change_detection.rs b/crates/bevy_ecs/src/change_detection.rs index 025c3804e73e2..39a363cefb795 100644 --- a/crates/bevy_ecs/src/change_detection.rs +++ b/crates/bevy_ecs/src/change_detection.rs @@ -1051,7 +1051,7 @@ impl<'w> MutUntyped<'w> { /// Transforms this [`MutUntyped`] into a [`Mut`] with the same lifetime. /// /// # Safety - /// - `T` must be the erased pointee type for this [`MutUntyped`]. + /// - `T` must be the erased, pointee type for this [`MutUntyped`]. pub unsafe fn with_type(self) -> Mut<'w, T> { Mut { // SAFETY: `value` is `Aligned` and caller ensures the pointee type is `T`. diff --git a/crates/bevy_ecs/src/entity/mod.rs b/crates/bevy_ecs/src/entity/mod.rs index c2f687af14d55..23ea321497e02 100644 --- a/crates/bevy_ecs/src/entity/mod.rs +++ b/crates/bevy_ecs/src/entity/mod.rs @@ -350,7 +350,7 @@ impl Entity { /// given index has been reused (index, generation) pairs uniquely identify a given Entity. #[inline] pub const fn generation(self) -> u32 { - // Mask so not to expose any flags + // Mask so as not to expose any flags IdentifierMask::extract_value_from_high(self.generation.get()) } } diff --git a/crates/bevy_ecs/src/event/collections.rs b/crates/bevy_ecs/src/event/collections.rs index c04512ba62bba..48c32cacd26f9 100644 --- a/crates/bevy_ecs/src/event/collections.rs +++ b/crates/bevy_ecs/src/event/collections.rs @@ -32,7 +32,7 @@ use { /// [`event_update_system`] is a system that does this, typically initialized automatically using /// [`add_event`](https://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_event). /// [`EventReader`]s are expected to read events from this collection at least once per loop/frame. -/// Events will persist across a single frame boundary and so ordering of event producers and +/// Events will persist across a single frame boundary, thus ordering of event producers and /// consumers is not critical (although poorly-planned ordering may cause accumulating lag). /// If events are not handled by the end of the frame after they are updated, they will be /// dropped silently. diff --git a/crates/bevy_ecs/src/event/mutator.rs b/crates/bevy_ecs/src/event/mutator.rs index ee77f9961a3b4..7a10f92052b7c 100644 --- a/crates/bevy_ecs/src/event/mutator.rs +++ b/crates/bevy_ecs/src/event/mutator.rs @@ -111,7 +111,7 @@ impl<'w, 's, E: Event> EventMutator<'w, 's, E> { /// # Example /// /// The following example shows a useful pattern where some behavior is triggered if new events are available. - /// [`EventMutator::clear()`] is used so the same events don't re-trigger the behavior the next time the system runs. + /// [`EventMutator::clear()`] is used so that the same events don't re-trigger the behavior the next time the system runs. /// /// ``` /// # use bevy_ecs::prelude::*; diff --git a/crates/bevy_ecs/src/event/reader.rs b/crates/bevy_ecs/src/event/reader.rs index 1611fa6ba5ffc..c86a509492d22 100644 --- a/crates/bevy_ecs/src/event/reader.rs +++ b/crates/bevy_ecs/src/event/reader.rs @@ -83,7 +83,7 @@ impl<'w, 's, E: Event> EventReader<'w, 's, E> { /// # Example /// /// The following example shows a useful pattern where some behavior is triggered if new events are available. - /// [`EventReader::clear()`] is used so the same events don't re-trigger the behavior the next time the system runs. + /// [`EventReader::clear()`] is used so that the same events don't re-trigger the behavior the next time the system runs. /// /// ``` /// # use bevy_ecs::prelude::*; diff --git a/crates/bevy_ecs/src/lib.rs b/crates/bevy_ecs/src/lib.rs index 67254d6298f11..16bdb036a03fc 100644 --- a/crates/bevy_ecs/src/lib.rs +++ b/crates/bevy_ecs/src/lib.rs @@ -350,13 +350,13 @@ mod tests { let e = world.spawn((TableStored("abc"), A(123))).id(); let f = world.spawn((TableStored("def"), A(456))).id(); - let ents = world + let entities = world .query::<(Entity, &A, &TableStored)>() .iter(&world) .map(|(e, &i, &s)| (e, i, s)) .collect::>(); assert_eq!( - ents, + entities, &[ (e, A(123), TableStored("abc")), (f, A(456), TableStored("def")) @@ -389,13 +389,13 @@ mod tests { let mut world = World::new(); let e = world.spawn((TableStored("abc"), A(123))).id(); let f = world.spawn((TableStored("def"), A(456), B(1))).id(); - let ents = world + let entities = world .query::<(Entity, &A)>() .iter(&world) .map(|(e, &i)| (e, i)) .collect::>(); - assert!(ents.contains(&(e, A(123)))); - assert!(ents.contains(&(f, A(456)))); + assert!(entities.contains(&(e, A(123)))); + assert!(entities.contains(&(f, A(456)))); } #[test] @@ -404,12 +404,12 @@ mod tests { let e = world.spawn((TableStored("abc"), A(123))).id(); let mut query = world.query::<(Entity, &A)>(); - let ents = query.iter(&world).map(|(e, &i)| (e, i)).collect::>(); - assert_eq!(ents, &[(e, A(123))]); + let entities = query.iter(&world).map(|(e, &i)| (e, i)).collect::>(); + assert_eq!(entities, &[(e, A(123))]); let f = world.spawn((TableStored("def"), A(456), B(1))).id(); - let ents = query.iter(&world).map(|(e, &i)| (e, i)).collect::>(); - assert_eq!(ents, &[(e, A(123)), (f, A(456))]); + let entities = query.iter(&world).map(|(e, &i)| (e, i)).collect::>(); + assert_eq!(entities, &[(e, A(123)), (f, A(456))]); } #[test] @@ -485,12 +485,12 @@ mod tests { let mut world = World::new(); world.spawn((TableStored("abc"), A(123))); let f = world.spawn((TableStored("def"), A(456), B(1))).id(); - let ents = world + let entities = world .query::<(Entity, &B)>() .iter(&world) .map(|(e, &b)| (e, b)) .collect::>(); - assert_eq!(ents, &[(f, B(1))]); + assert_eq!(entities, &[(f, B(1))]); } #[test] @@ -568,13 +568,13 @@ mod tests { let f = world.spawn((TableStored("def"), A(456), B(1))).id(); // this should be skipped world.spawn(TableStored("abc")); - let ents = world + let entities = world .query::<(Entity, Option<&B>, &A)>() .iter(&world) .map(|(e, b, &i)| (e, b.copied(), i)) .collect::>(); - assert!(ents.contains(&(e, None, A(123)))); - assert!(ents.contains(&(f, Some(B(1)), A(456)))); + assert!(entities.contains(&(e, None, A(123)))); + assert!(entities.contains(&(f, Some(B(1)), A(456)))); } #[test] @@ -587,13 +587,13 @@ mod tests { .id(); // this should be skipped // world.spawn(SparseStored(1)); - let ents = world + let entities = world .query::<(Entity, Option<&SparseStored>, &A)>() .iter(&world) .map(|(e, b, &i)| (e, b.copied(), i)) .collect::>(); assert_eq!( - ents, + entities, HashSet::from([(e, None, A(123)), (f, Some(SparseStored(1)), A(456))]) ); } @@ -606,12 +606,12 @@ mod tests { let f = world.spawn((TableStored("def"), A(456))).id(); // // this should be skipped world.spawn(TableStored("abc")); - let ents = world + let entities = world .query::<(Entity, Option<&SparseStored>, &A)>() .iter(&world) .map(|(e, b, &i)| (e, b.copied(), i)) .collect::>(); - assert_eq!(ents, &[(e, None, A(123)), (f, None, A(456))]); + assert_eq!(entities, &[(e, None, A(123)), (f, None, A(456))]); } #[test] @@ -1436,7 +1436,7 @@ mod tests { } #[test] - fn query_filters_dont_collide_with_fetches() { + fn query_filters_do_not_collide_with_fetches() { let mut world = World::new(); world.query_filtered::<&mut A, Changed>(); } diff --git a/crates/bevy_ecs/src/observer/mod.rs b/crates/bevy_ecs/src/observer/mod.rs index 674f98f650725..68493a6ec6ff3 100644 --- a/crates/bevy_ecs/src/observer/mod.rs +++ b/crates/bevy_ecs/src/observer/mod.rs @@ -468,7 +468,7 @@ impl World { if descriptor.components.is_empty() && descriptor.entities.is_empty() { cache.map.insert(observer_entity, observer_state.runner); } else if descriptor.components.is_empty() { - // Observer is not targeting any components so register it as an entity observer + // Observer is not targeting any components, so register it as an entity observer for &watched_entity in &observer_state.descriptor.entities { let map = cache.entity_observers.entry(watched_entity).or_default(); map.insert(observer_entity, observer_state.runner); diff --git a/crates/bevy_ecs/src/observer/runner.rs b/crates/bevy_ecs/src/observer/runner.rs index f2bfb465c85fb..4c73a1a1b5e54 100644 --- a/crates/bevy_ecs/src/observer/runner.rs +++ b/crates/bevy_ecs/src/observer/runner.rs @@ -332,13 +332,13 @@ fn observer_system_runner>( propagate: &mut bool, ) { let world = world.as_unsafe_world_cell(); - // SAFETY: Observer was triggered so must still exist in world + // SAFETY: Observer was triggered, so the entity must still exist in world let observer_cell = unsafe { world .get_entity(observer_trigger.observer) .debug_checked_unwrap() }; - // SAFETY: Observer was triggered so must have an `ObserverState` + // SAFETY: Observer was triggered, so the entity must have an `ObserverState` let mut state = unsafe { observer_cell .get_mut::() @@ -359,7 +359,7 @@ fn observer_system_runner>( observer_trigger, ); // SAFETY: - // - observer was triggered so must have an `Observer` component. + // - observer was triggered, so the entity must have an `Observer` component. // - observer cannot be dropped or mutated until after the system pointer is already dropped. let system: *mut dyn ObserverSystem = unsafe { let mut observe = observer_cell.get_mut::().debug_checked_unwrap(); @@ -370,7 +370,7 @@ fn observer_system_runner>( // SAFETY: // - `update_archetype_component_access` is called first // - there are no outstanding references to world except a private component - // - system is an `ObserverSystem` so won't mutate world beyond the access of a `DeferredWorld` + // - system is an `ObserverSystem`, so this won't mutate world beyond the access of a `DeferredWorld` // - system is the same type erased system from above unsafe { (*system).update_archetype_component_access(world); diff --git a/crates/bevy_ecs/src/query/access.rs b/crates/bevy_ecs/src/query/access.rs index 00167383fe803..5e0e158fecaac 100644 --- a/crates/bevy_ecs/src/query/access.rs +++ b/crates/bevy_ecs/src/query/access.rs @@ -1209,10 +1209,10 @@ impl FilteredAccessSet { /// compatible. /// 2. A "fine grained" check, it kicks in when the "coarse" check fails. /// the two access sets might still be compatible if some of the accesses - /// are restricted with the [`With`](super::With) or [`Without`](super::Without) filters so that access is - /// mutually exclusive. The fine grained phase iterates over all filters in - /// the `self` set and compares it to all the filters in the `other` set, - /// making sure they are all mutually compatible. + /// are restricted with the [`With`](super::With) or [`Without`](super::Without) + /// filters so that access is mutually exclusive. The fine grained phase + /// iterates over all filters in the `self` set and compares it to all the + /// filters in the `other` set, making sure they are all mutually compatible. pub fn is_compatible(&self, other: &FilteredAccessSet) -> bool { if self.combined_access.is_compatible(other.combined_access()) { return true; diff --git a/crates/bevy_ecs/src/query/filter.rs b/crates/bevy_ecs/src/query/filter.rs index ff73d6ca50016..0c30d8f13a6f0 100644 --- a/crates/bevy_ecs/src/query/filter.rs +++ b/crates/bevy_ecs/src/query/filter.rs @@ -499,7 +499,7 @@ macro_rules! impl_or_query_filter { } $(#[$meta])* - // SAFETY: This only performs access that subqueries perform, and they impl `QueryFilter` and so perform no mutable access. + // SAFETY: This only performs access that subqueries perform. The subqueries implement `QueryFilter`, thus perform no mutable access. unsafe impl<$($filter: QueryFilter),*> QueryFilter for Or<($($filter,)*)> { const IS_ARCHETYPAL: bool = true $(&& $filter::IS_ARCHETYPAL)*; @@ -522,7 +522,7 @@ macro_rules! impl_tuple_query_filter { #[allow(non_snake_case)] #[allow(clippy::unused_unit)] $(#[$meta])* - // SAFETY: This only performs access that subqueries perform, and they impl `QueryFilter` and so perform no mutable access. + // SAFETY: This only performs access that subqueries perform. The subqueries implement `QueryFilter`, thus perform no mutable access. unsafe impl<$($name: QueryFilter),*> QueryFilter for ($($name,)*) { const IS_ARCHETYPAL: bool = true $(&& $name::IS_ARCHETYPAL)*; diff --git a/crates/bevy_ecs/src/query/iter.rs b/crates/bevy_ecs/src/query/iter.rs index bf4c5432546f9..66b8b78a49d2f 100644 --- a/crates/bevy_ecs/src/query/iter.rs +++ b/crates/bevy_ecs/src/query/iter.rs @@ -130,7 +130,7 @@ impl<'w, 's, D: QueryData, F: QueryFilter> QueryIter<'w, 's, D, F> { #[inline] pub(super) unsafe fn fold_over_storage_range( &mut self, - mut accum: B, + mut accumulator: B, func: &mut Func, storage: StorageId, range: Option>, @@ -145,12 +145,12 @@ impl<'w, 's, D: QueryData, F: QueryFilter> QueryIter<'w, 's, D, F> { let table = unsafe { self.tables.get(table_id).debug_checked_unwrap() }; let range = range.unwrap_or(0..table.entity_count()); - accum = + accumulator = // SAFETY: // - The fetched table matches both D and F // - caller ensures `range` is within `[0, table.entity_count)` // - The if block ensures that the query iteration is dense - unsafe { self.fold_over_table_range(accum, func, table, range) }; + unsafe { self.fold_over_table_range(accumulator, func, table, range) }; } else { // SAFETY: `self.cursor.is_dense` is false, so storage ids are guaranteed to be archetype ids. let archetype_id = unsafe { storage.archetype_id }; @@ -164,23 +164,23 @@ impl<'w, 's, D: QueryData, F: QueryFilter> QueryIter<'w, 's, D, F> { // When an archetype and its table have equal entity counts, dense iteration can be safely used. // this leverages cache locality to optimize performance. if table.entity_count() == archetype.len() { - accum = + accumulator = // SAFETY: // - The fetched archetype matches both D and F // - The provided archetype and its' table have the same length. // - caller ensures `range` is within `[0, archetype.len)` // - The if block ensures that the query iteration is not dense. - unsafe { self.fold_over_dense_archetype_range(accum, func, archetype,range) }; + unsafe { self.fold_over_dense_archetype_range(accumulator, func, archetype,range) }; } else { - accum = + accumulator = // SAFETY: // - The fetched archetype matches both D and F // - caller ensures `range` is within `[0, archetype.len)` // - The if block ensures that the query iteration is not dense. - unsafe { self.fold_over_archetype_range(accum, func, archetype,range) }; + unsafe { self.fold_over_archetype_range(accumulator, func, archetype,range) }; } } - accum + accumulator } /// Executes the equivalent of [`Iterator::fold`] over a contiguous segment @@ -193,7 +193,7 @@ impl<'w, 's, D: QueryData, F: QueryFilter> QueryIter<'w, 's, D, F> { #[inline] pub(super) unsafe fn fold_over_table_range( &mut self, - mut accum: B, + mut accumulator: B, func: &mut Func, table: &'w Table, rows: Range, @@ -202,7 +202,7 @@ impl<'w, 's, D: QueryData, F: QueryFilter> QueryIter<'w, 's, D, F> { Func: FnMut(B, D::Item<'w>) -> B, { if table.is_empty() { - return accum; + return accumulator; } debug_assert!( rows.end <= u32::MAX as usize, @@ -233,9 +233,9 @@ impl<'w, 's, D: QueryData, F: QueryFilter> QueryIter<'w, 's, D, F> { // Caller assures `row` in range of the current archetype. let item = D::fetch(&mut self.cursor.fetch, *entity, row); - accum = func(accum, item); + accumulator = func(accumulator, item); } - accum + accumulator } /// Executes the equivalent of [`Iterator::fold`] over a contiguous segment @@ -248,7 +248,7 @@ impl<'w, 's, D: QueryData, F: QueryFilter> QueryIter<'w, 's, D, F> { #[inline] pub(super) unsafe fn fold_over_archetype_range( &mut self, - mut accum: B, + mut accumulator: B, func: &mut Func, archetype: &'w Archetype, indices: Range, @@ -257,7 +257,7 @@ impl<'w, 's, D: QueryData, F: QueryFilter> QueryIter<'w, 's, D, F> { Func: FnMut(B, D::Item<'w>) -> B, { if archetype.is_empty() { - return accum; + return accumulator; } let table = self.tables.get(archetype.table_id()).debug_checked_unwrap(); D::set_archetype( @@ -301,9 +301,9 @@ impl<'w, 's, D: QueryData, F: QueryFilter> QueryIter<'w, 's, D, F> { ) }; - accum = func(accum, item); + accumulator = func(accumulator, item); } - accum + accumulator } /// Executes the equivalent of [`Iterator::fold`] over a contiguous segment @@ -317,7 +317,7 @@ impl<'w, 's, D: QueryData, F: QueryFilter> QueryIter<'w, 's, D, F> { #[inline] pub(super) unsafe fn fold_over_dense_archetype_range( &mut self, - mut accum: B, + mut accumulator: B, func: &mut Func, archetype: &'w Archetype, rows: Range, @@ -326,7 +326,7 @@ impl<'w, 's, D: QueryData, F: QueryFilter> QueryIter<'w, 's, D, F> { Func: FnMut(B, D::Item<'w>) -> B, { if archetype.is_empty() { - return accum; + return accumulator; } debug_assert!( rows.end <= u32::MAX as usize, @@ -367,9 +367,9 @@ impl<'w, 's, D: QueryData, F: QueryFilter> QueryIter<'w, 's, D, F> { // Caller assures `row` in range of the current archetype. let item = D::fetch(&mut self.cursor.fetch, entity, row); - accum = func(accum, item); + accumulator = func(accumulator, item); } - accum + accumulator } /// Sorts all query items into a new iterator, using the query lens as a key. @@ -1084,19 +1084,19 @@ impl<'w, 's, D: QueryData, F: QueryFilter> Iterator for QueryIter<'w, 's, D, F> where Func: FnMut(B, Self::Item) -> B, { - let mut accum = init; + let mut accumulator = init; // Empty any remaining uniterated values from the current table/archetype while self.cursor.current_row != self.cursor.current_len { let Some(item) = self.next() else { break }; - accum = func(accum, item); + accumulator = func(accumulator, item); } for id in self.cursor.storage_id_iter.clone().copied() { // SAFETY: // - The range(None) is equivalent to [0, storage.entity_count) - accum = unsafe { self.fold_over_storage_range(accum, &mut func, id, None) }; + accumulator = unsafe { self.fold_over_storage_range(accumulator, &mut func, id, None) }; } - accum + accumulator } } diff --git a/crates/bevy_ecs/src/query/mod.rs b/crates/bevy_ecs/src/query/mod.rs index 0a9f664fb50ba..8930a65402cad 100644 --- a/crates/bevy_ecs/src/query/mod.rs +++ b/crates/bevy_ecs/src/query/mod.rs @@ -146,7 +146,7 @@ mod tests { } #[test] - fn query_filtered_exactsizeiterator_len() { + fn query_filtered_exact_size_iterator_len() { fn choose(n: usize, k: usize) -> usize { if n == 0 || k == 0 || n < k { return 0; @@ -349,14 +349,14 @@ mod tests { world.spawn(A(3)); world.spawn(A(4)); - let mut a_wout_b = world.query_filtered::<&A, Without>(); - let values: HashSet<[&A; 2]> = a_wout_b.iter_combinations(&world).collect(); + let mut a_without_b = world.query_filtered::<&A, Without>(); + let values: HashSet<[&A; 2]> = a_without_b.iter_combinations(&world).collect(); check_combinations( values, HashSet::from([[&A(2), &A(3)], [&A(2), &A(4)], [&A(3), &A(4)]]), ); - let values: HashSet<[&A; 3]> = a_wout_b.iter_combinations(&world).collect(); + let values: HashSet<[&A; 3]> = a_without_b.iter_combinations(&world).collect(); check_combinations(values, HashSet::from([[&A(2), &A(3), &A(4)]])); let mut query = world.query_filtered::<&A, Or<(With, With)>>(); @@ -381,7 +381,7 @@ mod tests { c.0 += 1000; } - let values: HashSet<[&A; 3]> = a_wout_b.iter_combinations(&world).collect(); + let values: HashSet<[&A; 3]> = a_without_b.iter_combinations(&world).collect(); check_combinations(values, HashSet::from([[&A(12), &A(103), &A(1004)]])); // Check if Added, Changed works @@ -490,7 +490,7 @@ mod tests { #[test] #[should_panic = "&mut bevy_ecs::query::tests::A conflicts with a previous access in this query."] - fn self_conflicting_worldquery() { + fn self_conflicting_world_query() { #[derive(QueryData)] #[query_data(mutable)] struct SelfConflicting { @@ -503,7 +503,7 @@ mod tests { } #[test] - fn derived_worldqueries() { + fn derived_world_queries() { let mut world = World::new(); world.spawn((A(10), B(18), C(3), Sparse(4))); @@ -728,7 +728,7 @@ mod tests { } #[test] - fn mut_to_immut_query_methods_have_immut_item() { + fn mut_to_immutable_query_methods_have_immutable_item() { #[derive(Component)] struct Foo; diff --git a/crates/bevy_ecs/src/query/state.rs b/crates/bevy_ecs/src/query/state.rs index 69b67368fe4f3..8b3b2e414f2ad 100644 --- a/crates/bevy_ecs/src/query/state.rs +++ b/crates/bevy_ecs/src/query/state.rs @@ -1485,7 +1485,7 @@ impl QueryState { #[cfg(all(not(target_arch = "wasm32"), feature = "multi_threaded"))] pub(crate) unsafe fn par_fold_init_unchecked_manual<'w, T, FN, INIT>( &self, - init_accum: INIT, + init_accumulator: INIT, world: UnsafeWorldCell<'w>, batch_size: usize, func: FN, @@ -1513,14 +1513,15 @@ impl QueryState { } let queue = core::mem::take(queue); let mut func = func.clone(); - let init_accum = init_accum.clone(); + let init_accumulator = init_accumulator.clone(); scope.spawn(async move { #[cfg(feature = "trace")] let _span = self.par_iter_span.enter(); let mut iter = self.iter_unchecked_manual(world, last_run, this_run); - let mut accum = init_accum(); + let mut accumulator = init_accumulator(); for storage_id in queue { - accum = iter.fold_over_storage_range(accum, &mut func, storage_id, None); + accumulator = + iter.fold_over_storage_range(accumulator, &mut func, storage_id, None); } }); }; @@ -1529,15 +1530,20 @@ impl QueryState { let submit_single = |count, storage_id: StorageId| { for offset in (0..count).step_by(batch_size) { let mut func = func.clone(); - let init_accum = init_accum.clone(); + let init_accumulator = init_accumulator.clone(); let len = batch_size.min(count - offset); let batch = offset..offset + len; scope.spawn(async move { #[cfg(feature = "trace")] let _span = self.par_iter_span.enter(); - let accum = init_accum(); + let accumulator = init_accumulator(); self.iter_unchecked_manual(world, last_run, this_run) - .fold_over_storage_range(accum, &mut func, storage_id, Some(batch)); + .fold_over_storage_range( + accumulator, + &mut func, + storage_id, + Some(batch), + ); }); } }; @@ -1875,7 +1881,7 @@ mod tests { } #[test] - fn can_transmute_immut_fetch() { + fn can_transmute_immutable_fetch() { let mut world = World::new(); world.spawn(A(10)); @@ -1934,7 +1940,7 @@ mod tests { #[should_panic( expected = "Transmuted state for (&mut bevy_ecs::query::state::tests::A, ()) attempts to access terms that are not allowed by original state (&bevy_ecs::query::state::tests::A, ())." )] - fn cannot_transmute_immut_to_mut() { + fn cannot_transmute_immutable_to_mut() { let mut world = World::new(); world.spawn(A(0)); @@ -1946,7 +1952,7 @@ mod tests { #[should_panic( expected = "Transmuted state for (&bevy_ecs::query::state::tests::A, ()) attempts to access terms that are not allowed by original state (core::option::Option<&bevy_ecs::query::state::tests::A>, ())." )] - fn cannot_transmute_option_to_immut() { + fn cannot_transmute_option_to_immutable() { let mut world = World::new(); world.spawn(C(0)); diff --git a/crates/bevy_ecs/src/removal_detection.rs b/crates/bevy_ecs/src/removal_detection.rs index 7df072ab2d39f..70d84a679eba5 100644 --- a/crates/bevy_ecs/src/removal_detection.rs +++ b/crates/bevy_ecs/src/removal_detection.rs @@ -191,7 +191,7 @@ impl<'w, 's, T: Component> RemovedComponents<'w, 's, T> { /// and a reference to `Events`. /// /// This is necessary since Rust can't detect destructuring through methods and most - /// usecases of the reader uses the `Events` as well. + /// use cases of the reader uses the `Events` as well. pub fn reader_mut_with_events( &mut self, ) -> Option<( diff --git a/crates/bevy_ecs/src/schedule/condition.rs b/crates/bevy_ecs/src/schedule/condition.rs index 6956d2715069f..be3aea4cad990 100644 --- a/crates/bevy_ecs/src/schedule/condition.rs +++ b/crates/bevy_ecs/src/schedule/condition.rs @@ -521,11 +521,11 @@ pub mod common_conditions { /// counter.0 += 1; /// } /// - /// // This is the first time the condition will be evaluated so `my_system` will run + /// // This is the first time the condition will be evaluated, so `my_system` will run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 1); /// - /// // This is the seconds time the condition will be evaluated so `my_system` won't run + /// // This is the seconds time the condition will be evaluated, so `my_system` won't run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 1); /// ``` @@ -558,11 +558,11 @@ pub mod common_conditions { /// counter.0 += 1; /// } /// - /// // `Counter` hasn't been added so `my_system` won't run + /// // `Counter` hasn't been added, so `my_system` won't run /// app.run(&mut world); /// world.init_resource::(); /// - /// // `Counter` has now been added so `my_system` can run + /// // `Counter` has now been added, so `my_system` can run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 1); /// ``` @@ -598,11 +598,11 @@ pub mod common_conditions { /// counter.0 += 1; /// } /// - /// // `Counter` is `0` so `my_system` can run + /// // `Counter` is `0`, so `my_system` can run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 1); /// - /// // `Counter` is no longer `0` so `my_system` won't run + /// // `Counter` is no longer `0`, so `my_system` won't run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 1); /// ``` @@ -636,7 +636,7 @@ pub mod common_conditions { /// counter.0 += 1; /// } /// - /// // `Counter` hasn't been added so `my_system` can't run + /// // `Counter` hasn't been added, so `my_system` can't run /// app.run(&mut world); /// world.init_resource::(); /// @@ -681,11 +681,11 @@ pub mod common_conditions { /// /// world.init_resource::(); /// - /// // `Counter` was just added so `my_system` will run + /// // `Counter` was just added, so `my_system` will run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 1); /// - /// // `Counter` was not just added so `my_system` will not run + /// // `Counter` was not just added, so `my_system` will not run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 1); /// ``` @@ -726,7 +726,7 @@ pub mod common_conditions { /// my_system.run_if( /// resource_changed:: /// // By default detecting changes will also trigger if the resource was - /// // just added, this won't work with my example so I will add a second + /// // just added, this won't work with my example, so I will add a second /// // condition to make sure the resource wasn't just added /// .and(not(resource_added::)) /// ), @@ -736,13 +736,13 @@ pub mod common_conditions { /// counter.0 += 1; /// } /// - /// // `Counter` hasn't been changed so `my_system` won't run + /// // `Counter` hasn't been changed, so `my_system` won't run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 0); /// /// world.resource_mut::().0 = 50; /// - /// // `Counter` was just changed so `my_system` will run + /// // `Counter` was just changed, so `my_system` will run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 51); /// ``` @@ -779,7 +779,7 @@ pub mod common_conditions { /// my_system.run_if( /// resource_exists_and_changed:: /// // By default detecting changes will also trigger if the resource was - /// // just added, this won't work with my example so I will add a second + /// // just added, this won't work with my example, so I will add a second /// // condition to make sure the resource wasn't just added /// .and(not(resource_added::)) /// ), @@ -789,17 +789,17 @@ pub mod common_conditions { /// counter.0 += 1; /// } /// - /// // `Counter` doesn't exist so `my_system` won't run + /// // `Counter` doesn't exist, so `my_system` won't run /// app.run(&mut world); /// world.init_resource::(); /// - /// // `Counter` hasn't been changed so `my_system` won't run + /// // `Counter` hasn't been changed, so `my_system` won't run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 0); /// /// world.resource_mut::().0 = 50; /// - /// // `Counter` was just changed so `my_system` will run + /// // `Counter` was just changed, so `my_system` will run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 51); /// ``` @@ -841,7 +841,7 @@ pub mod common_conditions { /// my_system.run_if( /// resource_changed_or_removed:: /// // By default detecting changes will also trigger if the resource was - /// // just added, this won't work with my example so I will add a second + /// // just added, this won't work with my example, so I will add a second /// // condition to make sure the resource wasn't just added /// .and(not(resource_added::)) /// ), @@ -859,19 +859,19 @@ pub mod common_conditions { /// } /// } /// - /// // `Counter` hasn't been changed so `my_system` won't run + /// // `Counter` hasn't been changed, so `my_system` won't run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 0); /// /// world.resource_mut::().0 = 50; /// - /// // `Counter` was just changed so `my_system` will run + /// // `Counter` was just changed, so `my_system` will run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 51); /// /// world.remove_resource::(); /// - /// // `Counter` was just removed so `my_system` will run + /// // `Counter` was just removed, so `my_system` will run /// app.run(&mut world); /// assert_eq!(world.contains_resource::(), true); /// ``` @@ -917,13 +917,13 @@ pub mod common_conditions { /// /// world.init_resource::(); /// - /// // `MyResource` hasn't just been removed so `my_system` won't run + /// // `MyResource` hasn't just been removed, so `my_system` won't run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 0); /// /// world.remove_resource::(); /// - /// // `MyResource` was just removed so `my_system` will run + /// // `MyResource` was just removed, so `my_system` will run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 1); /// ``` @@ -968,13 +968,13 @@ pub mod common_conditions { /// counter.0 += 1; /// } /// - /// // No new `MyEvent` events have been push so `my_system` won't run + /// // No new `MyEvent` events have been pushed, so `my_system` won't run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 0); /// /// world.resource_mut::>().send(MyEvent); /// - /// // A `MyEvent` event has been pushed so `my_system` will run + /// // A `MyEvent` event has been pushed, so `my_system` will run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 1); /// ``` @@ -1009,13 +1009,13 @@ pub mod common_conditions { /// counter.0 += 1; /// } /// - /// // No entities exist yet with a `MyComponent` component so `my_system` won't run + /// // No entities exist yet with a `MyComponent` component, so `my_system` won't run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 0); /// /// world.spawn(MyComponent); /// - /// // An entities with `MyComponent` now exists so `my_system` will run + /// // An entities with `MyComponent` now exists, so `my_system` will run /// app.run(&mut world); /// assert_eq!(world.resource::().0, 1); /// ``` diff --git a/crates/bevy_ecs/src/schedule/config.rs b/crates/bevy_ecs/src/schedule/config.rs index fd0aa58a8d950..67b1df13e282a 100644 --- a/crates/bevy_ecs/src/schedule/config.rs +++ b/crates/bevy_ecs/src/schedule/config.rs @@ -370,7 +370,7 @@ where /// /// Because the conditions are evaluated separately for each system, there is no guarantee /// that all evaluations in a single schedule run will yield the same result. If another - /// system is run inbetween two evaluations it could cause the result of the condition to change. + /// system is run in-between two evaluations it could cause the result of the condition to change. /// /// Use [`run_if`](IntoSystemSetConfigs::run_if) on a [`SystemSet`] if you want to make sure /// that either all or none of the systems are run, or you don't want to evaluate the run @@ -405,7 +405,7 @@ where /// /// Because the condition will only be evaluated once, there is no guarantee that the condition /// is upheld after the first system has run. You need to make sure that no other systems that - /// could invalidate the condition are scheduled inbetween the first and last run system. + /// could invalidate the condition are scheduled in-between the first and last run system. /// /// Use [`distributive_run_if`](IntoSystemConfigs::distributive_run_if) if you want the /// condition to be evaluated for each individual system, right before one is run. @@ -429,7 +429,7 @@ where /// /// Ordering constraints will be applied between the successive elements. /// - /// If the preceding node on a edge has deferred parameters, a [`apply_deferred`](crate::schedule::apply_deferred) + /// If the preceding node on an edge has deferred parameters, a [`apply_deferred`](crate::schedule::apply_deferred) /// will be inserted on the edge. If this behavior is not desired consider using /// [`chain_ignore_deferred`](Self::chain_ignore_deferred) instead. fn chain(self) -> SystemConfigs { diff --git a/crates/bevy_ecs/src/schedule/executor/multi_threaded.rs b/crates/bevy_ecs/src/schedule/executor/multi_threaded.rs index 53453240dcb88..98316e9de429a 100644 --- a/crates/bevy_ecs/src/schedule/executor/multi_threaded.rs +++ b/crates/bevy_ecs/src/schedule/executor/multi_threaded.rs @@ -298,7 +298,7 @@ impl<'scope, 'env: 'scope, 'sys> Context<'scope, 'env, 'sys> { fn tick_executor(&self) { // Ensure that the executor handles any events pushed to the system_completion queue by this thread. - // If this thread acquires the lock, the exector runs after the push() and they are processed. + // If this thread acquires the lock, the executor runs after the push() and they are processed. // If this thread does not acquire the lock, then the is_empty() check on the other thread runs // after the lock is released, which is after try_lock() failed, which is after the push() // on this thread, so the is_empty() check will see the new events and loop. diff --git a/crates/bevy_ecs/src/schedule/executor/simple.rs b/crates/bevy_ecs/src/schedule/executor/simple.rs index 508f1fbffd07a..f4eae2b4b89d9 100644 --- a/crates/bevy_ecs/src/schedule/executor/simple.rs +++ b/crates/bevy_ecs/src/schedule/executor/simple.rs @@ -148,9 +148,9 @@ fn skip_automatic_sync_points() { // Schedules automatically insert apply_deferred systems, but these should // not be executed as they only serve as markers and are not initialized use crate::prelude::*; - let mut sched = Schedule::default(); - sched.set_executor_kind(ExecutorKind::Simple); - sched.add_systems((|_: Commands| (), || ()).chain()); + let mut schedule = Schedule::default(); + schedule.set_executor_kind(ExecutorKind::Simple); + schedule.add_systems((|_: Commands| (), || ()).chain()); let mut world = World::new(); - sched.run(&mut world); + schedule.run(&mut world); } diff --git a/crates/bevy_ecs/src/schedule/graph_utils.rs b/crates/bevy_ecs/src/schedule/graph_utils.rs index a92579ca58293..f8ae4bfa33266 100644 --- a/crates/bevy_ecs/src/schedule/graph_utils.rs +++ b/crates/bevy_ecs/src/schedule/graph_utils.rs @@ -149,16 +149,16 @@ where let n = graph.node_count(); - // build a copy of the graph where the nodes and edges appear in topsorted order + // build a copy of the graph where the nodes and edges appear in topologically-sorted order let mut map = HashMap::with_capacity(n); - let mut topsorted = DiGraphMap::::new(); + let mut topologically_sorted = DiGraphMap::::new(); // iterate nodes in topological order for (i, &node) in topological_order.iter().enumerate() { map.insert(node, i); - topsorted.add_node(node); + topologically_sorted.add_node(node); // insert nodes as successors to their predecessors for pred in graph.neighbors_directed(node, Incoming) { - topsorted.add_edge(pred, node, ()); + topologically_sorted.add_edge(pred, node, ()); } } @@ -173,16 +173,16 @@ where let mut visited = FixedBitSet::with_capacity(n); // iterate nodes in topological order - for node in topsorted.nodes() { + for node in topologically_sorted.nodes() { transitive_reduction.add_node(node); transitive_closure.add_node(node); } // iterate nodes in reverse topological order - for a in topsorted.nodes().rev() { + for a in topologically_sorted.nodes().rev() { let index_a = *map.get(&a).unwrap(); // iterate their successors in topological order - for b in topsorted.neighbors_directed(a, Outgoing) { + for b in topologically_sorted.neighbors_directed(a, Outgoing) { let index_b = *map.get(&b).unwrap(); debug_assert!(index_a < index_b); if !visited[index_b] { @@ -214,7 +214,7 @@ where // partition pairs of nodes into "connected by path" and "not connected by path" for i in 0..(n - 1) { - // reachable is upper triangular because the nodes were topsorted + // reachable is upper triangular because the nodes were topologically sorted for index in index(i, i + 1, n)..=index(i, n - 1, n) { let (a, b) = row_col(index, n); let pair = (topological_order[a], topological_order[b]); diff --git a/crates/bevy_ecs/src/schedule/mod.rs b/crates/bevy_ecs/src/schedule/mod.rs index 73689d57ce57b..8550e12f35a8a 100644 --- a/crates/bevy_ecs/src/schedule/mod.rs +++ b/crates/bevy_ecs/src/schedule/mod.rs @@ -1114,7 +1114,7 @@ mod tests { ), ]; - // ordering isn't stable so do this + // ordering isn't stable, so do this for entry in expected { assert!(ambiguities.contains(entry)); } diff --git a/crates/bevy_ecs/src/schedule/schedule.rs b/crates/bevy_ecs/src/schedule/schedule.rs index b00304ae1462d..b83b2bfd78eb5 100644 --- a/crates/bevy_ecs/src/schedule/schedule.rs +++ b/crates/bevy_ecs/src/schedule/schedule.rs @@ -1083,11 +1083,14 @@ impl ScheduleGraph { self.hierarchy.topsort = self.topsort_graph(&self.hierarchy.graph, ReportCycles::Hierarchy)?; - let hier_results = check_graph(&self.hierarchy.graph, &self.hierarchy.topsort); - self.optionally_check_hierarchy_conflicts(&hier_results.transitive_edges, schedule_label)?; + let hierarchy_results = check_graph(&self.hierarchy.graph, &self.hierarchy.topsort); + self.optionally_check_hierarchy_conflicts( + &hierarchy_results.transitive_edges, + schedule_label, + )?; // remove redundant edges - self.hierarchy.graph = hier_results.transitive_reduction; + self.hierarchy.graph = hierarchy_results.transitive_reduction; // check dependencies for cycles self.dependency.topsort = @@ -1095,7 +1098,7 @@ impl ScheduleGraph { // check for systems or system sets depending on sets they belong to let dep_results = check_graph(&self.dependency.graph, &self.dependency.topsort); - self.check_for_cross_dependencies(&dep_results, &hier_results.connected)?; + self.check_for_cross_dependencies(&dep_results, &hierarchy_results.connected)?; // map all system sets to their systems // go in reverse topological order (bottom-up) for efficiency @@ -1140,7 +1143,7 @@ impl ScheduleGraph { self.conflicting_systems = conflicting_systems; // build the schedule - Ok(self.build_schedule_inner(dependency_flattened_dag, hier_results.reachable)) + Ok(self.build_schedule_inner(dependency_flattened_dag, hierarchy_results.reachable)) } // modify the graph to have sync nodes for any dependents after a system with deferred system params @@ -1149,12 +1152,14 @@ impl ScheduleGraph { dependency_flattened: &mut GraphMap, ) -> Result, ScheduleBuildError> { let mut sync_point_graph = dependency_flattened.clone(); - let topo = self.topsort_graph(dependency_flattened, ReportCycles::Dependency)?; + let topologically_sorted = + self.topsort_graph(dependency_flattened, ReportCycles::Dependency)?; // calculate the number of sync points each sync point is from the beginning of the graph // use the same sync point if the distance is the same - let mut distances: HashMap> = HashMap::with_capacity(topo.len()); - for node in &topo { + let mut distances: HashMap> = + HashMap::with_capacity(topologically_sorted.len()); + for node in &topologically_sorted { let add_sync_after = self.systems[node.index()].get().unwrap().has_deferred(); for target in dependency_flattened.neighbors_directed(*node, Outgoing) { @@ -1395,7 +1400,7 @@ impl ScheduleGraph { fn build_schedule_inner( &self, dependency_flattened_dag: Dag, - hier_results_reachable: FixedBitSet, + hierarchy_results_reachable: FixedBitSet, ) -> SystemSchedule { let dg_system_ids = dependency_flattened_dag.topsort.clone(); let dg_system_idx_map = dg_system_ids @@ -1414,7 +1419,7 @@ impl ScheduleGraph { .filter(|&(_i, id)| id.is_system()) .collect::>(); - let (hg_set_with_conditions_idxs, hg_set_ids): (Vec<_>, Vec<_>) = self + let (hg_set_with_conditions_indexes, hg_set_ids): (Vec<_>, Vec<_>) = self .hierarchy .topsort .iter() @@ -1455,11 +1460,11 @@ impl ScheduleGraph { // (needed to we can evaluate conditions in the correct order) let mut systems_in_sets_with_conditions = vec![FixedBitSet::with_capacity(sys_count); set_with_conditions_count]; - for (i, &row) in hg_set_with_conditions_idxs.iter().enumerate() { + for (i, &row) in hg_set_with_conditions_indexes.iter().enumerate() { let bitset = &mut systems_in_sets_with_conditions[i]; for &(col, sys_id) in &hg_systems { let idx = dg_system_idx_map[&sys_id]; - let is_descendant = hier_results_reachable[index(row, col, hg_node_count)]; + let is_descendant = hierarchy_results_reachable[index(row, col, hg_node_count)]; bitset.set(idx, is_descendant); } } @@ -1469,12 +1474,12 @@ impl ScheduleGraph { for &(col, sys_id) in &hg_systems { let i = dg_system_idx_map[&sys_id]; let bitset = &mut sets_with_conditions_of_systems[i]; - for (idx, &row) in hg_set_with_conditions_idxs + for (idx, &row) in hg_set_with_conditions_indexes .iter() .enumerate() .take_while(|&(_idx, &row)| row < col) { - let is_ancestor = hier_results_reachable[index(row, col, hg_node_count)]; + let is_ancestor = hierarchy_results_reachable[index(row, col, hg_node_count)]; bitset.set(idx, is_ancestor); } } @@ -1782,10 +1787,11 @@ impl ScheduleGraph { fn check_for_cross_dependencies( &self, dep_results: &CheckGraphResults, - hier_results_connected: &HashSet<(NodeId, NodeId)>, + hierarchy_results_connected: &HashSet<(NodeId, NodeId)>, ) -> Result<(), ScheduleBuildError> { for &(a, b) in &dep_results.connected { - if hier_results_connected.contains(&(a, b)) || hier_results_connected.contains(&(b, a)) + if hierarchy_results_connected.contains(&(a, b)) + || hierarchy_results_connected.contains(&(b, a)) { let name_a = self.get_node_name(&a); let name_b = self.get_node_name(&b); diff --git a/crates/bevy_ecs/src/storage/blob_vec.rs b/crates/bevy_ecs/src/storage/blob_vec.rs index d42c63a6f1605..52345156c5cb8 100644 --- a/crates/bevy_ecs/src/storage/blob_vec.rs +++ b/crates/bevy_ecs/src/storage/blob_vec.rs @@ -288,7 +288,7 @@ impl BlobVec { // so adding a multiple of `size` will preserve alignment. // - The removed element lives as long as this vector's mutable reference. let p = unsafe { self.get_ptr_mut().byte_add(new_len * size) }; - // SAFETY: The removed element is unreachable by this vector so it's safe to promote the + // SAFETY: The removed element is unreachable by this vector, so it's safe to promote the // `PtrMut` to an `OwningPtr`. unsafe { p.promote() } } @@ -382,7 +382,7 @@ impl BlobVec { // * `size` is a multiple of the erased type's alignment, // so adding a multiple of `size` will preserve alignment. // * The item lives until it's dropped. - // * The item is left unreachable so it can be safely promoted to an `OwningPtr`. + // * The item is left unreachable, so it can be safely promoted to an `OwningPtr`. // NOTE: `self.get_unchecked_mut(i)` cannot be used here, since the `debug_assert` // would panic due to `self.len` being set to 0. let item = unsafe { self.get_ptr_mut().byte_add(i * size).promote() }; diff --git a/crates/bevy_ecs/src/storage/table/mod.rs b/crates/bevy_ecs/src/storage/table/mod.rs index cabcbdc3782c4..8bfc40afb8020 100644 --- a/crates/bevy_ecs/src/storage/table/mod.rs +++ b/crates/bevy_ecs/src/storage/table/mod.rs @@ -86,7 +86,7 @@ impl TableId { } } -/// A opaque newtype for rows in [`Table`]s. Specifies a single row in a specific table. +/// An opaque newtype for rows in [`Table`]s. Specifies a single row in a specific table. /// /// Values of this type are retrievable from [`Archetype::entity_table_row`] and can be /// used alongside [`Archetype::table_id`] to fetch the exact table and row where an diff --git a/crates/bevy_ecs/src/storage/thin_array_ptr.rs b/crates/bevy_ecs/src/storage/thin_array_ptr.rs index a4d25265e0066..ea547b8e1e27f 100644 --- a/crates/bevy_ecs/src/storage/thin_array_ptr.rs +++ b/crates/bevy_ecs/src/storage/thin_array_ptr.rs @@ -144,12 +144,12 @@ impl ThinArrayPtr { let ptr = unsafe { self.data.as_ptr().add(index) }; // SAFETY: // - The pointer is properly aligned - // - It is derefrancable (all in the same allocation) + // - It is dereferenceable (all in the same allocation) // - `index` < `len` and the element is safe to write to, so its valid // - We have a reference to self, so no other mutable accesses to the element can occur unsafe { ptr.as_ref() - // SAFETY: We can use `unwarp_unchecked` because the pointer isn't null) + // SAFETY: We can use `unwrap_unchecked` because the pointer isn't null) .debug_checked_unwrap() } } @@ -166,12 +166,12 @@ impl ThinArrayPtr { let ptr = unsafe { self.data.as_ptr().add(index) }; // SAFETY: // - The pointer is properly aligned - // - It is derefrancable (all in the same allocation) + // - It is dereferenceable (all in the same allocation) // - `index` < `len` and the element is safe to write to, so its valid // - We have a mutable reference to `self` unsafe { ptr.as_mut() - // SAFETY: We can use `unwarp_unchecked` because the pointer isn't null) + // SAFETY: We can use `unwrap_unchecked` because the pointer isn't null) .unwrap_unchecked() } } @@ -294,7 +294,7 @@ impl ThinArrayPtr { #[inline] pub unsafe fn as_slice(&self, slice_len: usize) -> &[T] { // SAFETY: - // - the data is valid - allocated with the same allocater + // - the data is valid - allocated with the same allocator // - non-null and well-aligned // - we have a shared reference to self - the data will not be mutated during 'a unsafe { core::slice::from_raw_parts(self.data.as_ptr(), slice_len) } diff --git a/crates/bevy_ecs/src/system/commands/mod.rs b/crates/bevy_ecs/src/system/commands/mod.rs index 1480c200abb29..ff744a241dc39 100644 --- a/crates/bevy_ecs/src/system/commands/mod.rs +++ b/crates/bevy_ecs/src/system/commands/mod.rs @@ -864,14 +864,14 @@ impl<'w, 's> Commands<'w, 's> { /// # let mut world = World::default(); /// # world.insert_resource(Counter(0)); /// # let mut queue_1 = CommandQueue::default(); - /// # let systemid = { + /// # let system_id = { /// # let mut commands = Commands::new(&mut queue_1, &world); /// # commands.register_system(increment_counter) /// # }; /// # let mut queue_2 = CommandQueue::default(); /// # { /// # let mut commands = Commands::new(&mut queue_2, &world); - /// # commands.run_system(systemid); + /// # commands.run_system(system_id); /// # } /// # queue_1.append(&mut queue_2); /// # queue_1.apply(&mut world); diff --git a/crates/bevy_ecs/src/system/mod.rs b/crates/bevy_ecs/src/system/mod.rs index cd2452bcbca4e..49c170db5bed3 100644 --- a/crates/bevy_ecs/src/system/mod.rs +++ b/crates/bevy_ecs/src/system/mod.rs @@ -518,7 +518,7 @@ mod tests { } #[test] - fn option_doesnt_remove_unrelated_filter_with() { + fn option_does_not_remove_unrelated_filter_with() { fn sys(_: Query<(Option<&A>, &mut B, &A)>, _: Query<&mut B, Without>) {} let mut world = World::default(); run_system(&mut world, sys); @@ -600,7 +600,7 @@ mod tests { } #[test] - fn any_of_doesnt_remove_unrelated_filter_with() { + fn any_of_does_not_remove_unrelated_filter_with() { fn sys(_: Query<(AnyOf<(&A, ())>, &mut B, &A)>, _: Query<&mut B, Without>) {} let mut world = World::default(); run_system(&mut world, sys); @@ -736,7 +736,7 @@ mod tests { } #[test] - fn or_doesnt_remove_unrelated_filter_with() { + fn or_does_not_remove_unrelated_filter_with() { fn sys(_: Query<&mut B, (Or<(With, With)>, With)>, _: Query<&mut B, Without>) {} let mut world = World::default(); run_system(&mut world, sys); @@ -769,7 +769,7 @@ mod tests { #[test] #[should_panic] - fn conflicting_query_immut_system() { + fn conflicting_query_immutable_system() { fn sys(_q1: Query<&A>, _q2: Query<&mut A>) {} let mut world = World::default(); @@ -1328,7 +1328,7 @@ mod tests { } #[test] - fn convert_mut_to_immut() { + fn convert_mut_to_immutable() { { let mut world = World::new(); @@ -1551,12 +1551,12 @@ mod tests { fn query_validates_world_id() { let mut world1 = World::new(); let world2 = World::new(); - let qstate = world1.query::<()>(); - // SAFETY: doesnt access anything + let query_state = world1.query::<()>(); + // SAFETY: doesn't access anything let query = unsafe { Query::new( world2.as_unsafe_world_cell_readonly(), - &qstate, + &query_state, Tick::new(0), Tick::new(0), ) @@ -1733,8 +1733,8 @@ mod tests { world.insert_resource(A); world.insert_resource(C(0)); - let mut sched = Schedule::default(); - sched.add_systems( + let mut scheduled = Schedule::default(); + scheduled.add_systems( ( |mut res: ResMut| { res.0 += 1; @@ -1745,8 +1745,8 @@ mod tests { ) .distributive_run_if(resource_exists::.or(resource_exists::)), ); - sched.initialize(&mut world).unwrap(); - sched.run(&mut world); + scheduled.initialize(&mut world).unwrap(); + scheduled.run(&mut world); assert_eq!(world.get_resource(), Some(&C(3))); } } diff --git a/crates/bevy_ecs/src/system/query.rs b/crates/bevy_ecs/src/system/query.rs index b6a30b14aeb30..332e84fe89abb 100644 --- a/crates/bevy_ecs/src/system/query.rs +++ b/crates/bevy_ecs/src/system/query.rs @@ -649,7 +649,7 @@ impl<'w, 's, D: QueryData, F: QueryFilter> Query<'w, 's, D, F> { /// Returns an iterator over the query items generated from an [`Entity`] list. /// /// Items are returned in the order of the list of entities, and may not be unique if the input - /// doesnn't guarantee uniqueness. Entities that don't match the query are skipped. + /// doesn't guarantee uniqueness. Entities that don't match the query are skipped. /// /// # Examples /// @@ -748,7 +748,7 @@ impl<'w, 's, D: QueryData, F: QueryFilter> Query<'w, 's, D, F> { /// Returns an [`Iterator`] over the query items generated from an [`Entity`] list. /// /// Items are returned in the order of the list of entities, and may not be unique if the input - /// doesnn't guarantee uniqueness. Entities that don't match the query are skipped. + /// doesn't guarantee uniqueness. Entities that don't match the query are skipped. /// /// # Safety /// diff --git a/crates/bevy_ecs/src/system/system_param.rs b/crates/bevy_ecs/src/system/system_param.rs index c3e2645864094..352e8b24dd578 100644 --- a/crates/bevy_ecs/src/system/system_param.rs +++ b/crates/bevy_ecs/src/system/system_param.rs @@ -67,9 +67,9 @@ use super::Populated; /// Local<'s, u8>, /// # commands: /// Commands<'w, 's>, -/// # eventreader: +/// # event_reader: /// EventReader<'w, 's, SomeEvent>, -/// # eventwriter: +/// # event_writer: /// EventWriter<'w, SomeEvent> /// # } /// ``` @@ -238,7 +238,7 @@ pub unsafe trait SystemParam: Sized { /// ensures that the queried data will be the same in both calls. /// /// This method has to be called directly before [`SystemParam::get_param`] with no other (relevant) - /// world mutations inbetween. Otherwise, while it won't lead to any undefined behavior, + /// world mutations in-between. Otherwise, while it won't lead to any undefined behavior, /// the validity of the param may change. /// /// # Safety diff --git a/crates/bevy_ecs/src/world/command_queue.rs b/crates/bevy_ecs/src/world/command_queue.rs index 9fd3a06b9d8ef..c072d70271383 100644 --- a/crates/bevy_ecs/src/world/command_queue.rs +++ b/crates/bevy_ecs/src/world/command_queue.rs @@ -366,11 +366,11 @@ mod test { fn test_command_queue_inner_drop() { let mut queue = CommandQueue::default(); - let (dropcheck_a, drops_a) = DropCheck::new(); - let (dropcheck_b, drops_b) = DropCheck::new(); + let (drop_check_a, drops_a) = DropCheck::new(); + let (drop_check_b, drops_b) = DropCheck::new(); - queue.push(dropcheck_a); - queue.push(dropcheck_b); + queue.push(drop_check_a); + queue.push(drop_check_b); assert_eq!(drops_a.load(Ordering::Relaxed), 0); assert_eq!(drops_b.load(Ordering::Relaxed), 0); @@ -388,11 +388,11 @@ mod test { fn test_command_queue_inner_drop_early() { let mut queue = CommandQueue::default(); - let (dropcheck_a, drops_a) = DropCheck::new(); - let (dropcheck_b, drops_b) = DropCheck::new(); + let (drop_check_a, drops_a) = DropCheck::new(); + let (drop_check_b, drops_b) = DropCheck::new(); - queue.push(dropcheck_a); - queue.push(dropcheck_b); + queue.push(drop_check_a); + queue.push(drop_check_b); assert_eq!(drops_a.load(Ordering::Relaxed), 0); assert_eq!(drops_b.load(Ordering::Relaxed), 0); diff --git a/crates/bevy_ecs/src/world/deferred_world.rs b/crates/bevy_ecs/src/world/deferred_world.rs index 0ffd94e01e2f1..948367d249e11 100644 --- a/crates/bevy_ecs/src/world/deferred_world.rs +++ b/crates/bevy_ecs/src/world/deferred_world.rs @@ -203,8 +203,8 @@ impl<'w> DeferredWorld<'w> { /// # DeferredWorld::from(&mut world); /// /// let ids = vec![e1, e2, e3]; - /// for mut eref in world.entity_mut(&ids[..]) { - /// let mut pos = eref.get_mut::().unwrap(); + /// for mut entity_ref in world.entity_mut(&ids[..]) { + /// let mut pos = entity_ref.get_mut::().unwrap(); /// pos.y = 2.0; /// assert_eq!(pos.y, 2.0); /// } @@ -228,8 +228,8 @@ impl<'w> DeferredWorld<'w> { /// # DeferredWorld::from(&mut world); /// /// let ids = EntityHashSet::from_iter([e1, e2, e3]); - /// for (_id, mut eref) in world.entity_mut(&ids) { - /// let mut pos = eref.get_mut::().unwrap(); + /// for (_id, mut entity_ref) in world.entity_mut(&ids) { + /// let mut pos = entity_ref.get_mut::().unwrap(); /// pos.y = 2.0; /// assert_eq!(pos.y, 2.0); /// } diff --git a/crates/bevy_ecs/src/world/entity_fetch.rs b/crates/bevy_ecs/src/world/entity_fetch.rs index 62d63ced54fb7..cc09fb73b5fab 100644 --- a/crates/bevy_ecs/src/world/entity_fetch.rs +++ b/crates/bevy_ecs/src/world/entity_fetch.rs @@ -20,7 +20,7 @@ use crate::{ /// /// # Performance /// -/// - The slice and array implementations perform an aliased mutabiltiy check +/// - The slice and array implementations perform an aliased mutability check /// in [`WorldEntityFetch::fetch_mut`] that is `O(N^2)`. /// - The [`EntityHashSet`] implementation performs no such check as the type /// itself guarantees no duplicates. @@ -111,9 +111,9 @@ unsafe impl WorldEntityFetch for Entity { type DeferredMut<'w> = EntityMut<'w>; unsafe fn fetch_ref(self, cell: UnsafeWorldCell<'_>) -> Result, Entity> { - let ecell = cell.get_entity(self).ok_or(self)?; + let entity_cell = cell.get_entity(self).ok_or(self)?; // SAFETY: caller ensures that the world cell has read-only access to the entity. - Ok(unsafe { EntityRef::new(ecell) }) + Ok(unsafe { EntityRef::new(entity_cell) }) } unsafe fn fetch_mut( @@ -134,11 +134,11 @@ unsafe impl WorldEntityFetch for Entity { self, cell: UnsafeWorldCell<'_>, ) -> Result, EntityFetchError> { - let ecell = cell + let entity_cell = cell .get_entity(self) .ok_or(EntityFetchError::NoSuchEntity(self))?; // SAFETY: caller ensures that the world cell has mutable access to the entity. - Ok(unsafe { EntityMut::new(ecell) }) + Ok(unsafe { EntityMut::new(entity_cell) }) } } @@ -182,9 +182,9 @@ unsafe impl WorldEntityFetch for &'_ [Entity; N] { unsafe fn fetch_ref(self, cell: UnsafeWorldCell<'_>) -> Result, Entity> { let mut refs = [MaybeUninit::uninit(); N]; for (r, &id) in core::iter::zip(&mut refs, self) { - let ecell = cell.get_entity(id).ok_or(id)?; + let entity_cell = cell.get_entity(id).ok_or(id)?; // SAFETY: caller ensures that the world cell has read-only access to the entity. - *r = MaybeUninit::new(unsafe { EntityRef::new(ecell) }); + *r = MaybeUninit::new(unsafe { EntityRef::new(entity_cell) }); } // SAFETY: Each item was initialized in the loop above. @@ -208,11 +208,11 @@ unsafe impl WorldEntityFetch for &'_ [Entity; N] { let mut refs = [const { MaybeUninit::uninit() }; N]; for (r, &id) in core::iter::zip(&mut refs, self) { - let ecell = cell + let entity_cell = cell .get_entity(id) .ok_or(EntityFetchError::NoSuchEntity(id))?; // SAFETY: caller ensures that the world cell has mutable access to the entity. - *r = MaybeUninit::new(unsafe { EntityMut::new(ecell) }); + *r = MaybeUninit::new(unsafe { EntityMut::new(entity_cell) }); } // SAFETY: Each item was initialized in the loop above. @@ -243,9 +243,9 @@ unsafe impl WorldEntityFetch for &'_ [Entity] { unsafe fn fetch_ref(self, cell: UnsafeWorldCell<'_>) -> Result, Entity> { let mut refs = Vec::with_capacity(self.len()); for &id in self { - let ecell = cell.get_entity(id).ok_or(id)?; + let entity_cell = cell.get_entity(id).ok_or(id)?; // SAFETY: caller ensures that the world cell has read-only access to the entity. - refs.push(unsafe { EntityRef::new(ecell) }); + refs.push(unsafe { EntityRef::new(entity_cell) }); } Ok(refs) @@ -266,11 +266,11 @@ unsafe impl WorldEntityFetch for &'_ [Entity] { let mut refs = Vec::with_capacity(self.len()); for &id in self { - let ecell = cell + let entity_cell = cell .get_entity(id) .ok_or(EntityFetchError::NoSuchEntity(id))?; // SAFETY: caller ensures that the world cell has mutable access to the entity. - refs.push(unsafe { EntityMut::new(ecell) }); + refs.push(unsafe { EntityMut::new(entity_cell) }); } Ok(refs) @@ -298,9 +298,9 @@ unsafe impl WorldEntityFetch for &'_ EntityHashSet { unsafe fn fetch_ref(self, cell: UnsafeWorldCell<'_>) -> Result, Entity> { let mut refs = EntityHashMap::with_capacity_and_hasher(self.len(), EntityHash); for &id in self { - let ecell = cell.get_entity(id).ok_or(id)?; + let entity_cell = cell.get_entity(id).ok_or(id)?; // SAFETY: caller ensures that the world cell has read-only access to the entity. - refs.insert(id, unsafe { EntityRef::new(ecell) }); + refs.insert(id, unsafe { EntityRef::new(entity_cell) }); } Ok(refs) } @@ -311,11 +311,11 @@ unsafe impl WorldEntityFetch for &'_ EntityHashSet { ) -> Result, EntityFetchError> { let mut refs = EntityHashMap::with_capacity_and_hasher(self.len(), EntityHash); for &id in self { - let ecell = cell + let entity_cell = cell .get_entity(id) .ok_or(EntityFetchError::NoSuchEntity(id))?; // SAFETY: caller ensures that the world cell has mutable access to the entity. - refs.insert(id, unsafe { EntityMut::new(ecell) }); + refs.insert(id, unsafe { EntityMut::new(entity_cell) }); } Ok(refs) } diff --git a/crates/bevy_ecs/src/world/entity_ref.rs b/crates/bevy_ecs/src/world/entity_ref.rs index 8917b924b5f19..4f702c3a06dfa 100644 --- a/crates/bevy_ecs/src/world/entity_ref.rs +++ b/crates/bevy_ecs/src/world/entity_ref.rs @@ -124,16 +124,16 @@ impl<'w> EntityRef<'w> { unsafe { self.0.get_ref::() } } - /// Retrieves the change ticks for the given component. This can be useful for implementing change - /// detection in custom runtimes. + /// Retrieves the change ticks for the given component. + /// This can be useful for implementing change detection in custom runtimes. #[inline] pub fn get_change_ticks(&self) -> Option { // SAFETY: We have read-only access to all components of this entity. unsafe { self.0.get_change_ticks::() } } - /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change - /// detection in custom runtimes. + /// Retrieves the change ticks for the given [`ComponentId`]. + /// This can be useful for implementing change detection in custom runtimes. /// /// **You should prefer to use the typed API [`EntityRef::get_change_ticks`] where possible and only /// use this in cases where the actual component types are not known at @@ -3936,7 +3936,7 @@ mod tests { // Test that an `EntityRefExcept` with an exception for some component C can // coexist with a query for that component C. #[test] - fn entity_ref_except_doesnt_conflict() { + fn entity_ref_except_does_not_conflict() { let mut world = World::new(); world.spawn(TestComponent(0)).insert(TestComponent2(0)); @@ -4018,7 +4018,7 @@ mod tests { // Test that an `EntityMutExcept` with an exception for some component C can // coexist with a query for that component C. #[test] - fn entity_mut_except_doesnt_conflict() { + fn entity_mut_except_does_not_conflict() { let mut world = World::new(); world.spawn(TestComponent(0)).insert(TestComponent2(0)); diff --git a/crates/bevy_ecs/src/world/mod.rs b/crates/bevy_ecs/src/world/mod.rs index d50f8f421cfc2..3df46cc79b7d1 100644 --- a/crates/bevy_ecs/src/world/mod.rs +++ b/crates/bevy_ecs/src/world/mod.rs @@ -671,8 +671,8 @@ impl World { /// let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id(); /// /// let ids = vec![e1, e2, e3]; - /// for eref in world.entity(&ids[..]) { - /// assert_eq!(eref.get::().unwrap().y, 1.0); + /// for entity_reference in world.entity(&ids[..]) { + /// assert_eq!(entity_reference.get::().unwrap().y, 1.0); /// } /// ``` /// @@ -692,8 +692,8 @@ impl World { /// let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id(); /// /// let ids = EntityHashSet::from_iter([e1, e2, e3]); - /// for (_id, eref) in world.entity(&ids) { - /// assert_eq!(eref.get::().unwrap().y, 1.0); + /// for (_id, entity_reference) in world.entity(&ids) { + /// assert_eq!(entity_reference.get::().unwrap().y, 1.0); /// } /// ``` #[inline] @@ -798,8 +798,8 @@ impl World { /// let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id(); /// /// let ids = vec![e1, e2, e3]; - /// for mut eref in world.entity_mut(&ids[..]) { - /// let mut pos = eref.get_mut::().unwrap(); + /// for mut entity_reference in world.entity_mut(&ids[..]) { + /// let mut pos = entity_reference.get_mut::().unwrap(); /// pos.y = 2.0; /// assert_eq!(pos.y, 2.0); /// } @@ -821,8 +821,8 @@ impl World { /// let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id(); /// /// let ids = EntityHashSet::from_iter([e1, e2, e3]); - /// for (_id, mut eref) in world.entity_mut(&ids) { - /// let mut pos = eref.get_mut::().unwrap(); + /// for (_id, mut entity_reference) in world.entity_mut(&ids) { + /// let mut pos = entity_reference.get_mut::().unwrap(); /// pos.y = 2.0; /// assert_eq!(pos.y, 2.0); /// } @@ -1351,7 +1351,7 @@ impl World { /// position: Position { x: 2.0, y: 2.0 }, /// velocity: Velocity { x: 0.0, y: 4.0 }, /// }, - /// Name("Elaina Proctor"), + /// Name("Example Name"), /// )) /// // Calling id() will return the unique identifier for the spawned entity /// .id(); @@ -3717,7 +3717,7 @@ impl World { &mut self, label: impl ScheduleLabel, ) -> Result<(), TryRunScheduleError> { - self.try_schedule_scope(label, |world, sched| sched.run(world)) + self.try_schedule_scope(label, |world, scheduled| scheduled.run(world)) } /// Runs the [`Schedule`] associated with the `label` a single time. @@ -3731,7 +3731,7 @@ impl World { /// /// If the requested schedule does not exist. pub fn run_schedule(&mut self, label: impl ScheduleLabel) { - self.schedule_scope(label, |world, sched| sched.run(world)); + self.schedule_scope(label, |world, scheduled| scheduled.run(world)); } /// Ignore system order ambiguities caused by conflicts on [`Component`]s of type `T`. diff --git a/crates/bevy_ecs/src/world/reflect.rs b/crates/bevy_ecs/src/world/reflect.rs index cb6c76920eee3..a85431d9c9e18 100644 --- a/crates/bevy_ecs/src/world/reflect.rs +++ b/crates/bevy_ecs/src/world/reflect.rs @@ -164,7 +164,7 @@ impl World { }; // HACK: Only required for the `None`-case/`else`-branch, but it borrows `self`, which will - // already be mutablyy borrowed by `self.get_mut_by_id()`, and I didn't find a way around it. + // already be mutably borrowed by `self.get_mut_by_id()`, and I didn't find a way around it. let component_name = self .components() .get_name(component_id) @@ -275,17 +275,17 @@ mod tests { app_type_registry.write().register::(); { - let entity_with_rfoo = world.spawn(RFoo(42)).id(); + let entity_with_r_foo = world.spawn(RFoo(42)).id(); let comp_reflect = world - .get_reflect(entity_with_rfoo, TypeId::of::()) + .get_reflect(entity_with_r_foo, TypeId::of::()) .expect("Reflection of RFoo-component failed"); assert!(comp_reflect.is::()); } { - let entity_without_rfoo = world.spawn_empty().id(); - let reflect_opt = world.get_reflect(entity_without_rfoo, TypeId::of::()); + let entity_without_r_foo = world.spawn_empty().id(); + let reflect_opt = world.get_reflect(entity_without_r_foo, TypeId::of::()); assert!(reflect_opt.is_err()); } @@ -307,25 +307,25 @@ mod tests { app_type_registry.write().register::(); { - let entity_with_rfoo = world.spawn(RFoo(42)).id(); + let entity_with_r_foo = world.spawn(RFoo(42)).id(); let mut comp_reflect = world - .get_reflect_mut(entity_with_rfoo, TypeId::of::()) + .get_reflect_mut(entity_with_r_foo, TypeId::of::()) .expect("Mutable reflection of RFoo-component failed"); - let comp_rfoo_reflected = comp_reflect + let comp_r_foo_reflected = comp_reflect .downcast_mut::() .expect("Wrong type reflected (expected RFoo)"); - assert_eq!(comp_rfoo_reflected.0, 42); - comp_rfoo_reflected.0 = 1337; + assert_eq!(comp_r_foo_reflected.0, 42); + comp_r_foo_reflected.0 = 1337; - let rfoo_ref = world.entity(entity_with_rfoo).get_ref::().unwrap(); - assert!(rfoo_ref.is_changed()); - assert_eq!(rfoo_ref.0, 1337); + let r_foo_ref = world.entity(entity_with_r_foo).get_ref::().unwrap(); + assert!(r_foo_ref.is_changed()); + assert_eq!(r_foo_ref.0, 1337); } { - let entity_without_rfoo = world.spawn_empty().id(); - let reflect_opt = world.get_reflect_mut(entity_without_rfoo, TypeId::of::()); + let entity_without_r_foo = world.spawn_empty().id(); + let reflect_opt = world.get_reflect_mut(entity_without_r_foo, TypeId::of::()); assert!(reflect_opt.is_err()); } diff --git a/crates/bevy_ecs/src/world/unsafe_world_cell.rs b/crates/bevy_ecs/src/world/unsafe_world_cell.rs index 4c2813702a40c..8ff60e3b9247a 100644 --- a/crates/bevy_ecs/src/world/unsafe_world_cell.rs +++ b/crates/bevy_ecs/src/world/unsafe_world_cell.rs @@ -129,7 +129,7 @@ impl<'w> UnsafeWorldCell<'w> { /// ```no_run /// # use bevy_ecs::prelude::*; /// # #[derive(Component)] struct Player; - /// # fn store_but_dont_use(_: T) {} + /// # fn store_but_do_not_use(_: T) {} /// # let mut world = World::new(); /// // Make an UnsafeWorldCell. /// let world_cell = world.as_unsafe_world_cell(); @@ -139,7 +139,7 @@ impl<'w> UnsafeWorldCell<'w> { /// let world_mut = unsafe { world_cell.world_mut() }; /// /// // We can still use `world_cell` so long as we don't access the world with it. - /// store_but_dont_use(world_cell); + /// store_but_do_not_use(world_cell); /// /// // !!This is unsound!! Even though this method is safe, we cannot call it until /// // `world_mut` is no longer active. @@ -638,7 +638,7 @@ impl Debug for UnsafeWorldCell<'_> { } } -/// A interior-mutable reference to a particular [`Entity`] and all of its components +/// An interior-mutable reference to a particular [`Entity`] and all of its components #[derive(Copy, Clone)] pub struct UnsafeEntityCell<'w> { world: UnsafeWorldCell<'w>, diff --git a/crates/bevy_gizmos/src/grid.rs b/crates/bevy_gizmos/src/grid.rs index 20cb4e115b023..3c812f639ee31 100644 --- a/crates/bevy_gizmos/src/grid.rs +++ b/crates/bevy_gizmos/src/grid.rs @@ -408,11 +408,11 @@ fn draw_grid( cell_count: u32, start: Vec3, ) -> impl Iterator { - let dline = delta_a * cell_count as f32; + let delta_line = delta_a * cell_count as f32; (0..line_count.x).map(|v| v as f32).flat_map(move |b| { (0..line_count.y).map(|v| v as f32).map(move |c| { let line_start = start + b * delta_b + c * delta_c; - let line_end = line_start + dline; + let line_end = line_start + delta_line; [line_start, line_end] }) }) diff --git a/crates/bevy_gizmos/src/lib.rs b/crates/bevy_gizmos/src/lib.rs index 620a3e3700e8c..09bca41d4b4cb 100644 --- a/crates/bevy_gizmos/src/lib.rs +++ b/crates/bevy_gizmos/src/lib.rs @@ -218,7 +218,7 @@ impl Plugin for GizmoPlugin { } } -/// A extension trait adding `App::init_gizmo_group` and `App::insert_gizmo_config`. +/// An extension trait adding `App::init_gizmo_group` and `App::insert_gizmo_config`. pub trait AppGizmoBuilder { /// Registers [`GizmoConfigGroup`] in the app enabling the use of [Gizmos<Config>](crate::gizmos::Gizmos). /// diff --git a/crates/bevy_gizmos/src/lines.wgsl b/crates/bevy_gizmos/src/lines.wgsl index e608b4beabb09..e1292844a7cbc 100644 --- a/crates/bevy_gizmos/src/lines.wgsl +++ b/crates/bevy_gizmos/src/lines.wgsl @@ -78,7 +78,7 @@ fn vertex(vertex: VertexInput) -> VertexOutput { let position_b = view.world_from_clip * clip_b; let world_distance = length(position_a.xyz - position_b.xyz); - // Offset to compensate for moved clip positions. If removed dots on lines will slide when position a is ofscreen. + // Offset to compensate for moved clip positions. If removed dots on lines will slide when position a is off-screen. let clipped_offset = length(position_a.xyz - vertex.position_a); uv = (clipped_offset + position.y * world_distance) * resolution.y / near_clipping_plane_height / line_gizmo.line_width; @@ -87,15 +87,15 @@ fn vertex(vertex: VertexInput) -> VertexOutput { let camera_b = view.view_from_clip * clip_b; // This differentiates between orthographic and perspective cameras. - // For orthographic cameras no depth adaptment (depth_adaptment = 1) is needed. - var depth_adaptment: f32; + // For orthographic cameras no depth adaption (depth_adaption = 1) is needed. + var depth_adaption: f32; if (clip_b.w == 1.0) { - depth_adaptment = 1.0; + depth_adaption = 1.0; } else { - depth_adaptment = -camera_b.z; + depth_adaption = -camera_b.z; } - uv = position.y * depth_adaptment * length(screen_b - screen_a) / line_gizmo.line_width; + uv = position.y * depth_adaption * length(screen_b - screen_a) / line_gizmo.line_width; #endif // Line thinness fade from https://acegikmo.com/shapes/docs/#anti-aliasing @@ -127,7 +127,7 @@ fn vertex(vertex: VertexInput) -> VertexOutput { } fn clip_near_plane(a: vec4, b: vec4) -> vec4 { - // Move a if a is behind the near plane and b is in front. + // Move a if a is behind the near plane and b is in front. if a.z > a.w && b.z <= b.w { // Interpolate a towards b until it's at the near plane. let distance_a = a.z - a.w; @@ -162,6 +162,6 @@ fn fragment_dotted(in: FragmentInput) -> FragmentOutput { #else alpha = 1 - floor((in.uv * in.position.w) % 2.0); #endif - + return FragmentOutput(vec4(in.color.xyz, in.color.w * alpha)); } diff --git a/crates/bevy_gizmos/src/primitives/helpers.rs b/crates/bevy_gizmos/src/primitives/helpers.rs index 66e171c6c9f59..37253b14a9ac9 100644 --- a/crates/bevy_gizmos/src/primitives/helpers.rs +++ b/crates/bevy_gizmos/src/primitives/helpers.rs @@ -4,7 +4,7 @@ use bevy_math::{ops, Vec2}; /// Calculates the `nth` coordinate of a circle. /// -/// Given a circle's radiu and its resolution, this function computes the position +/// Given a circle's radius and its resolution, this function computes the position /// of the `nth` point along the circumference of the circle. The rotation starts at `(0.0, radius)` /// and proceeds counter-clockwise. pub(crate) fn single_circle_coordinate(radius: f32, resolution: u32, nth_point: u32) -> Vec2 { @@ -15,7 +15,7 @@ pub(crate) fn single_circle_coordinate(radius: f32, resolution: u32, nth_point: /// Generates an iterator over the coordinates of a circle. /// -/// The coordinates form a open circle, meaning the first and last points aren't the same. +/// The coordinates form an open circle, meaning the first and last points aren't the same. /// /// This function creates an iterator that yields the positions of points approximating a /// circle with the given radius, divided into linear segments. The iterator produces `resolution` diff --git a/crates/bevy_gltf/src/lib.rs b/crates/bevy_gltf/src/lib.rs index 46f9ad3ae90fb..b96d49c12d60c 100644 --- a/crates/bevy_gltf/src/lib.rs +++ b/crates/bevy_gltf/src/lib.rs @@ -284,7 +284,7 @@ pub struct GltfSkin { pub name: String, /// All the nodes that form this skin. pub joints: Vec>, - /// Inverse-bind matricy of this skin. + /// Inverse-bind matrices of this skin. pub inverse_bind_matrices: Handle, /// Additional data. pub extras: Option, diff --git a/crates/bevy_gltf/src/loader.rs b/crates/bevy_gltf/src/loader.rs index 04e8f4a48e232..70d0fd6cef26c 100644 --- a/crates/bevy_gltf/src/loader.rs +++ b/crates/bevy_gltf/src/loader.rs @@ -486,7 +486,7 @@ async fn load_gltf<'a, 'b, 'c>( // TODO: use the threaded impl on wasm once wasm thread pool doesn't deadlock on it // See https://github.com/bevyengine/bevy/issues/1924 for more details - // The taskpool use is also avoided when there is only one texture for performance reasons and + // The task pool use is also avoided when there is only one texture for performance reasons and // to avoid https://github.com/bevyengine/bevy/pull/2725 // PERF: could this be a Vec instead? Are gltf texture indices dense? fn process_loaded_texture( diff --git a/crates/bevy_image/src/image.rs b/crates/bevy_image/src/image.rs index cfe3a768d6f55..2e61992a848c8 100644 --- a/crates/bevy_image/src/image.rs +++ b/crates/bevy_image/src/image.rs @@ -1415,7 +1415,7 @@ pub enum TextureError { #[display("unsupported texture format: {_0}")] #[from(ignore)] UnsupportedTextureFormat(String), - #[display("supercompression not supported: {_0}")] + #[display("super compression not supported: {_0}")] #[from(ignore)] SuperCompressionNotSupported(String), #[display("failed to load an image: {_0}")] diff --git a/crates/bevy_image/src/image_texture_conversion.rs b/crates/bevy_image/src/image_texture_conversion.rs index c4d7fa426987e..b97dc62759d9e 100644 --- a/crates/bevy_image/src/image_texture_conversion.rs +++ b/crates/bevy_image/src/image_texture_conversion.rs @@ -231,7 +231,7 @@ mod test { let image = Image::from_dynamic(initial.clone(), true, RenderAssetUsages::RENDER_WORLD); - // NOTE: Fails if `is_srbg = false` or the dynamic image is of the type rgb8. + // NOTE: Fails if `is_srgb = false` or the dynamic image is of the type rgb8. assert_eq!(initial, image.try_into_dynamic().unwrap()); } } diff --git a/crates/bevy_image/src/ktx2.rs b/crates/bevy_image/src/ktx2.rs index 7ba3bb6106d7d..999eec22c05fe 100644 --- a/crates/bevy_image/src/ktx2.rs +++ b/crates/bevy_image/src/ktx2.rs @@ -1502,7 +1502,7 @@ mod tests { #[test] fn test_ktx_levels() { - // R8UnormSrgb textture with 4x4 pixels data and 3 levels of mipmaps + // R8UnormSrgb texture with 4x4 pixels data and 3 levels of mipmaps let buffer = vec![ 0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 10, 0x1a, 10, 0x0f, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, diff --git a/crates/bevy_input/src/common_conditions.rs b/crates/bevy_input/src/common_conditions.rs index bc2e161b1b55a..560ea693d982c 100644 --- a/crates/bevy_input/src/common_conditions.rs +++ b/crates/bevy_input/src/common_conditions.rs @@ -2,7 +2,7 @@ use crate::ButtonInput; use bevy_ecs::system::Res; use core::hash::Hash; -/// Stateful run condition that can be toggled via a input press using [`ButtonInput::just_pressed`]. +/// Stateful run condition that can be toggled via an input press using [`ButtonInput::just_pressed`]. /// /// ```no_run /// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, Update}; diff --git a/crates/bevy_input/src/keyboard.rs b/crates/bevy_input/src/keyboard.rs index d2253f73e27ef..7d9a3f170baf2 100644 --- a/crates/bevy_input/src/keyboard.rs +++ b/crates/bevy_input/src/keyboard.rs @@ -448,7 +448,7 @@ pub enum KeyCode { NumpadAdd, /// Found on the Microsoft Natural Keyboard. NumpadBackspace, - /// C or A (All Clear). Also for use with numpads that have a + /// C or A (All Clear). Also for use with number pads that have a /// Clear key that is separate from the NumLock key. On the Mac, the /// numpad Clear key is encoded as [`NumLock`]. /// @@ -481,7 +481,7 @@ pub enum KeyCode { NumpadMemoryStore, /// M Subtract current entry from the value stored in memory. NumpadMemorySubtract, - /// * on a keyboard. For use with numpads that provide mathematical + /// * on a keyboard. For use with number pads that provide mathematical /// operations (+, - * and /). /// /// Use `NumpadStar` for the * key on phones and remote controls. @@ -856,9 +856,9 @@ pub enum Key { /// The Erase to End of Field key. This key deletes all characters from the current cursor /// position to the end of the current field. EraseEof, - /// The Extend Selection (Exsel) key. + /// The Extend Selection (ExSel) key. ExSel, - /// Toggle between text modes for insertion or overtyping. + /// Toggle between text modes for insertion or over-typing. /// (`KEYCODE_INSERT`) Insert, /// The Paste key. (`APPCOMMAND_PASTE`) @@ -1061,10 +1061,10 @@ pub enum Key { Save, /// Spellcheck the current document or selection. (`APPCOMMAND_SPELL_CHECK`) SpellCheck, - /// The `11` key found on media numpads that + /// The `11` key found on media number pads that /// have buttons from `1` ... `12`. Key11, - /// The `12` key found on media numpads that + /// The `12` key found on media number pads that /// have buttons from `1` ... `12`. Key12, /// Adjust audio balance leftward. (`VK_AUDIO_BALANCE_LEFT`) diff --git a/crates/bevy_math/src/aspect_ratio.rs b/crates/bevy_math/src/aspect_ratio.rs index a318ff0296b1c..92aacac263240 100644 --- a/crates/bevy_math/src/aspect_ratio.rs +++ b/crates/bevy_math/src/aspect_ratio.rs @@ -89,7 +89,7 @@ pub enum AspectRatioError { /// Error due to width or height having zero as a value. #[display("AspectRatio error: width or height is zero")] Zero, - /// Error due towidth or height being infinite. + /// Error due to width or height being infinite. #[display("AspectRatio error: width or height is infinite")] Infinite, /// Error due to width or height being Not a Number (NaN). diff --git a/crates/bevy_math/src/bounding/bounded2d/primitive_impls.rs b/crates/bevy_math/src/bounding/bounded2d/primitive_impls.rs index d4d211cd127a5..f8fc54edaab3e 100644 --- a/crates/bevy_math/src/bounding/bounded2d/primitive_impls.rs +++ b/crates/bevy_math/src/bounding/bounded2d/primitive_impls.rs @@ -47,7 +47,7 @@ fn arc_bounding_points(arc: Arc2d, rotation: impl Into) -> SmallVec<[Vec2; for extremum in [Vec2::X, Vec2::Y, Vec2::NEG_X, Vec2::NEG_Y] { let angle = extremum.to_angle().rem_euclid(TAU); // If inverted = true, then right_angle > left_angle, so we are looking for an angle that is not between them. - // There's a chance that this condition fails due to rounding error, if the endpoint angle is juuuust shy of the axis. + // There's a chance that this condition fails due to rounding error, if the endpoint angle is just shy of the axis. // But in that case, the endpoint itself is within rounding error of the axis and will define the bounds just fine. #[allow(clippy::nonminimal_bool)] if !inverted && angle >= right_angle && angle <= left_angle @@ -409,7 +409,7 @@ impl Bounded2d for Capsule2d { fn aabb_2d(&self, isometry: impl Into) -> Aabb2d { let isometry = isometry.into(); - // Get the line segment between the hemicircles of the rotated capsule + // Get the line segment between the semicircles of the rotated capsule let segment = Segment2d { // Multiplying a normalized vector (Vec2::Y) with a rotation returns a normalized vector. direction: isometry.rotation * Dir2::Y, diff --git a/crates/bevy_math/src/bounding/bounded3d/extrusion.rs b/crates/bevy_math/src/bounding/bounded3d/extrusion.rs index 8eb3eb9791795..7c6d11c41196d 100644 --- a/crates/bevy_math/src/bounding/bounded3d/extrusion.rs +++ b/crates/bevy_math/src/bounding/bounded3d/extrusion.rs @@ -206,7 +206,7 @@ pub trait BoundedExtrusion: Primitive2d + Bounded2d { let cap_normal = isometry.rotation * Vec3A::Z; let conjugate_rot = isometry.rotation.conjugate(); - // The `(halfsize, offset)` for each axis + // The `(half_size, offset)` for each axis let axis_values = Vec3A::AXES.map(|ax| { // This is the direction of the line of intersection of a plane with the `ax` normal and the plane containing the cap of the extrusion. let intersect_line = ax.cross(cap_normal); @@ -218,7 +218,7 @@ pub trait BoundedExtrusion: Primitive2d + Bounded2d { let line_normal = (conjugate_rot * intersect_line).yx(); let angle = line_normal.to_angle(); - // Since the plane containing the caps of the extrusion is not guaranteed to be orthgonal to the `ax` plane, only a certain "scale" factor + // Since the plane containing the caps of the extrusion is not guaranteed to be orthogonal to the `ax` plane, only a certain "scale" factor // of the `Aabb2d` will actually go towards the dimensions of the `Aabb3d` let scale = cap_normal.reject_from(ax).length(); diff --git a/crates/bevy_math/src/bounding/raycast2d.rs b/crates/bevy_math/src/bounding/raycast2d.rs index 745e53de8267c..5fd641eac64bb 100644 --- a/crates/bevy_math/src/bounding/raycast2d.rs +++ b/crates/bevy_math/src/bounding/raycast2d.rs @@ -52,20 +52,20 @@ impl RayCast2d { // Calculate the minimum/maximum time for each axis based on how much the direction goes that // way. These values can get arbitrarily large, or even become NaN, which is handled by the // min/max operations below - let tmin_x = (min_x - self.ray.origin.x) * self.direction_recip.x; - let tmin_y = (min_y - self.ray.origin.y) * self.direction_recip.y; - let tmax_x = (max_x - self.ray.origin.x) * self.direction_recip.x; - let tmax_y = (max_y - self.ray.origin.y) * self.direction_recip.y; + let t_min_x = (min_x - self.ray.origin.x) * self.direction_recip.x; + let t_min_y = (min_y - self.ray.origin.y) * self.direction_recip.y; + let t_max_x = (max_x - self.ray.origin.x) * self.direction_recip.x; + let t_max_y = (max_y - self.ray.origin.y) * self.direction_recip.y; // An axis that is not relevant to the ray direction will be NaN. When one of the arguments // to min/max is NaN, the other argument is used. // An axis for which the direction is the wrong way will return an arbitrarily large // negative value. - let tmin = tmin_x.max(tmin_y).max(0.); - let tmax = tmax_y.min(tmax_x).min(self.max); + let t_min = t_min_x.max(t_min_y).max(0.); + let t_max = t_max_y.min(t_max_x).min(self.max); - if tmin <= tmax { - Some(tmin) + if t_min <= t_max { + Some(t_min) } else { None } diff --git a/crates/bevy_math/src/bounding/raycast3d.rs b/crates/bevy_math/src/bounding/raycast3d.rs index 3a369d9fe142a..f49c03eb04416 100644 --- a/crates/bevy_math/src/bounding/raycast3d.rs +++ b/crates/bevy_math/src/bounding/raycast3d.rs @@ -51,18 +51,18 @@ impl RayCast3d { // Calculate the minimum/maximum time for each axis based on how much the direction goes that // way. These values can get arbitrarily large, or even become NaN, which is handled by the // min/max operations below - let tmin = (min - self.origin) * self.direction_recip; - let tmax = (max - self.origin) * self.direction_recip; + let t_min = (min - self.origin) * self.direction_recip; + let t_max = (max - self.origin) * self.direction_recip; // An axis that is not relevant to the ray direction will be NaN. When one of the arguments // to min/max is NaN, the other argument is used. // An axis for which the direction is the wrong way will return an arbitrarily large // negative value. - let tmin = tmin.max_element().max(0.); - let tmax = tmax.min_element().min(self.max); + let t_min = t_min.max_element().max(0.); + let t_max = t_max.min_element().min(self.max); - if tmin <= tmax { - Some(tmin) + if t_min <= t_max { + Some(t_min) } else { None } diff --git a/crates/bevy_math/src/common_traits.rs b/crates/bevy_math/src/common_traits.rs index c6bc43ae9ce9a..197d709dcea03 100644 --- a/crates/bevy_math/src/common_traits.rs +++ b/crates/bevy_math/src/common_traits.rs @@ -180,7 +180,7 @@ impl NormedVectorSpace for f32 { /// /// 3. Importantly, the interpolation must be *subdivision-stable*: for any interpolation curve /// between two (unnamed) values and any parameter-value pairs `(t0, p)` and `(t1, q)`, the -/// interpolation curve between `p` and `q` must be the *linear* reparameterization of the original +/// interpolation curve between `p` and `q` must be the *linear* reparametrization of the original /// interpolation curve restricted to the interval `[t0, t1]`. /// /// The last of these conditions is very strong and indicates something like constant speed. It @@ -191,13 +191,13 @@ impl NormedVectorSpace for f32 { /// ```text /// top curve = u.interpolate_stable(v, t) /// -/// t0 => p t1 => q +/// t0 => p t1 => q /// |-------------|---------|-------------| /// 0 => u / \ 1 => v /// / \ /// / \ /// / linear \ -/// / reparameterization \ +/// / reparametrization \ /// / t = t0 * (1 - s) + t1 * s \ /// / \ /// |-------------------------------------| diff --git a/crates/bevy_math/src/cubic_splines.rs b/crates/bevy_math/src/cubic_splines.rs index 87d95b0fc2d85..1a03aa847156e 100644 --- a/crates/bevy_math/src/cubic_splines.rs +++ b/crates/bevy_math/src/cubic_splines.rs @@ -828,7 +828,7 @@ impl CubicGenerator

for LinearSpline

{ let a = points[0]; let b = points[1]; CubicSegment { - coeff: [a, b - a, P::default(), P::default()], + coefficients: [a, b - a, P::default(), P::default()], } }) .collect_vec(); @@ -853,7 +853,7 @@ impl CyclicCubicGenerator

for LinearSpline

{ .iter() .circular_tuple_windows() .map(|(&a, &b)| CubicSegment { - coeff: [a, b - a, P::default(), P::default()], + coefficients: [a, b - a, P::default(), P::default()], }) .collect_vec(); @@ -908,14 +908,14 @@ pub trait CyclicCubicGenerator { #[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Default))] pub struct CubicSegment { /// Polynomial coefficients for the segment. - pub coeff: [P; 4], + pub coefficients: [P; 4], } impl CubicSegment

{ /// Instantaneous position of a point at parametric value `t`. #[inline] pub fn position(&self, t: f32) -> P { - let [a, b, c, d] = self.coeff; + let [a, b, c, d] = self.coefficients; // Evaluate `a + bt + ct^2 + dt^3`, avoiding exponentiation a + (b + (c + d * t) * t) * t } @@ -923,7 +923,7 @@ impl CubicSegment

{ /// Instantaneous velocity of a point at parametric value `t`. #[inline] pub fn velocity(&self, t: f32) -> P { - let [_, b, c, d] = self.coeff; + let [_, b, c, d] = self.coefficients; // Evaluate the derivative, which is `b + 2ct + 3dt^2`, avoiding exponentiation b + (c * 2.0 + d * 3.0 * t) * t } @@ -931,7 +931,7 @@ impl CubicSegment

{ /// Instantaneous acceleration of a point at parametric value `t`. #[inline] pub fn acceleration(&self, t: f32) -> P { - let [_, _, c, d] = self.coeff; + let [_, _, c, d] = self.coefficients; // Evaluate the second derivative, which is `2c + 6dt` c * 2.0 + d * 6.0 * t } @@ -942,13 +942,13 @@ impl CubicSegment

{ let [c0, c1, c2, c3] = char_matrix; // These are the polynomial coefficients, computed by multiplying the characteristic // matrix by the point matrix. - let coeff = [ + let coefficients = [ p[0] * c0[0] + p[1] * c0[1] + p[2] * c0[2] + p[3] * c0[3], p[0] * c1[0] + p[1] * c1[1] + p[2] * c1[2] + p[3] * c1[3], p[0] * c2[0] + p[1] * c2[1] + p[2] * c2[2] + p[3] * c2[3], p[0] * c3[0] + p[1] * c3[1] + p[2] * c3[2] + p[3] * c3[3], ]; - Self { coeff } + Self { coefficients } } } @@ -1003,7 +1003,7 @@ impl CubicSegment { /// y /// │ ● /// │ ⬈ - /// │ ⬈ + /// │ ⬈ /// │ ⬈ /// │ ⬈ /// ●─────────── x (time) @@ -1017,8 +1017,8 @@ impl CubicSegment { /// ```text /// y /// ⬈➔● - /// │ ⬈ - /// │ ↑ + /// │ ⬈ + /// │ ↑ /// │ ↑ /// │ ⬈ /// ●➔⬈───────── x (time) @@ -1251,9 +1251,9 @@ pub trait RationalGenerator { #[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Default))] pub struct RationalSegment { /// The coefficients matrix of the cubic curve. - pub coeff: [P; 4], + pub coefficients: [P; 4], /// The homogeneous weight coefficients. - pub weight_coeff: [f32; 4], + pub weight_coefficients: [f32; 4], /// The width of the domain of this segment. pub knot_span: f32, } @@ -1262,8 +1262,8 @@ impl RationalSegment

{ /// Instantaneous position of a point at parametric value `t` in `[0, 1]`. #[inline] pub fn position(&self, t: f32) -> P { - let [a, b, c, d] = self.coeff; - let [x, y, z, w] = self.weight_coeff; + let [a, b, c, d] = self.coefficients; + let [x, y, z, w] = self.weight_coefficients; // Compute a cubic polynomial for the control points let numerator = a + (b + (c + d * t) * t) * t; // Compute a cubic polynomial for the weights @@ -1277,8 +1277,8 @@ impl RationalSegment

{ // A derivation for the following equations can be found in "Matrix representation for NURBS // curves and surfaces" by Choi et al. See equation 19. - let [a, b, c, d] = self.coeff; - let [x, y, z, w] = self.weight_coeff; + let [a, b, c, d] = self.coefficients; + let [x, y, z, w] = self.weight_coefficients; // Compute a cubic polynomial for the control points let numerator = a + (b + (c + d * t) * t) * t; // Compute a cubic polynomial for the weights @@ -1305,8 +1305,8 @@ impl RationalSegment

{ // + The first term has incorrect sign. // + The second term uses R when it should use the first derivative. - let [a, b, c, d] = self.coeff; - let [x, y, z, w] = self.weight_coeff; + let [a, b, c, d] = self.coefficients; + let [x, y, z, w] = self.weight_coefficients; // Compute a cubic polynomial for the control points let numerator = a + (b + (c + d * t) * t) * t; // Compute a cubic polynomial for the weights @@ -1349,7 +1349,7 @@ impl RationalSegment

{ let w = weights; // These are the control point polynomial coefficients, computed by multiplying the characteristic // matrix by the point matrix. - let coeff = [ + let coefficients = [ p[0] * c0[0] + p[1] * c0[1] + p[2] * c0[2] + p[3] * c0[3], p[0] * c1[0] + p[1] * c1[1] + p[2] * c1[2] + p[3] * c1[3], p[0] * c2[0] + p[1] * c2[1] + p[2] * c2[2] + p[3] * c2[3], @@ -1357,15 +1357,15 @@ impl RationalSegment

{ ]; // These are the weight polynomial coefficients, computed by multiplying the characteristic // matrix by the weight matrix. - let weight_coeff = [ + let weight_coefficients = [ w[0] * c0[0] + w[1] * c0[1] + w[2] * c0[2] + w[3] * c0[3], w[0] * c1[0] + w[1] * c1[1] + w[2] * c1[2] + w[3] * c1[3], w[0] * c2[0] + w[1] * c2[1] + w[2] * c2[2] + w[3] * c2[3], w[0] * c3[0] + w[1] * c3[1] + w[2] * c3[2] + w[3] * c3[3], ]; Self { - coeff, - weight_coeff, + coefficients, + weight_coefficients, knot_span, } } @@ -1562,8 +1562,8 @@ impl IntoIterator for RationalCurve

{ impl From> for RationalSegment

{ fn from(value: CubicSegment

) -> Self { Self { - coeff: value.coeff, - weight_coeff: [1.0, 0.0, 0.0, 0.0], + coefficients: value.coefficients, + weight_coefficients: [1.0, 0.0, 0.0, 0.0], knot_span: 1.0, // Cubic curves are uniform, so every segment has domain [0, 1). } } diff --git a/crates/bevy_math/src/curve/adaptors.rs b/crates/bevy_math/src/curve/adaptors.rs index 1d186706f264d..33086c29953d7 100644 --- a/crates/bevy_math/src/curve/adaptors.rs +++ b/crates/bevy_math/src/curve/adaptors.rs @@ -362,7 +362,7 @@ where } } -/// A curve that has had its domain changed by a linear reparameterization (stretching and scaling). +/// A curve that has had its domain changed by a linear reparametrization (stretching and scaling). /// Curves of this type are produced by [`Curve::reparametrize_linear`]. #[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] diff --git a/crates/bevy_math/src/curve/cores.rs b/crates/bevy_math/src/curve/cores.rs index 6c63eabb29cfa..fa4b4ae0ada5c 100644 --- a/crates/bevy_math/src/curve/cores.rs +++ b/crates/bevy_math/src/curve/cores.rs @@ -102,7 +102,7 @@ impl InterpolationDatum { /// fn domain(&self) -> Interval { /// self.core.domain() /// } -/// +/// /// fn sample_unchecked(&self, t: f32) -> T { /// // To sample this curve, check the interpolation mode and dispatch accordingly. /// match self.interpolation_mode { @@ -142,7 +142,7 @@ pub enum EvenCoreError { }, /// Unbounded domains are not compatible with `EvenCore`. - #[display("Cannot create a EvenCore over an unbounded domain")] + #[display("Cannot create an EvenCore over an unbounded domain")] UnboundedDomain, } @@ -231,15 +231,15 @@ impl EvenCore { /// /// This function will never panic, but it may return invalid indices if its assumptions are violated. pub fn even_interp(domain: Interval, samples: usize, t: f32) -> InterpolationDatum { - let subdivs = samples - 1; - let step = domain.length() / subdivs as f32; + let subdivisions = samples - 1; + let step = domain.length() / subdivisions as f32; let t_shifted = t - domain.start(); let steps_taken = t_shifted / step; if steps_taken <= 0.0 { // To the left side of all the samples. InterpolationDatum::LeftTail(0) - } else if steps_taken >= subdivs as f32 { + } else if steps_taken >= subdivisions as f32 { // To the right side of all the samples InterpolationDatum::RightTail(samples - 1) } else { @@ -297,7 +297,7 @@ pub fn even_interp(domain: Interval, samples: usize, t: f32) -> InterpolationDat /// fn domain(&self) -> Interval { /// self.core.domain() /// } -/// +/// /// fn sample_unchecked(&self, t: f32) -> T { /// // To sample the curve, we just look at the interpolation mode and /// // dispatch accordingly. diff --git a/crates/bevy_math/src/curve/mod.rs b/crates/bevy_math/src/curve/mod.rs index 34afaeca94ee4..d1fa0af3643c1 100644 --- a/crates/bevy_math/src/curve/mod.rs +++ b/crates/bevy_math/src/curve/mod.rs @@ -903,7 +903,7 @@ where } } -/// An error indicating that a linear reparameterization couldn't be performed because of +/// An error indicating that a linear reparametrization couldn't be performed because of /// malformed inputs. #[derive(Debug, Error, Display)] #[display("Could not build a linear function to reparametrize this curve")] @@ -912,8 +912,8 @@ pub enum LinearReparamError { #[display("This curve has unbounded domain")] SourceCurveUnbounded, - /// The target interval for reparameterization was unbounded. - #[display("The target interval for reparameterization is unbounded")] + /// The target interval for reparametrization was unbounded. + #[display("The target interval for reparametrization is unbounded")] TargetIntervalUnbounded, } @@ -1176,7 +1176,7 @@ mod tests { } #[test] - fn reparameterization() { + fn reparametrization() { let curve = FunctionCurve::new(interval(1.0, f32::INFINITY).unwrap(), ops::log2); let reparametrized_curve = curve .by_ref() @@ -1206,7 +1206,7 @@ mod tests { } #[test] - fn multiple_reparams() { + fn multiple_reparametrizations() { // Make sure these happen in the right order too. let curve = FunctionCurve::new(Interval::UNIT, ops::exp2); let first_reparam = curve.reparametrize(interval(1.0, 2.0).unwrap(), ops::log2); diff --git a/crates/bevy_math/src/direction.rs b/crates/bevy_math/src/direction.rs index acbc5816ad3f2..0c231ecdd0336 100644 --- a/crates/bevy_math/src/direction.rs +++ b/crates/bevy_math/src/direction.rs @@ -911,7 +911,7 @@ mod tests { } #[test] - fn dir2_renorm() { + fn dir2_renormalization() { // Evil denormalized Rot2 let (sin, cos) = ops::sin_cos(1.0_f32); let rot2 = Rot2::from_sin_cos(sin * (1.0 + 1e-5), cos * (1.0 + 1e-5)); @@ -930,9 +930,9 @@ mod tests { // `dir_a` should've gotten denormalized, meanwhile `dir_b` should stay normalized. assert!( !dir_a.is_normalized(), - "Dernormalization doesn't work, test is faulty" + "Denormalization doesn't work, test is faulty" ); - assert!(dir_b.is_normalized(), "Renormalisation did not work."); + assert!(dir_b.is_normalized(), "Renormalization did not work."); } #[test] @@ -983,7 +983,7 @@ mod tests { } #[test] - fn dir3_renorm() { + fn dir3_renormalization() { // Evil denormalized quaternion let rot3 = Quat::from_euler(glam::EulerRot::XYZ, 1.0, 2.0, 3.0) * (1.0 + 1e-5); let mut dir_a = Dir3::X; @@ -1001,9 +1001,9 @@ mod tests { // `dir_a` should've gotten denormalized, meanwhile `dir_b` should stay normalized. assert!( !dir_a.is_normalized(), - "Dernormalization doesn't work, test is faulty" + "Denormalization doesn't work, test is faulty" ); - assert!(dir_b.is_normalized(), "Renormalisation did not work."); + assert!(dir_b.is_normalized(), "Renormalization did not work."); } #[test] @@ -1054,7 +1054,7 @@ mod tests { } #[test] - fn dir3a_renorm() { + fn dir3a_renormalization() { // Evil denormalized quaternion let rot3 = Quat::from_euler(glam::EulerRot::XYZ, 1.0, 2.0, 3.0) * (1.0 + 1e-5); let mut dir_a = Dir3A::X; @@ -1072,8 +1072,8 @@ mod tests { // `dir_a` should've gotten denormalized, meanwhile `dir_b` should stay normalized. assert!( !dir_a.is_normalized(), - "Dernormalization doesn't work, test is faulty" + "Denormalization doesn't work, test is faulty" ); - assert!(dir_b.is_normalized(), "Renormalisation did not work."); + assert!(dir_b.is_normalized(), "Renormalization did not work."); } } diff --git a/crates/bevy_math/src/primitives/dim2.rs b/crates/bevy_math/src/primitives/dim2.rs index 62d1633622dde..f4682d1d1b147 100644 --- a/crates/bevy_math/src/primitives/dim2.rs +++ b/crates/bevy_math/src/primitives/dim2.rs @@ -1102,7 +1102,7 @@ impl Rhombus { let point_abs = point.abs(); let half_diagonals = self.half_diagonals.abs(); // to ensure correct sign - // The unnormalised normal vector perpendicular to the side of the rhombus + // The unnormalized normal vector perpendicular to the side of the rhombus let normal = Vec2::new(half_diagonals.y, half_diagonals.x); let normal_magnitude_squared = normal.length_squared(); if normal_magnitude_squared == 0.0 { @@ -1110,15 +1110,15 @@ impl Rhombus { } // The last term corresponds to normal.dot(rhombus_vertex) - let distance_unnormalised = normal.dot(point_abs) - half_diagonals.x * half_diagonals.y; + let distance_unnormalized = normal.dot(point_abs) - half_diagonals.x * half_diagonals.y; // The point is already inside so we simply return it. - if distance_unnormalised <= 0.0 { + if distance_unnormalized <= 0.0 { return point; } // Clamp the point to the edge - let mut result = point_abs - normal * distance_unnormalised / normal_magnitude_squared; + let mut result = point_abs - normal * distance_unnormalized / normal_magnitude_squared; // Clamp the point back to the positive quadrant // if it's outside, it needs to be clamped to either vertex @@ -1895,14 +1895,14 @@ impl Measured2d for RegularPolygon { pub struct Capsule2d { /// The radius of the capsule pub radius: f32, - /// Half the height of the capsule, excluding the hemicircles + /// Half the height of the capsule, excluding the semicircles pub half_length: f32, } impl Primitive2d for Capsule2d {} impl Default for Capsule2d { /// Returns the default [`Capsule2d`] with a radius of `0.5` and a half-height of `0.5`, - /// excluding the hemicircles. + /// excluding the semicircles. fn default() -> Self { Self { radius: 0.5, @@ -2208,9 +2208,9 @@ mod tests { let mut rotated_vertices = polygon.vertices(core::f32::consts::FRAC_PI_4).into_iter(); // Distance from the origin to the middle of a side, derived using Pythagorean theorem - let side_sistance = FRAC_1_SQRT_2; + let side_distance = FRAC_1_SQRT_2; assert!( - (rotated_vertices.next().unwrap() - Vec2::new(-side_sistance, side_sistance)).length() + (rotated_vertices.next().unwrap() - Vec2::new(-side_distance, side_distance)).length() < 1e-7, ); } diff --git a/crates/bevy_math/src/primitives/dim3.rs b/crates/bevy_math/src/primitives/dim3.rs index cd1b5013e6b72..7f4a4f3510a95 100644 --- a/crates/bevy_math/src/primitives/dim3.rs +++ b/crates/bevy_math/src/primitives/dim3.rs @@ -250,10 +250,10 @@ impl InfinitePlane3d { /// /// * the rotation used is generally not unique /// * the orientation of the transformed geometry in the XY plane might be arbitrary, to - /// enforce some kind of alignment the user has to use an extra transformation ontop of this + /// enforce some kind of alignment the user has to use an extra transformation on top of this /// one /// - /// See [`isometries_xy`] for example usescases. + /// See [`isometries_xy`] for example use cases. /// /// [congruence]: https://en.wikipedia.org/wiki/Congruence_(geometry) /// [`isometries_xy`]: `InfinitePlane3d::isometries_xy` @@ -281,10 +281,10 @@ impl InfinitePlane3d { /// /// * the rotation used is generally not unique /// * the orientation of the transformed geometry in the XY plane might be arbitrary, to - /// enforce some kind of alignment the user has to use an extra transformation ontop of this + /// enforce some kind of alignment the user has to use an extra transformation on top of this /// one /// - /// See [`isometries_xy`] for example usescases. + /// See [`isometries_xy`] for example use cases. /// /// [congruence]: https://en.wikipedia.org/wiki/Congruence_(geometry) /// [`isometries_xy`]: `InfinitePlane3d::isometries_xy` @@ -1074,7 +1074,7 @@ impl Triangle3d { /// /// This function finds the geometric center of the triangle by averaging the vertices: /// `centroid = (a + b + c) / 3`. - #[doc(alias("center", "barycenter", "baricenter"))] + #[doc(alias("center", "barycenter"))] #[inline(always)] pub fn centroid(&self) -> Vec3 { (self.vertices[0] + self.vertices[1] + self.vertices[2]) / 3.0 @@ -1203,7 +1203,7 @@ impl Tetrahedron { /// /// This function finds the geometric center of the tetrahedron /// by averaging the vertices: `centroid = (a + b + c + d) / 4`. - #[doc(alias("center", "barycenter", "baricenter"))] + #[doc(alias("center", "barycenter"))] #[inline(always)] pub fn centroid(&self) -> Vec3 { (self.vertices[0] + self.vertices[1] + self.vertices[2] + self.vertices[3]) / 4.0 diff --git a/crates/bevy_math/src/rects/rect.rs b/crates/bevy_math/src/rects/rect.rs index 8e804dcd085f0..169dddcc7f893 100644 --- a/crates/bevy_math/src/rects/rect.rs +++ b/crates/bevy_math/src/rects/rect.rs @@ -35,7 +35,7 @@ pub struct Rect { impl Rect { /// An empty `Rect`, represented by maximum and minimum corner points /// at `Vec2::NEG_INFINITY` and `Vec2::INFINITY`, respectively. - /// This is so the `Rect` has a infinitely negative size. + /// This is so the `Rect` has an infinitely negative size. /// This is useful, because when taking a union B of a non-empty `Rect` A and /// this empty `Rect`, B will simply equal A. pub const EMPTY: Self = Self { diff --git a/crates/bevy_math/src/sampling/shape_sampling.rs b/crates/bevy_math/src/sampling/shape_sampling.rs index fdec36aa0b101..1b440d02ad884 100644 --- a/crates/bevy_math/src/sampling/shape_sampling.rs +++ b/crates/bevy_math/src/sampling/shape_sampling.rs @@ -289,7 +289,7 @@ fn sample_triangle_interior( let ab = b - a; let ac = c - a; - // Generate random points on a parallelipiped and reflect so that + // Generate random points on a parallelepiped and reflect so that // we can use the points that lie outside the triangle let u = rng.gen_range(0.0..=1.0); let v = rng.gen_range(0.0..=1.0); diff --git a/crates/bevy_mesh/src/index.rs b/crates/bevy_mesh/src/index.rs index 096cd031d6126..bc595678ccaf2 100644 --- a/crates/bevy_mesh/src/index.rs +++ b/crates/bevy_mesh/src/index.rs @@ -37,7 +37,7 @@ where #[derive(Debug, Error, Display)] pub enum MeshWindingInvertError { /// This error occurs when you try to invert the winding for a mesh with [`PrimitiveTopology::PointList`](super::PrimitiveTopology::PointList). - #[display("Mesh winding invertation does not work for primitive topology `PointList`")] + #[display("Mesh winding inversion does not work for primitive topology `PointList`")] WrongTopology, /// This error occurs when you try to invert the winding for a mesh with diff --git a/crates/bevy_mesh/src/mikktspace.rs b/crates/bevy_mesh/src/mikktspace.rs index 08d8f14c3db9a..8850c7b556104 100644 --- a/crates/bevy_mesh/src/mikktspace.rs +++ b/crates/bevy_mesh/src/mikktspace.rs @@ -129,13 +129,17 @@ pub(crate) fn generate_tangents_for_mesh( Ok(mikktspace_mesh.tangents) } -/// Correctly scales and renormalizes an already normalized `normal` by the scale determined by its reciprocal `scale_recip` -pub(crate) fn scale_normal(normal: Vec3, scale_recip: Vec3) -> Vec3 { - // This is basically just `normal * scale_recip` but with the added rule that `0. * anything == 0.` - // This is necessary because components of `scale_recip` may be infinities, which do not multiply to zero - let n = Vec3::select(normal.cmpeq(Vec3::ZERO), Vec3::ZERO, normal * scale_recip); - - // If n is finite, no component of `scale_recip` was infinite or the normal was perpendicular to the scale +/// Correctly scales and renormalizes an already normalized `normal` by the scale determined by its reciprocal `scale_reciprocal` +pub(crate) fn scale_normal(normal: Vec3, scale_reciprocal: Vec3) -> Vec3 { + // This is basically just `normal * scale_reciprocal` but with the added rule that `0. * anything == 0.` + // This is necessary because components of `scale_reciprocal` may be infinities, which do not multiply to zero + let n = Vec3::select( + normal.cmpeq(Vec3::ZERO), + Vec3::ZERO, + normal * scale_reciprocal, + ); + + // If n is finite, no component of `scale_reciprocal` was infinite or the normal was perpendicular to the scale // else the scale had at least one zero-component and the normal needs to point along the direction of that component if n.is_finite() { n.normalize_or_zero() diff --git a/crates/bevy_mesh/src/primitives/dim2.rs b/crates/bevy_mesh/src/primitives/dim2.rs index f978a8f1d68c7..e628470f1bf58 100644 --- a/crates/bevy_mesh/src/primitives/dim2.rs +++ b/crates/bevy_mesh/src/primitives/dim2.rs @@ -896,7 +896,7 @@ impl From for Mesh { pub struct Capsule2dMeshBuilder { /// The [`Capsule2d`] shape. pub capsule: Capsule2d, - /// The number of vertices used for one hemicircle. + /// The number of vertices used for one semicircle. /// The total number of vertices for the capsule mesh will be two times the resolution. /// /// The default is `16`. @@ -914,7 +914,7 @@ impl Default for Capsule2dMeshBuilder { impl Capsule2dMeshBuilder { /// Creates a new [`Capsule2dMeshBuilder`] from a given radius, length, and the number of vertices - /// used for one hemicircle. The total number of vertices for the capsule mesh will be two times the resolution. + /// used for one semicircle. The total number of vertices for the capsule mesh will be two times the resolution. #[inline] pub fn new(radius: f32, length: f32, resolution: u32) -> Self { Self { @@ -923,7 +923,7 @@ impl Capsule2dMeshBuilder { } } - /// Sets the number of vertices used for one hemicircle. + /// Sets the number of vertices used for one semicircle. /// The total number of vertices for the capsule mesh will be two times the resolution. #[inline] pub const fn resolution(mut self, resolution: u32) -> Self { @@ -938,7 +938,7 @@ impl MeshBuilder for Capsule2dMeshBuilder { let resolution = self.resolution; let vertex_count = 2 * resolution; - // Six extra indices for the two triangles between the hemicircles + // Six extra indices for the two triangles between the semicircles let mut indices = Vec::with_capacity((resolution as usize - 2) * 2 * 3 + 6); let mut positions = Vec::with_capacity(vertex_count as usize); let normals = vec![[0.0, 0.0, 1.0]; vertex_count as usize]; @@ -955,8 +955,8 @@ impl MeshBuilder for Capsule2dMeshBuilder { 0.0 }; - // How much the hemicircle radius is of the total half-height of the capsule. - // This is used to prevent the UVs from stretching between the hemicircles. + // How much the semicircle radius is of the total half-height of the capsule. + // This is used to prevent the UVs from stretching between the semicircles. let radius_frac = self.capsule.radius / (self.capsule.half_length + self.capsule.radius); // Create top semicircle @@ -975,7 +975,7 @@ impl MeshBuilder for Capsule2dMeshBuilder { indices.extend_from_slice(&[0, i, i + 1]); } - // Add indices for top left triangle of the part between the hemicircles + // Add indices for top left triangle of the part between the semicircles indices.extend_from_slice(&[0, resolution - 1, resolution]); // Create bottom semicircle @@ -994,7 +994,7 @@ impl MeshBuilder for Capsule2dMeshBuilder { indices.extend_from_slice(&[resolution, resolution + i, resolution + i + 1]); } - // Add indices for bottom right triangle of the part between the hemicircles + // Add indices for bottom right triangle of the part between the semicircles indices.extend_from_slice(&[resolution, vertex_count - 1, 0]); Mesh::new( diff --git a/crates/bevy_mesh/src/primitives/dim3/capsule.rs b/crates/bevy_mesh/src/primitives/dim3/capsule.rs index 0fe4e4bef25e8..1336830cede83 100644 --- a/crates/bevy_mesh/src/primitives/dim3/capsule.rs +++ b/crates/bevy_mesh/src/primitives/dim3/capsule.rs @@ -107,25 +107,27 @@ impl MeshBuilder for Capsule3dMeshBuilder { } = capsule; let calc_middle = rings > 0; - let half_lats = latitudes / 2; - let half_latsn1 = half_lats - 1; - let half_latsn2 = half_lats - 2; - let ringsp1 = rings + 1; - let lonsp1 = longitudes + 1; + let half_latitudes = latitudes / 2; + let half_latitudes_n1 = half_latitudes - 1; + let half_latitudes_n2 = half_latitudes - 2; + let rings_p1 = rings + 1; + let longitudes_p1 = longitudes + 1; let summit = half_length + radius; // Vertex index offsets. - let vert_offset_north_hemi = longitudes; - let vert_offset_north_equator = vert_offset_north_hemi + lonsp1 * half_latsn1; - let vert_offset_cylinder = vert_offset_north_equator + lonsp1; + let vert_offset_north_hemisphere = longitudes; + let vert_offset_north_equator = + vert_offset_north_hemisphere + longitudes_p1 * half_latitudes_n1; + let vert_offset_cylinder = vert_offset_north_equator + longitudes_p1; let vert_offset_south_equator = if calc_middle { - vert_offset_cylinder + lonsp1 * rings + vert_offset_cylinder + longitudes_p1 * rings } else { vert_offset_cylinder }; - let vert_offset_south_hemi = vert_offset_south_equator + lonsp1; - let vert_offset_south_polar = vert_offset_south_hemi + lonsp1 * half_latsn2; - let vert_offset_south_cap = vert_offset_south_polar + lonsp1; + let vert_offset_south_hemisphere = vert_offset_south_equator + longitudes_p1; + let vert_offset_south_polar = + vert_offset_south_hemisphere + longitudes_p1 * half_latitudes_n2; + let vert_offset_south_cap = vert_offset_south_polar + longitudes_p1; // Initialize arrays. let vert_len = (vert_offset_south_cap + longitudes) as usize; @@ -136,12 +138,12 @@ impl MeshBuilder for Capsule3dMeshBuilder { let to_theta = 2.0 * core::f32::consts::PI / longitudes as f32; let to_phi = core::f32::consts::PI / latitudes as f32; - let to_tex_horizontal = 1.0 / longitudes as f32; - let to_tex_vertical = 1.0 / half_lats as f32; + let to_texture_horizontal = 1.0 / longitudes as f32; + let to_texture_vertical = 1.0 / half_latitudes as f32; let vt_aspect_ratio = match uv_profile { CapsuleUvProfile::Aspect => radius / (2.0 * half_length + radius + radius), - CapsuleUvProfile::Uniform => half_lats as f32 / (ringsp1 + latitudes) as f32, + CapsuleUvProfile::Uniform => half_latitudes as f32 / (rings_p1 + latitudes) as f32, CapsuleUvProfile::Fixed => 1.0 / 3.0, }; let vt_aspect_north = 1.0 - vt_aspect_ratio; @@ -149,11 +151,11 @@ impl MeshBuilder for Capsule3dMeshBuilder { let mut theta_cartesian: Vec = vec![Vec2::ZERO; longitudes as usize]; let mut rho_theta_cartesian: Vec = vec![Vec2::ZERO; longitudes as usize]; - let mut s_texture_cache: Vec = vec![0.0; lonsp1 as usize]; + let mut south_texture_cache: Vec = vec![0.0; longitudes_p1 as usize]; for j in 0..longitudes as usize { let jf = j as f32; - let s_texture_polar = 1.0 - ((jf + 0.5) * to_tex_horizontal); + let south_texture_polar = 1.0 - ((jf + 0.5) * to_texture_horizontal); let theta = jf * to_theta; theta_cartesian[j] = Vec2::from_angle(theta); @@ -161,20 +163,24 @@ impl MeshBuilder for Capsule3dMeshBuilder { // North. vs[j] = Vec3::new(0.0, summit, 0.0); - vts[j] = Vec2::new(s_texture_polar, 1.0); + vts[j] = Vec2::new(south_texture_polar, 1.0); vns[j] = Vec3::Y; // South. let idx = vert_offset_south_cap as usize + j; vs[idx] = Vec3::new(0.0, -summit, 0.0); - vts[idx] = Vec2::new(s_texture_polar, 0.0); + vts[idx] = Vec2::new(south_texture_polar, 0.0); vns[idx] = Vec3::new(0.0, -1.0, 0.0); } // Equatorial vertices. - for (j, s_texture_cache_j) in s_texture_cache.iter_mut().enumerate().take(lonsp1 as usize) { - let s_texture = 1.0 - j as f32 * to_tex_horizontal; - *s_texture_cache_j = s_texture; + for (j, south_texture_cache_j) in south_texture_cache + .iter_mut() + .enumerate() + .take(longitudes_p1 as usize) + { + let south_texture = 1.0 - j as f32 * to_texture_horizontal; + *south_texture_cache_j = south_texture; // Wrap to first element upon reaching last. let j_mod = j % longitudes as usize; @@ -182,22 +188,22 @@ impl MeshBuilder for Capsule3dMeshBuilder { let rtc = rho_theta_cartesian[j_mod]; // North equator. - let idxn = vert_offset_north_equator as usize + j; - vs[idxn] = Vec3::new(rtc.x, half_length, -rtc.y); - vts[idxn] = Vec2::new(s_texture, vt_aspect_north); - vns[idxn] = Vec3::new(tc.x, 0.0, -tc.y); + let index_north = vert_offset_north_equator as usize + j; + vs[index_north] = Vec3::new(rtc.x, half_length, -rtc.y); + vts[index_north] = Vec2::new(south_texture, vt_aspect_north); + vns[index_north] = Vec3::new(tc.x, 0.0, -tc.y); // South equator. - let idxs = vert_offset_south_equator as usize + j; - vs[idxs] = Vec3::new(rtc.x, -half_length, -rtc.y); - vts[idxs] = Vec2::new(s_texture, vt_aspect_south); - vns[idxs] = Vec3::new(tc.x, 0.0, -tc.y); + let index_south = vert_offset_south_equator as usize + j; + vs[index_south] = Vec3::new(rtc.x, -half_length, -rtc.y); + vts[index_south] = Vec2::new(south_texture, vt_aspect_south); + vns[index_south] = Vec3::new(tc.x, 0.0, -tc.y); } // Hemisphere vertices. - for i in 0..half_latsn1 { - let ip1f = i as f32 + 1.0; - let phi = ip1f * to_phi; + for i in 0..half_latitudes_n1 { + let i_plus1 = i as f32 + 1.0; + let phi = i_plus1 * to_phi; // For coordinates. let (sin_phi_south, cos_phi_south) = ops::sin_cos(phi); @@ -213,42 +219,48 @@ impl MeshBuilder for Capsule3dMeshBuilder { let rho_cos_phi_south = radius * cos_phi_south; let rho_sin_phi_south = radius * sin_phi_south; - let z_offset_sout = -half_length - rho_sin_phi_south; + let z_offset_south = -half_length - rho_sin_phi_south; // For texture coordinates. - let t_tex_fac = ip1f * to_tex_vertical; - let cmpl_tex_fac = 1.0 - t_tex_fac; - let t_tex_north = cmpl_tex_fac + vt_aspect_north * t_tex_fac; - let t_tex_south = cmpl_tex_fac * vt_aspect_south; - - let i_lonsp1 = i * lonsp1; - let vert_curr_lat_north = vert_offset_north_hemi + i_lonsp1; - let vert_curr_lat_south = vert_offset_south_hemi + i_lonsp1; - - for (j, s_texture) in s_texture_cache.iter().enumerate().take(lonsp1 as usize) { + let to_texture_factor = i_plus1 * to_texture_vertical; + let complement_texture_factor = 1.0 - to_texture_factor; + let t_texture_north = complement_texture_factor + vt_aspect_north * to_texture_factor; + let t_texture_south = complement_texture_factor * vt_aspect_south; + + let i_longitudes_p1 = i * longitudes_p1; + let vert_current_lat_north = vert_offset_north_hemisphere + i_longitudes_p1; + let vert_current_lat_south = vert_offset_south_hemisphere + i_longitudes_p1; + + for (j, south_texture) in south_texture_cache + .iter() + .enumerate() + .take(longitudes_p1 as usize) + { let j_mod = j % longitudes as usize; let tc = theta_cartesian[j_mod]; // North hemisphere. - let idxn = vert_curr_lat_north as usize + j; - vs[idxn] = Vec3::new( + let index_north = vert_current_lat_north as usize + j; + vs[index_north] = Vec3::new( rho_cos_phi_north * tc.x, z_offset_north, -rho_cos_phi_north * tc.y, ); - vts[idxn] = Vec2::new(*s_texture, t_tex_north); - vns[idxn] = Vec3::new(cos_phi_north * tc.x, -sin_phi_north, -cos_phi_north * tc.y); + vts[index_north] = Vec2::new(*south_texture, t_texture_north); + vns[index_north] = + Vec3::new(cos_phi_north * tc.x, -sin_phi_north, -cos_phi_north * tc.y); // South hemisphere. - let idxs = vert_curr_lat_south as usize + j; - vs[idxs] = Vec3::new( + let index_south = vert_current_lat_south as usize + j; + vs[index_south] = Vec3::new( rho_cos_phi_south * tc.x, - z_offset_sout, + z_offset_south, -rho_cos_phi_south * tc.y, ); - vts[idxs] = Vec2::new(*s_texture, t_tex_south); - vns[idxs] = Vec3::new(cos_phi_south * tc.x, -sin_phi_south, -cos_phi_south * tc.y); + vts[index_south] = Vec2::new(*south_texture, t_texture_south); + vns[index_south] = + Vec3::new(cos_phi_south * tc.x, -sin_phi_south, -cos_phi_south * tc.y); } } @@ -256,22 +268,26 @@ impl MeshBuilder for Capsule3dMeshBuilder { if calc_middle { // Exclude both origin and destination edges // (North and South equators) from the interpolation. - let to_fac = 1.0 / ringsp1 as f32; + let to_factor = 1.0 / rings_p1 as f32; let mut idx_cyl_lat = vert_offset_cylinder as usize; - for h in 1..ringsp1 { - let fac = h as f32 * to_fac; - let cmpl_fac = 1.0 - fac; - let t_texture = cmpl_fac * vt_aspect_north + fac * vt_aspect_south; - let z = half_length - 2.0 * half_length * fac; - - for (j, s_texture) in s_texture_cache.iter().enumerate().take(lonsp1 as usize) { + for h in 1..rings_p1 { + let factor = h as f32 * to_factor; + let complement_factor = 1.0 - factor; + let t_texture = complement_factor * vt_aspect_north + factor * vt_aspect_south; + let z = half_length - 2.0 * half_length * factor; + + for (j, south_texture) in south_texture_cache + .iter() + .enumerate() + .take(longitudes_p1 as usize) + { let j_mod = j % longitudes as usize; let tc = theta_cartesian[j_mod]; let rtc = rho_theta_cartesian[j_mod]; vs[idx_cyl_lat] = Vec3::new(rtc.x, z, -rtc.y); - vts[idx_cyl_lat] = Vec2::new(*s_texture, t_texture); + vts[idx_cyl_lat] = Vec2::new(*south_texture, t_texture); vns[idx_cyl_lat] = Vec3::new(tc.x, 0.0, -tc.y); idx_cyl_lat += 1; @@ -283,17 +299,17 @@ impl MeshBuilder for Capsule3dMeshBuilder { // Stride is 3 for polar triangles; // stride is 6 for two triangles forming a quad. - let lons3 = longitudes * 3; - let lons6 = longitudes * 6; - let hemi_lons = half_latsn1 * lons6; + let longitudes3 = longitudes * 3; + let longitudes6 = longitudes * 6; + let hemisphere_longitudes = half_latitudes_n1 * longitudes6; - let tri_offset_north_hemi = lons3; - let tri_offset_cylinder = tri_offset_north_hemi + hemi_lons; - let tri_offset_south_hemi = tri_offset_cylinder + ringsp1 * lons6; - let tri_offset_south_cap = tri_offset_south_hemi + hemi_lons; + let tri_offset_north_hemisphere = longitudes3; + let tri_offset_cylinder = tri_offset_north_hemisphere + hemisphere_longitudes; + let tri_offset_south_hemisphere = tri_offset_cylinder + rings_p1 * longitudes6; + let tri_offset_south_cap = tri_offset_south_hemisphere + hemisphere_longitudes; - let fs_len = tri_offset_south_cap + lons3; - let mut tris: Vec = vec![0; fs_len as usize]; + let fs_len = tri_offset_south_cap + longitudes3; + let mut triangles: Vec = vec![0; fs_len as usize]; // Polar caps. let mut i = 0; @@ -301,14 +317,14 @@ impl MeshBuilder for Capsule3dMeshBuilder { let mut m = tri_offset_south_cap as usize; while i < longitudes { // North. - tris[k] = i; - tris[k + 1] = vert_offset_north_hemi + i; - tris[k + 2] = vert_offset_north_hemi + i + 1; + triangles[k] = i; + triangles[k + 1] = vert_offset_north_hemisphere + i; + triangles[k + 2] = vert_offset_north_hemisphere + i + 1; // South. - tris[m] = vert_offset_south_cap + i; - tris[m + 1] = vert_offset_south_polar + i + 1; - tris[m + 2] = vert_offset_south_polar + i; + triangles[m] = vert_offset_south_cap + i; + triangles[m + 1] = vert_offset_south_polar + i + 1; + triangles[m + 2] = vert_offset_south_polar + i; i += 1; k += 3; @@ -318,47 +334,47 @@ impl MeshBuilder for Capsule3dMeshBuilder { // Hemispheres. let mut i = 0; - let mut k = tri_offset_north_hemi as usize; - let mut m = tri_offset_south_hemi as usize; + let mut k = tri_offset_north_hemisphere as usize; + let mut m = tri_offset_south_hemisphere as usize; - while i < half_latsn1 { - let i_lonsp1 = i * lonsp1; + while i < half_latitudes_n1 { + let i_longitudes_p1 = i * longitudes_p1; - let vert_curr_lat_north = vert_offset_north_hemi + i_lonsp1; - let vert_next_lat_north = vert_curr_lat_north + lonsp1; + let vert_current_lat_north = vert_offset_north_hemisphere + i_longitudes_p1; + let vert_next_lat_north = vert_current_lat_north + longitudes_p1; - let vert_curr_lat_south = vert_offset_south_equator + i_lonsp1; - let vert_next_lat_south = vert_curr_lat_south + lonsp1; + let vert_current_lat_south = vert_offset_south_equator + i_longitudes_p1; + let vert_next_lat_south = vert_current_lat_south + longitudes_p1; let mut j = 0; while j < longitudes { // North. - let north00 = vert_curr_lat_north + j; + let north00 = vert_current_lat_north + j; let north01 = vert_next_lat_north + j; let north11 = vert_next_lat_north + j + 1; - let north10 = vert_curr_lat_north + j + 1; + let north10 = vert_current_lat_north + j + 1; - tris[k] = north00; - tris[k + 1] = north11; - tris[k + 2] = north10; + triangles[k] = north00; + triangles[k + 1] = north11; + triangles[k + 2] = north10; - tris[k + 3] = north00; - tris[k + 4] = north01; - tris[k + 5] = north11; + triangles[k + 3] = north00; + triangles[k + 4] = north01; + triangles[k + 5] = north11; // South. - let south00 = vert_curr_lat_south + j; + let south00 = vert_current_lat_south + j; let south01 = vert_next_lat_south + j; let south11 = vert_next_lat_south + j + 1; - let south10 = vert_curr_lat_south + j + 1; + let south10 = vert_current_lat_south + j + 1; - tris[m] = south00; - tris[m + 1] = south11; - tris[m + 2] = south10; + triangles[m] = south00; + triangles[m + 1] = south11; + triangles[m + 2] = south10; - tris[m + 3] = south00; - tris[m + 4] = south01; - tris[m + 5] = south11; + triangles[m + 3] = south00; + triangles[m + 4] = south01; + triangles[m + 5] = south11; j += 1; k += 6; @@ -372,24 +388,24 @@ impl MeshBuilder for Capsule3dMeshBuilder { let mut i = 0; let mut k = tri_offset_cylinder as usize; - while i < ringsp1 { - let vert_curr_lat = vert_offset_north_equator + i * lonsp1; - let vert_next_lat = vert_curr_lat + lonsp1; + while i < rings_p1 { + let vert_current_lat = vert_offset_north_equator + i * longitudes_p1; + let vert_next_lat = vert_current_lat + longitudes_p1; let mut j = 0; while j < longitudes { - let cy00 = vert_curr_lat + j; + let cy00 = vert_current_lat + j; let cy01 = vert_next_lat + j; let cy11 = vert_next_lat + j + 1; - let cy10 = vert_curr_lat + j + 1; + let cy10 = vert_current_lat + j + 1; - tris[k] = cy00; - tris[k + 1] = cy11; - tris[k + 2] = cy10; + triangles[k] = cy00; + triangles[k + 1] = cy11; + triangles[k + 2] = cy10; - tris[k + 3] = cy00; - tris[k + 4] = cy01; - tris[k + 5] = cy11; + triangles[k + 3] = cy00; + triangles[k + 4] = cy01; + triangles[k + 5] = cy11; j += 1; k += 6; @@ -403,7 +419,7 @@ impl MeshBuilder for Capsule3dMeshBuilder { let vts: Vec<[f32; 2]> = vts.into_iter().map(Into::into).collect(); assert_eq!(vs.len(), vert_len); - assert_eq!(tris.len(), fs_len as usize); + assert_eq!(triangles.len(), fs_len as usize); Mesh::new( PrimitiveTopology::TriangleList, @@ -412,7 +428,7 @@ impl MeshBuilder for Capsule3dMeshBuilder { .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, vs) .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, vns) .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, vts) - .with_inserted_indices(Indices::U32(tris)) + .with_inserted_indices(Indices::U32(triangles)) } } diff --git a/crates/bevy_mesh/src/primitives/extrusion.rs b/crates/bevy_mesh/src/primitives/extrusion.rs index 5d84d933f22cb..c5b2645b0c726 100644 --- a/crates/bevy_mesh/src/primitives/extrusion.rs +++ b/crates/bevy_mesh/src/primitives/extrusion.rs @@ -153,7 +153,7 @@ impl ExtrusionBuilder { } impl ExtrusionBuilder { - /// Sets the number of vertices used for each hemicircle at the ends of the extrusion. + /// Sets the number of vertices used for each semicircle at the ends of the extrusion. pub fn resolution(mut self, resolution: u32) -> Self { self.base_builder.resolution = resolution; self @@ -221,7 +221,7 @@ where } let mantel = { - let Some(VertexAttributeValues::Float32x3(cap_verts)) = + let Some(VertexAttributeValues::Float32x3(cap_vertices)) = front_face.attribute(Mesh::ATTRIBUTE_POSITION) else { panic!("The base mesh did not have vertex positions"); @@ -236,9 +236,9 @@ where let (vert_count, index_count) = perimeter .iter() - .fold((0, 0), |(verts, indices), perimeter| { + .fold((0, 0), |(vertices, indices), perimeter| { ( - verts + layers * perimeter.vertices_per_layer() as usize, + vertices + layers * perimeter.vertices_per_layer() as usize, indices + self.segments * perimeter.indices_per_segment(), ) }); @@ -261,8 +261,8 @@ where for i in 0..(segment_indices.len() - 1) { let uv_x = uv_start + uv_delta * i as f32; // Get the positions for the current and the next index. - let a = cap_verts[segment_indices[i] as usize]; - let b = cap_verts[segment_indices[i + 1] as usize]; + let a = cap_vertices[segment_indices[i] as usize]; + let b = cap_vertices[segment_indices[i + 1] as usize]; // Get the index of the next vertex added to the mantel. let index = positions.len() as u32; @@ -314,7 +314,7 @@ where // If there is a first vertex, we need to add it and its counterparts on each layer. // The normal is provided by `segment.first_normal`. if let Some(i) = segment_indices.first() { - let p = cap_verts[*i as usize]; + let p = cap_vertices[*i as usize]; for i in 0..layers { let i = i as f32; let z = p[2] - layer_depth_delta * i; @@ -329,14 +329,14 @@ where ]); } - // For all points inbetween the first and last vertices, we can automatically compute the normals. + // For all points in-between the first and last vertices, we can automatically compute the normals. for i in 1..(segment_indices.len() - 1) { let uv_x = uv_start + uv_delta * i as f32; // Get the positions for the last, current and the next index. - let a = cap_verts[segment_indices[i - 1] as usize]; - let b = cap_verts[segment_indices[i] as usize]; - let c = cap_verts[segment_indices[i + 1] as usize]; + let a = cap_vertices[segment_indices[i - 1] as usize]; + let b = cap_vertices[segment_indices[i] as usize]; + let c = cap_vertices[segment_indices[i + 1] as usize]; // Add the current vertex and its counterparts on each layer. for i in 0..layers { @@ -366,7 +366,7 @@ where // If there is a last vertex, we need to add it and its counterparts on each layer. // The normal is provided by `segment.last_normal`. if let Some(i) = segment_indices.last() { - let p = cap_verts[*i as usize]; + let p = cap_vertices[*i as usize]; for i in 0..layers { let i = i as f32; let z = p[2] - layer_depth_delta * i; diff --git a/crates/bevy_mikktspace/README.md b/crates/bevy_mikktspace/README.md index a9049ee1ba175..6ad4a72a4f7d5 100644 --- a/crates/bevy_mikktspace/README.md +++ b/crates/bevy_mikktspace/README.md @@ -6,7 +6,7 @@ [![Docs](https://docs.rs/bevy_mikktspace/badge.svg)](https://docs.rs/bevy_mikktspace/latest/bevy_mikktspace/) [![Discord](https://img.shields.io/discord/691052431525675048.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/bevy) -This is a fork of [https://github.com/gltf-rs/mikktspace](https://github.com/gltf-rs/mikktspace), which in turn is a port of the Mikkelsen Tangent Space Algorithm reference implementation to Rust. It has been forked for use in the bevy game engine to be able to update maths crate dependencies in lock-step with bevy releases. It is vendored in the bevy repository itself as [crates/bevy_mikktspace](https://github.com/bevyengine/bevy/tree/main/crates/bevy_mikktspace). +This is a fork of [https://github.com/gltf-rs/mikktspace](https://github.com/gltf-rs/mikktspace), which in turn is a port of the Mikkelsen Tangent Space Algorithm reference implementation to Rust. It has been forked for use in the bevy game engine to be able to update math crate dependencies in lock-step with bevy releases. It is vendored in the bevy repository itself as [crates/bevy_mikktspace](https://github.com/bevyengine/bevy/tree/main/crates/bevy_mikktspace). Port of the [Mikkelsen Tangent Space Algorithm](https://archive.blender.org/wiki/2015/index.php/Dev:Shading/Tangent_Space_Normal_Maps/) reference implementation. diff --git a/crates/bevy_mikktspace/src/generated.rs b/crates/bevy_mikktspace/src/generated.rs index a35e1d205f16a..0794034f87553 100644 --- a/crates/bevy_mikktspace/src/generated.rs +++ b/crates/bevy_mikktspace/src/generated.rs @@ -95,7 +95,7 @@ impl STSpace { // of the vertex shader, as explained earlier, then be sure to do this in the normal map sampler also. // Finally, beware of quad triangulations. If the normal map sampler doesn't use the same triangulation of // quads as your renderer then problems will occur since the interpolated tangent spaces will differ -// eventhough the vertex level tangent spaces match. This can be solved either by triangulating before +// even though the vertex level tangent spaces match. This can be solved either by triangulating before // sampling/exporting or by using the order-independent choice of diagonal for splitting quads suggested earlier. // However, this must be used both by the sampler and your tools/rendering pipeline. // internal structure diff --git a/crates/bevy_pbr/src/cluster/assign.rs b/crates/bevy_pbr/src/cluster/assign.rs index 4c3e22febed65..da67774cc4c9f 100644 --- a/crates/bevy_pbr/src/cluster/assign.rs +++ b/crates/bevy_pbr/src/cluster/assign.rs @@ -838,10 +838,10 @@ fn cluster_space_clusterable_object_aabb( // such, projecting the min and max xy at both the closer and further z and taking // the min and max of those projected points addresses this. let ( - clusterable_object_aabb_view_xymin_near, - clusterable_object_aabb_view_xymin_far, - clusterable_object_aabb_view_xymax_near, - clusterable_object_aabb_view_xymax_far, + clusterable_object_aabb_view_xy_min_near, + clusterable_object_aabb_view_xy_min_far, + clusterable_object_aabb_view_xy_max_near, + clusterable_object_aabb_view_xy_max_far, ) = ( clusterable_object_aabb_view_min, clusterable_object_aabb_view_min @@ -853,36 +853,36 @@ fn cluster_space_clusterable_object_aabb( clusterable_object_aabb_view_max, ); let ( - clusterable_object_aabb_clip_xymin_near, - clusterable_object_aabb_clip_xymin_far, - clusterable_object_aabb_clip_xymax_near, - clusterable_object_aabb_clip_xymax_far, + clusterable_object_aabb_clip_xy_min_near, + clusterable_object_aabb_clip_xy_min_far, + clusterable_object_aabb_clip_xy_max_near, + clusterable_object_aabb_clip_xy_max_far, ) = ( - clip_from_view * clusterable_object_aabb_view_xymin_near.extend(1.0), - clip_from_view * clusterable_object_aabb_view_xymin_far.extend(1.0), - clip_from_view * clusterable_object_aabb_view_xymax_near.extend(1.0), - clip_from_view * clusterable_object_aabb_view_xymax_far.extend(1.0), + clip_from_view * clusterable_object_aabb_view_xy_min_near.extend(1.0), + clip_from_view * clusterable_object_aabb_view_xy_min_far.extend(1.0), + clip_from_view * clusterable_object_aabb_view_xy_max_near.extend(1.0), + clip_from_view * clusterable_object_aabb_view_xy_max_far.extend(1.0), ); let ( - clusterable_object_aabb_ndc_xymin_near, - clusterable_object_aabb_ndc_xymin_far, - clusterable_object_aabb_ndc_xymax_near, - clusterable_object_aabb_ndc_xymax_far, + clusterable_object_aabb_ndc_xy_min_near, + clusterable_object_aabb_ndc_xy_min_far, + clusterable_object_aabb_ndc_xy_max_near, + clusterable_object_aabb_ndc_xy_max_far, ) = ( - clusterable_object_aabb_clip_xymin_near.xyz() / clusterable_object_aabb_clip_xymin_near.w, - clusterable_object_aabb_clip_xymin_far.xyz() / clusterable_object_aabb_clip_xymin_far.w, - clusterable_object_aabb_clip_xymax_near.xyz() / clusterable_object_aabb_clip_xymax_near.w, - clusterable_object_aabb_clip_xymax_far.xyz() / clusterable_object_aabb_clip_xymax_far.w, + clusterable_object_aabb_clip_xy_min_near.xyz() / clusterable_object_aabb_clip_xy_min_near.w, + clusterable_object_aabb_clip_xy_min_far.xyz() / clusterable_object_aabb_clip_xy_min_far.w, + clusterable_object_aabb_clip_xy_max_near.xyz() / clusterable_object_aabb_clip_xy_max_near.w, + clusterable_object_aabb_clip_xy_max_far.xyz() / clusterable_object_aabb_clip_xy_max_far.w, ); let (clusterable_object_aabb_ndc_min, clusterable_object_aabb_ndc_max) = ( - clusterable_object_aabb_ndc_xymin_near - .min(clusterable_object_aabb_ndc_xymin_far) - .min(clusterable_object_aabb_ndc_xymax_near) - .min(clusterable_object_aabb_ndc_xymax_far), - clusterable_object_aabb_ndc_xymin_near - .max(clusterable_object_aabb_ndc_xymin_far) - .max(clusterable_object_aabb_ndc_xymax_near) - .max(clusterable_object_aabb_ndc_xymax_far), + clusterable_object_aabb_ndc_xy_min_near + .min(clusterable_object_aabb_ndc_xy_min_far) + .min(clusterable_object_aabb_ndc_xy_max_near) + .min(clusterable_object_aabb_ndc_xy_max_far), + clusterable_object_aabb_ndc_xy_min_near + .max(clusterable_object_aabb_ndc_xy_min_far) + .max(clusterable_object_aabb_ndc_xy_max_near) + .max(clusterable_object_aabb_ndc_xy_max_far), ); // clamp to ndc coords without depth diff --git a/crates/bevy_pbr/src/cluster/mod.rs b/crates/bevy_pbr/src/cluster/mod.rs index f30dc0f432d24..6c8c4c158a952 100644 --- a/crates/bevy_pbr/src/cluster/mod.rs +++ b/crates/bevy_pbr/src/cluster/mod.rs @@ -522,7 +522,7 @@ pub(crate) fn clusterable_object_order( b: ClusterableObjectOrderData, ) -> core::cmp::Ordering { a.is_spot_light - .cmp(b.is_spot_light) // pointlights before spot lights + .cmp(b.is_spot_light) // point lights before spot lights .then_with(|| b.shadows_enabled.cmp(a.shadows_enabled)) // shadow casters before non-casters .then_with(|| b.is_volumetric_light.cmp(a.is_volumetric_light)) // volumetric lights before non-volumetric lights .then_with(|| a.entity.cmp(b.entity)) // stable diff --git a/crates/bevy_pbr/src/cluster/test.rs b/crates/bevy_pbr/src/cluster/test.rs index 23809da7f6b49..d3d0b1dd55e94 100644 --- a/crates/bevy_pbr/src/cluster/test.rs +++ b/crates/bevy_pbr/src/cluster/test.rs @@ -27,7 +27,7 @@ fn test_cluster_tiling(config: ClusterConfig, screen_size: UVec2) -> Clusters { #[test] // check tiling for small screen sizes -fn test_default_cluster_setup_small_screensizes() { +fn test_default_cluster_setup_small_screen_sizes() { for x in 1..100 { for y in 1..100 { let screen_size = UVec2::new(x, y); diff --git a/crates/bevy_pbr/src/deferred/deferred_lighting.wgsl b/crates/bevy_pbr/src/deferred/deferred_lighting.wgsl index 843ed2bbf69ab..45fff7f9aff7e 100644 --- a/crates/bevy_pbr/src/deferred/deferred_lighting.wgsl +++ b/crates/bevy_pbr/src/deferred/deferred_lighting.wgsl @@ -10,7 +10,7 @@ #ifdef SCREEN_SPACE_AMBIENT_OCCLUSION #import bevy_pbr::mesh_view_bindings::screen_space_ambient_occlusion_texture -#import bevy_pbr::ssao_utils::ssao_multibounce +#import bevy_pbr::ssao_utils::ssao_multi_bounce #endif struct FullscreenVertexOutput { @@ -64,11 +64,11 @@ fn fragment(in: FullscreenVertexOutput) -> @location(0) vec4 { #ifdef SCREEN_SPACE_AMBIENT_OCCLUSION let ssao = textureLoad(screen_space_ambient_occlusion_texture, vec2(in.position.xy), 0i).r; - let ssao_multibounce = ssao_multibounce(ssao, pbr_input.material.base_color.rgb); - pbr_input.diffuse_occlusion = min(pbr_input.diffuse_occlusion, ssao_multibounce); + let ssao_multi_bounce = ssao_multi_bounce(ssao, pbr_input.material.base_color.rgb); + pbr_input.diffuse_occlusion = min(pbr_input.diffuse_occlusion, ssao_multi_bounce); // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886" - let NdotV = max(dot(pbr_input.N, pbr_input.V), 0.0001); + let NdotV = max(dot(pbr_input.N, pbr_input.V), 0.0001); var perceptual_roughness: f32 = pbr_input.material.perceptual_roughness; let roughness = lighting::perceptualRoughnessToRoughness(perceptual_roughness); // Use SSAO to estimate the specular occlusion. diff --git a/crates/bevy_pbr/src/deferred/pbr_deferred_types.wgsl b/crates/bevy_pbr/src/deferred/pbr_deferred_types.wgsl index ef39307b49c22..4dce6fc6b3b54 100644 --- a/crates/bevy_pbr/src/deferred/pbr_deferred_types.wgsl +++ b/crates/bevy_pbr/src/deferred/pbr_deferred_types.wgsl @@ -27,9 +27,9 @@ fn mesh_material_flags_from_deferred_flags(deferred_flags: u32) -> vec2 { return vec2(mesh_flags, mat_flags); } -const U12MAXF = 4095.0; -const U16MAXF = 65535.0; -const U20MAXF = 1048575.0; +const U12_MAX_F = 4095.0; +const U16_MAX_F = 65535.0; +const U20_MAX_F = 1048575.0; // Storing normals as oct24. // Flags are stored in the remaining 8 bits. @@ -37,15 +37,15 @@ const U20MAXF = 1048575.0; // Could possibly go down to oct20 if the space is needed. fn pack_24bit_normal_and_flags(octahedral_normal: vec2, flags: u32) -> u32 { - let unorm1 = u32(saturate(octahedral_normal.x) * U12MAXF + 0.5); - let unorm2 = u32(saturate(octahedral_normal.y) * U12MAXF + 0.5); + let unorm1 = u32(saturate(octahedral_normal.x) * U12_MAX_F + 0.5); + let unorm2 = u32(saturate(octahedral_normal.y) * U12_MAX_F + 0.5); return (unorm1 & 0xFFFu) | ((unorm2 & 0xFFFu) << 12u) | ((flags & 0xFFu) << 24u); } fn unpack_24bit_normal(packed: u32) -> vec2 { let unorm1 = packed & 0xFFFu; let unorm2 = (packed >> 12u) & 0xFFFu; - return vec2(f32(unorm1) / U12MAXF, f32(unorm2) / U12MAXF); + return vec2(f32(unorm1) / U12_MAX_F, f32(unorm2) / U12_MAX_F); } fn unpack_flags(packed: u32) -> u32 { @@ -74,7 +74,7 @@ fn pack_unorm4x8_(values: vec4) -> u32 { // Pack 3x 4bit unorm + 1x 20bit fn pack_unorm3x4_plus_unorm_20_(v: vec4) -> u32 { let sm = vec3(saturate(v.xyz) * 15.0 + 0.5); - let bg = u32(saturate(v.w) * U20MAXF + 0.5); + let bg = u32(saturate(v.w) * U20_MAX_F + 0.5); return (bg << 12u) | (sm.z << 8u) | (sm.y << 4u) | sm.x; } @@ -84,6 +84,6 @@ fn unpack_unorm3x4_plus_unorm_20_(v: u32) -> vec4 { f32(v & 0xfu) / 15.0, f32((v >> 4u) & 0xFu) / 15.0, f32((v >> 8u) & 0xFu) / 15.0, - f32((v >> 12u) & 0xFFFFFFu) / U20MAXF, + f32((v >> 12u) & 0xFFFFFFu) / U20_MAX_F, ); } diff --git a/crates/bevy_pbr/src/light/mod.rs b/crates/bevy_pbr/src/light/mod.rs index 0b93c93c6792c..745f7fd97608d 100644 --- a/crates/bevy_pbr/src/light/mod.rs +++ b/crates/bevy_pbr/src/light/mod.rs @@ -78,7 +78,7 @@ pub mod light_consts { pub const OFFICE: f32 = 320.; /// The amount of light (lux) during sunrise or sunset on a clear day. pub const CLEAR_SUNRISE: f32 = 400.; - /// The amount of light (lux) on a overcast day; typical TV studio lighting + /// The amount of light (lux) on an overcast day; typical TV studio lighting pub const OVERCAST_DAY: f32 = 1000.; /// The amount of light (lux) from ambient daylight (not direct sunlight). pub const AMBIENT_DAYLIGHT: f32 = 10_000.; @@ -514,7 +514,7 @@ pub enum SimulationLightSystems { UpdateDirectionalLightCascades, UpdateLightFrusta, /// System order ambiguities between systems in this set are ignored: - /// the order of systems within this set is irrelevant, as the various visibility-checking systesms + /// the order of systems within this set is irrelevant, as the various visibility-checking systems /// assumes that their operations are irreversible during the frame. CheckLightVisibility, } diff --git a/crates/bevy_pbr/src/light_probe/mod.rs b/crates/bevy_pbr/src/light_probe/mod.rs index cab462c2801bf..b0a299a1f8c42 100644 --- a/crates/bevy_pbr/src/light_probe/mod.rs +++ b/crates/bevy_pbr/src/light_probe/mod.rs @@ -171,7 +171,7 @@ pub struct ViewLightProbesUniformOffset(u32); /// Information that [`gather_light_probes`] keeps about each light probe. /// -/// This information is parameterized by the [`LightProbeComponent`] type. This +/// This information is parametrized by the [`LightProbeComponent`] type. This /// will either be [`EnvironmentMapLight`] for reflection probes or /// [`IrradianceVolume`] for irradiance volumes. #[allow(dead_code)] diff --git a/crates/bevy_pbr/src/lightmap/lightmap.wgsl b/crates/bevy_pbr/src/lightmap/lightmap.wgsl index cf3c2275c9a08..022ecc568bdbb 100644 --- a/crates/bevy_pbr/src/lightmap/lightmap.wgsl +++ b/crates/bevy_pbr/src/lightmap/lightmap.wgsl @@ -20,7 +20,7 @@ fn lightmap(uv: vec2, exposure: f32, instance_index: u32) -> vec3 { // islands, so there's no harm in using mip level 0 and it lets us avoid // control flow uniformity problems. // - // TODO(pcwalton): Consider bicubic filtering. + // TODO: Consider bicubic filtering. return textureSampleLevel( lightmaps_texture, lightmaps_sampler, diff --git a/crates/bevy_pbr/src/meshlet/cull_clusters.wgsl b/crates/bevy_pbr/src/meshlet/cull_clusters.wgsl index 47f6dbb04b6be..92772c8cab0e3 100644 --- a/crates/bevy_pbr/src/meshlet/cull_clusters.wgsl +++ b/crates/bevy_pbr/src/meshlet/cull_clusters.wgsl @@ -16,7 +16,7 @@ constants, MeshletBoundingSphere, } -#import bevy_render::maths::affine3_to_square +#import bevy_render::math::affine3_to_square /// Culls individual clusters (1 per thread) in two passes (two pass occlusion culling), and outputs a bitmask of which clusters survived. /// 1. The first pass tests instance visibility, frustum culling, LOD selection, and finally occlusion culling using last frame's depth pyramid. diff --git a/crates/bevy_pbr/src/meshlet/from_mesh.rs b/crates/bevy_pbr/src/meshlet/from_mesh.rs index 5b5c503d3d1b3..959b3d866560d 100644 --- a/crates/bevy_pbr/src/meshlet/from_mesh.rs +++ b/crates/bevy_pbr/src/meshlet/from_mesh.rs @@ -248,7 +248,7 @@ fn validate_input_mesh(mesh: &Mesh) -> Result, MeshToMeshletMeshC } fn compute_meshlets(indices: &[u32], vertices: &VertexDataAdapter) -> Meshlets { - build_meshlets(indices, vertices, 255, 128, 0.0) // Meshoptimizer won't currently let us do 256 vertices + build_meshlets(indices, vertices, 255, 128, 0.0) // meshoptimizer won't currently let us do 256 vertices } fn find_connected_meshlets( @@ -311,29 +311,34 @@ fn group_meshlets( connected_meshlets_per_meshlet: &[Vec<(usize, usize)>], simplification_queue: &[usize], ) -> Vec> { - let mut xadj = Vec::with_capacity(simplification_queue.len() + 1); - let mut adjncy = Vec::new(); - let mut adjwgt = Vec::new(); + let mut adjacency_offsets = Vec::with_capacity(simplification_queue.len() + 1); + let mut adjacent_nodes = Vec::new(); + let mut adjacency_weights = Vec::new(); for connected_meshlets in connected_meshlets_per_meshlet { - xadj.push(adjncy.len() as i32); + adjacency_offsets.push(adjacent_nodes.len() as i32); for (connected_meshlet_queue_id, shared_vertex_count) in connected_meshlets { - adjncy.push(*connected_meshlet_queue_id as i32); - adjwgt.push(*shared_vertex_count as i32); + adjacent_nodes.push(*connected_meshlet_queue_id as i32); + adjacency_weights.push(*shared_vertex_count as i32); // TODO: Additional weight based on meshlet spatial proximity } } - xadj.push(adjncy.len() as i32); + adjacency_offsets.push(adjacent_nodes.len() as i32); let mut group_per_meshlet = vec![0; simplification_queue.len()]; let partition_count = simplification_queue .len() .div_ceil(TARGET_MESHLETS_PER_GROUP); // TODO: Nanite uses groups of 8-32, probably based on some kind of heuristic - Graph::new(1, partition_count as i32, &xadj, &adjncy) - .unwrap() - .set_option(metis::option::Seed(17)) - .set_adjwgt(&adjwgt) - .part_kway(&mut group_per_meshlet) - .unwrap(); + Graph::new( + 1, + partition_count as i32, + &adjacency_offsets, + &adjacent_nodes, + ) + .unwrap() + .set_option(metis::option::Seed(17)) + .set_adjwgt(&adjacency_weights) + .part_kway(&mut group_per_meshlet) + .unwrap(); let mut groups = vec![SmallVec::new(); partition_count]; for (meshlet_queue_id, meshlet_group) in group_per_meshlet.into_iter().enumerate() { diff --git a/crates/bevy_pbr/src/meshlet/visibility_buffer_hardware_raster.wgsl b/crates/bevy_pbr/src/meshlet/visibility_buffer_hardware_raster.wgsl index 65ccb1748257d..5f130d872fd4d 100644 --- a/crates/bevy_pbr/src/meshlet/visibility_buffer_hardware_raster.wgsl +++ b/crates/bevy_pbr/src/meshlet/visibility_buffer_hardware_raster.wgsl @@ -13,7 +13,7 @@ }, mesh_functions::mesh_position_local_to_world, } -#import bevy_render::maths::affine3_to_square +#import bevy_render::math::affine3_to_square var meshlet_raster_cluster_rightmost_slot: u32; /// Vertex/fragment shader for rasterizing large clusters into a visibility buffer. diff --git a/crates/bevy_pbr/src/meshlet/visibility_buffer_resolve.wgsl b/crates/bevy_pbr/src/meshlet/visibility_buffer_resolve.wgsl index 33c8df6a0e2c6..4ef7e806b8600 100644 --- a/crates/bevy_pbr/src/meshlet/visibility_buffer_resolve.wgsl +++ b/crates/bevy_pbr/src/meshlet/visibility_buffer_resolve.wgsl @@ -18,7 +18,7 @@ mesh_types::Mesh, view_transformations::{position_world_to_clip, frag_coord_to_ndc}, } -#import bevy_render::maths::{affine3_to_square, mat2x4_f32_to_mat3x3_unpack} +#import bevy_render::math::{affine3_to_square, mat2x4_f32_to_mat3x3_unpack} #ifdef PREPASS_FRAGMENT #ifdef MOTION_VECTOR_PREPASS diff --git a/crates/bevy_pbr/src/meshlet/visibility_buffer_software_raster.wgsl b/crates/bevy_pbr/src/meshlet/visibility_buffer_software_raster.wgsl index ec00bb29303e6..aebbf95b4bfb4 100644 --- a/crates/bevy_pbr/src/meshlet/visibility_buffer_software_raster.wgsl +++ b/crates/bevy_pbr/src/meshlet/visibility_buffer_software_raster.wgsl @@ -16,7 +16,7 @@ mesh_functions::mesh_position_local_to_world, view_transformations::ndc_to_uv, } -#import bevy_render::maths::affine3_to_square +#import bevy_render::math::affine3_to_square /// Compute shader for rasterizing small clusters into a visibility buffer. diff --git a/crates/bevy_pbr/src/pbr_material.rs b/crates/bevy_pbr/src/pbr_material.rs index fffbaebc922fb..471d74e94d040 100644 --- a/crates/bevy_pbr/src/pbr_material.rs +++ b/crates/bevy_pbr/src/pbr_material.rs @@ -129,7 +129,7 @@ pub struct StandardMaterial { /// 0.089 is the minimum floating point value that won't be rounded down to 0 in the /// calculations used. // Technically for 32-bit floats, 0.045 could be used. - // See + // See pub perceptual_roughness: f32, /// How "metallic" the material appears, within `[0.0, 1.0]`. @@ -185,10 +185,10 @@ pub struct StandardMaterial { /// The amount of light transmitted _diffusely_ through the material (i.e. “translucency”) /// /// Implemented as a second, flipped [Lambertian diffuse](https://en.wikipedia.org/wiki/Lambertian_reflectance) lobe, - /// which provides an inexpensive but plausible approximation of translucency for thin dieletric objects (e.g. paper, + /// which provides an inexpensive but plausible approximation of translucency for thin dielectric objects (e.g. paper, /// leaves, some fabrics) or thicker volumetric materials with short scattering distances (e.g. porcelain, wax). /// - /// For specular transmission usecases with refraction (e.g. glass) use the [`StandardMaterial::specular_transmission`] and + /// For specular transmission use cases with refraction (e.g. glass) use the [`StandardMaterial::specular_transmission`] and /// [`StandardMaterial::ior`] properties instead. /// /// - When set to `0.0` (the default) no diffuse light is transmitted; @@ -231,7 +231,7 @@ pub struct StandardMaterial { /// /// ## Performance /// - /// Specular transmission is implemented as a relatively expensive screen-space effect that allows ocluded objects to be seen through the material, + /// Specular transmission is implemented as a relatively expensive screen-space effect that allows occluded objects to be seen through the material, /// with distortion and blur effects. /// /// - [`Camera3d::screen_space_specular_transmission_steps`](bevy_core_pipeline::core_3d::Camera3d::screen_space_specular_transmission_steps) can be used to enable transmissive objects @@ -463,7 +463,7 @@ pub struct StandardMaterial { /// /// Note that, if a clearcoat normal map isn't specified, the main normal /// map, if any, won't be applied to the clearcoat. If you want a normal map - /// that applies to both the main materal and to the clearcoat, specify it + /// that applies to both the main material and to the clearcoat, specify it /// in both [`StandardMaterial::normal_map_texture`] and this field. /// /// As this is a non-color map, it must not be loaded as sRGB. diff --git a/crates/bevy_pbr/src/render/clustered_forward.wgsl b/crates/bevy_pbr/src/render/clustered_forward.wgsl index 7b303764db3a8..d009337b69912 100644 --- a/crates/bevy_pbr/src/render/clustered_forward.wgsl +++ b/crates/bevy_pbr/src/render/clustered_forward.wgsl @@ -7,7 +7,7 @@ #import bevy_render::{ color_operations::hsv_to_rgb, - maths::PI_2, + math::PI_2, } // NOTE: Keep in sync with bevy_pbr/src/light.rs diff --git a/crates/bevy_pbr/src/render/light.rs b/crates/bevy_pbr/src/render/light.rs index b307429c8ee92..15b783625cebf 100644 --- a/crates/bevy_pbr/src/render/light.rs +++ b/crates/bevy_pbr/src/render/light.rs @@ -627,10 +627,10 @@ pub fn calculate_cluster_factors( if is_orthographic { Vec2::new(-near, z_slices / (-far - -near)) } else { - let z_slices_of_ln_zfar_over_znear = (z_slices - 1.0) / ops::ln(far / near); + let z_slices_of_ln_z_far_over_z_near = (z_slices - 1.0) / ops::ln(far / near); Vec2::new( - z_slices_of_ln_zfar_over_znear, - ops::ln(near) * z_slices_of_ln_zfar_over_znear, + z_slices_of_ln_z_far_over_z_near, + ops::ln(near) * z_slices_of_ln_z_far_over_z_near, ) } } diff --git a/crates/bevy_pbr/src/render/mesh.rs b/crates/bevy_pbr/src/render/mesh.rs index e8adff671b01e..7b6606e67cb5f 100644 --- a/crates/bevy_pbr/src/render/mesh.rs +++ b/crates/bevy_pbr/src/render/mesh.rs @@ -1485,7 +1485,7 @@ bitflags::bitflags! { const NORMAL_PREPASS = 1 << 4; const DEFERRED_PREPASS = 1 << 5; const MOTION_VECTOR_PREPASS = 1 << 6; - const MAY_DISCARD = 1 << 7; // Guards shader codepaths that may discard, allowing early depth tests in most cases + const MAY_DISCARD = 1 << 7; // Guards shader code paths that may discard, allowing early depth tests in most cases // See: https://www.khronos.org/opengl/wiki/Early_Fragment_Test const ENVIRONMENT_MAP = 1 << 8; const SCREEN_SPACE_AMBIENT_OCCLUSION = 1 << 9; diff --git a/crates/bevy_pbr/src/render/mesh_functions.wgsl b/crates/bevy_pbr/src/render/mesh_functions.wgsl index b58004cadf1e9..c5fb938c0361e 100644 --- a/crates/bevy_pbr/src/render/mesh_functions.wgsl +++ b/crates/bevy_pbr/src/render/mesh_functions.wgsl @@ -10,7 +10,7 @@ mesh_types::MESH_FLAGS_SIGN_DETERMINANT_MODEL_3X3_BIT, view_transformations::position_world_to_clip, } -#import bevy_render::maths::{affine3_to_square, mat2x4_f32_to_mat3x3_unpack} +#import bevy_render::math::{affine3_to_square, mat2x4_f32_to_mat3x3_unpack} fn get_world_from_local(instance_index: u32) -> mat4x4 { diff --git a/crates/bevy_pbr/src/render/mesh_preprocess.wgsl b/crates/bevy_pbr/src/render/mesh_preprocess.wgsl index 6a5a1fcf06e33..481ab78d8eac4 100644 --- a/crates/bevy_pbr/src/render/mesh_preprocess.wgsl +++ b/crates/bevy_pbr/src/render/mesh_preprocess.wgsl @@ -8,7 +8,7 @@ // so that TAA works. #import bevy_pbr::mesh_types::Mesh -#import bevy_render::maths +#import bevy_render::math #import bevy_render::view::View // Per-frame data that the CPU supplies to the GPU. @@ -79,7 +79,7 @@ struct IndirectParameters { @group(0) @binding(3) var output: array; #ifdef INDIRECT -// The array of indirect parameters for drawcalls. +// The array of indirect parameters for draw calls. @group(0) @binding(4) var indirect_parameters: array; #endif @@ -116,7 +116,7 @@ fn view_frustum_intersects_obb( ); // Check the frustum plane. - if (!maths::sphere_intersects_plane_half_space( + if (!math::sphere_intersects_plane_half_space( plane_normal, aabb_center, relative_radius)) { return false; } @@ -140,7 +140,7 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3) { let input_index = work_items[instance_index].input_index; let output_index = work_items[instance_index].output_index; let world_from_local_affine_transpose = current_input[input_index].world_from_local; - let world_from_local = maths::affine3_to_square(world_from_local_affine_transpose); + let world_from_local = math::affine3_to_square(world_from_local_affine_transpose); // Cull if necessary. #ifdef FRUSTUM_CULLING @@ -155,7 +155,7 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3) { #endif // Calculate inverse transpose. - let local_from_world_transpose = transpose(maths::inverse_affine3(transpose( + let local_from_world_transpose = transpose(math::inverse_affine3(transpose( world_from_local_affine_transpose))); // Pack inverse transpose. diff --git a/crates/bevy_pbr/src/render/mesh_types.wgsl b/crates/bevy_pbr/src/render/mesh_types.wgsl index 57576a3bb3805..032d65a9f0c91 100644 --- a/crates/bevy_pbr/src/render/mesh_types.wgsl +++ b/crates/bevy_pbr/src/render/mesh_types.wgsl @@ -2,7 +2,7 @@ struct Mesh { // Affine 4x3 matrices transposed to 3x4 - // Use bevy_render::maths::affine3_to_square to unpack + // Use bevy_render::math::affine3_to_square to unpack world_from_local: mat3x4, previous_world_from_local: mat3x4, // 3x3 matrix packed in mat2x4 and f32 as: diff --git a/crates/bevy_pbr/src/render/mesh_view_bindings.rs b/crates/bevy_pbr/src/render/mesh_view_bindings.rs index c3a723164e21f..32065e0808ee8 100644 --- a/crates/bevy_pbr/src/render/mesh_view_bindings.rs +++ b/crates/bevy_pbr/src/render/mesh_view_bindings.rs @@ -560,7 +560,7 @@ pub fn prepare_mesh_view_bind_groups( ) in &views { let fallback_ssao = fallback_images - .image_for_samplecount(1, TextureFormat::bevy_default()) + .image_for_sample_count(1, TextureFormat::bevy_default()) .texture_view .clone(); let ssao_view = ssao_resources diff --git a/crates/bevy_pbr/src/render/mesh_view_types.wgsl b/crates/bevy_pbr/src/render/mesh_view_types.wgsl index d9cc61cad91e7..7ff103cedcb61 100644 --- a/crates/bevy_pbr/src/render/mesh_view_types.wgsl +++ b/crates/bevy_pbr/src/render/mesh_view_types.wgsl @@ -58,7 +58,7 @@ struct Lights { // w is cluster_dimensions.z * log(near) / log(far / near) // // For orthographic projections: - // NOTE: near and far are +ve but -z is infront of the camera + // NOTE: near and far are +ve but -z is in front of the camera // z is -near // w is cluster_dimensions.z / (-far - -near) cluster_factors: vec4, diff --git a/crates/bevy_pbr/src/render/pbr_fragment.wgsl b/crates/bevy_pbr/src/render/pbr_fragment.wgsl index 91e104ede525f..4d662ba21a3f8 100644 --- a/crates/bevy_pbr/src/render/pbr_fragment.wgsl +++ b/crates/bevy_pbr/src/render/pbr_fragment.wgsl @@ -15,7 +15,7 @@ #ifdef SCREEN_SPACE_AMBIENT_OCCLUSION #import bevy_pbr::mesh_view_bindings::screen_space_ambient_occlusion_texture -#import bevy_pbr::ssao_utils::ssao_multibounce +#import bevy_pbr::ssao_utils::ssao_multi_bounce #endif #ifdef MESHLET_MESH_MATERIAL_PASS @@ -344,8 +344,8 @@ fn pbr_input_from_standard_material( #endif #ifdef SCREEN_SPACE_AMBIENT_OCCLUSION let ssao = textureLoad(screen_space_ambient_occlusion_texture, vec2(in.position.xy), 0i).r; - let ssao_multibounce = ssao_multibounce(ssao, pbr_input.material.base_color.rgb); - diffuse_occlusion = min(diffuse_occlusion, ssao_multibounce); + let ssao_multi_bounce = ssao_multi_bounce(ssao, pbr_input.material.base_color.rgb); + diffuse_occlusion = min(diffuse_occlusion, ssao_multi_bounce); // Use SSAO to estimate the specular occlusion. // Lagarde and Rousiers 2014, "Moving Frostbite to Physically Based Rendering" specular_occlusion = saturate(pow(NdotV + ssao, exp2(-16.0 * roughness - 1.0)) - 1.0 + ssao); diff --git a/crates/bevy_pbr/src/render/pbr_functions.wgsl b/crates/bevy_pbr/src/render/pbr_functions.wgsl index ef357284cbfa7..1ff23b64c4a2c 100644 --- a/crates/bevy_pbr/src/render/pbr_functions.wgsl +++ b/crates/bevy_pbr/src/render/pbr_functions.wgsl @@ -14,7 +14,7 @@ irradiance_volume, mesh_types::{MESH_FLAGS_SHADOW_RECEIVER_BIT, MESH_FLAGS_TRANSMITTED_SHADOW_RECEIVER_BIT}, } -#import bevy_render::maths::{E, powsafe} +#import bevy_render::math::{E, powsafe} #ifdef MESHLET_MESH_MATERIAL_PASS #import bevy_pbr::meshlet_visibility_buffer_resolve::VertexOutput @@ -125,14 +125,14 @@ fn alpha_discard(material: pbr_types::StandardMaterial, output_color: vec4) // in use (mesh vs. meshlet). fn sample_texture( texture: texture_2d, - samp: sampler, + textureSample: sampler, uv: vec2, bias: SampleBias, ) -> vec4 { #ifdef MESHLET_MESH_MATERIAL_PASS - return textureSampleGrad(texture, samp, uv, bias.ddx_uv, bias.ddy_uv); + return textureSampleGrad(texture, textureSample, uv, bias.ddx_uv, bias.ddy_uv); #else - return textureSampleBias(texture, samp, uv, bias.mip_bias); + return textureSampleBias(texture, textureSample, uv, bias.mip_bias); #endif } @@ -257,7 +257,7 @@ fn bend_normal_for_anisotropy(lighting_input: ptr, metallic: f32, @@ -288,7 +288,7 @@ fn calculate_diffuse_color( } // Remapping [0,1] reflectance to F0 -// See https://google.github.io/filament/Filament.html#materialsystem/parameterization/remapping +// See https://google.github.io/filament/Filament.html#materialsystem/parametrization/remapping fn calculate_F0(base_color: vec3, metallic: f32, reflectance: f32) -> vec3 { return 0.16 * reflectance * reflectance * (1.0 - metallic) + base_color * metallic; } @@ -338,7 +338,7 @@ fn apply_pbr_lighting( diffuse_transmission ); - // Diffuse transmissive strength is inversely related to metallicity and specular transmission, but directly related to diffuse transmission + // Diffuse transmissive strength is inversely related to metalness and specular transmission, but directly related to diffuse transmission let diffuse_transmissive_color = output_color.rgb * (1.0 - metallic) * (1.0 - specular_transmission) * diffuse_transmission; // Calculate the world position of the second Lambertian lobe used for diffuse transmission, by subtracting material thickness diff --git a/crates/bevy_pbr/src/render/pbr_lighting.wgsl b/crates/bevy_pbr/src/render/pbr_lighting.wgsl index 0e88642333643..09ab16d589ba3 100644 --- a/crates/bevy_pbr/src/render/pbr_lighting.wgsl +++ b/crates/bevy_pbr/src/render/pbr_lighting.wgsl @@ -4,7 +4,7 @@ mesh_view_types::POINT_LIGHT_FLAGS_SPOT_LIGHT_Y_NEGATIVE, mesh_view_bindings as view_bindings, } -#import bevy_render::maths::PI +#import bevy_render::math::PI const LAYER_BASE: u32 = 0; const LAYER_CLEARCOAT: u32 = 1; @@ -12,21 +12,21 @@ const LAYER_CLEARCOAT: u32 = 1; // From the Filament design doc // https://google.github.io/filament/Filament.html#table_symbols // Symbol Definition -// v View unit vector -// l Incident light unit vector -// n Surface normal unit vector -// h Half unit vector between l and v -// f BRDF +// v View unit vector +// l Incident light unit vector +// n Surface normal unit vector +// h Half unit vector between l and v +// f BRDF // f_d Diffuse component of a BRDF // f_r Specular component of a BRDF -// α Roughness, remapped from using input perceptualRoughness -// σ Diffuse reflectance -// Ω Spherical domain -// f0 Reflectance at normal incidence +// α Roughness, remapped from using input perceptualRoughness +// σ Diffuse reflectance +// Ω Spherical domain +// f0 Reflectance at normal incidence // f90 Reflectance at grazing angle -// χ+(a) Heaviside function (1 if a>0 and 0 otherwise) -// nior Index of refraction (IOR) of an interface -// ⟨n⋅l⟩ Dot product clamped to [0..1] +// χ+(a) Heaviside function (1 if a>0 and 0 otherwise) +// n_ior Index of refraction (IOR) of an interface +// ⟨n⋅l⟩ Dot product clamped to [0..1] // ⟨a⟩ Saturated value (clamped to [0..1]) // The Bidirectional Reflectance Distribution Function (BRDF) describes the surface response of a standard material diff --git a/crates/bevy_pbr/src/render/pbr_transmission.wgsl b/crates/bevy_pbr/src/render/pbr_transmission.wgsl index 83a71096ebdfe..d9216a0cce5d8 100644 --- a/crates/bevy_pbr/src/render/pbr_transmission.wgsl +++ b/crates/bevy_pbr/src/render/pbr_transmission.wgsl @@ -8,14 +8,14 @@ mesh_view_bindings as view_bindings, }; -#import bevy_render::maths::PI +#import bevy_render::math::PI #ifdef TONEMAP_IN_SHADER #import bevy_core_pipeline::tonemapping::approximate_inverse_tone_mapping #endif fn specular_transmissive_light(world_position: vec4, frag_coord: vec3, view_z: f32, N: vec3, V: vec3, F0: vec3, ior: f32, thickness: f32, perceptual_roughness: f32, specular_transmissive_color: vec3, transmitted_environment_light_specular: vec3) -> vec3 { - // Calculate the ratio between refaction indexes. Assume air/vacuum for the space outside the mesh + // Calculate the ratio between refraction indexes. Assume air/vacuum for the space outside the mesh let eta = 1.0 / ior; // Calculate incidence vector (opposite to view vector) and its dot product with the mesh normal @@ -26,7 +26,7 @@ fn specular_transmissive_light(world_position: vec4, frag_coord: vec3, let k = 1.0 - eta * eta * (1.0 - NdotI * NdotI); let T = eta * I - (eta * NdotI + sqrt(k)) * N; - // Calculate the exit position of the refracted ray, by propagating refacted direction through thickness + // Calculate the exit position of the refracted ray, by propagating refracted direction through thickness let exit_position = world_position.xyz + T * thickness; // Transform exit_position into clip space @@ -109,7 +109,7 @@ fn fetch_transmissive_background(offset_position: vec2, frag_coord: vec3, frag_coord: vec3 i32 { let f = bitcast(x); - let biasedexponent = (f & 0x7F800000u) >> 23u; - return i32(biasedexponent) - 127; + let biasedExponent = (f & 0x7F800000u) >> 23u; + return i32(biasedExponent) - 127; } // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_texture_shared_exponent.txt fn vec3_to_rgb9e5_(rgb_in: vec3) -> u32 { let rgb = clamp(rgb_in, vec3(0.0), vec3(MAX_RGB9E5_)); - let maxrgb = max(rgb.r, max(rgb.g, rgb.b)); - var exp_shared = max(-RGB9E5_EXP_BIAS - 1, floor_log2_(maxrgb)) + 1 + RGB9E5_EXP_BIAS; + let max_rgb = max(rgb.r, max(rgb.g, rgb.b)); + var exp_shared = max(-RGB9E5_EXP_BIAS - 1, floor_log2_(max_rgb)) + 1 + RGB9E5_EXP_BIAS; var denom = exp2(f32(exp_shared - RGB9E5_EXP_BIAS - RGB9E5_MANTISSA_BITS)); - let maxm = i32(floor(maxrgb / denom + 0.5)); - if (maxm == RGB9E5_MANTISSA_VALUES) { + let max_m = i32(floor(max_rgb / denom + 0.5)); + if (max_m == RGB9E5_MANTISSA_VALUES) { denom *= 2.0; exp_shared += 1; } let n = vec3(floor(rgb / denom + 0.5)); - + return (u32(exp_shared) << 27u) | (n.b << 18u) | (n.g << 9u) | (n.r << 0u); } @@ -56,8 +56,8 @@ fn rgb9e5_to_vec3_(v: u32) -> vec3 { let scale = exp2(f32(exponent)); return vec3( - f32(extract_bits(v, 0u, RGB9E5_MANTISSA_BITSU)), - f32(extract_bits(v, 9u, RGB9E5_MANTISSA_BITSU)), - f32(extract_bits(v, 18u, RGB9E5_MANTISSA_BITSU)) + f32(extract_bits(v, 0u, RGB9E5_MANTISSA_BITS_U)), + f32(extract_bits(v, 9u, RGB9E5_MANTISSA_BITS_U)), + f32(extract_bits(v, 18u, RGB9E5_MANTISSA_BITS_U)) ) * scale; } diff --git a/crates/bevy_pbr/src/render/shadow_sampling.wgsl b/crates/bevy_pbr/src/render/shadow_sampling.wgsl index 22f2e28310bd0..7cf2db853f358 100644 --- a/crates/bevy_pbr/src/render/shadow_sampling.wgsl +++ b/crates/bevy_pbr/src/render/shadow_sampling.wgsl @@ -5,7 +5,7 @@ utils::interleaved_gradient_noise, utils, } -#import bevy_render::maths::{orthonormalize, PI} +#import bevy_render::math::{orthonormalize, PI} // Do the lookup, using HW 2x2 PCF and comparison fn sample_shadow_map_hardware(light_local: vec2, depth: f32, array_index: i32) -> f32 { @@ -90,7 +90,7 @@ const D3D_SAMPLE_POINT_POSITIONS: array, 8> = array( // And these are the coefficients corresponding to the probability distribution // function of a 2D Gaussian lobe with zero mean and the identity covariance // matrix at those points. -const D3D_SAMPLE_POINT_COEFFS: array = array( +const D3D_SAMPLE_POINT_COEFFICIENTS: array = array( 0.157112, 0.157112, 0.138651, @@ -374,7 +374,7 @@ fn search_for_blockers_in_shadow_cubemap_hardware( fn sample_shadow_cubemap_at_offset( position: vec2, - coeff: f32, + coefficient: f32, x_basis: vec3, y_basis: vec3, light_local: vec3, @@ -385,7 +385,7 @@ fn sample_shadow_cubemap_at_offset( light_local + position.x * x_basis + position.y * y_basis, depth, light_id - ) * coeff; + ) * coefficient; } // Computes the search position and performs one sample of the blocker search. @@ -430,28 +430,28 @@ fn sample_shadow_cubemap_gaussian( var sum: f32 = 0.0; sum += sample_shadow_cubemap_at_offset( - D3D_SAMPLE_POINT_POSITIONS[0], D3D_SAMPLE_POINT_COEFFS[0], + D3D_SAMPLE_POINT_POSITIONS[0], D3D_SAMPLE_POINT_COEFFICIENTS[0], basis[0], basis[1], light_local, depth, light_id); sum += sample_shadow_cubemap_at_offset( - D3D_SAMPLE_POINT_POSITIONS[1], D3D_SAMPLE_POINT_COEFFS[1], + D3D_SAMPLE_POINT_POSITIONS[1], D3D_SAMPLE_POINT_COEFFICIENTS[1], basis[0], basis[1], light_local, depth, light_id); sum += sample_shadow_cubemap_at_offset( - D3D_SAMPLE_POINT_POSITIONS[2], D3D_SAMPLE_POINT_COEFFS[2], + D3D_SAMPLE_POINT_POSITIONS[2], D3D_SAMPLE_POINT_COEFFICIENTS[2], basis[0], basis[1], light_local, depth, light_id); sum += sample_shadow_cubemap_at_offset( - D3D_SAMPLE_POINT_POSITIONS[3], D3D_SAMPLE_POINT_COEFFS[3], + D3D_SAMPLE_POINT_POSITIONS[3], D3D_SAMPLE_POINT_COEFFICIENTS[3], basis[0], basis[1], light_local, depth, light_id); sum += sample_shadow_cubemap_at_offset( - D3D_SAMPLE_POINT_POSITIONS[4], D3D_SAMPLE_POINT_COEFFS[4], + D3D_SAMPLE_POINT_POSITIONS[4], D3D_SAMPLE_POINT_COEFFICIENTS[4], basis[0], basis[1], light_local, depth, light_id); sum += sample_shadow_cubemap_at_offset( - D3D_SAMPLE_POINT_POSITIONS[5], D3D_SAMPLE_POINT_COEFFS[5], + D3D_SAMPLE_POINT_POSITIONS[5], D3D_SAMPLE_POINT_COEFFICIENTS[5], basis[0], basis[1], light_local, depth, light_id); sum += sample_shadow_cubemap_at_offset( - D3D_SAMPLE_POINT_POSITIONS[6], D3D_SAMPLE_POINT_COEFFS[6], + D3D_SAMPLE_POINT_POSITIONS[6], D3D_SAMPLE_POINT_COEFFICIENTS[6], basis[0], basis[1], light_local, depth, light_id); sum += sample_shadow_cubemap_at_offset( - D3D_SAMPLE_POINT_POSITIONS[7], D3D_SAMPLE_POINT_COEFFS[7], + D3D_SAMPLE_POINT_POSITIONS[7], D3D_SAMPLE_POINT_COEFFICIENTS[7], basis[0], basis[1], light_local, depth, light_id); return sum; } diff --git a/crates/bevy_pbr/src/render/shadows.wgsl b/crates/bevy_pbr/src/render/shadows.wgsl index 0e539f00091c5..4dd617ff97abf 100644 --- a/crates/bevy_pbr/src/render/shadows.wgsl +++ b/crates/bevy_pbr/src/render/shadows.wgsl @@ -11,7 +11,7 @@ #import bevy_render::{ color_operations::hsv_to_rgb, - maths::PI_2 + math::PI_2 } const flip_z: vec3 = vec3(1.0, 1.0, -1.0); diff --git a/crates/bevy_pbr/src/render/utils.wgsl b/crates/bevy_pbr/src/render/utils.wgsl index c887e3005e707..83a90b75e9a44 100644 --- a/crates/bevy_pbr/src/render/utils.wgsl +++ b/crates/bevy_pbr/src/render/utils.wgsl @@ -37,7 +37,7 @@ fn rand_range_u(n: u32, state: ptr) -> u32 { // returns the (0-1, 0-1) position within the given viewport for the current buffer coords . // buffer coords can be obtained from `@builtin(position).xy`. // the view uniform struct contains the current camera viewport in `view.viewport`. -// topleft = 0,0 +// top left = 0,0 fn coords_to_viewport_uv(position: vec2, viewport: vec4) -> vec2 { return (position - viewport.xy) / viewport.zw; } diff --git a/crates/bevy_pbr/src/ssao/spatial_denoise.wgsl b/crates/bevy_pbr/src/ssao/spatial_denoise.wgsl index 1c04f9cfab2f7..679dd88c3e745 100644 --- a/crates/bevy_pbr/src/ssao/spatial_denoise.wgsl +++ b/crates/bevy_pbr/src/ssao/spatial_denoise.wgsl @@ -1,4 +1,4 @@ -// 3x3 bilaterial filter (edge-preserving blur) +// 3x3 bilateral filter (edge-preserving blur) // https://people.csail.mit.edu/sparis/bf_course/course_notes.pdf // Note: Does not use the Gaussian kernel part of a typical bilateral blur diff --git a/crates/bevy_pbr/src/ssao/ssao.wgsl b/crates/bevy_pbr/src/ssao/ssao.wgsl index 1fbd73e8d98ac..641a6825cccac 100644 --- a/crates/bevy_pbr/src/ssao/ssao.wgsl +++ b/crates/bevy_pbr/src/ssao/ssao.wgsl @@ -1,5 +1,5 @@ // Visibility Bitmask Ambient Occlusion (VBAO) -// Paper: ttps://ar5iv.labs.arxiv.org/html/2301.11376 +// Paper: https://ar5iv.labs.arxiv.org/html/2301.11376 // Source code heavily based on XeGTAO v1.30 from Intel // https://github.com/GameTechDev/XeGTAO/blob/0d177ce06bfa642f64d8af4de1197ad1bcb862d4/Source/Rendering/Shaders/XeGTAO.hlsli @@ -15,7 +15,7 @@ #import bevy_render::{ view::View, globals::Globals, - maths::{PI, HALF_PI}, + math::{PI, HALF_PI}, } @group(0) @binding(0) var preprocessed_depth: texture_2d; diff --git a/crates/bevy_pbr/src/ssao/ssao_utils.wgsl b/crates/bevy_pbr/src/ssao/ssao_utils.wgsl index ecc5a4a54de2a..5df9abf769149 100644 --- a/crates/bevy_pbr/src/ssao/ssao_utils.wgsl +++ b/crates/bevy_pbr/src/ssao/ssao_utils.wgsl @@ -1,10 +1,10 @@ #define_import_path bevy_pbr::ssao_utils -#import bevy_render::maths::{PI, HALF_PI} +#import bevy_render::math::{PI, HALF_PI} // Approximates single-bounce ambient occlusion to multi-bounce ambient occlusion // https://blog.selfshadow.com/publications/s2016-shading-course/activision/s2016_pbs_activision_occlusion.pdf#page=78 -fn ssao_multibounce(visibility: f32, base_color: vec3) -> vec3 { +fn ssao_multi_bounce(visibility: f32, base_color: vec3) -> vec3 { let a = 2.0404 * base_color - 0.3324; let b = -4.7951 * base_color + 0.6417; let c = 2.7552 * base_color + 0.6903; diff --git a/crates/bevy_pbr/src/ssr/raymarch.wgsl b/crates/bevy_pbr/src/ssr/raymarch.wgsl index 0731057287b8c..52ef706ccf07a 100644 --- a/crates/bevy_pbr/src/ssr/raymarch.wgsl +++ b/crates/bevy_pbr/src/ssr/raymarch.wgsl @@ -223,9 +223,9 @@ fn depth_raymarch_distance_fn_evaluate( // // That's really stupid but works like magic. For samples taken near the ray origin, // the discrete nature of the depth buffer becomes a problem. It's not a land of continuous surfaces, - // but a bunch of stacked duplo bricks. + // but a bunch of stacked Duplo bricks. // - // Technically we should be taking discrete steps in distance_fn duplo land, but then we're at the mercy + // Technically we should be taking discrete steps in distance_fn Duplo land, but then we're at the mercy // of arbitrary quantization of our directions -- and sometimes we'll take a step which would // claim that the ray is occluded -- even though the underlying smooth surface wouldn't occlude it. // @@ -238,7 +238,7 @@ fn depth_raymarch_distance_fn_evaluate( // when the ray descends below both. // // The two approaches end up fixing each other's artifacts: - // * The false occlusions due to duplo land are rejected because the ray stays above the smooth surface. + // * The false occlusions due to Duplo land are rejected because the ray stays above the smooth surface. // * The shrink-wrap surface is no longer continuous, so it's possible for rays to miss it. let linear_depth = @@ -286,7 +286,7 @@ struct DepthRayMarchResult { /// Range: `0..=1` as a lerp factor over `ray_start_cs..=ray_end_cs`. hit_t: f32, - /// UV correspindong to `hit_t`. + /// UV corresponding to `hit_t`. hit_uv: vec2, /// The distance that the hit point penetrates into the hit surface. diff --git a/crates/bevy_pbr/src/volumetric_fog/volumetric_fog.wgsl b/crates/bevy_pbr/src/volumetric_fog/volumetric_fog.wgsl index bb72f82616d06..40e3bbd9f3ca7 100644 --- a/crates/bevy_pbr/src/volumetric_fog/volumetric_fog.wgsl +++ b/crates/bevy_pbr/src/volumetric_fog/volumetric_fog.wgsl @@ -17,14 +17,14 @@ #import bevy_pbr::mesh_functions::{get_world_from_local, mesh_position_local_to_clip} #import bevy_pbr::mesh_view_bindings::{globals, lights, view, clusterable_objects} #import bevy_pbr::mesh_view_types::{ - DIRECTIONAL_LIGHT_FLAGS_VOLUMETRIC_BIT, - POINT_LIGHT_FLAGS_SHADOWS_ENABLED_BIT, + DIRECTIONAL_LIGHT_FLAGS_VOLUMETRIC_BIT, + POINT_LIGHT_FLAGS_SHADOWS_ENABLED_BIT, POINT_LIGHT_FLAGS_VOLUMETRIC_BIT, POINT_LIGHT_FLAGS_SPOT_LIGHT_Y_NEGATIVE, ClusterableObject } #import bevy_pbr::shadow_sampling::{ - sample_shadow_map_hardware, + sample_shadow_map_hardware, sample_shadow_cubemap, sample_shadow_map, SPOT_SHADOW_TEXEL_SIZE @@ -338,8 +338,8 @@ fn fragment(@builtin(position) position: vec4) -> @location(0) vec4 { let V = Rd_world; let L = normalize(light_to_frag); let distance_square = dot(light_to_frag, light_to_frag); - let distance_atten = getDistanceAttenuation(distance_square, (*light).color_inverse_square_range.w); - var local_light_attenuation = distance_atten; + let distance_attenuation = getDistanceAttenuation(distance_square, (*light).color_inverse_square_range.w); + var local_light_attenuation = distance_attenuation; if (i < spot_light_start_index) { var shadow: f32 = 1.0; if (((*light).flags & POINT_LIGHT_FLAGS_SHADOWS_ENABLED_BIT) != 0u) { @@ -369,7 +369,7 @@ fn fragment(@builtin(position) position: vec4) -> @location(0) vec4 { } local_light_attenuation *= spot_attenuation * shadow; } - + // Calculate absorption (amount of light absorbed by the fog) and // out-scattering (amount of light the fog scattered away). let sample_attenuation = exp(-step_size_world * density * (absorption + scattering)); @@ -481,4 +481,4 @@ fn fetch_spot_shadow_without_normal(light_id: u32, frag_position: vec4) -> i32(light_id) + lights.spot_light_shadowmap_offset, SPOT_SHADOW_TEXEL_SIZE ); -} \ No newline at end of file +} diff --git a/crates/bevy_picking/src/events.rs b/crates/bevy_picking/src/events.rs index e75d6a68196a9..04227b388e497 100644 --- a/crates/bevy_picking/src/events.rs +++ b/crates/bevy_picking/src/events.rs @@ -287,7 +287,7 @@ impl PointerState { .or_default() } - /// Clears all the data assoceated with all of the buttons on a pointer. Does not free the underlying memory. + /// Clears all the data associated with all of the buttons on a pointer. Does not free the underlying memory. pub fn clear(&mut self, pointer_id: PointerId) { for button in PointerButton::iter() { if let Some(state) = self.pointer_buttons.get_mut(&(pointer_id, button)) { @@ -358,7 +358,7 @@ pub struct PickingEventWriters<'w> { /// Both [`Click`] and [`Up`] target the entity hovered in the *previous frame*, /// rather than the current frame. This is because touch pointers hover nothing /// on the frame they are released. The end effect is that these two events can -/// be received sequentally after an [`Out`] event (but always on the same frame +/// be received sequentially after an [`Out`] event (but always on the same frame /// as the [`Out`] event). /// /// Note: Though it is common for the [`PointerInput`] stream may contain diff --git a/crates/bevy_picking/src/lib.rs b/crates/bevy_picking/src/lib.rs index 945385e5f672c..7144c545eb164 100644 --- a/crates/bevy_picking/src/lib.rs +++ b/crates/bevy_picking/src/lib.rs @@ -18,7 +18,7 @@ //! .observe(|mut trigger: Trigger>| { //! // Get the underlying event type //! let click_event: &Pointer = trigger.event(); -//! // Stop the event from bubbling up the entity hierarchjy +//! // Stop the event from bubbling up the entity hierarchy //! trigger.propagate(false); //! }); //! ``` @@ -287,8 +287,8 @@ impl PluginGroup for DefaultPickingPlugins { /// This plugin sets up the core picking infrastructure. It receives input events, and provides the shared /// types used by other picking plugins. /// -/// This plugin contains several settings, and is added to the wrold as a resource after initialization. You -/// can configure picking settings at runtime through the resource. +/// This plugin contains several settings, and is added to the world as a resource after initialization. +/// You can configure picking settings at runtime through the resource. #[derive(Copy, Clone, Debug, Resource, Reflect)] #[reflect(Resource, Default, Debug)] pub struct PickingPlugin { diff --git a/crates/bevy_picking/src/mesh_picking/ray_cast/intersections.rs b/crates/bevy_picking/src/mesh_picking/ray_cast/intersections.rs index d4ec97e1f3549..ea2e2181003e0 100644 --- a/crates/bevy_picking/src/mesh_picking/ray_cast/intersections.rs +++ b/crates/bevy_picking/src/mesh_picking/ray_cast/intersections.rs @@ -293,18 +293,18 @@ pub fn ray_aabb_intersection_3d(ray: Ray3d, aabb: &Aabb3d, model_to_world: &Mat4 // Calculate the minimum/maximum time for each axis based on how much the direction goes that // way. These values can get arbitrarily large, or even become NaN, which is handled by the // min/max operations below - let tmin = (min - ray_origin) * ray_direction_recip; - let tmax = (max - ray_origin) * ray_direction_recip; + let t_min = (min - ray_origin) * ray_direction_recip; + let t_max = (max - ray_origin) * ray_direction_recip; // An axis that is not relevant to the ray direction will be NaN. When one of the arguments // to min/max is NaN, the other argument is used. // An axis for which the direction is the wrong way will return an arbitrarily large // negative value. - let tmin = tmin.max_element().max(0.0); - let tmax = tmax.min_element(); + let t_min = t_min.max_element().max(0.0); + let t_max = t_max.min_element(); - if tmin <= tmax { - Some(tmin) + if t_min <= t_max { + Some(t_min) } else { None } diff --git a/crates/bevy_ptr/README.md b/crates/bevy_ptr/README.md index cce9b80f29660..1b496f7593d93 100644 --- a/crates/bevy_ptr/README.md +++ b/crates/bevy_ptr/README.md @@ -9,7 +9,7 @@ Pointers in computer programming are objects that store a memory address. They're a fundamental building block for constructing more complex data structures. -They're also *the* definitive source of memory safety bugs: you can dereference a invalid (null) pointer, access a pointer after the underlying +They're also *the* definitive source of memory safety bugs: you can dereference an invalid (null) pointer, access a pointer after the underlying memory has been freed, and even ignore type safety and misread or mutate the underlying memory improperly. Rust is a programming language that heavily relies on its types to enforce correctness, and by proxy, memory safety. As a result, @@ -39,17 +39,17 @@ build these safety guarantees... ## Standard Pointers -|Pointer Type |Lifetime'ed|Mutable|Strongly Typed|Aligned|Not Null|Forbids Aliasing|Forbids Arithmetic| -|-------------------|-----------|-------|--------------|-------|--------|----------------|------------------| -|`Box` |Owned |Yes |Yes |Yes |Yes |Yes |Yes | -|`&'a mut T` |Yes |Yes |Yes |Yes |Yes |Yes |Yes | -|`&'a T` |Yes |No |Yes |Yes |Yes |No |Yes | -|`&'a UnsafeCell`|Yes |Maybe |Yes |Yes |Yes |Yes |Yes | -|`NonNull` |No |Yes |Yes |No |Yes |No |No | -|`*const T` |No |No |Yes |No |No |No |No | -|`*mut T` |No |Yes |Yes |No |No |No |No | -|`*const ()` |No |No |No |No |No |No |No | -|`*mut ()` |No |Yes |No |No |No |No |No | +| Pointer Type | Lifetime'ed | Mutable | Strongly Typed | Aligned | Not Null | Forbids Aliasing | Forbids Arithmetic | +| ------------------- | ----------- | ------- | -------------- | ------- | -------- | ---------------- | ------------------ | +| `Box` | Owned | Yes | Yes | Yes | Yes | Yes | Yes | +| `&'a mut T` | Yes | Yes | Yes | Yes | Yes | Yes | Yes | +| `&'a T` | Yes | No | Yes | Yes | Yes | No | Yes | +| `&'a UnsafeCell` | Yes | Maybe | Yes | Yes | Yes | Yes | Yes | +| `NonNull` | No | Yes | Yes | No | Yes | No | No | +| `*const T` | No | No | Yes | No | No | No | No | +| `*mut T` | No | Yes | Yes | No | No | No | No | +| `*const ()` | No | No | No | No | No | No | No | +| `*mut ()` | No | Yes | No | No | No | No | No | `&T`, `&mut T`, and `Box` are by far the most common pointer types that Rust developers will see. They're the only ones in this list that are entirely usable without the use of `unsafe`. @@ -74,10 +74,10 @@ all usage patterns. `*mut ()` should only be used to carry the mutability of the ## Available in Nightly -|Pointer Type |Lifetime'ed|Mutable|Strongly Typed|Aligned|Not Null|Forbids Aliasing|Forbids Arithmetic| -|-------------------|-----------|-------|--------------|-------|--------|----------------|------------------| -|`Unique` |Owned |Yes |Yes |Yes |Yes |Yes |Yes | -|`Shared` |Owned* |Yes |Yes |Yes |Yes |No |Yes | +| Pointer Type | Lifetime'ed | Mutable | Strongly Typed | Aligned | Not Null | Forbids Aliasing | Forbids Arithmetic | +| ------------ | ----------- | ------- | -------------- | ------- | -------- | ---------------- | ------------------ | +| `Unique` | Owned | Yes | Yes | Yes | Yes | Yes | Yes | +| `Shared` | Owned* | Yes | Yes | Yes | Yes | No | Yes | `Unique` is currently available in `core::ptr` on nightly Rust builds. It's a pointer type that acts like it owns the value it points to. It can be thought of as a `Box` that does not allocate on initialization or deallocated when it's dropped, and is in fact used to implement common types like `Box`, `Vec`, @@ -92,13 +92,13 @@ multiple instances to collectively own the data it points to, and as a result, f ## Available in `bevy_ptr` -|Pointer Type |Lifetime'ed|Mutable|Strongly Typed|Aligned|Not Null|Forbids Aliasing|Forbids Arithmetic| -|---------------------|-----------|-------|--------------|-------|--------|----------------|------------------| -|`ConstNonNull` |No |No |Yes |No |Yes |No |Yes | -|`ThinSlicePtr<'a, T>`|Yes |No |Yes |Yes |Yes |Yes |Yes | -|`OwningPtr<'a>` |Yes |Yes |No |Maybe |Yes |Yes |No | -|`Ptr<'a>` |Yes |No |No |Maybe |Yes |No |No | -|`PtrMut<'a>` |Yes |Yes |No |Maybe |Yes |Yes |No | +| Pointer Type | Lifetime'ed | Mutable | Strongly Typed | Aligned | Not Null | Forbids Aliasing | Forbids Arithmetic | +| --------------------- | ----------- | ------- | -------------- | ------- | -------- | ---------------- | ------------------ | +| `ConstNonNull` | No | No | Yes | No | Yes | No | Yes | +| `ThinSlicePtr<'a, T>` | Yes | No | Yes | Yes | Yes | Yes | Yes | +| `OwningPtr<'a>` | Yes | Yes | No | Maybe | Yes | Yes | No | +| `Ptr<'a>` | Yes | No | No | Maybe | Yes | No | No | +| `PtrMut<'a>` | Yes | Yes | No | Maybe | Yes | Yes | No | `ConstNonNull` is like `NonNull` but disallows safe conversions into types that allow mutable access to the value it points to. It's the `*const T` to `NonNull`'s `*mut T`. diff --git a/crates/bevy_ptr/src/lib.rs b/crates/bevy_ptr/src/lib.rs index d767a25d4c63d..f43650f326dc7 100644 --- a/crates/bevy_ptr/src/lib.rs +++ b/crates/bevy_ptr/src/lib.rs @@ -280,7 +280,7 @@ impl<'a, A: IsAligned> Ptr<'a, A> { /// - If the `A` type parameter is [`Aligned`] then `inner` must be sufficiently aligned for the pointee type. /// - `inner` must have correct provenance to allow reads of the pointee type. /// - The lifetime `'a` must be constrained such that this [`Ptr`] will stay valid and nothing - /// can mutate the pointee while this [`Ptr`] is live except through an [`UnsafeCell`]. + /// can mutate the pointed while this [`Ptr`] is live except through an [`UnsafeCell`]. #[inline] pub unsafe fn new(inner: NonNull) -> Self { Self(inner, PhantomData) @@ -304,7 +304,7 @@ impl<'a, A: IsAligned> Ptr<'a, A> { #[inline] pub unsafe fn deref(self) -> &'a T { let ptr = self.as_ptr().cast::().debug_ensure_aligned(); - // SAFETY: The caller ensures the pointee is of type `T` and the pointer can be dereferenced. + // SAFETY: The caller ensures the pointed is of type `T` and the pointer can be dereferenced. unsafe { &*ptr } } @@ -335,7 +335,7 @@ impl<'a, A: IsAligned> PtrMut<'a, A> { /// - If the `A` type parameter is [`Aligned`] then `inner` must be sufficiently aligned for the pointee type. /// - `inner` must have correct provenance to allow read and writes of the pointee type. /// - The lifetime `'a` must be constrained such that this [`PtrMut`] will stay valid and nothing - /// else can read or mutate the pointee while this [`PtrMut`] is live. + /// else can read or mutate the pointed while this [`PtrMut`] is live. #[inline] pub unsafe fn new(inner: NonNull) -> Self { Self(inner, PhantomData) @@ -359,7 +359,7 @@ impl<'a, A: IsAligned> PtrMut<'a, A> { #[inline] pub unsafe fn deref_mut(self) -> &'a mut T { let ptr = self.as_ptr().cast::().debug_ensure_aligned(); - // SAFETY: The caller ensures the pointee is of type `T` and the pointer can be dereferenced. + // SAFETY: The caller ensures the pointed is of type `T` and the pointer can be dereferenced. unsafe { &mut *ptr } } @@ -375,7 +375,7 @@ impl<'a, A: IsAligned> PtrMut<'a, A> { /// Gets a [`PtrMut`] from this with a smaller lifetime. #[inline] pub fn reborrow(&mut self) -> PtrMut<'_, A> { - // SAFETY: the ptrmut we're borrowing from is assumed to be valid + // SAFETY: the PtrMut we're borrowing from is assumed to be valid unsafe { PtrMut::new(self.0) } } @@ -425,7 +425,7 @@ impl<'a, A: IsAligned> OwningPtr<'a, A> { /// - If the `A` type parameter is [`Aligned`] then `inner` must be sufficiently aligned for the pointee type. /// - `inner` must have correct provenance to allow read and writes of the pointee type. /// - The lifetime `'a` must be constrained such that this [`OwningPtr`] will stay valid and nothing - /// else can read or mutate the pointee while this [`OwningPtr`] is live. + /// else can read or mutate the pointed while this [`OwningPtr`] is live. #[inline] pub unsafe fn new(inner: NonNull) -> Self { Self(inner, PhantomData) @@ -440,7 +440,7 @@ impl<'a, A: IsAligned> OwningPtr<'a, A> { #[inline] pub unsafe fn read(self) -> T { let ptr = self.as_ptr().cast::().debug_ensure_aligned(); - // SAFETY: The caller ensure the pointee is of type `T` and uphold safety for `read`. + // SAFETY: The caller ensure the pointed is of type `T` and uphold safety for `read`. unsafe { ptr.read() } } @@ -453,7 +453,7 @@ impl<'a, A: IsAligned> OwningPtr<'a, A> { #[inline] pub unsafe fn drop_as(self) { let ptr = self.as_ptr().cast::().debug_ensure_aligned(); - // SAFETY: The caller ensure the pointee is of type `T` and uphold safety for `drop_in_place`. + // SAFETY: The caller ensure the pointed is of type `T` and uphold safety for `drop_in_place`. unsafe { ptr.drop_in_place(); } @@ -490,7 +490,7 @@ impl<'a> OwningPtr<'a, Unaligned> { /// - `T` must be the erased pointee type for this [`OwningPtr`]. pub unsafe fn read_unaligned(self) -> T { let ptr = self.as_ptr().cast::(); - // SAFETY: The caller ensure the pointee is of type `T` and uphold safety for `read_unaligned`. + // SAFETY: The caller ensure the pointed is of type `T` and uphold safety for `read_unaligned`. unsafe { ptr.read_unaligned() } } } diff --git a/crates/bevy_reflect/derive/src/from_reflect.rs b/crates/bevy_reflect/derive/src/from_reflect.rs index d994cbd2f79a2..377f56ac87687 100644 --- a/crates/bevy_reflect/derive/src/from_reflect.rs +++ b/crates/bevy_reflect/derive/src/from_reflect.rs @@ -42,7 +42,7 @@ pub(crate) fn impl_opaque(meta: &ReflectMeta) -> proc_macro2::TokenStream { /// Implements `FromReflect` for the given enum type pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> proc_macro2::TokenStream { - let fqoption = FQOption.into_token_stream(); + let fq_option = FQOption.into_token_stream(); let enum_path = reflect_enum.meta().type_path(); let bevy_reflect_path = reflect_enum.meta().bevy_reflect_path(); @@ -57,11 +57,11 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> proc_macro2::TokenStream let match_branches = if reflect_enum.meta().is_remote_wrapper() { quote! { - #(#variant_names => #fqoption::Some(Self(#variant_constructors)),)* + #(#variant_names => #fq_option::Some(Self(#variant_constructors)),)* } } else { quote! { - #(#variant_names => #fqoption::Some(#variant_constructors),)* + #(#variant_names => #fq_option::Some(#variant_constructors),)* } }; @@ -74,7 +74,7 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> proc_macro2::TokenStream quote! { impl #impl_generics #bevy_reflect_path::FromReflect for #enum_path #ty_generics #where_from_reflect_clause { - fn from_reflect(#ref_value: &dyn #bevy_reflect_path::PartialReflect) -> #FQOption { + fn from_reflect(#ref_value: &dyn #bevy_reflect_path::PartialReflect) -> #fq_option { if let #bevy_reflect_path::ReflectRef::Enum(#ref_value) = #bevy_reflect_path::PartialReflect::reflect_ref(#ref_value) { @@ -83,7 +83,7 @@ pub(crate) fn impl_enum(reflect_enum: &ReflectEnum) -> proc_macro2::TokenStream name => panic!("variant with name `{}` does not exist on enum `{}`", name, ::type_path()), } } else { - #FQOption::None + #fq_option::None } } } @@ -104,7 +104,7 @@ fn impl_struct_internal( reflect_struct: &ReflectStruct, is_tuple: bool, ) -> proc_macro2::TokenStream { - let fqoption = FQOption.into_token_stream(); + let fq_option = FQOption.into_token_stream(); let struct_path = reflect_struct.meta().type_path(); let remote_ty = reflect_struct.meta().remote_ty(); @@ -126,7 +126,7 @@ fn impl_struct_internal( let __this = Ident::new("__this", Span::call_site()); // The reflected type: either `Self` or a remote type - let (reflect_ty, constructor, retval) = if let Some(remote_ty) = remote_ty { + let (reflect_ty, constructor, return_value) = if let Some(remote_ty) = remote_ty { let constructor = match remote_ty.as_expr_path() { Ok(path) => path, Err(err) => return err.into_compile_error(), @@ -146,12 +146,12 @@ fn impl_struct_internal( quote! { let mut #__this = <#reflect_ty as #FQDefault>::default(); #( - if let #fqoption::Some(__field) = #active_values() { + if let #fq_option::Some(__field) = #active_values() { // Iff field exists -> use its value #__this.#active_members = __field; } )* - #FQOption::Some(#retval) + #fq_option::Some(#return_value) } } else { let MemberValuePair(ignored_members, ignored_values) = get_ignored_fields(reflect_struct); @@ -161,7 +161,7 @@ fn impl_struct_internal( #(#active_members: #active_values()?,)* #(#ignored_members: #ignored_values,)* }; - #FQOption::Some(#retval) + #fq_option::Some(#return_value) } }; @@ -178,13 +178,13 @@ fn impl_struct_internal( quote! { impl #impl_generics #bevy_reflect_path::FromReflect for #struct_path #ty_generics #where_from_reflect_clause { - fn from_reflect(reflect: &dyn #bevy_reflect_path::PartialReflect) -> #FQOption { + fn from_reflect(reflect: &dyn #bevy_reflect_path::PartialReflect) -> #fq_option { if let #bevy_reflect_path::ReflectRef::#ref_struct_type(#ref_struct) = #bevy_reflect_path::PartialReflect::reflect_ref(reflect) { #constructor } else { - #FQOption::None + #fq_option::None } } } diff --git a/crates/bevy_reflect/derive/src/impls/structs.rs b/crates/bevy_reflect/derive/src/impls/structs.rs index fa1b454cfc373..7cfdade246bef 100644 --- a/crates/bevy_reflect/derive/src/impls/structs.rs +++ b/crates/bevy_reflect/derive/src/impls/structs.rs @@ -8,7 +8,7 @@ use quote::{quote, ToTokens}; /// Implements `Struct`, `GetTypeRegistration`, and `Reflect` for the given derive data. pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> proc_macro2::TokenStream { - let fqoption = FQOption.into_token_stream(); + let fq_option = FQOption.into_token_stream(); let bevy_reflect_path = reflect_struct.meta().bevy_reflect_path(); let struct_path = reflect_struct.meta().type_path(); @@ -78,35 +78,35 @@ pub(crate) fn impl_struct(reflect_struct: &ReflectStruct) -> proc_macro2::TokenS impl #impl_generics #bevy_reflect_path::Struct for #struct_path #ty_generics #where_reflect_clause { fn field(&self, name: &str) -> #FQOption<&dyn #bevy_reflect_path::PartialReflect> { match name { - #(#field_names => #fqoption::Some(#fields_ref),)* + #(#field_names => #fq_option::Some(#fields_ref),)* _ => #FQOption::None, } } fn field_mut(&mut self, name: &str) -> #FQOption<&mut dyn #bevy_reflect_path::PartialReflect> { match name { - #(#field_names => #fqoption::Some(#fields_mut),)* + #(#field_names => #fq_option::Some(#fields_mut),)* _ => #FQOption::None, } } fn field_at(&self, index: usize) -> #FQOption<&dyn #bevy_reflect_path::PartialReflect> { match index { - #(#field_indices => #fqoption::Some(#fields_ref),)* + #(#field_indices => #fq_option::Some(#fields_ref),)* _ => #FQOption::None, } } fn field_at_mut(&mut self, index: usize) -> #FQOption<&mut dyn #bevy_reflect_path::PartialReflect> { match index { - #(#field_indices => #fqoption::Some(#fields_mut),)* + #(#field_indices => #fq_option::Some(#fields_mut),)* _ => #FQOption::None, } } fn name_at(&self, index: usize) -> #FQOption<&str> { match index { - #(#field_indices => #fqoption::Some(#field_names),)* + #(#field_indices => #fq_option::Some(#field_names),)* _ => #FQOption::None, } } diff --git a/crates/bevy_reflect/derive/src/impls/tuple_structs.rs b/crates/bevy_reflect/derive/src/impls/tuple_structs.rs index f0f3cc8f2bdf0..61e440ddf3f2f 100644 --- a/crates/bevy_reflect/derive/src/impls/tuple_structs.rs +++ b/crates/bevy_reflect/derive/src/impls/tuple_structs.rs @@ -8,7 +8,7 @@ use quote::{quote, ToTokens}; /// Implements `TupleStruct`, `GetTypeRegistration`, and `Reflect` for the given derive data. pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> proc_macro2::TokenStream { - let fqoption = FQOption.into_token_stream(); + let fq_option = FQOption.into_token_stream(); let bevy_reflect_path = reflect_struct.meta().bevy_reflect_path(); let struct_path = reflect_struct.meta().type_path(); @@ -66,14 +66,14 @@ pub(crate) fn impl_tuple_struct(reflect_struct: &ReflectStruct) -> proc_macro2:: impl #impl_generics #bevy_reflect_path::TupleStruct for #struct_path #ty_generics #where_reflect_clause { fn field(&self, index: usize) -> #FQOption<&dyn #bevy_reflect_path::PartialReflect> { match index { - #(#field_indices => #fqoption::Some(#fields_ref),)* + #(#field_indices => #fq_option::Some(#fields_ref),)* _ => #FQOption::None, } } fn field_mut(&mut self, index: usize) -> #FQOption<&mut dyn #bevy_reflect_path::PartialReflect> { match index { - #(#field_indices => #fqoption::Some(#fields_mut),)* + #(#field_indices => #fq_option::Some(#fields_mut),)* _ => #FQOption::None, } } diff --git a/crates/bevy_reflect/derive/src/string_expr.rs b/crates/bevy_reflect/derive/src/string_expr.rs index 1284736fc91b8..c077f2071fd6e 100644 --- a/crates/bevy_reflect/derive/src/string_expr.rs +++ b/crates/bevy_reflect/derive/src/string_expr.rs @@ -7,7 +7,7 @@ use syn::{spanned::Spanned, LitStr}; pub(crate) enum StringExpr { /// A string that is valid at compile time. /// - /// This is either a string literal like `"mystring"`, + /// This is either a string literal like `"my string"`, /// or a string created by a macro like [`module_path`] /// or [`concat`]. Const(TokenStream), diff --git a/crates/bevy_reflect/examples/reflect_docs.rs b/crates/bevy_reflect/examples/reflect_docs.rs index 10852185c00d8..eaf88e97cae37 100644 --- a/crates/bevy_reflect/examples/reflect_docs.rs +++ b/crates/bevy_reflect/examples/reflect_docs.rs @@ -19,7 +19,7 @@ fn main() { /// # Example /// /// ``` - /// let player = Player::new("Urist McPlayer"); + /// let player = Player::new("Example Player Name"); /// ``` #[derive(Reflect)] struct Player { @@ -36,7 +36,7 @@ fn main() { // From here, we already have access to the struct's docs: let player_docs = player_info.docs().unwrap(); - assert_eq!(" The struct that defines our player.\n\n # Example\n\n ```\n let player = Player::new(\"Urist McPlayer\");\n ```", player_docs); + assert_eq!(" The struct that defines our player.\n\n # Example\n\n ```\n let player = Player::new(\"Example Player Name\");\n ```", player_docs); println!("=====[ Player ]=====\n{player_docs}"); // We can then iterate through our struct's fields to get their documentation as well: diff --git a/crates/bevy_reflect/src/array.rs b/crates/bevy_reflect/src/array.rs index 481b29648baa3..a440addd3de71 100644 --- a/crates/bevy_reflect/src/array.rs +++ b/crates/bevy_reflect/src/array.rs @@ -517,7 +517,7 @@ mod tests { const SIZE: usize = if cfg!(debug_assertions) { 4 } else { - // If compiled in release mode, verify we dont overflow + // If compiled in release mode, verify we don't overflow usize::MAX }; diff --git a/crates/bevy_reflect/src/enums/dynamic_enum.rs b/crates/bevy_reflect/src/enums/dynamic_enum.rs index d114b6d86e0d8..fe571f4eb20d4 100644 --- a/crates/bevy_reflect/src/enums/dynamic_enum.rs +++ b/crates/bevy_reflect/src/enums/dynamic_enum.rs @@ -55,7 +55,7 @@ impl From<()> for DynamicVariant { /// // Apply the DynamicEnum as a patch to the original value /// value.apply(dyn_enum.as_partial_reflect()); /// -/// // Tada! +/// // Ta-da! /// assert_eq!(None, value); /// ``` #[derive(Default, Debug)] diff --git a/crates/bevy_reflect/src/func/dynamic_function.rs b/crates/bevy_reflect/src/func/dynamic_function.rs index e6cfd9bea7022..f03138f4ec46a 100644 --- a/crates/bevy_reflect/src/func/dynamic_function.rs +++ b/crates/bevy_reflect/src/func/dynamic_function.rs @@ -374,8 +374,8 @@ mod tests { fn should_allow_recursive_dynamic_function() { let factorial = DynamicFunction::new( |mut args| { - let curr = args.pop::()?; - if curr == 0 { + let current = args.pop::()?; + if current == 0 { return Ok(1_i32.into_return()); } @@ -387,10 +387,10 @@ mod tests { let result = func.reflect_call( ArgList::new() .push_ref(this.as_partial_reflect()) - .push_owned(curr - 1), + .push_owned(current - 1), ); let value = result.unwrap().unwrap_owned().try_take::().unwrap(); - Ok((curr * value).into_return()) + Ok((current * value).into_return()) } _ => panic!("expected function"), } @@ -398,7 +398,7 @@ mod tests { // The `FunctionInfo` doesn't really matter for this test // so we can just give it dummy information. FunctionInfo::anonymous() - .with_arg::("curr") + .with_arg::("current") .with_arg::<()>("this"), ); diff --git a/crates/bevy_reflect/src/kind.rs b/crates/bevy_reflect/src/kind.rs index 2e3928162a73f..1dcbca359f8a2 100644 --- a/crates/bevy_reflect/src/kind.rs +++ b/crates/bevy_reflect/src/kind.rs @@ -54,7 +54,7 @@ pub enum ReflectKind { /// An opaque type. /// /// This most often represents a type where it is either impossible, difficult, - /// or unuseful to reflect the type further. + /// or useless to reflect the type further. /// /// This includes types like `String` and `Instant`. /// @@ -138,10 +138,10 @@ pub struct ReflectKindMismatchError { } macro_rules! impl_cast_method { - ($name:ident : Opaque => $retval:ty) => { + ($name:ident : Opaque => $okay:ty) => { #[doc = "Attempts a cast to a [`PartialReflect`] trait object."] #[doc = "\n\nReturns an error if `self` is not the [`Self::Opaque`] variant."] - pub fn $name(self) -> Result<$retval, ReflectKindMismatchError> { + pub fn $name(self) -> Result<$okay, ReflectKindMismatchError> { match self { Self::Opaque(value) => Ok(value), _ => Err(ReflectKindMismatchError { @@ -151,10 +151,10 @@ macro_rules! impl_cast_method { } } }; - ($name:ident : $kind:ident => $retval:ty) => { + ($name:ident : $kind:ident => $okay:ty) => { #[doc = concat!("Attempts a cast to a [`", stringify!($kind), "`] trait object.")] #[doc = concat!("\n\nReturns an error if `self` is not the [`Self::", stringify!($kind), "`] variant.")] - pub fn $name(self) -> Result<$retval, ReflectKindMismatchError> { + pub fn $name(self) -> Result<$okay, ReflectKindMismatchError> { match self { Self::$kind(value) => Ok(value), _ => Err(ReflectKindMismatchError { diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index ab69019ee1128..339c64661f8c4 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -444,7 +444,7 @@ //! # Limitations //! //! While this crate offers a lot in terms of adding reflection to Rust, -//! it does come with some limitations that don't make it as featureful as reflection +//! it does come with some limitations that don't make it as feature-rich as reflection //! in other programming languages. //! //! ## Non-Static Lifetimes @@ -457,8 +457,7 @@ //! ## Generic Function Reflection //! //! Another limitation is the inability to reflect over generic functions directly. It can be done, but will -//! typically require manual monomorphization (i.e. manually specifying the types the generic method can -//! take). +//! typically require manual monomorphization (i.e. manually specifying the types the generic method can take). //! //! ## Manual Registration //! @@ -2480,7 +2479,7 @@ bevy_reflect::tests::Test { // test unknown DynamicTupleStruct let mut test_unknown_tuple_struct = DynamicTupleStruct::default(); test_unknown_tuple_struct.insert(14); - test_struct.insert("unknown_tuplestruct", test_unknown_tuple_struct); + test_struct.insert("unknown_tuple_struct", test_unknown_tuple_struct); assert_eq!( format!("{:?}", test_struct), "DynamicStruct(bevy_reflect::tests::TestStruct { \ @@ -2492,7 +2491,7 @@ bevy_reflect::tests::Test { map: DynamicMap({9: 10}), \ value: 12, \ unknown_struct: DynamicStruct(_ { a: 13 }), \ - unknown_tuplestruct: DynamicTupleStruct(_(14)) \ + unknown_tuple_struct: DynamicTupleStruct(_(14)) \ })" ); } diff --git a/crates/bevy_reflect/src/list.rs b/crates/bevy_reflect/src/list.rs index 49a479154faaa..ae46b89ef193e 100644 --- a/crates/bevy_reflect/src/list.rs +++ b/crates/bevy_reflect/src/list.rs @@ -556,7 +556,7 @@ mod tests { const SIZE: usize = if cfg!(debug_assertions) { 4 } else { - // If compiled in release mode, verify we dont overflow + // If compiled in release mode, verify we don't overflow usize::MAX }; let b = Box::new(vec![(); SIZE]).into_reflect(); diff --git a/crates/bevy_reflect/src/path/access.rs b/crates/bevy_reflect/src/path/access.rs index c0a141fcbaee1..81b7f2b049eaf 100644 --- a/crates/bevy_reflect/src/path/access.rs +++ b/crates/bevy_reflect/src/path/access.rs @@ -16,7 +16,7 @@ type InnerResult = Result; pub enum Access<'a> { /// A name-based field access on a struct. Field(Cow<'a, str>), - /// A index-based field access on a struct. + /// An index-based field access on a struct. FieldIndex(usize), /// An index-based access on a tuple. TupleIndex(usize), diff --git a/crates/bevy_reflect/src/path/mod.rs b/crates/bevy_reflect/src/path/mod.rs index 9fc7d1b9f2213..e6e61c000c640 100644 --- a/crates/bevy_reflect/src/path/mod.rs +++ b/crates/bevy_reflect/src/path/mod.rs @@ -754,10 +754,10 @@ mod tests { assert_eq!(a.tuple_variant, F::Tuple(1337, 321)); assert_eq!( - a.reflect_path("x.notreal").err().unwrap(), + a.reflect_path("x.not_real").err().unwrap(), ReflectPathError::InvalidAccess(AccessError { kind: AccessErrorKind::MissingField(ReflectKind::Struct), - access: access_field("notreal"), + access: access_field("not_real"), offset: Some(2), }) ); diff --git a/crates/bevy_reflect/src/path/parse.rs b/crates/bevy_reflect/src/path/parse.rs index 40b39365ff054..3fd3fc7da2a42 100644 --- a/crates/bevy_reflect/src/path/parse.rs +++ b/crates/bevy_reflect/src/path/parse.rs @@ -191,11 +191,11 @@ mod test { }), ); assert!(matches!( - ParsedPath::parse_static("y[badindex]"), + ParsedPath::parse_static("y[bad_index]"), Err(ReflectPathError::ParseError { error: ParseError(Error::InvalidIndex(_)), offset: 2, - path: "y[badindex]", + path: "y[bad_index]", }), )); } diff --git a/crates/bevy_reflect/src/reflect.rs b/crates/bevy_reflect/src/reflect.rs index 993366e61dd6d..ed9d70195e627 100644 --- a/crates/bevy_reflect/src/reflect.rs +++ b/crates/bevy_reflect/src/reflect.rs @@ -12,11 +12,11 @@ use derive_more::derive::{Display, Error}; use crate::utility::NonGenericTypeInfoCell; -/// A enumeration of all error outcomes that might happen when running [`try_apply`](PartialReflect::try_apply). +/// An enumeration of all error outcomes that might happen when running [`try_apply`](PartialReflect::try_apply). #[derive(Error, Display, Debug)] pub enum ApplyError { #[display("attempted to apply `{from_kind}` to `{to_kind}`")] - /// Attempted to apply the wrong [kind](ReflectKind) to a type, e.g. a struct to a enum. + /// Attempted to apply the wrong [kind](ReflectKind) to a type, e.g. a struct to an enum. MismatchedKinds { from_kind: ReflectKind, to_kind: ReflectKind, @@ -37,7 +37,7 @@ pub enum ApplyError { }, #[display("attempted to apply type with {from_size} size to a type with {to_size} size")] - /// Attempted to apply to types with mismatched sizez, e.g. a [u8; 4] to [u8; 3]. + /// Attempted to apply to types with mismatched sizes, e.g. a [u8; 4] to [u8; 3]. DifferentSize { from_size: usize, to_size: usize }, #[display("variant with name `{variant_name}` does not exist on enum `{enum_name}`")] @@ -189,8 +189,8 @@ where /// /// # Handling Errors /// - /// This function may leave `self` in a partially mutated state if a error was encountered on the way. - /// consider maintaining a cloned instance of this data you can switch to if a error is encountered. + /// This function may leave `self` in a partially mutated state if an error was encountered on the way. + /// consider maintaining a cloned instance of this data you can switch to if an error is encountered. fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError>; /// Returns a zero-sized enumeration of "kinds" of type. diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index 1b0fd84c71e0c..df6c4f8f1a709 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -869,8 +869,8 @@ mod test { // SAFETY: reflect_from_ptr was constructed for the correct type let dyn_reflect = unsafe { reflect_from_ptr.as_reflect_mut(value) }; match dyn_reflect.reflect_mut() { - bevy_reflect::ReflectMut::Struct(strukt) => { - strukt.field_mut("a").unwrap().apply(&2.0f32); + bevy_reflect::ReflectMut::Struct(r#struct) => { + r#struct.field_mut("a").unwrap().apply(&2.0f32); } _ => panic!("invalid reflection"), } @@ -880,8 +880,8 @@ mod test { // SAFETY: reflect_from_ptr was constructed for the correct type let dyn_reflect = unsafe { reflect_from_ptr.as_reflect(Ptr::from(&value)) }; match dyn_reflect.reflect_ref() { - bevy_reflect::ReflectRef::Struct(strukt) => { - let a = strukt + bevy_reflect::ReflectRef::Struct(r#struct) => { + let a = r#struct .field("a") .unwrap() .try_downcast_ref::() diff --git a/crates/bevy_render/src/color_operations.wgsl b/crates/bevy_render/src/color_operations.wgsl index b68ad2a3db57f..56c831c86ed0e 100644 --- a/crates/bevy_render/src/color_operations.wgsl +++ b/crates/bevy_render/src/color_operations.wgsl @@ -1,6 +1,6 @@ #define_import_path bevy_render::color_operations -#import bevy_render::maths::FRAC_PI_3 +#import bevy_render::math::FRAC_PI_3 // Converts HSV to RGB. // diff --git a/crates/bevy_render/src/lib.rs b/crates/bevy_render/src/lib.rs index c220470e48635..edca84da97f03 100644 --- a/crates/bevy_render/src/lib.rs +++ b/crates/bevy_render/src/lib.rs @@ -397,7 +397,7 @@ impl Plugin for RenderPlugin { } fn finish(&self, app: &mut App) { - load_internal_asset!(app, MATHS_SHADER_HANDLE, "maths.wgsl", Shader::from_wgsl); + load_internal_asset!(app, MATHS_SHADER_HANDLE, "math.wgsl", Shader::from_wgsl); load_internal_asset!( app, COLOR_OPERATIONS_SHADER_HANDLE, diff --git a/crates/bevy_render/src/maths.wgsl b/crates/bevy_render/src/math.wgsl similarity index 98% rename from crates/bevy_render/src/maths.wgsl rename to crates/bevy_render/src/math.wgsl index a9cb80c0fcabb..818ae7f80b8fb 100644 --- a/crates/bevy_render/src/maths.wgsl +++ b/crates/bevy_render/src/math.wgsl @@ -1,4 +1,4 @@ -#define_import_path bevy_render::maths +#define_import_path bevy_render::math const PI: f32 = 3.141592653589793; // π const PI_2: f32 = 6.283185307179586; // 2π diff --git a/crates/bevy_render/src/render_phase/mod.rs b/crates/bevy_render/src/render_phase/mod.rs index f460a37d0441c..70c70ee8fbf17 100644 --- a/crates/bevy_render/src/render_phase/mod.rs +++ b/crates/bevy_render/src/render_phase/mod.rs @@ -111,7 +111,7 @@ where /// The unbatchable bins. /// - /// Each entity here is rendered in a separate drawcall. + /// Each entity here is rendered in a separate draw call. pub unbatchable_mesh_values: HashMap, /// Items in the bin that aren't meshes at all. @@ -885,7 +885,7 @@ pub trait PhaseItem: Sized + Send + Sync + 'static { /// buffers, to work around uniform buffer size limitations. /// /// * The *indirect parameters index*: an index into the buffer that specifies -/// the indirect parameters for this [`PhaseItem`]'s drawcall. This is used when +/// the indirect parameters for this [`PhaseItem`]'s draw call. This is used when /// indirect mode is on (as used for GPU culling). /// /// Note that our indirect draw functionality requires storage buffers, so it's @@ -939,7 +939,7 @@ impl PhaseItemExtraIndex { *self != Self::NONE && (self.0 & Self::INDIRECT_PARAMETER_INDEX) != 0 } - /// Packs a indirect parameters index into this extra index. + /// Packs an indirect parameters index into this extra index. #[inline] pub fn indirect_parameters_index(indirect_parameter_index: u32) -> PhaseItemExtraIndex { // Make sure we didn't overflow. @@ -1114,8 +1114,7 @@ where } impl BinnedRenderPhaseType { - /// Creates the appropriate [`BinnedRenderPhaseType`] for a mesh, given its - /// batchability. + /// Creates the appropriate [`BinnedRenderPhaseType`] for a mesh based on whether it can be batched. pub fn mesh(batchable: bool) -> BinnedRenderPhaseType { if batchable { BinnedRenderPhaseType::BatchableMesh diff --git a/crates/bevy_render/src/render_resource/pipeline_cache.rs b/crates/bevy_render/src/render_resource/pipeline_cache.rs index 5396b720e3055..9bb26a62e2be2 100644 --- a/crates/bevy_render/src/render_resource/pipeline_cache.rs +++ b/crates/bevy_render/src/render_resource/pipeline_cache.rs @@ -467,7 +467,7 @@ impl PipelineCache { self.pipelines.iter() } - /// Returns a iterator of the IDs of all currently waiting pipelines. + /// Returns an iterator of the IDs of all currently waiting pipelines. pub fn waiting_pipelines(&self) -> impl Iterator + '_ { self.waiting_pipelines.iter().copied() } diff --git a/crates/bevy_render/src/renderer/render_device.rs b/crates/bevy_render/src/renderer/render_device.rs index 407d1b361b0e5..95d792a723b88 100644 --- a/crates/bevy_render/src/renderer/render_device.rs +++ b/crates/bevy_render/src/renderer/render_device.rs @@ -211,7 +211,7 @@ impl RenderDevice { /// /// # Panics /// - /// - A old [`SurfaceTexture`](wgpu::SurfaceTexture) is still alive referencing an old surface. + /// - An old [`SurfaceTexture`](wgpu::SurfaceTexture) is still alive referencing an old surface. /// - Texture format requested is unsupported on the surface. pub fn configure_surface(&self, surface: &wgpu::Surface, config: &wgpu::SurfaceConfiguration) { surface.configure(&self.device, config); diff --git a/crates/bevy_render/src/texture/fallback_image.rs b/crates/bevy_render/src/texture/fallback_image.rs index ee359f1d3f3bb..00edd2faa9c79 100644 --- a/crates/bevy_render/src/texture/fallback_image.rs +++ b/crates/bevy_render/src/texture/fallback_image.rs @@ -241,7 +241,11 @@ pub struct FallbackImageMsaa<'w> { } impl<'w> FallbackImageMsaa<'w> { - pub fn image_for_samplecount(&mut self, sample_count: u32, format: TextureFormat) -> &GpuImage { + pub fn image_for_sample_count( + &mut self, + sample_count: u32, + format: TextureFormat, + ) -> &GpuImage { self.cache.entry((sample_count, format)).or_insert_with(|| { fallback_image_new( &self.render_device, diff --git a/crates/bevy_render/src/view/visibility/range.rs b/crates/bevy_render/src/view/visibility/range.rs index c476c9e9c640e..4167a1abb87bd 100644 --- a/crates/bevy_render/src/view/visibility/range.rs +++ b/crates/bevy_render/src/view/visibility/range.rs @@ -90,7 +90,7 @@ impl Plugin for VisibilityRangePlugin { /// You can also use this feature to replace multiple meshes with a single mesh /// when the camera is distant. This is the reason for the term "*hierarchical* /// level of detail". Reducing the number of meshes can be useful for reducing -/// drawcall count. Note that you must place the [`VisibilityRange`] component +/// draw call count. Note that you must place the [`VisibilityRange`] component /// on each entity you want to be part of a LOD group, as [`VisibilityRange`] /// isn't automatically propagated down to children. /// @@ -118,7 +118,7 @@ pub struct VisibilityRange { /// smoothly fade into view as the camera zooms out. /// /// If the start and end of this range are identical, the transition will be - /// abrupt, with no crossfading. + /// abrupt, with no cross-fading. /// /// `start_margin.end` must be less than or equal to `end_margin.start`. pub start_margin: Range, @@ -127,7 +127,7 @@ pub struct VisibilityRange { /// smoothly fade out of view as the camera zooms out. /// /// If the start and end of this range are identical, the transition will be - /// abrupt, with no crossfading. + /// abrupt, with no cross-fading. /// /// `end_margin.start` must be greater than or equal to `start_margin.end`. pub end_margin: Range, @@ -164,7 +164,7 @@ impl VisibilityRange { } /// Returns true if both the start and end transitions for this range are - /// abrupt: that is, there is no crossfading. + /// abrupt: that is, there is no cross-fading. #[inline] pub fn is_abrupt(&self) -> bool { self.start_margin.start == self.start_margin.end diff --git a/crates/bevy_render/src/view/window/mod.rs b/crates/bevy_render/src/view/window/mod.rs index 2e282bfcab048..d79b20f4527b0 100644 --- a/crates/bevy_render/src/view/window/mod.rs +++ b/crates/bevy_render/src/view/window/mod.rs @@ -328,7 +328,7 @@ pub fn create_surfaces( // SAFETY: The window handles in ExtractedWindows will always be valid objects to create surfaces on let surface = unsafe { // NOTE: On some OSes this MUST be called from the main thread. - // As of wgpu 0.15, only fallible if the given window is a HTML canvas and obtaining a WebGPU or WebGL2 context fails. + // As of wgpu 0.15, only fallible if the given window is an HTML canvas and obtaining a WebGPU or WebGL2 context fails. render_instance .create_surface_unsafe(surface_target) .expect("Failed to create wgpu surface") diff --git a/crates/bevy_render/src/view/window/screenshot.rs b/crates/bevy_render/src/view/window/screenshot.rs index ad03ca0920937..f0640fbb6cf5e 100644 --- a/crates/bevy_render/src/view/window/screenshot.rs +++ b/crates/bevy_render/src/view/window/screenshot.rs @@ -362,7 +362,7 @@ fn prepare_screenshot_state( pipelines: &mut SpecializedRenderPipelines, ) -> (TextureView, ScreenshotPreparedState) { let texture = render_device.create_texture(&wgpu::TextureDescriptor { - label: Some("screenshot-capture-rendertarget"), + label: Some("screenshot-capture-render-target"), size, mip_level_count: 1, sample_count: 1, diff --git a/crates/bevy_scene/src/serde.rs b/crates/bevy_scene/src/serde.rs index e1498ccc1c978..efa462c0f3cc1 100644 --- a/crates/bevy_scene/src/serde.rs +++ b/crates/bevy_scene/src/serde.rs @@ -836,7 +836,7 @@ mod tests { } #[test] - fn should_roundtrip_messagepack() { + fn should_roundtrip_message_pack() { let mut world = create_world(); world.spawn(MyComponent { diff --git a/crates/bevy_sprite/src/dynamic_texture_atlas_builder.rs b/crates/bevy_sprite/src/dynamic_texture_atlas_builder.rs index 4c53e321ae4a7..87245d463f6bd 100644 --- a/crates/bevy_sprite/src/dynamic_texture_atlas_builder.rs +++ b/crates/bevy_sprite/src/dynamic_texture_atlas_builder.rs @@ -38,7 +38,7 @@ impl DynamicTextureAtlasBuilder { /// /// # Arguments /// - /// * `altas_layout` - The atlas layout to add the texture to. + /// * `atlas_layout` - The atlas layout to add the texture to. /// * `texture` - The source texture to add to the atlas. /// * `atlas_texture` - The destination atlas texture to copy the source texture to. pub fn add_texture( diff --git a/crates/bevy_sprite/src/mesh2d/mesh2d_functions.wgsl b/crates/bevy_sprite/src/mesh2d/mesh2d_functions.wgsl index 0b994822112d8..47549f712f95b 100644 --- a/crates/bevy_sprite/src/mesh2d/mesh2d_functions.wgsl +++ b/crates/bevy_sprite/src/mesh2d/mesh2d_functions.wgsl @@ -4,7 +4,7 @@ mesh2d_view_bindings::view, mesh2d_bindings::mesh, } -#import bevy_render::maths::{affine3_to_square, mat2x4_f32_to_mat3x3_unpack} +#import bevy_render::math::{affine3_to_square, mat2x4_f32_to_mat3x3_unpack} fn get_world_from_local(instance_index: u32) -> mat4x4 { return affine3_to_square(mesh[instance_index].world_from_local); diff --git a/crates/bevy_sprite/src/mesh2d/mesh2d_types.wgsl b/crates/bevy_sprite/src/mesh2d/mesh2d_types.wgsl index d5038c818d58e..dd51e345cbc90 100644 --- a/crates/bevy_sprite/src/mesh2d/mesh2d_types.wgsl +++ b/crates/bevy_sprite/src/mesh2d/mesh2d_types.wgsl @@ -2,13 +2,13 @@ struct Mesh2d { // Affine 4x3 matrix transposed to 3x4 - // Use bevy_render::maths::affine3_to_square to unpack + // Use bevy_render::math::affine3_to_square to unpack world_from_local: mat3x4, // 3x3 matrix packed in mat2x4 and f32 as: // [0].xyz, [1].x, // [1].yz, [2].xy // [2].z - // Use bevy_render::maths::mat2x4_f32_to_mat3x3_unpack to unpack + // Use bevy_render::math::mat2x4_f32_to_mat3x3_unpack to unpack local_from_world_transpose_a: mat2x4, local_from_world_transpose_b: f32, // 'flags' is a bit field indicating various options. u32 is 32 bits so we have up to 32 options. diff --git a/crates/bevy_sprite/src/render/sprite.wgsl b/crates/bevy_sprite/src/render/sprite.wgsl index 03e43d0d5b5a3..0a7a01205fa8a 100644 --- a/crates/bevy_sprite/src/render/sprite.wgsl +++ b/crates/bevy_sprite/src/render/sprite.wgsl @@ -3,7 +3,7 @@ #endif #import bevy_render::{ - maths::affine3_to_square, + math::affine3_to_square, view::View, } diff --git a/crates/bevy_sprite/src/texture_slice/slicer.rs b/crates/bevy_sprite/src/texture_slice/slicer.rs index 325e7ccb2b8be..d8e6a9ac451f8 100644 --- a/crates/bevy_sprite/src/texture_slice/slicer.rs +++ b/crates/bevy_sprite/src/texture_slice/slicer.rs @@ -47,14 +47,17 @@ impl TextureSlicer { /// Computes the 4 corner slices: top left, top right, bottom left, bottom right. #[must_use] fn corner_slices(&self, base_rect: Rect, render_size: Vec2) -> [TextureSlice; 4] { - let coef = render_size / base_rect.size(); + let coefficients = render_size / base_rect.size(); let BorderRect { left, right, top, bottom, } = self.border; - let min_coef = coef.x.min(coef.y).min(self.max_corner_scale); + let min_coefficient = coefficients + .x + .min(coefficients.y) + .min(self.max_corner_scale); [ // Top Left Corner TextureSlice { @@ -62,10 +65,10 @@ impl TextureSlicer { min: base_rect.min, max: base_rect.min + vec2(left, top), }, - draw_size: vec2(left, top) * min_coef, + draw_size: vec2(left, top) * min_coefficient, offset: vec2( - -render_size.x + left * min_coef, - render_size.y - top * min_coef, + -render_size.x + left * min_coefficient, + render_size.y - top * min_coefficient, ) / 2.0, }, // Top Right Corner @@ -74,10 +77,10 @@ impl TextureSlicer { min: vec2(base_rect.max.x - right, base_rect.min.y), max: vec2(base_rect.max.x, base_rect.min.y + top), }, - draw_size: vec2(right, top) * min_coef, + draw_size: vec2(right, top) * min_coefficient, offset: vec2( - render_size.x - right * min_coef, - render_size.y - top * min_coef, + render_size.x - right * min_coefficient, + render_size.y - top * min_coefficient, ) / 2.0, }, // Bottom Left @@ -86,10 +89,10 @@ impl TextureSlicer { min: vec2(base_rect.min.x, base_rect.max.y - bottom), max: vec2(base_rect.min.x + left, base_rect.max.y), }, - draw_size: vec2(left, bottom) * min_coef, + draw_size: vec2(left, bottom) * min_coefficient, offset: vec2( - -render_size.x + left * min_coef, - -render_size.y + bottom * min_coef, + -render_size.x + left * min_coefficient, + -render_size.y + bottom * min_coefficient, ) / 2.0, }, // Bottom Right Corner @@ -98,10 +101,10 @@ impl TextureSlicer { min: vec2(base_rect.max.x - right, base_rect.max.y - bottom), max: base_rect.max, }, - draw_size: vec2(right, bottom) * min_coef, + draw_size: vec2(right, bottom) * min_coefficient, offset: vec2( - render_size.x - right * min_coef, - -render_size.y + bottom * min_coef, + render_size.x - right * min_coefficient, + -render_size.y + bottom * min_coefficient, ) / 2.0, }, ] diff --git a/crates/bevy_state/src/state/mod.rs b/crates/bevy_state/src/state/mod.rs index d02d3a32ed452..78b515b9f8ff0 100644 --- a/crates/bevy_state/src/state/mod.rs +++ b/crates/bevy_state/src/state/mod.rs @@ -330,22 +330,22 @@ mod tests { } #[derive(PartialEq, Eq, Debug, Hash, Clone)] - enum TestNewcomputedState { + enum TestNewComputedState { A1, B2, B1, } - impl ComputedStates for TestNewcomputedState { + impl ComputedStates for TestNewComputedState { type SourceStates = (Option, Option); fn compute((s1, s2): (Option, Option)) -> Option { match (s1, s2) { - (Some(SimpleState::A), Some(SimpleState2::A1)) => Some(TestNewcomputedState::A1), + (Some(SimpleState::A), Some(SimpleState2::A1)) => Some(TestNewComputedState::A1), (Some(SimpleState::B(true)), Some(SimpleState2::B2)) => { - Some(TestNewcomputedState::B2) + Some(TestNewComputedState::B2) } - (Some(SimpleState::B(true)), _) => Some(TestNewcomputedState::B1), + (Some(SimpleState::B(true)), _) => Some(TestNewComputedState::B1), _ => None, } } @@ -356,7 +356,7 @@ mod tests { let mut world = World::new(); EventRegistry::register_event::>(&mut world); EventRegistry::register_event::>(&mut world); - EventRegistry::register_event::>(&mut world); + EventRegistry::register_event::>(&mut world); world.init_resource::>(); world.init_resource::>(); world.init_resource::(); @@ -370,13 +370,13 @@ mod tests { .get_mut(StateTransition) .expect("State Transition Schedule Doesn't Exist"); - TestNewcomputedState::register_computed_state_systems(apply_changes); + TestNewComputedState::register_computed_state_systems(apply_changes); SimpleState::register_state(apply_changes); SimpleState2::register_state(apply_changes); schedules.insert({ - let mut schedule = Schedule::new(OnEnter(TestNewcomputedState::A1)); + let mut schedule = Schedule::new(OnEnter(TestNewComputedState::A1)); schedule.add_systems(|mut count: ResMut| { count.enter += 1; }); @@ -384,7 +384,7 @@ mod tests { }); schedules.insert({ - let mut schedule = Schedule::new(OnExit(TestNewcomputedState::A1)); + let mut schedule = Schedule::new(OnExit(TestNewComputedState::A1)); schedule.add_systems(|mut count: ResMut| { count.exit += 1; }); @@ -392,7 +392,7 @@ mod tests { }); schedules.insert({ - let mut schedule = Schedule::new(OnEnter(TestNewcomputedState::B1)); + let mut schedule = Schedule::new(OnEnter(TestNewComputedState::B1)); schedule.add_systems(|mut count: ResMut| { count.enter += 1; }); @@ -400,7 +400,7 @@ mod tests { }); schedules.insert({ - let mut schedule = Schedule::new(OnExit(TestNewcomputedState::B1)); + let mut schedule = Schedule::new(OnExit(TestNewComputedState::B1)); schedule.add_systems(|mut count: ResMut| { count.exit += 1; }); @@ -408,7 +408,7 @@ mod tests { }); schedules.insert({ - let mut schedule = Schedule::new(OnEnter(TestNewcomputedState::B2)); + let mut schedule = Schedule::new(OnEnter(TestNewComputedState::B2)); schedule.add_systems(|mut count: ResMut| { count.enter += 1; }); @@ -416,7 +416,7 @@ mod tests { }); schedules.insert({ - let mut schedule = Schedule::new(OnExit(TestNewcomputedState::B2)); + let mut schedule = Schedule::new(OnExit(TestNewComputedState::B2)); schedule.add_systems(|mut count: ResMut| { count.exit += 1; }); @@ -429,14 +429,14 @@ mod tests { assert_eq!(world.resource::>().0, SimpleState::A); assert_eq!(world.resource::>().0, SimpleState2::A1); - assert!(!world.contains_resource::>()); + assert!(!world.contains_resource::>()); world.insert_resource(NextState::Pending(SimpleState::B(true))); world.insert_resource(NextState::Pending(SimpleState2::B2)); world.run_schedule(StateTransition); assert_eq!( - world.resource::>().0, - TestNewcomputedState::B2 + world.resource::>().0, + TestNewComputedState::B2 ); assert_eq!(world.resource::().enter, 1); assert_eq!(world.resource::().exit, 0); @@ -445,8 +445,8 @@ mod tests { world.insert_resource(NextState::Pending(SimpleState::A)); world.run_schedule(StateTransition); assert_eq!( - world.resource::>().0, - TestNewcomputedState::A1 + world.resource::>().0, + TestNewComputedState::A1 ); assert_eq!( world.resource::().enter, @@ -463,8 +463,8 @@ mod tests { world.insert_resource(NextState::Pending(SimpleState2::B2)); world.run_schedule(StateTransition); assert_eq!( - world.resource::>().0, - TestNewcomputedState::B2 + world.resource::>().0, + TestNewComputedState::B2 ); assert_eq!( world.resource::().enter, @@ -479,7 +479,7 @@ mod tests { world.insert_resource(NextState::Pending(SimpleState::A)); world.run_schedule(StateTransition); - assert!(!world.contains_resource::>()); + assert!(!world.contains_resource::>()); assert_eq!( world.resource::().enter, 3, diff --git a/crates/bevy_state/src/state/state_set.rs b/crates/bevy_state/src/state/state_set.rs index 67cbe1a90c069..fbb8f36bb8536 100644 --- a/crates/bevy_state/src/state/state_set.rs +++ b/crates/bevy_state/src/state/state_set.rs @@ -347,5 +347,5 @@ all_tuples!( 15, S, s, - ereader + event_reader ); diff --git a/crates/bevy_tasks/src/iter/adapters.rs b/crates/bevy_tasks/src/iter/adapters.rs index 617f5bdf868ca..1f8177a745bc6 100644 --- a/crates/bevy_tasks/src/iter/adapters.rs +++ b/crates/bevy_tasks/src/iter/adapters.rs @@ -190,7 +190,7 @@ where #[derive(Debug)] pub struct Cycle

{ pub(crate) iter: P, - pub(crate) curr: Option

, + pub(crate) current: Option

, } impl ParallelIterator for Cycle

@@ -199,11 +199,11 @@ where P: ParallelIterator + Clone, { fn next_batch(&mut self) -> Option { - self.curr + self.current .as_mut() .and_then(ParallelIterator::next_batch) .or_else(|| { - self.curr = Some(self.iter.clone()); + self.current = Some(self.iter.clone()); self.next_batch() }) } diff --git a/crates/bevy_tasks/src/iter/mod.rs b/crates/bevy_tasks/src/iter/mod.rs index 3910166904856..180eb66b81e20 100644 --- a/crates/bevy_tasks/src/iter/mod.rs +++ b/crates/bevy_tasks/src/iter/mod.rs @@ -107,9 +107,9 @@ where { pool.scope(|s| { while let Some(batch) = self.next_batch() { - let newf = f.clone(); + let new_f = f.clone(); s.spawn(async move { - batch.for_each(newf); + batch.for_each(new_f); }); } }); @@ -218,8 +218,8 @@ where let (mut a, mut b) = <(C, C)>::default(); pool.scope(|s| { while let Some(batch) = self.next_batch() { - let newf = f.clone(); - s.spawn(async move { batch.partition::, F>(newf) }); + let new_f = f.clone(); + s.spawn(async move { batch.partition::, F>(new_f) }); } }) .into_iter() @@ -244,9 +244,9 @@ where { pool.scope(|s| { while let Some(batch) = self.next_batch() { - let newf = f.clone(); - let newi = init.clone(); - s.spawn(async move { batch.fold(newi, newf) }); + let new_f = f.clone(); + let new_i = init.clone(); + s.spawn(async move { batch.fold(new_i, new_f) }); } }) } @@ -262,8 +262,8 @@ where { pool.scope(|s| { while let Some(mut batch) = self.next_batch() { - let newf = f.clone(); - s.spawn(async move { batch.all(newf) }); + let new_f = f.clone(); + s.spawn(async move { batch.all(new_f) }); } }) .into_iter() @@ -281,8 +281,8 @@ where { pool.scope(|s| { while let Some(mut batch) = self.next_batch() { - let newf = f.clone(); - s.spawn(async move { batch.any(newf) }); + let new_f = f.clone(); + s.spawn(async move { batch.any(new_f) }); } }) .into_iter() @@ -301,12 +301,12 @@ where { let poses = pool.scope(|s| { while let Some(batch) = self.next_batch() { - let mut newf = f.clone(); + let mut new_f = f.clone(); s.spawn(async move { let mut len = 0; let mut pos = None; for item in batch { - if pos.is_none() && newf(item) { + if pos.is_none() && new_f(item) { pos = Some(len); } len += 1; @@ -370,8 +370,8 @@ where { pool.scope(|s| { while let Some(batch) = self.next_batch() { - let newf = f.clone(); - s.spawn(async move { batch.max_by_key(newf) }); + let new_f = f.clone(); + s.spawn(async move { batch.max_by_key(new_f) }); } }) .into_iter() @@ -390,8 +390,8 @@ where { pool.scope(|s| { while let Some(batch) = self.next_batch() { - let newf = f.clone(); - s.spawn(async move { batch.max_by(newf) }); + let new_f = f.clone(); + s.spawn(async move { batch.max_by(new_f) }); } }) .into_iter() @@ -410,8 +410,8 @@ where { pool.scope(|s| { while let Some(batch) = self.next_batch() { - let newf = f.clone(); - s.spawn(async move { batch.min_by_key(newf) }); + let new_f = f.clone(); + s.spawn(async move { batch.min_by_key(new_f) }); } }) .into_iter() @@ -430,8 +430,8 @@ where { pool.scope(|s| { while let Some(batch) = self.next_batch() { - let newf = f.clone(); - s.spawn(async move { batch.min_by(newf) }); + let new_f = f.clone(); + s.spawn(async move { batch.min_by(new_f) }); } }) .into_iter() @@ -470,7 +470,7 @@ where { Cycle { iter: self, - curr: None, + current: None, } } diff --git a/crates/bevy_tasks/src/usages.rs b/crates/bevy_tasks/src/usages.rs index b260274a0fb11..20b74934189d1 100644 --- a/crates/bevy_tasks/src/usages.rs +++ b/crates/bevy_tasks/src/usages.rs @@ -2,7 +2,7 @@ use super::TaskPool; use core::ops::Deref; use std::sync::OnceLock; -macro_rules! taskpool { +macro_rules! task_pool { ($(#[$attr:meta])* ($static:ident, $type:ident)) => { static $static: OnceLock<$type> = OnceLock::new(); @@ -49,7 +49,7 @@ macro_rules! taskpool { }; } -taskpool! { +task_pool! { /// A newtype for a task pool for CPU-intensive work that must be completed to /// deliver the next frame /// @@ -59,7 +59,7 @@ taskpool! { (COMPUTE_TASK_POOL, ComputeTaskPool) } -taskpool! { +task_pool! { /// A newtype for a task pool for CPU-intensive work that may span across multiple frames /// /// See [`TaskPool`] documentation for details on Bevy tasks. @@ -67,7 +67,7 @@ taskpool! { (ASYNC_COMPUTE_TASK_POOL, AsyncComputeTaskPool) } -taskpool! { +task_pool! { /// A newtype for a task pool for IO-intensive work (i.e. tasks that spend very little time in a /// "woken" state) /// diff --git a/crates/bevy_text/src/error.rs b/crates/bevy_text/src/error.rs index cd4d884d459b0..8c856fcef72b6 100644 --- a/crates/bevy_text/src/error.rs +++ b/crates/bevy_text/src/error.rs @@ -2,7 +2,7 @@ use cosmic_text::CacheKey; use derive_more::derive::{Display, Error}; #[derive(Debug, PartialEq, Eq, Error, Display)] -/// Errors related to the textsystem +/// Errors related to the text system pub enum TextError { /// Font was not found, this could be that the font has not yet been loaded, or /// that the font failed to load for some other reason diff --git a/crates/bevy_text/src/pipeline.rs b/crates/bevy_text/src/pipeline.rs index 92b5cd902e814..b3670c9d5b27e 100644 --- a/crates/bevy_text/src/pipeline.rs +++ b/crates/bevy_text/src/pipeline.rs @@ -151,7 +151,7 @@ impl TextPipeline { metrics.font_size = metrics.font_size.max(0.000001); metrics.line_height = metrics.line_height.max(0.000001); - // Map text sections to cosmic-text spans, and ignore sections with negative or zero fontsizes, + // Map text sections to cosmic-text spans, and ignore sections with negative or zero font sizes, // since they cannot be rendered by cosmic-text. // // The section index is stored in the metadata of the spans, and could be used diff --git a/crates/bevy_transform/src/components/global_transform.rs b/crates/bevy_transform/src/components/global_transform.rs index 9a9961c60483a..880e6071cd612 100644 --- a/crates/bevy_transform/src/components/global_transform.rs +++ b/crates/bevy_transform/src/components/global_transform.rs @@ -372,7 +372,7 @@ mod test { ); } #[test] - fn reparented_usecase() { + fn reparented_use_case() { let t1 = GlobalTransform::from(Transform { translation: Vec3::new(1034.0, 34.0, -1324.34), rotation: Quat::from_euler(XYZ, 0.8, 1.9, 2.1), diff --git a/crates/bevy_ui/src/geometry.rs b/crates/bevy_ui/src/geometry.rs index 391085d0dcc2d..59d2103efd48a 100644 --- a/crates/bevy_ui/src/geometry.rs +++ b/crates/bevy_ui/src/geometry.rs @@ -644,7 +644,7 @@ mod tests { let viewport_size = vec2(500., 500.); for value in (-10..10).map(|value| value as f32) { - // for a square viewport there should be no difference between `Vw` and `Vh` and between `Vmin` and `Vmax`. + // for a square viewport there should be no difference between `Vw` and `Vh` and between `VMin` and `VMax`. assert_eq!( Val::Vw(value).resolve(size, viewport_size), Val::Vh(value).resolve(size, viewport_size) @@ -669,7 +669,7 @@ mod tests { } #[test] - fn val_auto_is_non_resolveable() { + fn val_auto_is_non_resolvable() { let size = 250.; let viewport_size = vec2(1000., 500.); let resolve_auto = Val::Auto.resolve(size, viewport_size); diff --git a/crates/bevy_ui/src/layout/mod.rs b/crates/bevy_ui/src/layout/mod.rs index aaa3f47050307..59e6d4d74d1a6 100644 --- a/crates/bevy_ui/src/layout/mod.rs +++ b/crates/bevy_ui/src/layout/mod.rs @@ -1049,7 +1049,7 @@ mod tests { } #[test] - fn measure_funcs_should_be_removed_on_content_size_removal() { + fn measure_functions_should_be_removed_on_content_size_removal() { let (mut world, mut ui_schedule) = setup_ui_test_world(); let content_size = Vec2::new(50., 25.); diff --git a/crates/bevy_ui/src/layout/ui_surface.rs b/crates/bevy_ui/src/layout/ui_surface.rs index 8f464abedbe81..2cb06eca60f30 100644 --- a/crates/bevy_ui/src/layout/ui_surface.rs +++ b/crates/bevy_ui/src/layout/ui_surface.rs @@ -275,7 +275,7 @@ impl UiSurface { /// Get the layout geometry for the taffy node corresponding to the ui node [`Entity`]. /// Does not compute the layout geometry, `compute_window_layouts` should be run before using this function. - /// On success returns a pair consisiting of the final resolved layout values after rounding + /// On success returns a pair consisting of the final resolved layout values after rounding /// and the size of the node after layout resolution but before rounding. pub fn get_layout(&mut self, entity: Entity) -> Result<(taffy::Layout, Vec2), LayoutError> { let Some(taffy_node) = self.entity_to_taffy.get(&entity) else { diff --git a/crates/bevy_ui/src/render/ui_material_pipeline.rs b/crates/bevy_ui/src/render/ui_material_pipeline.rs index c0bd6a0673f6f..17d03476389b1 100644 --- a/crates/bevy_ui/src/render/ui_material_pipeline.rs +++ b/crates/bevy_ui/src/render/ui_material_pipeline.rs @@ -80,7 +80,7 @@ where Render, ( queue_ui_material_nodes::.in_set(RenderSet::Queue), - prepare_uimaterial_nodes::.in_set(RenderSet::PrepareBindGroups), + prepare_ui_material_nodes::.in_set(RenderSet::PrepareBindGroups), ), ); } @@ -425,7 +425,7 @@ pub fn extract_ui_material_nodes( } #[allow(clippy::too_many_arguments)] -pub fn prepare_uimaterial_nodes( +pub fn prepare_ui_material_nodes( mut commands: Commands, render_device: Res, render_queue: Res, diff --git a/crates/bevy_ui/src/render/ui_texture_slice_pipeline.rs b/crates/bevy_ui/src/render/ui_texture_slice_pipeline.rs index 423a57bd1cde6..59adba64399fd 100644 --- a/crates/bevy_ui/src/render/ui_texture_slice_pipeline.rs +++ b/crates/bevy_ui/src/render/ui_texture_slice_pipeline.rs @@ -744,7 +744,7 @@ fn compute_texture_slices( sides_scale_mode, max_corner_scale, }) => { - let min_coeff = (target_size / image_size) + let min_coefficient = (target_size / image_size) .min_element() .min(*max_corner_scale); @@ -758,10 +758,10 @@ fn compute_texture_slices( // calculate the normalized extents of the target slices let border = [ - (border_rect.left / target_size.x) * min_coeff, - (border_rect.top / target_size.y) * min_coeff, - 1. - (border_rect.right / target_size.x) * min_coeff, - 1. - (border_rect.bottom / target_size.y) * min_coeff, + (border_rect.left / target_size.x) * min_coefficient, + (border_rect.top / target_size.y) * min_coefficient, + 1. - (border_rect.right / target_size.x) * min_coefficient, + 1. - (border_rect.bottom / target_size.y) * min_coefficient, ]; let image_side_width = image_size.x * (slices[2] - slices[0]); diff --git a/crates/bevy_ui/src/stack.rs b/crates/bevy_ui/src/stack.rs index e419ce67fd771..83ccc9a23c0d5 100644 --- a/crates/bevy_ui/src/stack.rs +++ b/crates/bevy_ui/src/stack.rs @@ -35,7 +35,7 @@ impl ChildBufferCache { /// Generates the render stack for UI nodes. /// -/// Create a list of root nodes from unparented entities and entities with a `GlobalZIndex` component. +/// Create a list of root nodes from parentless entities and entities with a `GlobalZIndex` component. /// Then build the `UiStack` from a walk of the existing layout trees starting from each root node, /// filtering branches by `Without`so that we don't revisit nodes. #[allow(clippy::too_many_arguments)] diff --git a/crates/bevy_ui/src/ui_node.rs b/crates/bevy_ui/src/ui_node.rs index 05fb3ca4d3e46..172c0d0e33b96 100644 --- a/crates/bevy_ui/src/ui_node.rs +++ b/crates/bevy_ui/src/ui_node.rs @@ -1408,7 +1408,7 @@ impl GridTrack { } /// Create a grid track with a percentage of the viewport's smaller dimension - pub fn vmin>(value: f32) -> T { + pub fn v_min>(value: f32) -> T { Self { min_sizing_function: MinTrackSizingFunction::VMin(value), max_sizing_function: MaxTrackSizingFunction::VMin(value), @@ -1417,7 +1417,7 @@ impl GridTrack { } /// Create a grid track with a percentage of the viewport's larger dimension - pub fn vmax>(value: f32) -> T { + pub fn v_max>(value: f32) -> T { Self { min_sizing_function: MinTrackSizingFunction::VMax(value), max_sizing_function: MaxTrackSizingFunction::VMax(value), @@ -1615,19 +1615,19 @@ impl RepeatedGridTrack { } /// Create a repeating set of grid tracks with the percentage size of the viewport's smaller dimension - pub fn vmin>(repetition: impl Into, value: f32) -> T { + pub fn v_min>(repetition: impl Into, value: f32) -> T { Self { repetition: repetition.into(), - tracks: SmallVec::from_buf([GridTrack::vmin(value)]), + tracks: SmallVec::from_buf([GridTrack::v_min(value)]), } .into() } /// Create a repeating set of grid tracks with the percentage size of the viewport's larger dimension - pub fn vmax>(repetition: impl Into, value: f32) -> T { + pub fn v_max>(repetition: impl Into, value: f32) -> T { Self { repetition: repetition.into(), - tracks: SmallVec::from_buf([GridTrack::vmax(value)]), + tracks: SmallVec::from_buf([GridTrack::v_max(value)]), } .into() } diff --git a/crates/bevy_utils/src/parallel_queue.rs b/crates/bevy_utils/src/parallel_queue.rs index 01377c7573beb..a5593de4dee5e 100644 --- a/crates/bevy_utils/src/parallel_queue.rs +++ b/crates/bevy_utils/src/parallel_queue.rs @@ -12,7 +12,7 @@ pub struct Parallel { locals: ThreadLocal>, } -/// A scope guard of a `Parallel`, when this struct is dropped ,the value will writeback to its `Parallel` +/// A scope guard of a `Parallel`, when this struct is dropped, the value will write back to its `Parallel`. impl Parallel { /// Gets a mutable iterator over all of the per-thread queues. pub fn iter_mut(&mut self) -> impl Iterator { @@ -50,8 +50,8 @@ where /// Drains all enqueued items from all threads and returns an iterator over them. /// /// Unlike [`Vec::drain`], this will piecemeal remove chunks of the data stored. - /// If iteration is terminated part way, the rest of the enqueued items in the same - /// chunk will be dropped, and the rest of the undrained elements will remain. + /// If iteration is terminated part-way, the rest of the enqueued items in the same + /// chunk will be dropped and the rest of the undrained elements will remain. /// /// The ordering is not guaranteed. pub fn drain(&mut self) -> impl Iterator + '_ { diff --git a/crates/bevy_window/src/lib.rs b/crates/bevy_window/src/lib.rs index b9c458780b850..607a286af8ee1 100644 --- a/crates/bevy_window/src/lib.rs +++ b/crates/bevy_window/src/lib.rs @@ -138,7 +138,7 @@ impl Plugin for WindowPlugin { ExitCondition::OnAllClosed => { app.add_systems(PostUpdate, exit_on_all_closed); } - ExitCondition::DontExit => {} + ExitCondition::DoNotExit => {} } if self.close_when_requested { @@ -189,7 +189,7 @@ pub enum ExitCondition { /// event when the app should exit. If this does not occur, you will /// create 'headless' processes (processes without windows), which may /// surprise your users. - DontExit, + DoNotExit, } /// [`AndroidApp`] provides an interface to query the application state as well as monitor events diff --git a/crates/bevy_window/src/monitor.rs b/crates/bevy_window/src/monitor.rs index 10cb3b226faf9..93b7334dff18d 100644 --- a/crates/bevy_window/src/monitor.rs +++ b/crates/bevy_window/src/monitor.rs @@ -31,7 +31,7 @@ pub struct Monitor { pub physical_width: u32, /// The position of the monitor in physical pixels pub physical_position: IVec2, - /// The refresh rate of the monitor in millihertz + /// The refresh rate of the monitor in mHz pub refresh_rate_millihertz: Option, /// The scale factor of the monitor pub scale_factor: f64, diff --git a/crates/bevy_window/src/window.rs b/crates/bevy_window/src/window.rs index 97e4cf3c3ea19..ace1d689e9510 100644 --- a/crates/bevy_window/src/window.rs +++ b/crates/bevy_window/src/window.rs @@ -168,8 +168,7 @@ pub struct Window { pub resize_constraints: WindowResizeConstraints, /// Should the window be resizable? /// - /// Note: This does not stop the program from fullscreening/setting - /// the size programmatically. + /// Note: This does not stop the program from going fullscreen/setting the size programmatically. pub resizable: bool, /// Specifies which window control buttons should be enabled. /// diff --git a/crates/bevy_winit/src/lib.rs b/crates/bevy_winit/src/lib.rs index 80b04b0de7342..e6f608114eabb 100644 --- a/crates/bevy_winit/src/lib.rs +++ b/crates/bevy_winit/src/lib.rs @@ -5,7 +5,7 @@ html_favicon_url = "https://bevyengine.org/assets/icon.png" )] -//! `bevy_winit` provides utilities to handle window creation and the eventloop through [`winit`] +//! `bevy_winit` provides utilities to handle window creation and the event loop through [`winit`] //! //! Most commonly, the [`WinitPlugin`] is used as part of //! [`DefaultPlugins`](https://docs.rs/bevy/latest/bevy/struct.DefaultPlugins.html). diff --git a/crates/bevy_winit/src/state.rs b/crates/bevy_winit/src/state.rs index a9d4831592ff2..354a45f7b90f2 100644 --- a/crates/bevy_winit/src/state.rs +++ b/crates/bevy_winit/src/state.rs @@ -865,7 +865,7 @@ pub fn winit_runner(mut app: App) -> AppExit { // If everything is working correctly then the event loop only exits after it's sent an exit code. runner_state.app_exit.unwrap_or_else(|| { - error!("Failed to receive a app exit code! This is a bug"); + error!("Failed to receive an app exit code! This is a bug."); AppExit::error() }) } diff --git a/crates/bevy_winit/src/system.rs b/crates/bevy_winit/src/system.rs index f46f0b06ca3fb..148c08719ef25 100644 --- a/crates/bevy_winit/src/system.rs +++ b/crates/bevy_winit/src/system.rs @@ -31,7 +31,7 @@ use crate::{ convert_enabled_buttons, convert_resize_direction, convert_window_level, convert_window_theme, convert_winit_theme, }, - get_best_videomode, get_fitting_videomode, select_monitor, + get_best_video_mode, get_fitting_video_mode, select_monitor, state::react_to_resize, winit_monitors::WinitMonitors, CreateMonitorParams, CreateWindowParams, WinitWindows, @@ -290,8 +290,8 @@ pub(crate) fn changed_windows( )))) } mode @ (WindowMode::Fullscreen(_) | WindowMode::SizedFullscreen(_)) => { - let videomode = match mode { - WindowMode::Fullscreen(monitor_selection) => get_best_videomode( + let video_mode = match mode { + WindowMode::Fullscreen(monitor_selection) => get_best_video_mode( &select_monitor( &monitors, winit_window.primary_monitor(), @@ -302,7 +302,7 @@ pub(crate) fn changed_windows( panic!("Could not find monitor for {:?}", monitor_selection) }), ), - WindowMode::SizedFullscreen(monitor_selection) => get_fitting_videomode( + WindowMode::SizedFullscreen(monitor_selection) => get_fitting_video_mode( &select_monitor( &monitors, winit_window.primary_monitor(), @@ -318,7 +318,7 @@ pub(crate) fn changed_windows( _ => unreachable!(), }; - Some(Some(winit::window::Fullscreen::Exclusive(videomode))) + Some(Some(winit::window::Fullscreen::Exclusive(video_mode))) } WindowMode::Windowed => Some(None), }; diff --git a/crates/bevy_winit/src/winit_windows.rs b/crates/bevy_winit/src/winit_windows.rs index ff08b20b4053d..989aa99307cbc 100644 --- a/crates/bevy_winit/src/winit_windows.rs +++ b/crates/bevy_winit/src/winit_windows.rs @@ -78,19 +78,19 @@ impl WinitWindows { let select_monitor = &maybe_selected_monitor .clone() .expect("Unable to get monitor."); - let videomode = get_best_videomode(select_monitor); - winit_window_attributes.with_fullscreen(Some(Fullscreen::Exclusive(videomode))) + let video_mode = get_best_video_mode(select_monitor); + winit_window_attributes.with_fullscreen(Some(Fullscreen::Exclusive(video_mode))) } WindowMode::SizedFullscreen(_) => { let select_monitor = &maybe_selected_monitor .clone() .expect("Unable to get monitor."); - let videomode = get_fitting_videomode( + let video_mode = get_fitting_video_mode( select_monitor, window.width() as u32, window.height() as u32, ); - winit_window_attributes.with_fullscreen(Some(Fullscreen::Exclusive(videomode))) + winit_window_attributes.with_fullscreen(Some(Fullscreen::Exclusive(video_mode))) } WindowMode::Windowed => { if let Some(position) = winit_window_position( @@ -285,13 +285,13 @@ impl WinitWindows { winit_window.set_cursor_visible(window.cursor_options.visible); - // Do not set the cursor hittest on window creation if it's false, as it will always fail on + // Do not set the cursor hit test on window creation if it's false, as it will always fail on // some platforms and log an unfixable warning. if !window.cursor_options.hit_test { - if let Err(err) = winit_window.set_cursor_hittest(window.cursor_options.hit_test) { + if let Err(error) = winit_window.set_cursor_hittest(window.cursor_options.hit_test) { warn!( "Could not set cursor hit test for window {:?}: {:?}", - window.title, err + window.title, error ); } } @@ -332,7 +332,7 @@ impl WinitWindows { /// Gets the "best" video mode which fits the given dimensions. /// /// The heuristic for "best" prioritizes width, height, and refresh rate in that order. -pub fn get_fitting_videomode(monitor: &MonitorHandle, width: u32, height: u32) -> VideoModeHandle { +pub fn get_fitting_video_mode(monitor: &MonitorHandle, width: u32, height: u32) -> VideoModeHandle { let mut modes = monitor.video_modes().collect::>(); fn abs_diff(a: u32, b: u32) -> u32 { @@ -363,7 +363,7 @@ pub fn get_fitting_videomode(monitor: &MonitorHandle, width: u32, height: u32) - /// Gets the "best" video-mode handle from a monitor. /// /// The heuristic for "best" prioritizes width, height, and refresh rate in that order. -pub fn get_best_videomode(monitor: &MonitorHandle) -> VideoModeHandle { +pub fn get_best_video_mode(monitor: &MonitorHandle) -> VideoModeHandle { let mut modes = monitor.video_modes().collect::>(); modes.sort_by(|a, b| { use core::cmp::Ordering::*; @@ -395,22 +395,22 @@ pub(crate) fn attempt_grab( .or_else(|_e| winit_window.set_cursor_grab(WinitCursorGrabMode::Confined)), }; - if let Err(err) = grab_result { - let err_desc = match grab_mode { + if let Err(error) = grab_result { + let description = match grab_mode { CursorGrabMode::Confined | CursorGrabMode::Locked => "grab", CursorGrabMode::None => "ungrab", }; - bevy_utils::tracing::error!("Unable to {} cursor: {}", err_desc, err); - Err(err) + bevy_utils::tracing::error!("Unable to {} cursor: {}", description, error); + Err(error) } else { Ok(()) } } /// Compute the physical window position for a given [`WindowPosition`]. -// Ideally we could generify this across window backends, but we only really have winit atm -// so whatever. +// Ideally we could make this generic across window backends, +// but we only really have winit atm, so it is whatever. pub fn winit_window_position( position: &WindowPosition, resolution: &WindowResolution, diff --git a/docs-template/EXAMPLE_README.md.tpl b/docs-template/EXAMPLE_README.md.tpl index c1fbfc08eb153..829dbc4aaf583 100644 --- a/docs-template/EXAMPLE_README.md.tpl +++ b/docs-template/EXAMPLE_README.md.tpl @@ -65,24 +65,24 @@ git checkout v0.4.0 ## Hello, World! -Example | Description ---- | --- -[`hello_world.rs`](./hello_world.rs) | Runs a minimal example that outputs "hello world" +|Example | Description| +|--- | ---| +|[`hello_world.rs`](./hello_world.rs) | Runs a minimal example that outputs "hello world"| # Cross-Platform Examples {% for category, details in all_examples %} ## {{ category }} {% if details.description is string %}{{ details.description }} -{% endif %}Example | Description ---- | --- -{% for example in details.examples %}[{{ example.name }}](../{{ example.path }}) | {{ example.description }} +{% endif %}|Example | Description| +|--- | ---| +{% for example in details.examples %}|[{{ example.name }}](../{{ example.path }}) | {{ example.description }}| {% endfor %}{% endfor %} # Tests -Example | Description ---- | --- -[How to Test Systems](../tests/how_to_test_systems.rs) | How to test systems with commands, queries or resources +|Example | Description| +|--- | ---| +|[How to Test Systems](../tests/how_to_test_systems.rs) | How to test systems with commands, queries or resources| # Platform-Specific Examples @@ -157,7 +157,7 @@ adb uninstall org.bevyengine.example In its examples, Bevy targets the minimum Android API that Play Store [requires](https://developer.android.com/distribute/best-practices/develop/target-sdk) to upload and update apps. -Users of older phones may want to use an older API when testing. By default, Bevy uses [`GameAvtivity`](https://developer.android.com/games/agdk/game-activity), which only works for Android API level 31 and higher, so if you want to use older API, you need to switch to `NativeActivity`. +Users of older phones may want to use an older API when testing. By default, Bevy uses [`GameActivity`](https://developer.android.com/games/agdk/game-activity), which only works for Android API level 31 and higher, so if you want to use older API, you need to switch to `NativeActivity`. To use `NativeActivity`, you need to edit it in `cargo.toml` manually like this: @@ -171,9 +171,9 @@ Then build it as the [Build & Run](#build--run) section stated above. You can also build an APK with `cargo-apk`, a simpler and deprecated tool which doesn't support `GameActivity`. If you want to use this, there is a [folder](./mobile/android_basic) inside the mobile example with instructions. -Example | File | Description ---- | --- | --- -`android` | [`mobile/src/lib.rs`](./mobile/src/lib.rs) | A 3d Scene with a button and playing sound +|Example | File | Description| +|--- | --- | ---| +|`android` | [`mobile/src/lib.rs`](./mobile/src/lib.rs) | A 3d Scene with a button and playing sound| ## iOS @@ -215,9 +215,9 @@ open bevy_mobile_example.xcodeproj/ which will open xcode. You then must push the zoom zoom play button and wait for the magic. -Example | File | Description ---- | --- | --- -`ios` | [`mobile/src/lib.rs`](./mobile/src/lib.rs) | A 3d Scene with a button and playing sound +|Example | File | Description| +|--- | --- | ---| +|`ios` | [`mobile/src/lib.rs`](./mobile/src/lib.rs) | A 3d Scene with a button and playing sound| ## Wasm @@ -303,7 +303,7 @@ may not be worth keeping due to compilation time increases. For a small project with a basic 3d model and two lights, the generated file sizes are, as of July 2022, as follows: -|profile | wasm-opt | no wasm-opt | +| profile | wasm-opt | no wasm-opt | |----------------------------------|----------|-------------| |Default | 8.5M | 13.0M | |opt-level = "z" | 6.1M | 12.7M | diff --git a/examples/3d/irradiance_volumes.rs b/examples/3d/irradiance_volumes.rs index b3da971e3680c..39e097f895b3c 100644 --- a/examples/3d/irradiance_volumes.rs +++ b/examples/3d/irradiance_volumes.rs @@ -469,7 +469,7 @@ fn handle_mouse_clicks( }; let plane_intersection = ray.origin + ray.direction.normalize() * ray_distance; - // Move all the main objeccts. + // Move all the main objects. for mut transform in main_objects.iter_mut() { transform.translation = vec3( plane_intersection.x, diff --git a/examples/3d/motion_blur.rs b/examples/3d/motion_blur.rs index 94a203ea69301..39fc2bf17b6d3 100644 --- a/examples/3d/motion_blur.rs +++ b/examples/3d/motion_blur.rs @@ -114,13 +114,13 @@ fn spawn_cars( let box_mesh = meshes.add(Cuboid::new(0.3, 0.15, 0.55)); let cylinder = meshes.add(Cylinder::default()); let logo = asset_server.load("branding/icon.png"); - let wheel_matl = materials.add(StandardMaterial { + let wheel_material = materials.add(StandardMaterial { base_color: Color::WHITE, base_color_texture: Some(logo.clone()), ..default() }); - let mut matl = |color| { + let mut material = |color| { materials.add(StandardMaterial { base_color: color, ..default() @@ -128,14 +128,14 @@ fn spawn_cars( }; let colors = [ - matl(Color::linear_rgb(1.0, 0.0, 0.0)), - matl(Color::linear_rgb(1.0, 1.0, 0.0)), - matl(Color::BLACK), - matl(Color::linear_rgb(0.0, 0.0, 1.0)), - matl(Color::linear_rgb(0.0, 1.0, 0.0)), - matl(Color::linear_rgb(1.0, 0.0, 1.0)), - matl(Color::linear_rgb(0.5, 0.5, 0.0)), - matl(Color::linear_rgb(1.0, 0.5, 0.0)), + material(Color::linear_rgb(1.0, 0.0, 0.0)), + material(Color::linear_rgb(1.0, 1.0, 0.0)), + material(Color::BLACK), + material(Color::linear_rgb(0.0, 0.0, 1.0)), + material(Color::linear_rgb(0.0, 1.0, 0.0)), + material(Color::linear_rgb(1.0, 0.0, 1.0)), + material(Color::linear_rgb(0.5, 0.5, 0.0)), + material(Color::linear_rgb(1.0, 0.5, 0.0)), ]; for i in 0..N_CARS { @@ -157,7 +157,7 @@ fn spawn_cars( let mut spawn_wheel = |x: f32, z: f32| { parent.spawn(( Mesh3d(cylinder.clone()), - MeshMaterial3d(wheel_matl.clone()), + MeshMaterial3d(wheel_material.clone()), Transform::from_xyz(0.14 * x, -0.045, 0.15 * z) .with_scale(Vec3::new(0.15, 0.04, 0.15)) .with_rotation(Quat::from_rotation_z(std::f32::consts::FRAC_PI_2)), @@ -179,7 +179,7 @@ fn spawn_barriers( ) { const N_CONES: usize = 100; let capsule = meshes.add(Capsule3d::default()); - let matl = materials.add(StandardMaterial { + let material = materials.add(StandardMaterial { base_color: Color::srgb_u8(255, 87, 51), reflectance: 1.0, ..default() @@ -192,7 +192,7 @@ fn spawn_barriers( ); commands.spawn(( Mesh3d(capsule.clone()), - MeshMaterial3d(matl.clone()), + MeshMaterial3d(material.clone()), Transform::from_xyz(pos.x, -0.65, pos.y).with_scale(Vec3::splat(0.07)), )); } diff --git a/examples/3d/order_independent_transparency.rs b/examples/3d/order_independent_transparency.rs index 03590eb21b3ca..74e8edc4d18b2 100644 --- a/examples/3d/order_independent_transparency.rs +++ b/examples/3d/order_independent_transparency.rs @@ -102,7 +102,7 @@ fn cycle_scenes( mut scene_id: Local, ) { if keyboard_input.just_pressed(KeyCode::KeyC) { - // depsawn current scene + // despawn current scene for e in &q { commands.entity(e).despawn_recursive(); } diff --git a/examples/3d/shadow_biases.rs b/examples/3d/shadow_biases.rs index 10fe6cffec51d..ddca90dbd53e0 100644 --- a/examples/3d/shadow_biases.rs +++ b/examples/3d/shadow_biases.rs @@ -135,7 +135,7 @@ fn setup( p.spawn(TextSpan::new("0.0")); p.spawn(TextSpan::new("]\n")); p.spawn(TextSpan::new( - "left/right/up/down/pgup/pgdown - adjust light position (looking at 0,0,0) [", + "Left/Right/Up/Down/PgUp/PgDown - adjust light position (looking at 0,0,0) [", )); p.spawn(TextSpan(format!("{:.1},", light_transform.translation.x))); p.spawn(TextSpan(format!(" {:.1},", light_transform.translation.y))); diff --git a/examples/README.md b/examples/README.md index 92bf3f188be1b..2e89487de49e1 100644 --- a/examples/README.md +++ b/examples/README.md @@ -92,318 +92,318 @@ git checkout v0.4.0 ## Hello, World! -Example | Description ---- | --- -[`hello_world.rs`](./hello_world.rs) | Runs a minimal example that outputs "hello world" +|Example | Description| +|--- | ---| +|[`hello_world.rs`](./hello_world.rs) | Runs a minimal example that outputs "hello world"| # Cross-Platform Examples ## 2D Rendering -Example | Description ---- | --- -[2D Bloom](../examples/2d/bloom_2d.rs) | Illustrates bloom post-processing in 2d -[2D Bounding Volume Intersections](../examples/2d/bounding_2d.rs) | Showcases bounding volumes and intersection tests -[2D Rotation](../examples/2d/rotation.rs) | Demonstrates rotating entities in 2D with quaternions -[2D Shapes](../examples/2d/2d_shapes.rs) | Renders simple 2D primitive shapes like circles and polygons -[2D Viewport To World](../examples/2d/2d_viewport_to_world.rs) | Demonstrates how to use the `Camera::viewport_to_world_2d` method -[2D Wireframe](../examples/2d/wireframe_2d.rs) | Showcases wireframes for 2d meshes -[Arc 2D Meshes](../examples/2d/mesh2d_arcs.rs) | Demonstrates UV-mapping of the circular segment and sector primitives -[CPU Drawing](../examples/2d/cpu_draw.rs) | Manually read/write the pixels of a texture -[Custom glTF vertex attribute 2D](../examples/2d/custom_gltf_vertex_attribute.rs) | Renders a glTF mesh in 2D with a custom vertex attribute -[Manual Mesh 2D](../examples/2d/mesh2d_manual.rs) | Renders a custom mesh "manually" with "mid-level" renderer apis -[Mesh 2D](../examples/2d/mesh2d.rs) | Renders a 2d mesh -[Mesh 2D With Vertex Colors](../examples/2d/mesh2d_vertex_color_texture.rs) | Renders a 2d mesh with vertex color attributes -[Mesh2d Alpha Mode](../examples/2d/mesh2d_alpha_mode.rs) | Used to test alpha modes with mesh2d -[Move Sprite](../examples/2d/move_sprite.rs) | Changes the transform of a sprite -[Pixel Grid Snapping](../examples/2d/pixel_grid_snap.rs) | Shows how to create graphics that snap to the pixel grid by rendering to a texture in 2D -[Sprite](../examples/2d/sprite.rs) | Renders a sprite -[Sprite Animation](../examples/2d/sprite_animation.rs) | Animates a sprite in response to an event -[Sprite Flipping](../examples/2d/sprite_flipping.rs) | Renders a sprite flipped along an axis -[Sprite Sheet](../examples/2d/sprite_sheet.rs) | Renders an animated sprite -[Sprite Slice](../examples/2d/sprite_slice.rs) | Showcases slicing sprites into sections that can be scaled independently via the 9-patch technique -[Sprite Tile](../examples/2d/sprite_tile.rs) | Renders a sprite tiled in a grid -[Text 2D](../examples/2d/text2d.rs) | Generates text in 2D -[Texture Atlas](../examples/2d/texture_atlas.rs) | Generates a texture atlas (sprite sheet) from individual sprites -[Transparency in 2D](../examples/2d/transparency_2d.rs) | Demonstrates transparency in 2d +|Example | Description| +|--- | ---| +|[2D Bloom](../examples/2d/bloom_2d.rs) | Illustrates bloom post-processing in 2d| +|[2D Bounding Volume Intersections](../examples/2d/bounding_2d.rs) | Showcases bounding volumes and intersection tests| +|[2D Rotation](../examples/2d/rotation.rs) | Demonstrates rotating entities in 2D with quaternions| +|[2D Shapes](../examples/2d/2d_shapes.rs) | Renders simple 2D primitive shapes like circles and polygons| +|[2D Viewport To World](../examples/2d/2d_viewport_to_world.rs) | Demonstrates how to use the `Camera::viewport_to_world_2d` method| +|[2D Wireframe](../examples/2d/wireframe_2d.rs) | Showcases wireframes for 2d meshes| +|[Arc 2D Meshes](../examples/2d/mesh2d_arcs.rs) | Demonstrates UV-mapping of the circular segment and sector primitives| +|[CPU Drawing](../examples/2d/cpu_draw.rs) | Manually read/write the pixels of a texture| +|[Custom glTF vertex attribute 2D](../examples/2d/custom_gltf_vertex_attribute.rs) | Renders a glTF mesh in 2D with a custom vertex attribute| +|[Manual Mesh 2D](../examples/2d/mesh2d_manual.rs) | Renders a custom mesh "manually" with "mid-level" renderer apis| +|[Mesh 2D](../examples/2d/mesh2d.rs) | Renders a 2d mesh| +|[Mesh 2D With Vertex Colors](../examples/2d/mesh2d_vertex_color_texture.rs) | Renders a 2d mesh with vertex color attributes| +|[Mesh2d Alpha Mode](../examples/2d/mesh2d_alpha_mode.rs) | Used to test alpha modes with mesh2d| +|[Move Sprite](../examples/2d/move_sprite.rs) | Changes the transform of a sprite| +|[Pixel Grid Snapping](../examples/2d/pixel_grid_snap.rs) | Shows how to create graphics that snap to the pixel grid by rendering to a texture in 2D| +|[Sprite](../examples/2d/sprite.rs) | Renders a sprite| +|[Sprite Animation](../examples/2d/sprite_animation.rs) | Animates a sprite in response to an event| +|[Sprite Flipping](../examples/2d/sprite_flipping.rs) | Renders a sprite flipped along an axis| +|[Sprite Sheet](../examples/2d/sprite_sheet.rs) | Renders an animated sprite| +|[Sprite Slice](../examples/2d/sprite_slice.rs) | Showcases slicing sprites into sections that can be scaled independently via the 9-patch technique| +|[Sprite Tile](../examples/2d/sprite_tile.rs) | Renders a sprite tiled in a grid| +|[Text 2D](../examples/2d/text2d.rs) | Generates text in 2D| +|[Texture Atlas](../examples/2d/texture_atlas.rs) | Generates a texture atlas (sprite sheet) from individual sprites| +|[Transparency in 2D](../examples/2d/transparency_2d.rs) | Demonstrates transparency in 2d| ## 3D Rendering -Example | Description ---- | --- -[3D Bloom](../examples/3d/bloom_3d.rs) | Illustrates bloom configuration using HDR and emissive materials -[3D Scene](../examples/3d/3d_scene.rs) | Simple 3D scene with basic shapes and lighting -[3D Shapes](../examples/3d/3d_shapes.rs) | A scene showcasing the built-in 3D shapes -[3D Viewport To World](../examples/3d/3d_viewport_to_world.rs) | Demonstrates how to use the `Camera::viewport_to_world` method -[Animated Material](../examples/3d/animated_material.rs) | Shows how to animate material properties -[Anisotropy](../examples/3d/anisotropy.rs) | Displays an example model with anisotropy -[Anti-aliasing](../examples/3d/anti_aliasing.rs) | Compares different anti-aliasing methods -[Atmospheric Fog](../examples/3d/atmospheric_fog.rs) | A scene showcasing the atmospheric fog effect -[Auto Exposure](../examples/3d/auto_exposure.rs) | A scene showcasing auto exposure -[Blend Modes](../examples/3d/blend_modes.rs) | Showcases different blend modes -[Built-in postprocessing](../examples/3d/post_processing.rs) | Demonstrates the built-in postprocessing features -[Camera sub view](../examples/3d/camera_sub_view.rs) | Demonstrates using different sub view effects on a camera -[Clearcoat](../examples/3d/clearcoat.rs) | Demonstrates the clearcoat PBR feature -[Color grading](../examples/3d/color_grading.rs) | Demonstrates color grading -[Deferred Rendering](../examples/3d/deferred_rendering.rs) | Renders meshes with both forward and deferred pipelines -[Depth of field](../examples/3d/depth_of_field.rs) | Demonstrates depth of field -[Fog](../examples/3d/fog.rs) | A scene showcasing the distance fog effect -[Fog volumes](../examples/3d/fog_volumes.rs) | Demonstrates fog volumes -[Generate Custom Mesh](../examples/3d/generate_custom_mesh.rs) | Simple showcase of how to generate a custom mesh with a custom texture -[Irradiance Volumes](../examples/3d/irradiance_volumes.rs) | Demonstrates irradiance volumes -[Lighting](../examples/3d/lighting.rs) | Illustrates various lighting options in a simple scene -[Lightmaps](../examples/3d/lightmaps.rs) | Rendering a scene with baked lightmaps -[Lines](../examples/3d/lines.rs) | Create a custom material to draw 3d lines -[Load glTF](../examples/3d/load_gltf.rs) | Loads and renders a glTF file as a scene -[Load glTF extras](../examples/3d/load_gltf_extras.rs) | Loads and renders a glTF file as a scene, including the gltf extras -[Mesh Ray Cast](../examples/3d/mesh_ray_cast.rs) | Demonstrates ray casting with the `MeshRayCast` system parameter -[Meshlet](../examples/3d/meshlet.rs) | Meshlet rendering for dense high-poly scenes (experimental) -[Motion Blur](../examples/3d/motion_blur.rs) | Demonstrates per-pixel motion blur -[Order Independent Transparency](../examples/3d/order_independent_transparency.rs) | Demonstrates how to use OIT -[Orthographic View](../examples/3d/orthographic.rs) | Shows how to create a 3D orthographic view (for isometric-look in games or CAD applications) -[Parallax Mapping](../examples/3d/parallax_mapping.rs) | Demonstrates use of a normal map and depth map for parallax mapping -[Parenting](../examples/3d/parenting.rs) | Demonstrates parent->child relationships and relative transformations -[Percentage-closer soft shadows](../examples/3d/pcss.rs) | Demonstrates percentage-closer soft shadows (PCSS) -[Physically Based Rendering](../examples/3d/pbr.rs) | Demonstrates use of Physically Based Rendering (PBR) properties -[Query glTF primitives](../examples/3d/query_gltf_primitives.rs) | Query primitives in a glTF scene -[Reflection Probes](../examples/3d/reflection_probes.rs) | Demonstrates reflection probes -[Render to Texture](../examples/3d/render_to_texture.rs) | Shows how to render to a texture, useful for mirrors, UI, or exporting images -[Rotate Environment Map](../examples/3d/rotate_environment_map.rs) | Demonstrates how to rotate the skybox and the environment map simultaneously -[Screen Space Ambient Occlusion](../examples/3d/ssao.rs) | A scene showcasing screen space ambient occlusion -[Screen Space Reflections](../examples/3d/ssr.rs) | Demonstrates screen space reflections with water ripples -[Scrolling fog](../examples/3d/scrolling_fog.rs) | Demonstrates how to create the effect of fog moving in the wind -[Shadow Biases](../examples/3d/shadow_biases.rs) | Demonstrates how shadow biases affect shadows in a 3d scene -[Shadow Caster and Receiver](../examples/3d/shadow_caster_receiver.rs) | Demonstrates how to prevent meshes from casting/receiving shadows in a 3d scene -[Skybox](../examples/3d/skybox.rs) | Load a cubemap texture onto a cube like a skybox and cycle through different compressed texture formats. -[Spherical Area Lights](../examples/3d/spherical_area_lights.rs) | Demonstrates how point light radius values affect light behavior -[Split Screen](../examples/3d/split_screen.rs) | Demonstrates how to render two cameras to the same window to accomplish "split screen" -[Spotlight](../examples/3d/spotlight.rs) | Illustrates spot lights -[Texture](../examples/3d/texture.rs) | Shows configuration of texture materials -[Tonemapping](../examples/3d/tonemapping.rs) | Compares tonemapping options -[Transmission](../examples/3d/transmission.rs) | Showcases light transmission in the PBR material -[Transparency in 3D](../examples/3d/transparency_3d.rs) | Demonstrates transparency in 3d -[Two Passes](../examples/3d/two_passes.rs) | Renders two 3d passes to the same window from different perspectives -[Update glTF Scene](../examples/3d/update_gltf_scene.rs) | Update a scene from a glTF file, either by spawning the scene as a child of another entity, or by accessing the entities of the scene -[Vertex Colors](../examples/3d/vertex_colors.rs) | Shows the use of vertex colors -[Visibility range](../examples/3d/visibility_range.rs) | Demonstrates visibility ranges -[Volumetric fog](../examples/3d/volumetric_fog.rs) | Demonstrates volumetric fog and lighting -[Wireframe](../examples/3d/wireframe.rs) | Showcases wireframe rendering +|Example | Description| +|--- | ---| +|[3D Bloom](../examples/3d/bloom_3d.rs) | Illustrates bloom configuration using HDR and emissive materials| +|[3D Scene](../examples/3d/3d_scene.rs) | Simple 3D scene with basic shapes and lighting| +|[3D Shapes](../examples/3d/3d_shapes.rs) | A scene showcasing the built-in 3D shapes| +|[3D Viewport To World](../examples/3d/3d_viewport_to_world.rs) | Demonstrates how to use the `Camera::viewport_to_world` method| +|[Animated Material](../examples/3d/animated_material.rs) | Shows how to animate material properties| +|[Anisotropy](../examples/3d/anisotropy.rs) | Displays an example model with anisotropy| +|[Anti-aliasing](../examples/3d/anti_aliasing.rs) | Compares different anti-aliasing methods| +|[Atmospheric Fog](../examples/3d/atmospheric_fog.rs) | A scene showcasing the atmospheric fog effect| +|[Auto Exposure](../examples/3d/auto_exposure.rs) | A scene showcasing auto exposure| +|[Blend Modes](../examples/3d/blend_modes.rs) | Showcases different blend modes| +|[Built-in postprocessing](../examples/3d/post_processing.rs) | Demonstrates the built-in postprocessing features| +|[Camera sub view](../examples/3d/camera_sub_view.rs) | Demonstrates using different sub view effects on a camera| +|[Clearcoat](../examples/3d/clearcoat.rs) | Demonstrates the clearcoat PBR feature| +|[Color grading](../examples/3d/color_grading.rs) | Demonstrates color grading| +|[Deferred Rendering](../examples/3d/deferred_rendering.rs) | Renders meshes with both forward and deferred pipelines| +|[Depth of field](../examples/3d/depth_of_field.rs) | Demonstrates depth of field| +|[Fog](../examples/3d/fog.rs) | A scene showcasing the distance fog effect| +|[Fog volumes](../examples/3d/fog_volumes.rs) | Demonstrates fog volumes| +|[Generate Custom Mesh](../examples/3d/generate_custom_mesh.rs) | Simple showcase of how to generate a custom mesh with a custom texture| +|[Irradiance Volumes](../examples/3d/irradiance_volumes.rs) | Demonstrates irradiance volumes| +|[Lighting](../examples/3d/lighting.rs) | Illustrates various lighting options in a simple scene| +|[Lightmaps](../examples/3d/lightmaps.rs) | Rendering a scene with baked lightmaps| +|[Lines](../examples/3d/lines.rs) | Create a custom material to draw 3d lines| +|[Load glTF](../examples/3d/load_gltf.rs) | Loads and renders a glTF file as a scene| +|[Load glTF extras](../examples/3d/load_gltf_extras.rs) | Loads and renders a glTF file as a scene, including the gltf extras| +|[Mesh Ray Cast](../examples/3d/mesh_ray_cast.rs) | Demonstrates ray casting with the `MeshRayCast` system parameter| +|[Meshlet](../examples/3d/meshlet.rs) | Meshlet rendering for dense high-poly scenes (experimental)| +|[Motion Blur](../examples/3d/motion_blur.rs) | Demonstrates per-pixel motion blur| +|[Order Independent Transparency](../examples/3d/order_independent_transparency.rs) | Demonstrates how to use OIT| +|[Orthographic View](../examples/3d/orthographic.rs) | Shows how to create a 3D orthographic view (for isometric-look in games or CAD applications)| +|[Parallax Mapping](../examples/3d/parallax_mapping.rs) | Demonstrates use of a normal map and depth map for parallax mapping| +|[Parenting](../examples/3d/parenting.rs) | Demonstrates parent->child relationships and relative transformations| +|[Percentage-closer soft shadows](../examples/3d/pcss.rs) | Demonstrates percentage-closer soft shadows (PCSS)| +|[Physically Based Rendering](../examples/3d/pbr.rs) | Demonstrates use of Physically Based Rendering (PBR) properties| +|[Query glTF primitives](../examples/3d/query_gltf_primitives.rs) | Query primitives in a glTF scene| +|[Reflection Probes](../examples/3d/reflection_probes.rs) | Demonstrates reflection probes| +|[Render to Texture](../examples/3d/render_to_texture.rs) | Shows how to render to a texture, useful for mirrors, UI, or exporting images| +|[Rotate Environment Map](../examples/3d/rotate_environment_map.rs) | Demonstrates how to rotate the skybox and the environment map simultaneously| +|[Screen Space Ambient Occlusion](../examples/3d/ssao.rs) | A scene showcasing screen space ambient occlusion| +|[Screen Space Reflections](../examples/3d/ssr.rs) | Demonstrates screen space reflections with water ripples| +|[Scrolling fog](../examples/3d/scrolling_fog.rs) | Demonstrates how to create the effect of fog moving in the wind| +|[Shadow Biases](../examples/3d/shadow_biases.rs) | Demonstrates how shadow biases affect shadows in a 3d scene| +|[Shadow Caster and Receiver](../examples/3d/shadow_caster_receiver.rs) | Demonstrates how to prevent meshes from casting/receiving shadows in a 3d scene| +|[Skybox](../examples/3d/skybox.rs) | Load a cubemap texture onto a cube like a skybox and cycle through different compressed texture formats.| +|[Spherical Area Lights](../examples/3d/spherical_area_lights.rs) | Demonstrates how point light radius values affect light behavior| +|[Split Screen](../examples/3d/split_screen.rs) | Demonstrates how to render two cameras to the same window to accomplish "split screen"| +|[Spotlight](../examples/3d/spotlight.rs) | Illustrates spot lights| +|[Texture](../examples/3d/texture.rs) | Shows configuration of texture materials| +|[Tonemapping](../examples/3d/tonemapping.rs) | Compares tonemapping options| +|[Transmission](../examples/3d/transmission.rs) | Showcases light transmission in the PBR material| +|[Transparency in 3D](../examples/3d/transparency_3d.rs) | Demonstrates transparency in 3d| +|[Two Passes](../examples/3d/two_passes.rs) | Renders two 3d passes to the same window from different perspectives| +|[Update glTF Scene](../examples/3d/update_gltf_scene.rs) | Update a scene from a glTF file, either by spawning the scene as a child of another entity, or by accessing the entities of the scene| +|[Vertex Colors](../examples/3d/vertex_colors.rs) | Shows the use of vertex colors| +|[Visibility range](../examples/3d/visibility_range.rs) | Demonstrates visibility ranges| +|[Volumetric fog](../examples/3d/volumetric_fog.rs) | Demonstrates volumetric fog and lighting| +|[Wireframe](../examples/3d/wireframe.rs) | Showcases wireframe rendering| ## Animation -Example | Description ---- | --- -[Animated Fox](../examples/animation/animated_fox.rs) | Plays an animation from a skinned glTF -[Animated Transform](../examples/animation/animated_transform.rs) | Create and play an animation defined by code that operates on the `Transform` component -[Animated UI](../examples/animation/animated_ui.rs) | Shows how to use animation clips to animate UI properties -[Animation Events](../examples/animation/animation_events.rs) | Demonstrate how to use animation events -[Animation Graph](../examples/animation/animation_graph.rs) | Blends multiple animations together with a graph -[Animation Masks](../examples/animation/animation_masks.rs) | Demonstrates animation masks -[Color animation](../examples/animation/color_animation.rs) | Demonstrates how to animate colors using mixing and splines in different color spaces -[Custom Skinned Mesh](../examples/animation/custom_skinned_mesh.rs) | Skinned mesh example with mesh and joints data defined in code -[Eased Motion](../examples/animation/eased_motion.rs) | Demonstrates the application of easing curves to animate an object -[Easing Functions](../examples/animation/easing_functions.rs) | Showcases the built-in easing functions -[Morph Targets](../examples/animation/morph_targets.rs) | Plays an animation from a glTF file with meshes with morph targets -[glTF Skinned Mesh](../examples/animation/gltf_skinned_mesh.rs) | Skinned mesh example with mesh and joints data loaded from a glTF file +|Example | Description| +|--- | ---| +|[Animated Fox](../examples/animation/animated_fox.rs) | Plays an animation from a skinned glTF| +|[Animated Transform](../examples/animation/animated_transform.rs) | Create and play an animation defined by code that operates on the `Transform` component| +|[Animated UI](../examples/animation/animated_ui.rs) | Shows how to use animation clips to animate UI properties| +|[Animation Events](../examples/animation/animation_events.rs) | Demonstrate how to use animation events| +|[Animation Graph](../examples/animation/animation_graph.rs) | Blends multiple animations together with a graph| +|[Animation Masks](../examples/animation/animation_masks.rs) | Demonstrates animation masks| +|[Color animation](../examples/animation/color_animation.rs) | Demonstrates how to animate colors using mixing and splines in different color spaces| +|[Custom Skinned Mesh](../examples/animation/custom_skinned_mesh.rs) | Skinned mesh example with mesh and joints data defined in code| +|[Eased Motion](../examples/animation/eased_motion.rs) | Demonstrates the application of easing curves to animate an object| +|[Easing Functions](../examples/animation/easing_functions.rs) | Showcases the built-in easing functions| +|[Morph Targets](../examples/animation/morph_targets.rs) | Plays an animation from a glTF file with meshes with morph targets| +|[glTF Skinned Mesh](../examples/animation/gltf_skinned_mesh.rs) | Skinned mesh example with mesh and joints data loaded from a glTF file| ## Application -Example | Description ---- | --- -[Advanced log layers](../examples/app/log_layers_ecs.rs) | Illustrate how to transfer data between log layers and Bevy's ECS -[Custom Loop](../examples/app/custom_loop.rs) | Demonstrates how to create a custom runner (to update an app manually) -[Drag and Drop](../examples/app/drag_and_drop.rs) | An example that shows how to handle drag and drop in an app -[Empty](../examples/app/empty.rs) | An empty application (does nothing) -[Empty with Defaults](../examples/app/empty_defaults.rs) | An empty application with default plugins -[Headless](../examples/app/headless.rs) | An application that runs without default plugins -[Headless Renderer](../examples/app/headless_renderer.rs) | An application that runs with no window, but renders into image file -[Log layers](../examples/app/log_layers.rs) | Illustrate how to add custom log layers -[Logs](../examples/app/logs.rs) | Illustrate how to use generate log output -[No Renderer](../examples/app/no_renderer.rs) | An application that runs with default plugins and displays an empty window, but without an actual renderer -[Plugin](../examples/app/plugin.rs) | Demonstrates the creation and registration of a custom plugin -[Plugin Group](../examples/app/plugin_group.rs) | Demonstrates the creation and registration of a custom plugin group -[Return after Run](../examples/app/return_after_run.rs) | Show how to return to main after the Bevy app has exited -[Thread Pool Resources](../examples/app/thread_pool_resources.rs) | Creates and customizes the internal thread pool -[Without Winit](../examples/app/without_winit.rs) | Create an application without winit (runs single time, no event loop) +|Example | Description| +|--- | ---| +|[Advanced log layers](../examples/app/log_layers_ecs.rs) | Illustrate how to transfer data between log layers and Bevy's ECS| +|[Custom Loop](../examples/app/custom_loop.rs) | Demonstrates how to create a custom runner (to update an app manually)| +|[Drag and Drop](../examples/app/drag_and_drop.rs) | An example that shows how to handle drag and drop in an app| +|[Empty](../examples/app/empty.rs) | An empty application (does nothing)| +|[Empty with Defaults](../examples/app/empty_defaults.rs) | An empty application with default plugins| +|[Headless](../examples/app/headless.rs) | An application that runs without default plugins| +|[Headless Renderer](../examples/app/headless_renderer.rs) | An application that runs with no window, but renders into image file| +|[Log layers](../examples/app/log_layers.rs) | Illustrate how to add custom log layers| +|[Logs](../examples/app/logs.rs) | Illustrate how to use generate log output| +|[No Renderer](../examples/app/no_renderer.rs) | An application that runs with default plugins and displays an empty window, but without an actual renderer| +|[Plugin](../examples/app/plugin.rs) | Demonstrates the creation and registration of a custom plugin| +|[Plugin Group](../examples/app/plugin_group.rs) | Demonstrates the creation and registration of a custom plugin group| +|[Return after Run](../examples/app/return_after_run.rs) | Show how to return to main after the Bevy app has exited| +|[Thread Pool Resources](../examples/app/thread_pool_resources.rs) | Creates and customizes the internal thread pool| +|[Without Winit](../examples/app/without_winit.rs) | Create an application without winit (runs single time, no event loop)| ## Assets -Example | Description ---- | --- -[Alter Mesh](../examples/asset/alter_mesh.rs) | Shows how to modify the underlying asset of a Mesh after spawning. -[Alter Sprite](../examples/asset/alter_sprite.rs) | Shows how to modify texture assets after spawning. -[Asset Decompression](../examples/asset/asset_decompression.rs) | Demonstrates loading a compressed asset -[Asset Loading](../examples/asset/asset_loading.rs) | Demonstrates various methods to load assets -[Asset Processing](../examples/asset/processing/asset_processing.rs) | Demonstrates how to process and load custom assets -[Asset Settings](../examples/asset/asset_settings.rs) | Demonstrates various methods of applying settings when loading an asset -[Custom Asset](../examples/asset/custom_asset.rs) | Implements a custom asset loader -[Custom Asset IO](../examples/asset/custom_asset_reader.rs) | Implements a custom AssetReader -[Embedded Asset](../examples/asset/embedded_asset.rs) | Embed an asset in the application binary and load it -[Extra asset source](../examples/asset/extra_source.rs) | Load an asset from a non-standard asset source -[Hot Reloading of Assets](../examples/asset/hot_asset_reloading.rs) | Demonstrates automatic reloading of assets when modified on disk -[Mult-asset synchronization](../examples/asset/multi_asset_sync.rs) | Demonstrates how to wait for multiple assets to be loaded. -[Repeated texture configuration](../examples/asset/repeated_texture.rs) | How to configure the texture to repeat instead of the default clamp to edges +|Example | Description| +|--- | ---| +|[Alter Mesh](../examples/asset/alter_mesh.rs) | Shows how to modify the underlying asset of a Mesh after spawning.| +|[Alter Sprite](../examples/asset/alter_sprite.rs) | Shows how to modify texture assets after spawning.| +|[Asset Decompression](../examples/asset/asset_decompression.rs) | Demonstrates loading a compressed asset| +|[Asset Loading](../examples/asset/asset_loading.rs) | Demonstrates various methods to load assets| +|[Asset Processing](../examples/asset/processing/asset_processing.rs) | Demonstrates how to process and load custom assets| +|[Asset Settings](../examples/asset/asset_settings.rs) | Demonstrates various methods of applying settings when loading an asset| +|[Custom Asset](../examples/asset/custom_asset.rs) | Implements a custom asset loader| +|[Custom Asset IO](../examples/asset/custom_asset_reader.rs) | Implements a custom AssetReader| +|[Embedded Asset](../examples/asset/embedded_asset.rs) | Embed an asset in the application binary and load it| +|[Extra asset source](../examples/asset/extra_source.rs) | Load an asset from a non-standard asset source| +|[Hot Reloading of Assets](../examples/asset/hot_asset_reloading.rs) | Demonstrates automatic reloading of assets when modified on disk| +|[Multi-asset synchronization](../examples/asset/multi_asset_sync.rs) | Demonstrates how to wait for multiple assets to be loaded.| +|[Repeated texture configuration](../examples/asset/repeated_texture.rs) | How to configure the texture to repeat instead of the default clamp to edges| ## Async Tasks -Example | Description ---- | --- -[Async Compute](../examples/async_tasks/async_compute.rs) | How to use `AsyncComputeTaskPool` to complete longer running tasks -[External Source of Data on an External Thread](../examples/async_tasks/external_source_external_thread.rs) | How to use an external thread to run an infinite task and communicate with a channel +|Example | Description| +|--- | ---| +|[Async Compute](../examples/async_tasks/async_compute.rs) | How to use `AsyncComputeTaskPool` to complete longer running tasks| +|[External Source of Data on an External Thread](../examples/async_tasks/external_source_external_thread.rs) | How to use an external thread to run an infinite task and communicate with a channel| ## Audio -Example | Description ---- | --- -[Audio](../examples/audio/audio.rs) | Shows how to load and play an audio file -[Audio Control](../examples/audio/audio_control.rs) | Shows how to load and play an audio file, and control how it's played -[Decodable](../examples/audio/decodable.rs) | Shows how to create and register a custom audio source by implementing the `Decodable` type. -[Pitch](../examples/audio/pitch.rs) | Shows how to directly play a simple pitch -[Soundtrack](../examples/audio/soundtrack.rs) | Shows how to play different soundtracks based on game state -[Spatial Audio 2D](../examples/audio/spatial_audio_2d.rs) | Shows how to play spatial audio, and moving the emitter in 2D -[Spatial Audio 3D](../examples/audio/spatial_audio_3d.rs) | Shows how to play spatial audio, and moving the emitter in 3D +|Example | Description| +|--- | ---| +|[Audio](../examples/audio/audio.rs) | Shows how to load and play an audio file| +|[Audio Control](../examples/audio/audio_control.rs) | Shows how to load and play an audio file, and control how it's played| +|[Decodable](../examples/audio/decodable.rs) | Shows how to create and register a custom audio source by implementing the `Decodable` type.| +|[Pitch](../examples/audio/pitch.rs) | Shows how to directly play a simple pitch| +|[Soundtrack](../examples/audio/soundtrack.rs) | Shows how to play different soundtracks based on game state| +|[Spatial Audio 2D](../examples/audio/spatial_audio_2d.rs) | Shows how to play spatial audio, and moving the emitter in 2D| +|[Spatial Audio 3D](../examples/audio/spatial_audio_3d.rs) | Shows how to play spatial audio, and moving the emitter in 3D| ## Camera -Example | Description ---- | --- -[2D top-down camera](../examples/camera/2d_top_down_camera.rs) | A 2D top-down camera smoothly following player movements -[Camera Orbit](../examples/camera/camera_orbit.rs) | Shows how to orbit a static scene using pitch, yaw, and roll. -[First person view model](../examples/camera/first_person_view_model.rs) | A first-person camera that uses a world model and a view model with different field of views (FOV) -[Projection Zoom](../examples/camera/projection_zoom.rs) | Shows how to zoom orthographic and perspective projection cameras. -[Screen Shake](../examples/camera/2d_screen_shake.rs) | A simple 2D screen shake effect +|Example | Description| +|--- | ---| +|[2D top-down camera](../examples/camera/2d_top_down_camera.rs) | A 2D top-down camera smoothly following player movements| +|[Camera Orbit](../examples/camera/camera_orbit.rs) | Shows how to orbit a static scene using pitch, yaw, and roll.| +|[First person view model](../examples/camera/first_person_view_model.rs) | A first-person camera that uses a world model and a view model with different field of views (FOV)| +|[Projection Zoom](../examples/camera/projection_zoom.rs) | Shows how to zoom orthographic and perspective projection cameras.| +|[Screen Shake](../examples/camera/2d_screen_shake.rs) | A simple 2D screen shake effect| ## Dev tools -Example | Description ---- | --- -[FPS overlay](../examples/dev_tools/fps_overlay.rs) | Demonstrates FPS overlay +|Example | Description| +|--- | ---| +|[FPS overlay](../examples/dev_tools/fps_overlay.rs) | Demonstrates FPS overlay| ## Diagnostics -Example | Description ---- | --- -[Custom Diagnostic](../examples/diagnostics/custom_diagnostic.rs) | Shows how to create a custom diagnostic -[Enabling/disabling diagnostic](../examples/diagnostics/enabling_disabling_diagnostic.rs) | Shows how to disable/re-enable a Diagnostic during runtime -[Log Diagnostics](../examples/diagnostics/log_diagnostics.rs) | Add a plugin that logs diagnostics, like frames per second (FPS), to the console +|Example | Description| +|--- | ---| +|[Custom Diagnostic](../examples/diagnostics/custom_diagnostic.rs) | Shows how to create a custom diagnostic| +|[Enabling/disabling diagnostic](../examples/diagnostics/enabling_disabling_diagnostic.rs) | Shows how to disable/re-enable a Diagnostic during runtime| +|[Log Diagnostics](../examples/diagnostics/log_diagnostics.rs) | Add a plugin that logs diagnostics, like frames per second (FPS), to the console| ## ECS (Entity Component System) -Example | Description ---- | --- -[Change Detection](../examples/ecs/change_detection.rs) | Change detection on components and resources -[Component Hooks](../examples/ecs/component_hooks.rs) | Define component hooks to manage component lifecycle events -[Custom Query Parameters](../examples/ecs/custom_query_param.rs) | Groups commonly used compound queries and query filters into a single type -[Custom Schedule](../examples/ecs/custom_schedule.rs) | Demonstrates how to add custom schedules -[Dynamic ECS](../examples/ecs/dynamic.rs) | Dynamically create components, spawn entities with those components and query those components -[ECS Guide](../examples/ecs/ecs_guide.rs) | Full guide to Bevy's ECS -[Event](../examples/ecs/event.rs) | Illustrates event creation, activation, and reception -[Fallible System Parameters](../examples/ecs/fallible_params.rs) | Systems are skipped if their parameters cannot be acquired -[Fixed Timestep](../examples/ecs/fixed_timestep.rs) | Shows how to create systems that run every fixed timestep, rather than every tick -[Generic System](../examples/ecs/generic_system.rs) | Shows how to create systems that can be reused with different types -[Hierarchy](../examples/ecs/hierarchy.rs) | Creates a hierarchy of parents and children entities -[Iter Combinations](../examples/ecs/iter_combinations.rs) | Shows how to iterate over combinations of query results -[Nondeterministic System Order](../examples/ecs/nondeterministic_system_order.rs) | Systems run in parallel, but their order isn't always deterministic. Here's how to detect and fix this. -[Observer Propagation](../examples/ecs/observer_propagation.rs) | Demonstrates event propagation with observers -[Observers](../examples/ecs/observers.rs) | Demonstrates observers that react to events (both built-in life-cycle events and custom events) -[One Shot Systems](../examples/ecs/one_shot_systems.rs) | Shows how to flexibly run systems without scheduling them -[Parallel Query](../examples/ecs/parallel_query.rs) | Illustrates parallel queries with `ParallelIterator` -[Removal Detection](../examples/ecs/removal_detection.rs) | Query for entities that had a specific component removed earlier in the current frame -[Run Conditions](../examples/ecs/run_conditions.rs) | Run systems only when one or multiple conditions are met -[Send and receive events](../examples/ecs/send_and_receive_events.rs) | Demonstrates how to send and receive events of the same type in a single system -[Startup System](../examples/ecs/startup_system.rs) | Demonstrates a startup system (one that runs once when the app starts up) -[System Closure](../examples/ecs/system_closure.rs) | Show how to use closures as systems, and how to configure `Local` variables by capturing external state -[System Parameter](../examples/ecs/system_param.rs) | Illustrates creating custom system parameters with `SystemParam` -[System Piping](../examples/ecs/system_piping.rs) | Pipe the output of one system into a second, allowing you to handle any errors gracefully -[System Stepping](../examples/ecs/system_stepping.rs) | Demonstrate stepping through systems in order of execution. +|Example | Description| +|--- | ---| +|[Change Detection](../examples/ecs/change_detection.rs) | Change detection on components and resources| +|[Component Hooks](../examples/ecs/component_hooks.rs) | Define component hooks to manage component lifecycle events| +|[Custom Query Parameters](../examples/ecs/custom_query_param.rs) | Groups commonly used compound queries and query filters into a single type| +|[Custom Schedule](../examples/ecs/custom_schedule.rs) | Demonstrates how to add custom schedules| +|[Dynamic ECS](../examples/ecs/dynamic.rs) | Dynamically create components, spawn entities with those components and query those components| +|[ECS Guide](../examples/ecs/ecs_guide.rs) | Full guide to Bevy's ECS| +|[Event](../examples/ecs/event.rs) | Illustrates event creation, activation, and reception| +|[Fallible System Parameters](../examples/ecs/fallible_params.rs) | Systems are skipped if their parameters cannot be acquired| +|[Fixed Timestep](../examples/ecs/fixed_timestep.rs) | Shows how to create systems that run every fixed timestep, rather than every tick| +|[Generic System](../examples/ecs/generic_system.rs) | Shows how to create systems that can be reused with different types| +|[Hierarchy](../examples/ecs/hierarchy.rs) | Creates a hierarchy of parents and children entities| +|[Iter Combinations](../examples/ecs/iter_combinations.rs) | Shows how to iterate over combinations of query results| +|[Nondeterministic System Order](../examples/ecs/nondeterministic_system_order.rs) | Systems run in parallel, but their order isn't always deterministic. Here's how to detect and fix this.| +|[Observer Propagation](../examples/ecs/observer_propagation.rs) | Demonstrates event propagation with observers| +|[Observers](../examples/ecs/observers.rs) | Demonstrates observers that react to events (both built-in life-cycle events and custom events)| +|[One Shot Systems](../examples/ecs/one_shot_systems.rs) | Shows how to flexibly run systems without scheduling them| +|[Parallel Query](../examples/ecs/parallel_query.rs) | Illustrates parallel queries with `ParallelIterator`| +|[Removal Detection](../examples/ecs/removal_detection.rs) | Query for entities that had a specific component removed earlier in the current frame| +|[Run Conditions](../examples/ecs/run_conditions.rs) | Run systems only when one or multiple conditions are met| +|[Send and receive events](../examples/ecs/send_and_receive_events.rs) | Demonstrates how to send and receive events of the same type in a single system| +|[Startup System](../examples/ecs/startup_system.rs) | Demonstrates a startup system (one that runs once when the app starts up)| +|[System Closure](../examples/ecs/system_closure.rs) | Show how to use closures as systems, and how to configure `Local` variables by capturing external state| +|[System Parameter](../examples/ecs/system_param.rs) | Illustrates creating custom system parameters with `SystemParam`| +|[System Piping](../examples/ecs/system_piping.rs) | Pipe the output of one system into a second, allowing you to handle any errors gracefully| +|[System Stepping](../examples/ecs/system_stepping.rs) | Demonstrate stepping through systems in order of execution.| ## Games -Example | Description ---- | --- -[Alien Cake Addict](../examples/games/alien_cake_addict.rs) | Eat the cakes. Eat them all. An example 3D game -[Breakout](../examples/games/breakout.rs) | An implementation of the classic game "Breakout". -[Contributors](../examples/games/contributors.rs) | Displays each contributor as a bouncy bevy-ball! -[Desk Toy](../examples/games/desk_toy.rs) | Bevy logo as a desk toy using transparent windows! Now with Googly Eyes! -[Game Menu](../examples/games/game_menu.rs) | A simple game menu -[Loading Screen](../examples/games/loading_screen.rs) | Demonstrates how to create a loading screen that waits for all assets to be loaded and render pipelines to be compiled. +|Example | Description| +|--- | ---| +|[Alien Cake Addict](../examples/games/alien_cake_addict.rs) | Eat the cakes. Eat them all. An example 3D game| +|[Breakout](../examples/games/breakout.rs) | An implementation of the classic game "Breakout".| +|[Contributors](../examples/games/contributors.rs) | Displays each contributor as a bouncy bevy-ball!| +|[Desk Toy](../examples/games/desk_toy.rs) | Bevy logo as a desk toy using transparent windows! Now with Googly Eyes!| +|[Game Menu](../examples/games/game_menu.rs) | A simple game menu| +|[Loading Screen](../examples/games/loading_screen.rs) | Demonstrates how to create a loading screen that waits for all assets to be loaded and render pipelines to be compiled.| ## Gizmos -Example | Description ---- | --- -[2D Gizmos](../examples/gizmos/2d_gizmos.rs) | A scene showcasing 2D gizmos -[3D Gizmos](../examples/gizmos/3d_gizmos.rs) | A scene showcasing 3D gizmos -[Axes](../examples/gizmos/axes.rs) | Demonstrates the function of axes gizmos -[Light Gizmos](../examples/gizmos/light_gizmos.rs) | A scene showcasing light gizmos +|Example | Description| +|--- | ---| +|[2D Gizmos](../examples/gizmos/2d_gizmos.rs) | A scene showcasing 2D gizmos| +|[3D Gizmos](../examples/gizmos/3d_gizmos.rs) | A scene showcasing 3D gizmos| +|[Axes](../examples/gizmos/axes.rs) | Demonstrates the function of axes gizmos| +|[Light Gizmos](../examples/gizmos/light_gizmos.rs) | A scene showcasing light gizmos| ## Input -Example | Description ---- | --- -[Char Input Events](../examples/input/char_input_events.rs) | Prints out all chars as they are inputted -[Gamepad Input](../examples/input/gamepad_input.rs) | Shows handling of gamepad input, connections, and disconnections -[Gamepad Input Events](../examples/input/gamepad_input_events.rs) | Iterates and prints gamepad input and connection events -[Gamepad Rumble](../examples/input/gamepad_rumble.rs) | Shows how to rumble a gamepad using force feedback -[Keyboard Input](../examples/input/keyboard_input.rs) | Demonstrates handling a key press/release -[Keyboard Input Events](../examples/input/keyboard_input_events.rs) | Prints out all keyboard events -[Keyboard Modifiers](../examples/input/keyboard_modifiers.rs) | Demonstrates using key modifiers (ctrl, shift) -[Mouse Grab](../examples/input/mouse_grab.rs) | Demonstrates how to grab the mouse, locking the cursor to the app's screen -[Mouse Input](../examples/input/mouse_input.rs) | Demonstrates handling a mouse button press/release -[Mouse Input Events](../examples/input/mouse_input_events.rs) | Prints out all mouse events (buttons, movement, etc.) -[Text Input](../examples/input/text_input.rs) | Simple text input with IME support -[Touch Input](../examples/input/touch_input.rs) | Displays touch presses, releases, and cancels -[Touch Input Events](../examples/input/touch_input_events.rs) | Prints out all touch inputs +|Example | Description| +|--- | ---| +|[Char Input Events](../examples/input/char_input_events.rs) | Prints out all chars as they are inputted| +|[Gamepad Input](../examples/input/gamepad_input.rs) | Shows handling of gamepad input, connections, and disconnections| +|[Gamepad Input Events](../examples/input/gamepad_input_events.rs) | Iterates and prints gamepad input and connection events| +|[Gamepad Rumble](../examples/input/gamepad_rumble.rs) | Shows how to rumble a gamepad using force feedback| +|[Keyboard Input](../examples/input/keyboard_input.rs) | Demonstrates handling a key press/release| +|[Keyboard Input Events](../examples/input/keyboard_input_events.rs) | Prints out all keyboard events| +|[Keyboard Modifiers](../examples/input/keyboard_modifiers.rs) | Demonstrates using key modifiers (ctrl, shift)| +|[Mouse Grab](../examples/input/mouse_grab.rs) | Demonstrates how to grab the mouse, locking the cursor to the app's screen| +|[Mouse Input](../examples/input/mouse_input.rs) | Demonstrates handling a mouse button press/release| +|[Mouse Input Events](../examples/input/mouse_input_events.rs) | Prints out all mouse events (buttons, movement, etc.)| +|[Text Input](../examples/input/text_input.rs) | Simple text input with IME support| +|[Touch Input](../examples/input/touch_input.rs) | Displays touch presses, releases, and cancels| +|[Touch Input Events](../examples/input/touch_input_events.rs) | Prints out all touch inputs| ## Math -Example | Description ---- | --- -[Cubic Splines](../examples/math/cubic_splines.rs) | Exhibits different modes of constructing cubic curves using splines -[Custom Primitives](../examples/math/custom_primitives.rs) | Demonstrates how to add custom primitives and useful traits for them. -[Random Sampling](../examples/math/random_sampling.rs) | Demonstrates how to sample random points from mathematical primitives -[Rendering Primitives](../examples/math/render_primitives.rs) | Shows off rendering for all math primitives as both Meshes and Gizmos -[Sampling Primitives](../examples/math/sampling_primitives.rs) | Demonstrates all the primitives which can be sampled. -[Smooth Follow](../examples/movement/smooth_follow.rs) | Demonstrates how to make an entity smoothly follow another using interpolation +|Example | Description| +|--- | ---| +|[Cubic Splines](../examples/math/cubic_splines.rs) | Exhibits different modes of constructing cubic curves using splines| +|[Custom Primitives](../examples/math/custom_primitives.rs) | Demonstrates how to add custom primitives and useful traits for them.| +|[Random Sampling](../examples/math/random_sampling.rs) | Demonstrates how to sample random points from mathematical primitives| +|[Rendering Primitives](../examples/math/render_primitives.rs) | Shows off rendering for all math primitives as both Meshes and Gizmos| +|[Sampling Primitives](../examples/math/sampling_primitives.rs) | Demonstrates all the primitives which can be sampled.| +|[Smooth Follow](../examples/movement/smooth_follow.rs) | Demonstrates how to make an entity smoothly follow another using interpolation| ## Movement -Example | Description ---- | --- -[Run physics in a fixed timestep](../examples/movement/physics_in_fixed_timestep.rs) | Handles input, physics, and rendering in an industry-standard way by using a fixed timestep +|Example | Description| +|--- | ---| +|[Run physics in a fixed timestep](../examples/movement/physics_in_fixed_timestep.rs) | Handles input, physics, and rendering in an industry-standard way by using a fixed timestep| ## Picking -Example | Description ---- | --- -[Mesh Picking](../examples/picking/mesh_picking.rs) | Demonstrates picking meshes -[Showcases simple picking events and usage](../examples/picking/simple_picking.rs) | Demonstrates how to use picking events to spawn simple objects -[Sprite Picking](../examples/picking/sprite_picking.rs) | Demonstrates picking sprites and sprite atlases +|Example | Description| +|--- | ---| +|[Mesh Picking](../examples/picking/mesh_picking.rs) | Demonstrates picking meshes| +|[Showcases simple picking events and usage](../examples/picking/simple_picking.rs) | Demonstrates how to use picking events to spawn simple objects| +|[Sprite Picking](../examples/picking/sprite_picking.rs) | Demonstrates picking sprites and sprite atlases| ## Reflection -Example | Description ---- | --- -[Custom Attributes](../examples/reflection/custom_attributes.rs) | Registering and accessing custom attributes on reflected types -[Dynamic Types](../examples/reflection/dynamic_types.rs) | How dynamic types are used with reflection -[Function Reflection](../examples/reflection/function_reflection.rs) | Demonstrates how functions can be called dynamically using reflection -[Generic Reflection](../examples/reflection/generic_reflection.rs) | Registers concrete instances of generic types that may be used with reflection -[Reflection](../examples/reflection/reflection.rs) | Demonstrates how reflection in Bevy provides a way to dynamically interact with Rust types -[Reflection Types](../examples/reflection/reflection_types.rs) | Illustrates the various reflection types available -[Type Data](../examples/reflection/type_data.rs) | Demonstrates how to create and use type data +|Example | Description| +|--- | ---| +|[Custom Attributes](../examples/reflection/custom_attributes.rs) | Registering and accessing custom attributes on reflected types| +|[Dynamic Types](../examples/reflection/dynamic_types.rs) | How dynamic types are used with reflection| +|[Function Reflection](../examples/reflection/function_reflection.rs) | Demonstrates how functions can be called dynamically using reflection| +|[Generic Reflection](../examples/reflection/generic_reflection.rs) | Registers concrete instances of generic types that may be used with reflection| +|[Reflection](../examples/reflection/reflection.rs) | Demonstrates how reflection in Bevy provides a way to dynamically interact with Rust types| +|[Reflection Types](../examples/reflection/reflection_types.rs) | Illustrates the various reflection types available| +|[Type Data](../examples/reflection/type_data.rs) | Demonstrates how to create and use type data| ## Remote Protocol -Example | Description ---- | --- -[client](../examples/remote/client.rs) | A simple command line client that can control Bevy apps via the BRP -[server](../examples/remote/server.rs) | A Bevy app that you can connect to with the BRP and edit +|Example | Description| +|--- | ---| +|[client](../examples/remote/client.rs) | A simple command line client that can control Bevy apps via the BRP| +|[server](../examples/remote/server.rs) | A Bevy app that you can connect to with the BRP and edit| ## Scene -Example | Description ---- | --- -[Scene](../examples/scene/scene.rs) | Demonstrates loading from and saving scenes to files +|Example | Description| +|--- | ---| +|[Scene](../examples/scene/scene.rs) | Demonstrates loading from and saving scenes to files| ## Shaders @@ -413,36 +413,36 @@ A shader in its most common usage is a small program that is run by the GPU per- There are also compute shaders which are used for more general processing leveraging the GPU's parallelism. -Example | Description ---- | --- -[Animated](../examples/shader/animate_shader.rs) | A shader that uses dynamic data like the time since startup -[Array Texture](../examples/shader/array_texture.rs) | A shader that shows how to reuse the core bevy PBR shading functionality in a custom material that obtains the base color from an array texture. -[Compute - Game of Life](../examples/shader/compute_shader_game_of_life.rs) | A compute shader that simulates Conway's Game of Life -[Custom Vertex Attribute](../examples/shader/custom_vertex_attribute.rs) | A shader that reads a mesh's custom vertex attribute -[Custom phase item](../examples/shader/custom_phase_item.rs) | Demonstrates how to enqueue custom draw commands in a render phase -[Extended Material](../examples/shader/extended_material.rs) | A custom shader that builds on the standard material -[GPU readback](../examples/shader/gpu_readback.rs) | A very simple compute shader that writes to a buffer that is read by the cpu -[Instancing](../examples/shader/custom_shader_instancing.rs) | A shader that renders a mesh multiple times in one draw call using low level rendering api -[Instancing](../examples/shader/automatic_instancing.rs) | Shows that multiple instances of a cube are automatically instanced in one draw call -[Material](../examples/shader/shader_material.rs) | A shader and a material that uses it -[Material](../examples/shader/shader_material_2d.rs) | A shader and a material that uses it on a 2d mesh -[Material - GLSL](../examples/shader/shader_material_glsl.rs) | A shader that uses the GLSL shading language -[Material - Screenspace Texture](../examples/shader/shader_material_screenspace_texture.rs) | A shader that samples a texture with view-independent UV coordinates -[Material Prepass](../examples/shader/shader_prepass.rs) | A shader that uses the various textures generated by the prepass -[Post Processing - Custom Render Pass](../examples/shader/custom_post_processing.rs) | A custom post processing effect, using a custom render pass that runs after the main pass -[Shader Defs](../examples/shader/shader_defs.rs) | A shader that uses "shaders defs" (a bevy tool to selectively toggle parts of a shader) -[Specialized Mesh Pipeline](../examples/shader/specialized_mesh_pipeline.rs) | Demonstrates how to write a specialized mesh pipeline -[Storage Buffer](../examples/shader/storage_buffer.rs) | A shader that shows how to bind a storage buffer using a custom material. -[Texture Binding Array (Bindless Textures)](../examples/shader/texture_binding_array.rs) | A shader that shows how to bind and sample multiple textures as a binding array (a.k.a. bindless textures). +|Example | Description| +|--- | ---| +|[Animated](../examples/shader/animate_shader.rs) | A shader that uses dynamic data like the time since startup| +|[Array Texture](../examples/shader/array_texture.rs) | A shader that shows how to reuse the core bevy PBR shading functionality in a custom material that obtains the base color from an array texture.| +|[Compute - Game of Life](../examples/shader/compute_shader_game_of_life.rs) | A compute shader that simulates Conway's Game of Life| +|[Custom Vertex Attribute](../examples/shader/custom_vertex_attribute.rs) | A shader that reads a mesh's custom vertex attribute| +|[Custom phase item](../examples/shader/custom_phase_item.rs) | Demonstrates how to enqueue custom draw commands in a render phase| +|[Extended Material](../examples/shader/extended_material.rs) | A custom shader that builds on the standard material| +|[GPU readback](../examples/shader/gpu_readback.rs) | A very simple compute shader that writes to a buffer that is read by the cpu| +|[Instancing](../examples/shader/custom_shader_instancing.rs) | A shader that renders a mesh multiple times in one draw call using low level rendering api| +|[Instancing](../examples/shader/automatic_instancing.rs) | Shows that multiple instances of a cube are automatically instanced in one draw call| +|[Material](../examples/shader/shader_material.rs) | A shader and a material that uses it| +|[Material](../examples/shader/shader_material_2d.rs) | A shader and a material that uses it on a 2d mesh| +|[Material - GLSL](../examples/shader/shader_material_glsl.rs) | A shader that uses the GLSL shading language| +|[Material - Screenspace Texture](../examples/shader/shader_material_screenspace_texture.rs) | A shader that samples a texture with view-independent UV coordinates| +|[Material Prepass](../examples/shader/shader_prepass.rs) | A shader that uses the various textures generated by the prepass| +|[Post Processing - Custom Render Pass](../examples/shader/custom_post_processing.rs) | A custom post processing effect, using a custom render pass that runs after the main pass| +|[Shader Defs](../examples/shader/shader_defs.rs) | A shader that uses "shaders defs" (a bevy tool to selectively toggle parts of a shader)| +|[Specialized Mesh Pipeline](../examples/shader/specialized_mesh_pipeline.rs) | Demonstrates how to write a specialized mesh pipeline| +|[Storage Buffer](../examples/shader/storage_buffer.rs) | A shader that shows how to bind a storage buffer using a custom material.| +|[Texture Binding Array (Bindless Textures)](../examples/shader/texture_binding_array.rs) | A shader that shows how to bind and sample multiple textures as a binding array (a.k.a. bindless textures).| ## State -Example | Description ---- | --- -[Computed States](../examples/state/computed_states.rs) | Advanced state patterns using Computed States. -[Custom State Transition Behavior](../examples/state/custom_transitions.rs) | Creating and working with custom state transition schedules. -[States](../examples/state/states.rs) | Illustrates how to use States to control transitioning from a Menu state to an InGame state. -[Sub States](../examples/state/sub_states.rs) | Using Sub States for hierarchical state handling. +|Example | Description| +|--- | ---| +|[Computed States](../examples/state/computed_states.rs) | Advanced state patterns using Computed States.| +|[Custom State Transition Behavior](../examples/state/custom_transitions.rs) | Creating and working with custom state transition schedules.| +|[States](../examples/state/states.rs) | Illustrates how to use States to control transitioning from a Menu state to an InGame state.| +|[Sub States](../examples/state/sub_states.rs) | Using Sub States for hierarchical state handling.| ## Stress Tests @@ -454,100 +454,100 @@ Due to the focus on performance it's recommended to run the stress tests in rele cargo run --release --example ``` -Example | Description ---- | --- -[Bevymark](../examples/stress_tests/bevymark.rs) | A heavy sprite rendering workload to benchmark your system with Bevy -[Many Animated Sprites](../examples/stress_tests/many_animated_sprites.rs) | Displays many animated sprites in a grid arrangement with slight offsets to their animation timers. Used for performance testing. -[Many Buttons](../examples/stress_tests/many_buttons.rs) | Test rendering of many UI elements -[Many Cameras & Lights](../examples/stress_tests/many_cameras_lights.rs) | Test rendering of many cameras and lights -[Many Cubes](../examples/stress_tests/many_cubes.rs) | Simple benchmark to test per-entity draw overhead. Run with the `sphere` argument to test frustum culling -[Many Foxes](../examples/stress_tests/many_foxes.rs) | Loads an animated fox model and spawns lots of them. Good for testing skinned mesh performance. Takes an unsigned integer argument for the number of foxes to spawn. Defaults to 1000 -[Many Gizmos](../examples/stress_tests/many_gizmos.rs) | Test rendering of many gizmos -[Many Glyphs](../examples/stress_tests/many_glyphs.rs) | Simple benchmark to test text rendering. -[Many Lights](../examples/stress_tests/many_lights.rs) | Simple benchmark to test rendering many point lights. Run with `WGPU_SETTINGS_PRIO=webgl2` to restrict to uniform buffers and max 256 lights -[Many Sprites](../examples/stress_tests/many_sprites.rs) | Displays many sprites in a grid arrangement! Used for performance testing. Use `--colored` to enable color tinted sprites. -[Text Pipeline](../examples/stress_tests/text_pipeline.rs) | Text Pipeline benchmark -[Transform Hierarchy](../examples/stress_tests/transform_hierarchy.rs) | Various test cases for hierarchy and transform propagation performance +|Example | Description| +|--- | ---| +|[Bevymark](../examples/stress_tests/bevymark.rs) | A heavy sprite rendering workload to benchmark your system with Bevy| +|[Many Animated Sprites](../examples/stress_tests/many_animated_sprites.rs) | Displays many animated sprites in a grid arrangement with slight offsets to their animation timers. Used for performance testing.| +|[Many Buttons](../examples/stress_tests/many_buttons.rs) | Test rendering of many UI elements| +|[Many Cameras & Lights](../examples/stress_tests/many_cameras_lights.rs) | Test rendering of many cameras and lights| +|[Many Cubes](../examples/stress_tests/many_cubes.rs) | Simple benchmark to test per-entity draw overhead. Run with the `sphere` argument to test frustum culling| +|[Many Foxes](../examples/stress_tests/many_foxes.rs) | Loads an animated fox model and spawns lots of them. Good for testing skinned mesh performance. Takes an unsigned integer argument for the number of foxes to spawn. Defaults to 1000| +|[Many Gizmos](../examples/stress_tests/many_gizmos.rs) | Test rendering of many gizmos| +|[Many Glyphs](../examples/stress_tests/many_glyphs.rs) | Simple benchmark to test text rendering.| +|[Many Lights](../examples/stress_tests/many_lights.rs) | Simple benchmark to test rendering many point lights. Run with `WGPU_SETTINGS_PRIO=webgl2` to restrict to uniform buffers and max 256 lights| +|[Many Sprites](../examples/stress_tests/many_sprites.rs) | Displays many sprites in a grid arrangement! Used for performance testing. Use `--colored` to enable color tinted sprites.| +|[Text Pipeline](../examples/stress_tests/text_pipeline.rs) | Text Pipeline benchmark| +|[Transform Hierarchy](../examples/stress_tests/transform_hierarchy.rs) | Various test cases for hierarchy and transform propagation performance| ## Time -Example | Description ---- | --- -[Time handling](../examples/time/time.rs) | Explains how Time is handled in ECS -[Timers](../examples/time/timers.rs) | Illustrates ticking `Timer` resources inside systems and handling their state -[Virtual time](../examples/time/virtual_time.rs) | Shows how `Time` can be used to pause, resume, slow down and speed up a game. +|Example | Description| +|--- | ---| +|[Time handling](../examples/time/time.rs) | Explains how Time is handled in ECS| +|[Timers](../examples/time/timers.rs) | Illustrates ticking `Timer` resources inside systems and handling their state| +|[Virtual time](../examples/time/virtual_time.rs) | Shows how `Time` can be used to pause, resume, slow down and speed up a game.| ## Tools -Example | Description ---- | --- -[Gamepad Viewer](../examples/tools/gamepad_viewer.rs) | Shows a visualization of gamepad buttons, sticks, and triggers -[Scene Viewer](../examples/tools/scene_viewer/main.rs) | A simple way to view glTF models with Bevy. Just run `cargo run --release --example scene_viewer /path/to/model.gltf#Scene0`, replacing the path as appropriate. With no arguments it will load the FieldHelmet glTF model from the repository assets subdirectory +|Example | Description| +|--- | ---| +|[Gamepad Viewer](../examples/tools/gamepad_viewer.rs) | Shows a visualization of gamepad buttons, sticks, and triggers| +|[Scene Viewer](../examples/tools/scene_viewer/main.rs) | A simple way to view glTF models with Bevy. Just run `cargo run --release --example scene_viewer /path/to/model.gltf#Scene0`, replacing the path as appropriate. With no arguments it will load the FieldHelmet glTF model from the repository assets subdirectory| ## Transforms -Example | Description ---- | --- -[3D Rotation](../examples/transforms/3d_rotation.rs) | Illustrates how to (constantly) rotate an object around an axis -[Alignment](../examples/transforms/align.rs) | A demonstration of Transform's axis-alignment feature -[Scale](../examples/transforms/scale.rs) | Illustrates how to scale an object in each direction -[Transform](../examples/transforms/transform.rs) | Shows multiple transformations of objects -[Translation](../examples/transforms/translation.rs) | Illustrates how to move an object along an axis +|Example | Description| +|--- | ---| +|[3D Rotation](../examples/transforms/3d_rotation.rs) | Illustrates how to (constantly) rotate an object around an axis| +|[Alignment](../examples/transforms/align.rs) | A demonstration of Transform's axis-alignment feature| +|[Scale](../examples/transforms/scale.rs) | Illustrates how to scale an object in each direction| +|[Transform](../examples/transforms/transform.rs) | Shows multiple transformations of objects| +|[Translation](../examples/transforms/translation.rs) | Illustrates how to move an object along an axis| ## UI (User Interface) -Example | Description ---- | --- -[Borders](../examples/ui/borders.rs) | Demonstrates how to create a node with a border -[Box Shadow](../examples/ui/box_shadow.rs) | Demonstrates how to create a node with a shadow -[Button](../examples/ui/button.rs) | Illustrates creating and updating a button -[CSS Grid](../examples/ui/grid.rs) | An example for CSS Grid layout -[Display and Visibility](../examples/ui/display_and_visibility.rs) | Demonstrates how Display and Visibility work in the UI. -[Flex Layout](../examples/ui/flex_layout.rs) | Demonstrates how the AlignItems and JustifyContent properties can be composed to layout nodes and position text -[Font Atlas Debug](../examples/ui/font_atlas_debug.rs) | Illustrates how FontAtlases are populated (used to optimize text rendering internally) -[Ghost Nodes](../examples/ui/ghost_nodes.rs) | Demonstrates the use of Ghost Nodes to skip entities in the UI layout hierarchy -[Overflow](../examples/ui/overflow.rs) | Simple example demonstrating overflow behavior -[Overflow Clip Margin](../examples/ui/overflow_clip_margin.rs) | Simple example demonstrating the OverflowClipMargin style property -[Overflow and Clipping Debug](../examples/ui/overflow_debug.rs) | An example to debug overflow and clipping behavior -[Relative Cursor Position](../examples/ui/relative_cursor_position.rs) | Showcases the RelativeCursorPosition component -[Render UI to Texture](../examples/ui/render_ui_to_texture.rs) | An example of rendering UI as a part of a 3D world -[Scroll](../examples/ui/scroll.rs) | Demonstrates scrolling UI containers -[Size Constraints](../examples/ui/size_constraints.rs) | Demonstrates how the to use the size constraints to control the size of a UI node. -[Text](../examples/ui/text.rs) | Illustrates creating and updating text -[Text Debug](../examples/ui/text_debug.rs) | An example for debugging text layout -[Text Wrap Debug](../examples/ui/text_wrap_debug.rs) | Demonstrates text wrapping -[Transparency UI](../examples/ui/transparency_ui.rs) | Demonstrates transparency for UI -[UI Material](../examples/ui/ui_material.rs) | Demonstrates creating and using custom Ui materials -[UI Scaling](../examples/ui/ui_scaling.rs) | Illustrates how to scale the UI -[UI Texture Atlas](../examples/ui/ui_texture_atlas.rs) | Illustrates how to use TextureAtlases in UI -[UI Texture Atlas Slice](../examples/ui/ui_texture_atlas_slice.rs) | Illustrates how to use 9 Slicing for TextureAtlases in UI -[UI Texture Slice](../examples/ui/ui_texture_slice.rs) | Illustrates how to use 9 Slicing in UI -[UI Texture Slice Flipping and Tiling](../examples/ui/ui_texture_slice_flip_and_tile.rs) | Illustrates how to flip and tile images with 9 Slicing in UI -[UI Z-Index](../examples/ui/z_index.rs) | Demonstrates how to control the relative depth (z-position) of UI elements -[Viewport Debug](../examples/ui/viewport_debug.rs) | An example for debugging viewport coordinates -[Window Fallthrough](../examples/ui/window_fallthrough.rs) | Illustrates how to access `winit::window::Window`'s `hittest` functionality. +|Example | Description| +|--- | ---| +|[Borders](../examples/ui/borders.rs) | Demonstrates how to create a node with a border| +|[Box Shadow](../examples/ui/box_shadow.rs) | Demonstrates how to create a node with a shadow| +|[Button](../examples/ui/button.rs) | Illustrates creating and updating a button| +|[CSS Grid](../examples/ui/grid.rs) | An example for CSS Grid layout| +|[Display and Visibility](../examples/ui/display_and_visibility.rs) | Demonstrates how Display and Visibility work in the UI.| +|[Flex Layout](../examples/ui/flex_layout.rs) | Demonstrates how the AlignItems and JustifyContent properties can be composed to layout nodes and position text| +|[Font Atlas Debug](../examples/ui/font_atlas_debug.rs) | Illustrates how FontAtlases are populated (used to optimize text rendering internally)| +|[Ghost Nodes](../examples/ui/ghost_nodes.rs) | Demonstrates the use of Ghost Nodes to skip entities in the UI layout hierarchy| +|[Overflow](../examples/ui/overflow.rs) | Simple example demonstrating overflow behavior| +|[Overflow Clip Margin](../examples/ui/overflow_clip_margin.rs) | Simple example demonstrating the OverflowClipMargin style property| +|[Overflow and Clipping Debug](../examples/ui/overflow_debug.rs) | An example to debug overflow and clipping behavior| +|[Relative Cursor Position](../examples/ui/relative_cursor_position.rs) | Showcases the RelativeCursorPosition component| +|[Render UI to Texture](../examples/ui/render_ui_to_texture.rs) | An example of rendering UI as a part of a 3D world| +|[Scroll](../examples/ui/scroll.rs) | Demonstrates scrolling UI containers| +|[Size Constraints](../examples/ui/size_constraints.rs) | Demonstrates how the to use the size constraints to control the size of a UI node.| +|[Text](../examples/ui/text.rs) | Illustrates creating and updating text| +|[Text Debug](../examples/ui/text_debug.rs) | An example for debugging text layout| +|[Text Wrap Debug](../examples/ui/text_wrap_debug.rs) | Demonstrates text wrapping| +|[Transparency UI](../examples/ui/transparency_ui.rs) | Demonstrates transparency for UI| +|[UI Material](../examples/ui/ui_material.rs) | Demonstrates creating and using custom Ui materials| +|[UI Scaling](../examples/ui/ui_scaling.rs) | Illustrates how to scale the UI| +|[UI Texture Atlas](../examples/ui/ui_texture_atlas.rs) | Illustrates how to use TextureAtlases in UI| +|[UI Texture Atlas Slice](../examples/ui/ui_texture_atlas_slice.rs) | Illustrates how to use 9 Slicing for TextureAtlases in UI| +|[UI Texture Slice](../examples/ui/ui_texture_slice.rs) | Illustrates how to use 9 Slicing in UI| +|[UI Texture Slice Flipping and Tiling](../examples/ui/ui_texture_slice_flip_and_tile.rs) | Illustrates how to flip and tile images with 9 Slicing in UI| +|[UI Z-Index](../examples/ui/z_index.rs) | Demonstrates how to control the relative depth (z-position) of UI elements| +|[Viewport Debug](../examples/ui/viewport_debug.rs) | An example for debugging viewport coordinates| +|[Window Fallthrough](../examples/ui/window_fallthrough.rs) | Illustrates how to access `winit::window::Window`'s `hittest` functionality.| ## Window -Example | Description ---- | --- -[Clear Color](../examples/window/clear_color.rs) | Creates a solid color window -[Custom User Event](../examples/window/custom_user_event.rs) | Handles custom user events within the event loop -[Low Power](../examples/window/low_power.rs) | Demonstrates settings to reduce power use for bevy applications -[Monitor info](../examples/window/monitor_info.rs) | Displays information about available monitors (displays). -[Multiple Windows](../examples/window/multiple_windows.rs) | Demonstrates creating multiple windows, and rendering to them -[Scale Factor Override](../examples/window/scale_factor_override.rs) | Illustrates how to customize the default window settings -[Screenshot](../examples/window/screenshot.rs) | Shows how to save screenshots to disk -[Transparent Window](../examples/window/transparent_window.rs) | Illustrates making the window transparent and hiding the window decoration -[Window Drag Move](../examples/window/window_drag_move.rs) | Demonstrates drag move and drag resize without window decoration -[Window Resizing](../examples/window/window_resizing.rs) | Demonstrates resizing and responding to resizing a window -[Window Settings](../examples/window/window_settings.rs) | Demonstrates customizing default window settings +|Example | Description| +|--- | ---| +|[Clear Color](../examples/window/clear_color.rs) | Creates a solid color window| +|[Custom User Event](../examples/window/custom_user_event.rs) | Handles custom user events within the event loop| +|[Low Power](../examples/window/low_power.rs) | Demonstrates settings to reduce power use for bevy applications| +|[Monitor info](../examples/window/monitor_info.rs) | Displays information about available monitors (displays).| +|[Multiple Windows](../examples/window/multiple_windows.rs) | Demonstrates creating multiple windows, and rendering to them| +|[Scale Factor Override](../examples/window/scale_factor_override.rs) | Illustrates how to customize the default window settings| +|[Screenshot](../examples/window/screenshot.rs) | Shows how to save screenshots to disk| +|[Transparent Window](../examples/window/transparent_window.rs) | Illustrates making the window transparent and hiding the window decoration| +|[Window Drag Move](../examples/window/window_drag_move.rs) | Demonstrates drag move and drag resize without window decoration| +|[Window Resizing](../examples/window/window_resizing.rs) | Demonstrates resizing and responding to resizing a window| +|[Window Settings](../examples/window/window_settings.rs) | Demonstrates customizing default window settings| # Tests -Example | Description ---- | --- -[How to Test Systems](../tests/how_to_test_systems.rs) | How to test systems with commands, queries or resources +|Example | Description| +|--- | ---| +|[How to Test Systems](../tests/how_to_test_systems.rs) | How to test systems with commands, queries or resources| # Platform-Specific Examples @@ -622,7 +622,7 @@ adb uninstall org.bevyengine.example In its examples, Bevy targets the minimum Android API that Play Store [requires](https://developer.android.com/distribute/best-practices/develop/target-sdk) to upload and update apps. -Users of older phones may want to use an older API when testing. By default, Bevy uses [`GameAvtivity`](https://developer.android.com/games/agdk/game-activity), which only works for Android API level 31 and higher, so if you want to use older API, you need to switch to `NativeActivity`. +Users of older phones may want to use an older API when testing. By default, Bevy uses [`GameActivity`](https://developer.android.com/games/agdk/game-activity), which only works for Android API level 31 and higher, so if you want to use older API, you need to switch to `NativeActivity`. To use `NativeActivity`, you need to edit it in `cargo.toml` manually like this: @@ -636,9 +636,9 @@ Then build it as the [Build & Run](#build--run) section stated above. You can also build an APK with `cargo-apk`, a simpler and deprecated tool which doesn't support `GameActivity`. If you want to use this, there is a [folder](./mobile/android_basic) inside the mobile example with instructions. -Example | File | Description ---- | --- | --- -`android` | [`mobile/src/lib.rs`](./mobile/src/lib.rs) | A 3d Scene with a button and playing sound +|Example | File | Description| +|--- | --- | ---| +|`android` | [`mobile/src/lib.rs`](./mobile/src/lib.rs) | A 3d Scene with a button and playing sound| ## iOS @@ -680,9 +680,9 @@ open bevy_mobile_example.xcodeproj/ which will open xcode. You then must push the zoom zoom play button and wait for the magic. -Example | File | Description ---- | --- | --- -`ios` | [`mobile/src/lib.rs`](./mobile/src/lib.rs) | A 3d Scene with a button and playing sound +|Example | File | Description| +|--- | --- | ---| +|`ios` | [`mobile/src/lib.rs`](./mobile/src/lib.rs) | A 3d Scene with a button and playing sound| ## Wasm @@ -768,7 +768,7 @@ may not be worth keeping due to compilation time increases. For a small project with a basic 3d model and two lights, the generated file sizes are, as of July 2022, as follows: -|profile | wasm-opt | no wasm-opt | +| profile | wasm-opt | no wasm-opt | |----------------------------------|----------|-------------| |Default | 8.5M | 13.0M | |opt-level = "z" | 6.1M | 12.7M | diff --git a/examples/animation/animated_fox.rs b/examples/animation/animated_fox.rs index db17bbecc0e15..b4e2b44f69d17 100644 --- a/examples/animation/animated_fox.rs +++ b/examples/animation/animated_fox.rs @@ -267,12 +267,12 @@ fn simulate_particles( time: Res