repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_light/src/cluster/test.rs
crates/bevy_light/src/cluster/test.rs
use bevy_math::UVec2; use super::{ClusterConfig, Clusters}; fn test_cluster_tiling(config: ClusterConfig, screen_size: UVec2) -> Clusters { let dims = config.dimensions_for_screen_size(screen_size); // note: near & far do not affect tiling let mut clusters = Clusters::default(); clusters.update(screen_size, dims); // check we cover the screen assert!(clusters.tile_size.x * clusters.dimensions.x >= screen_size.x); assert!(clusters.tile_size.y * clusters.dimensions.y >= screen_size.y); // check a smaller number of clusters would not cover the screen assert!(clusters.tile_size.x * (clusters.dimensions.x - 1) < screen_size.x); assert!(clusters.tile_size.y * (clusters.dimensions.y - 1) < screen_size.y); // check a smaller tile size would not cover the screen assert!((clusters.tile_size.x - 1) * clusters.dimensions.x < screen_size.x); assert!((clusters.tile_size.y - 1) * clusters.dimensions.y < screen_size.y); // check we don't have more clusters than pixels assert!(clusters.dimensions.x <= screen_size.x); assert!(clusters.dimensions.y <= screen_size.y); clusters } #[test] // check tiling for small screen sizes fn test_default_cluster_setup_small_screensizes() { for x in 1..100 { for y in 1..100 { let screen_size = UVec2::new(x, y); let clusters = test_cluster_tiling(ClusterConfig::default(), screen_size); assert!(clusters.dimensions.x * clusters.dimensions.y * clusters.dimensions.z <= 4096); } } } #[test] // check tiling for long thin screen sizes fn test_default_cluster_setup_small_x() { for x in 1..10 { for y in 1..5000 { let screen_size = UVec2::new(x, y); let clusters = test_cluster_tiling(ClusterConfig::default(), screen_size); assert!(clusters.dimensions.x * clusters.dimensions.y * clusters.dimensions.z <= 4096); let screen_size = UVec2::new(y, x); let clusters = test_cluster_tiling(ClusterConfig::default(), screen_size); assert!(clusters.dimensions.x * clusters.dimensions.y * clusters.dimensions.z <= 4096); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_light/src/cluster/mod.rs
crates/bevy_light/src/cluster/mod.rs
//! Spatial clustering of objects, currently just point and spot lights. use bevy_asset::Handle; use bevy_camera::{ visibility::{self, Visibility, VisibilityClass}, Camera, Camera3d, }; use bevy_ecs::{ component::Component, entity::Entity, query::{With, Without}, reflect::ReflectComponent, resource::Resource, system::{Commands, Query}, }; use bevy_image::Image; use bevy_math::{AspectRatio, UVec2, UVec3, Vec3Swizzles as _}; use bevy_platform::collections::HashSet; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_transform::components::Transform; use tracing::warn; pub mod assign; #[cfg(test)] mod test; // Clustered-forward rendering notes // The main initial reference material used was this rather accessible article: // http://www.aortiz.me/2018/12/21/CG.html // Some inspiration was taken from “Practical Clustered Shading” which is part 2 of: // https://efficientshading.com/2015/01/01/real-time-many-light-management-and-shadows-with-clustered-shading/ // (Also note that Part 3 of the above shows how we could support the shadow mapping for many lights.) // The z-slicing method mentioned in the aortiz article is originally from Tiago Sousa's Siggraph 2016 talk about Doom 2016: // http://advances.realtimerendering.com/s2016/Siggraph2016_idTech6.pdf #[derive(Resource)] pub struct GlobalClusterSettings { pub supports_storage_buffers: bool, pub clustered_decals_are_usable: bool, pub max_uniform_buffer_clusterable_objects: usize, pub view_cluster_bindings_max_indices: usize, } /// Configure the far z-plane mode used for the furthest depth slice for clustered forward /// rendering #[derive(Debug, Copy, Clone, Reflect)] #[reflect(Clone)] pub enum ClusterFarZMode { /// Calculate the required maximum z-depth based on currently visible /// clusterable objects. Makes better use of available clusters, speeding /// up GPU lighting operations at the expense of some CPU time and using /// more indices in the clusterable object index lists. MaxClusterableObjectRange, /// Constant max z-depth Constant(f32), } /// Configure the depth-slicing strategy for clustered forward rendering #[derive(Debug, Copy, Clone, Reflect)] #[reflect(Default, Clone)] pub struct ClusterZConfig { /// Far `Z` plane of the first depth slice pub first_slice_depth: f32, /// Strategy for how to evaluate the far `Z` plane of the furthest depth slice pub far_z_mode: ClusterFarZMode, } /// Configuration of the clustering strategy for clustered forward rendering #[derive(Debug, Copy, Clone, Component, Reflect)] #[reflect(Component, Debug, Default, Clone)] pub enum ClusterConfig { /// Disable cluster calculations for this view None, /// One single cluster. Optimal for low-light complexity scenes or scenes where /// most lights affect the entire scene. Single, /// Explicit `X`, `Y` and `Z` counts (may yield non-square `X/Y` clusters depending on the aspect ratio) XYZ { dimensions: UVec3, z_config: ClusterZConfig, /// Specify if clusters should automatically resize in `X/Y` if there is a risk of exceeding /// the available cluster-object index limit dynamic_resizing: bool, }, /// Fixed number of `Z` slices, `X` and `Y` calculated to give square clusters /// with at most total clusters. For top-down games where lights will generally always be within a /// short depth range, it may be useful to use this configuration with 1 or few `Z` slices. This /// would reduce the number of lights per cluster by distributing more clusters in screen space /// `X/Y` which matches how lights are distributed in the scene. FixedZ { total: u32, z_slices: u32, z_config: ClusterZConfig, /// Specify if clusters should automatically resize in `X/Y` if there is a risk of exceeding /// the available clusterable object index limit dynamic_resizing: bool, }, } #[derive(Component, Debug, Default)] pub struct Clusters { /// Tile size pub tile_size: UVec2, /// Number of clusters in `X` / `Y` / `Z` in the view frustum pub dimensions: UVec3, /// Distance to the far plane of the first depth slice. The first depth slice is special /// and explicitly-configured to avoid having unnecessarily many slices close to the camera. pub near: f32, pub far: f32, pub clusterable_objects: Vec<VisibleClusterableObjects>, } /// The [`VisibilityClass`] used for clusterables (decals, point lights, directional lights, and spot lights). /// /// [`VisibilityClass`]: bevy_camera::visibility::VisibilityClass pub struct ClusterVisibilityClass; #[derive(Clone, Component, Debug, Default)] pub struct VisibleClusterableObjects { pub entities: Vec<Entity>, pub counts: ClusterableObjectCounts, } #[derive(Resource, Default)] pub struct GlobalVisibleClusterableObjects { pub(crate) entities: HashSet<Entity>, } /// Stores the number of each type of clusterable object in a single cluster. /// /// Note that `reflection_probes` and `irradiance_volumes` won't be clustered if /// fewer than 3 SSBOs are available, which usually means on WebGL 2. #[derive(Clone, Copy, Default, Debug)] pub struct ClusterableObjectCounts { /// The number of point lights in the cluster. pub point_lights: u32, /// The number of spot lights in the cluster. pub spot_lights: u32, /// The number of reflection probes in the cluster. pub reflection_probes: u32, /// The number of irradiance volumes in the cluster. pub irradiance_volumes: u32, /// The number of decals in the cluster. pub decals: u32, } /// An object that projects a decal onto surfaces within its bounds. /// /// Conceptually, a clustered decal is a 1×1×1 cube centered on its origin. It /// projects its images onto surfaces in the -Z direction (thus you may find /// [`Transform::looking_at`] useful). /// /// Each decal may project any of a base color texture, a normal map, a /// metallic/roughness map, and/or a texture that specifies emissive light. In /// addition, you may associate an arbitrary integer [`Self::tag`] with each /// clustered decal, which Bevy doesn't use, but that you can use in your /// shaders in order to associate application-specific data with your decals. /// /// Clustered decals are the highest-quality types of decals that Bevy supports, /// but they require bindless textures. This means that they presently can't be /// used on WebGL 2, WebGPU, macOS, or iOS. Bevy's clustered decals can be used /// with forward or deferred rendering and don't require a prepass. #[derive(Component, Debug, Clone, Default, Reflect)] #[reflect(Component, Debug, Clone, Default)] #[require(Transform, Visibility, VisibilityClass)] #[component(on_add = visibility::add_visibility_class::<ClusterVisibilityClass>)] pub struct ClusteredDecal { /// The image that the clustered decal projects onto the base color of the /// surface material. /// /// This must be a 2D image. If it has an alpha channel, it'll be alpha /// blended with the underlying surface and/or other decals. All decal /// images in the scene must use the same sampler. pub base_color_texture: Option<Handle<Image>>, /// The normal map that the clustered decal projects onto surfaces. /// /// Bevy uses the *Whiteout* method to combine normal maps from decals with /// any normal map that the surface has, as described in the /// [*Blending in Detail* article]. /// /// Note that the normal map must be three-channel and must be in OpenGL /// format, not DirectX format. That is, the green channel must point up, /// not down. /// /// [*Blending in Detail* article]: https://blog.selfshadow.com/publications/blending-in-detail/ pub normal_map_texture: Option<Handle<Image>>, /// The metallic-roughness map that the clustered decal projects onto /// surfaces. /// /// Metallic and roughness PBR parameters are blended onto the base surface /// using the alpha channel of the base color. /// /// Metallic is expected to be in the blue channel, while roughness is /// expected to be in the green channel, following glTF conventions. pub metallic_roughness_texture: Option<Handle<Image>>, /// The emissive map that the clustered decal projects onto surfaces. /// /// Including this texture effectively causes the decal to glow. The /// emissive component is blended onto the surface according to the alpha /// channel. pub emissive_texture: Option<Handle<Image>>, /// An application-specific tag you can use for any purpose you want, in /// conjunction with a custom shader. /// /// This value is exposed to the shader via the iterator API /// (`bevy_pbr::decal::clustered::clustered_decal_iterator_new` and /// `bevy_pbr::decal::clustered::clustered_decal_iterator_next`). /// /// For example, you might use the tag to restrict the set of surfaces to /// which a decal can be rendered. /// /// See the `clustered_decals` example for an example of use. pub tag: u32, } impl Default for ClusterZConfig { fn default() -> Self { Self { first_slice_depth: 5.0, far_z_mode: ClusterFarZMode::MaxClusterableObjectRange, } } } impl Default for ClusterConfig { fn default() -> Self { // 24 depth slices, square clusters with at most 4096 total clusters // use max light distance as clusters max `Z`-depth, first slice extends to 5.0 Self::FixedZ { total: 4096, z_slices: 24, z_config: ClusterZConfig::default(), dynamic_resizing: true, } } } impl ClusterConfig { fn dimensions_for_screen_size(&self, screen_size: UVec2) -> UVec3 { match &self { ClusterConfig::None => UVec3::ZERO, ClusterConfig::Single => UVec3::ONE, ClusterConfig::XYZ { dimensions, .. } => *dimensions, ClusterConfig::FixedZ { total, z_slices, .. } => { let aspect_ratio: f32 = AspectRatio::try_from_pixels(screen_size.x, screen_size.y) .expect("Failed to calculate aspect ratio for Cluster: screen dimensions must be positive, non-zero values") .ratio(); let mut z_slices = *z_slices; if *total < z_slices { warn!("ClusterConfig has more z-slices than total clusters!"); z_slices = *total; } let per_layer = *total as f32 / z_slices as f32; let y = f32::sqrt(per_layer / aspect_ratio); let mut x = (y * aspect_ratio) as u32; let mut y = y as u32; // check extremes if x == 0 { x = 1; y = per_layer as u32; } if y == 0 { x = per_layer as u32; y = 1; } UVec3::new(x, y, z_slices) } } } fn first_slice_depth(&self) -> f32 { match self { ClusterConfig::None | ClusterConfig::Single => 0.0, ClusterConfig::XYZ { z_config, .. } | ClusterConfig::FixedZ { z_config, .. } => { z_config.first_slice_depth } } } fn far_z_mode(&self) -> ClusterFarZMode { match self { ClusterConfig::None => ClusterFarZMode::Constant(0.0), ClusterConfig::Single => ClusterFarZMode::MaxClusterableObjectRange, ClusterConfig::XYZ { z_config, .. } | ClusterConfig::FixedZ { z_config, .. } => { z_config.far_z_mode } } } fn dynamic_resizing(&self) -> bool { match self { ClusterConfig::None | ClusterConfig::Single => false, ClusterConfig::XYZ { dynamic_resizing, .. } | ClusterConfig::FixedZ { dynamic_resizing, .. } => *dynamic_resizing, } } } impl Clusters { fn update(&mut self, screen_size: UVec2, requested_dimensions: UVec3) { debug_assert!( requested_dimensions.x > 0 && requested_dimensions.y > 0 && requested_dimensions.z > 0 ); let tile_size = (screen_size.as_vec2() / requested_dimensions.xy().as_vec2()) .ceil() .as_uvec2() .max(UVec2::ONE); self.tile_size = tile_size; self.dimensions = (screen_size.as_vec2() / tile_size.as_vec2()) .ceil() .as_uvec2() .extend(requested_dimensions.z) .max(UVec3::ONE); // NOTE: Maximum 4096 clusters due to uniform buffer size constraints debug_assert!(self.dimensions.x * self.dimensions.y * self.dimensions.z <= 4096); } fn clear(&mut self) { self.tile_size = UVec2::ONE; self.dimensions = UVec3::ZERO; self.near = 0.0; self.far = 0.0; self.clusterable_objects.clear(); } } pub fn add_clusters( mut commands: Commands, cameras: Query<(Entity, Option<&ClusterConfig>, &Camera), (Without<Clusters>, With<Camera3d>)>, ) { for (entity, config, camera) in &cameras { if !camera.is_active { continue; } let config = config.copied().unwrap_or_default(); // actual settings here don't matter - they will be overwritten in // `assign_objects_to_clusters`` commands .entity(entity) .insert((Clusters::default(), config)); } } impl VisibleClusterableObjects { #[inline] pub fn iter(&self) -> impl DoubleEndedIterator<Item = &Entity> { self.entities.iter() } #[inline] pub fn len(&self) -> usize { self.entities.len() } #[inline] pub fn is_empty(&self) -> bool { self.entities.is_empty() } } impl GlobalVisibleClusterableObjects { #[inline] pub fn iter(&self) -> impl Iterator<Item = &Entity> { self.entities.iter() } #[inline] pub fn contains(&self, entity: Entity) -> bool { self.entities.contains(&entity) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_light/src/cluster/assign.rs
crates/bevy_light/src/cluster/assign.rs
//! Assigning objects to clusters. use bevy_camera::{ primitives::{Aabb, Frustum, HalfSpace, Sphere}, visibility::{RenderLayers, ViewVisibility}, Camera, }; use bevy_ecs::{ entity::Entity, query::{Has, With}, system::{Commands, Local, Query, Res, ResMut}, }; use bevy_math::{ ops::{self, sin_cos}, Mat4, UVec3, Vec2, Vec3, Vec3A, Vec3Swizzles as _, Vec4, Vec4Swizzles as _, }; use bevy_transform::components::GlobalTransform; use bevy_utils::prelude::default; use tracing::warn; use super::{ ClusterConfig, ClusterFarZMode, ClusteredDecal, Clusters, GlobalClusterSettings, GlobalVisibleClusterableObjects, VisibleClusterableObjects, }; use crate::{EnvironmentMapLight, LightProbe, PointLight, SpotLight, VolumetricLight}; const NDC_MIN: Vec2 = Vec2::NEG_ONE; const NDC_MAX: Vec2 = Vec2::ONE; const VEC2_HALF: Vec2 = Vec2::splat(0.5); const VEC2_HALF_NEGATIVE_Y: Vec2 = Vec2::new(0.5, -0.5); /// Data required for assigning objects to clusters. #[derive(Clone, Debug)] pub(crate) struct ClusterableObjectAssignmentData { entity: Entity, // TODO: We currently ignore the scale on the transform. This is confusing. // Replace with an `Isometry3d`. transform: GlobalTransform, range: f32, object_type: ClusterableObjectType, render_layers: RenderLayers, } impl ClusterableObjectAssignmentData { pub fn sphere(&self) -> Sphere { Sphere { center: self.transform.translation_vec3a(), radius: self.range, } } } /// Data needed to assign objects to clusters that's specific to the type of /// clusterable object. #[derive(Clone, Copy, Debug)] pub enum ClusterableObjectType { /// Data needed to assign point lights to clusters. PointLight { /// Whether shadows are enabled for this point light. /// /// This is used for sorting the light list. shadows_enabled: bool, /// Whether this light interacts with volumetrics. /// /// This is used for sorting the light list. volumetric: bool, }, /// Data needed to assign spot lights to clusters. SpotLight { /// Whether shadows are enabled for this spot light. /// /// This is used for sorting the light list. shadows_enabled: bool, /// Whether this light interacts with volumetrics. /// /// This is used for sorting the light list. volumetric: bool, /// The outer angle of the light cone in radians. outer_angle: f32, }, /// Marks that the clusterable object is a reflection probe. ReflectionProbe, /// Marks that the clusterable object is an irradiance volume. IrradianceVolume, /// Marks that the clusterable object is a decal. Decal, } impl ClusterableObjectType { /// Returns a tuple that can be sorted to obtain the order in which indices /// to clusterable objects must be stored in the cluster offsets and counts /// list. /// /// Generally, we sort first by type, then, for lights, by whether shadows /// are enabled (enabled before disabled), and then whether volumetrics are /// enabled (enabled before disabled). pub fn ordering(&self) -> (u8, bool, bool) { match *self { ClusterableObjectType::PointLight { shadows_enabled, volumetric, } => (0, !shadows_enabled, !volumetric), ClusterableObjectType::SpotLight { shadows_enabled, volumetric, .. } => (1, !shadows_enabled, !volumetric), ClusterableObjectType::ReflectionProbe => (2, false, false), ClusterableObjectType::IrradianceVolume => (3, false, false), ClusterableObjectType::Decal => (4, false, false), } } } // NOTE: Run this before update_point_light_frusta! pub(crate) fn assign_objects_to_clusters( mut commands: Commands, mut global_clusterable_objects: ResMut<GlobalVisibleClusterableObjects>, mut views: Query<( Entity, &GlobalTransform, &Camera, &Frustum, &ClusterConfig, &mut Clusters, Option<&RenderLayers>, Option<&mut VisibleClusterableObjects>, )>, point_lights_query: Query<( Entity, &GlobalTransform, &PointLight, Option<&RenderLayers>, Option<&VolumetricLight>, &ViewVisibility, )>, spot_lights_query: Query<( Entity, &GlobalTransform, &SpotLight, Option<&RenderLayers>, Option<&VolumetricLight>, &ViewVisibility, )>, light_probes_query: Query< (Entity, &GlobalTransform, Has<EnvironmentMapLight>), With<LightProbe>, >, decals_query: Query<(Entity, &GlobalTransform), With<ClusteredDecal>>, mut clusterable_objects: Local<Vec<ClusterableObjectAssignmentData>>, mut cluster_aabb_spheres: Local<Vec<Option<Sphere>>>, mut max_clusterable_objects_warning_emitted: Local<bool>, global_cluster_settings: Option<Res<GlobalClusterSettings>>, ) { let Some(global_cluster_settings) = global_cluster_settings else { return; }; global_clusterable_objects.entities.clear(); clusterable_objects.clear(); // collect just the relevant query data into a persisted vec to avoid reallocating each frame clusterable_objects.extend( point_lights_query .iter() .filter(|(.., visibility)| visibility.get()) .map( |(entity, transform, point_light, maybe_layers, volumetric, _visibility)| { ClusterableObjectAssignmentData { entity, transform: GlobalTransform::from_translation(transform.translation()), range: point_light.range, object_type: ClusterableObjectType::PointLight { shadows_enabled: point_light.shadows_enabled, volumetric: volumetric.is_some(), }, render_layers: maybe_layers.unwrap_or_default().clone(), } }, ), ); clusterable_objects.extend( spot_lights_query .iter() .filter(|(.., visibility)| visibility.get()) .map( |(entity, transform, spot_light, maybe_layers, volumetric, _visibility)| { ClusterableObjectAssignmentData { entity, transform: *transform, range: spot_light.range, object_type: ClusterableObjectType::SpotLight { outer_angle: spot_light.outer_angle, shadows_enabled: spot_light.shadows_enabled, volumetric: volumetric.is_some(), }, render_layers: maybe_layers.unwrap_or_default().clone(), } }, ), ); // Gather up light probes, but only if we're clustering them. // // UBOs aren't large enough to hold indices for light probes, so we can't // cluster light probes on such platforms (mainly WebGL 2). Besides, those // platforms typically lack bindless textures, so multiple light probes // wouldn't be supported anyhow. if global_cluster_settings.supports_storage_buffers { clusterable_objects.extend(light_probes_query.iter().map( |(entity, transform, is_reflection_probe)| ClusterableObjectAssignmentData { entity, transform: *transform, range: transform.radius_vec3a(Vec3A::ONE), object_type: if is_reflection_probe { ClusterableObjectType::ReflectionProbe } else { ClusterableObjectType::IrradianceVolume }, render_layers: RenderLayers::default(), }, )); } // Add decals if the current platform supports them. if global_cluster_settings.clustered_decals_are_usable { clusterable_objects.extend(decals_query.iter().map(|(entity, transform)| { ClusterableObjectAssignmentData { entity, transform: *transform, range: transform.scale().length(), object_type: ClusterableObjectType::Decal, render_layers: RenderLayers::default(), } })); } if clusterable_objects.len() > global_cluster_settings.max_uniform_buffer_clusterable_objects && !global_cluster_settings.supports_storage_buffers { clusterable_objects.sort_by_cached_key(|clusterable_object| { ( clusterable_object.object_type.ordering(), clusterable_object.entity, ) }); // check each clusterable object against each view's frustum, keep only // those that affect at least one of our views let frusta: Vec<_> = views .iter() .map(|(_, _, _, frustum, _, _, _, _)| *frustum) .collect(); let mut clusterable_objects_in_view_count = 0; clusterable_objects.retain(|clusterable_object| { // take one extra clusterable object to check if we should emit the warning if clusterable_objects_in_view_count == global_cluster_settings.max_uniform_buffer_clusterable_objects + 1 { false } else { let clusterable_object_sphere = clusterable_object.sphere(); let clusterable_object_in_view = frusta .iter() .any(|frustum| frustum.intersects_sphere(&clusterable_object_sphere, true)); if clusterable_object_in_view { clusterable_objects_in_view_count += 1; } clusterable_object_in_view } }); if clusterable_objects.len() > global_cluster_settings.max_uniform_buffer_clusterable_objects && !*max_clusterable_objects_warning_emitted { warn!( "max_uniform_buffer_clusterable_objects ({}) exceeded", global_cluster_settings.max_uniform_buffer_clusterable_objects ); *max_clusterable_objects_warning_emitted = true; } clusterable_objects .truncate(global_cluster_settings.max_uniform_buffer_clusterable_objects); } for ( view_entity, camera_transform, camera, frustum, config, clusters, maybe_layers, mut visible_clusterable_objects, ) in &mut views { let view_layers = maybe_layers.unwrap_or_default(); let clusters = clusters.into_inner(); if matches!(config, ClusterConfig::None) { if visible_clusterable_objects.is_some() { commands .entity(view_entity) .remove::<VisibleClusterableObjects>(); } clusters.clear(); continue; } let screen_size = match camera.physical_viewport_size() { Some(screen_size) if screen_size.x != 0 && screen_size.y != 0 => screen_size, _ => { clusters.clear(); continue; } }; let mut requested_cluster_dimensions = config.dimensions_for_screen_size(screen_size); let world_from_view = camera_transform.affine(); let view_from_world_scale = camera_transform.compute_transform().scale.recip(); let view_from_world_scale_max = view_from_world_scale.abs().max_element(); let view_from_world = Mat4::from(world_from_view.inverse()); let is_orthographic = camera.clip_from_view().w_axis.w == 1.0; let far_z = match config.far_z_mode() { ClusterFarZMode::MaxClusterableObjectRange => { let view_from_world_row_2 = view_from_world.row(2); clusterable_objects .iter() .map(|object| { -view_from_world_row_2.dot(object.transform.translation().extend(1.0)) + object.range * view_from_world_scale.z }) .reduce(f32::max) .unwrap_or(0.0) } ClusterFarZMode::Constant(far) => far, }; let first_slice_depth = match (is_orthographic, requested_cluster_dimensions.z) { (true, _) => { // NOTE: Based on glam's Mat4::orthographic_rh(), as used to calculate the orthographic projection // matrix, we can calculate the projection's view-space near plane as follows: // component 3,2 = r * near and 2,2 = r where r = 1.0 / (near - far) // There is a caveat here that when calculating the projection matrix, near and far were swapped to give // reversed z, consistent with the perspective projection. So, // 3,2 = r * far and 2,2 = r where r = 1.0 / (far - near) // rearranging r = 1.0 / (far - near), r * (far - near) = 1.0, r * far - 1.0 = r * near, near = (r * far - 1.0) / r // = (3,2 - 1.0) / 2,2 (camera.clip_from_view().w_axis.z - 1.0) / camera.clip_from_view().z_axis.z } (false, 1) => config.first_slice_depth().max(far_z), _ => config.first_slice_depth(), }; let first_slice_depth = first_slice_depth * view_from_world_scale.z; // NOTE: Ensure the far_z is at least as far as the first_depth_slice to avoid clustering problems. let far_z = far_z.max(first_slice_depth); let cluster_factors = calculate_cluster_factors( first_slice_depth, far_z, requested_cluster_dimensions.z as f32, is_orthographic, ); if config.dynamic_resizing() { let mut cluster_index_estimate = 0.0; for clusterable_object in &clusterable_objects { let clusterable_object_sphere = clusterable_object.sphere(); // Check if the clusterable object is within the view frustum if !frustum.intersects_sphere(&clusterable_object_sphere, true) { continue; } // calculate a conservative aabb estimate of number of clusters affected by this light // this overestimates index counts by at most 50% (and typically much less) when the whole light range is in view // it can overestimate more significantly when light ranges are only partially in view let (clusterable_object_aabb_min, clusterable_object_aabb_max) = cluster_space_clusterable_object_aabb( view_from_world, view_from_world_scale, camera.clip_from_view(), &clusterable_object_sphere, ); // since we won't adjust z slices we can calculate exact number of slices required in z dimension let z_cluster_min = view_z_to_z_slice( cluster_factors, requested_cluster_dimensions.z, clusterable_object_aabb_min.z, is_orthographic, ); let z_cluster_max = view_z_to_z_slice( cluster_factors, requested_cluster_dimensions.z, clusterable_object_aabb_max.z, is_orthographic, ); let z_count = z_cluster_min.max(z_cluster_max) - z_cluster_min.min(z_cluster_max) + 1; // calculate x/y count using floats to avoid overestimating counts due to large initial tile sizes let xy_min = clusterable_object_aabb_min.xy(); let xy_max = clusterable_object_aabb_max.xy(); // multiply by 0.5 to move from [-1,1] to [-0.5, 0.5], max extent of 1 in each dimension let xy_count = (xy_max - xy_min) * 0.5 * Vec2::new( requested_cluster_dimensions.x as f32, requested_cluster_dimensions.y as f32, ); // add up to 2 to each axis to account for overlap let x_overlap = if xy_min.x <= -1.0 { 0.0 } else { 1.0 } + if xy_max.x >= 1.0 { 0.0 } else { 1.0 }; let y_overlap = if xy_min.y <= -1.0 { 0.0 } else { 1.0 } + if xy_max.y >= 1.0 { 0.0 } else { 1.0 }; cluster_index_estimate += (xy_count.x + x_overlap) * (xy_count.y + y_overlap) * z_count as f32; } if cluster_index_estimate > global_cluster_settings.view_cluster_bindings_max_indices as f32 { // scale x and y cluster count to be able to fit all our indices // we take the ratio of the actual indices over the index estimate. // this is not guaranteed to be small enough due to overlapped tiles, but // the conservative estimate is more than sufficient to cover the // difference let index_ratio = global_cluster_settings.view_cluster_bindings_max_indices as f32 / cluster_index_estimate; let xy_ratio = index_ratio.sqrt(); requested_cluster_dimensions.x = ((requested_cluster_dimensions.x as f32 * xy_ratio).floor() as u32).max(1); requested_cluster_dimensions.y = ((requested_cluster_dimensions.y as f32 * xy_ratio).floor() as u32).max(1); } } clusters.update(screen_size, requested_cluster_dimensions); clusters.near = first_slice_depth; clusters.far = far_z; // NOTE: Maximum 4096 clusters due to uniform buffer size constraints debug_assert!( clusters.dimensions.x * clusters.dimensions.y * clusters.dimensions.z <= 4096 ); let view_from_clip = camera.clip_from_view().inverse(); for clusterable_objects in &mut clusters.clusterable_objects { clusterable_objects.entities.clear(); clusterable_objects.counts = default(); } let cluster_count = (clusters.dimensions.x * clusters.dimensions.y * clusters.dimensions.z) as usize; clusters .clusterable_objects .resize_with(cluster_count, VisibleClusterableObjects::default); // initialize empty cluster bounding spheres cluster_aabb_spheres.clear(); cluster_aabb_spheres.extend(core::iter::repeat_n(None, cluster_count)); // Calculate the x/y/z cluster frustum planes in view space let mut x_planes = Vec::with_capacity(clusters.dimensions.x as usize + 1); let mut y_planes = Vec::with_capacity(clusters.dimensions.y as usize + 1); let mut z_planes = Vec::with_capacity(clusters.dimensions.z as usize + 1); if is_orthographic { let x_slices = clusters.dimensions.x as f32; for x in 0..=clusters.dimensions.x { let x_proportion = x as f32 / x_slices; let x_pos = x_proportion * 2.0 - 1.0; let view_x = clip_to_view(view_from_clip, Vec4::new(x_pos, 0.0, 1.0, 1.0)).x; let normal = Vec3::X; let d = view_x * normal.x; x_planes.push(HalfSpace::new(normal.extend(d))); } let y_slices = clusters.dimensions.y as f32; for y in 0..=clusters.dimensions.y { let y_proportion = 1.0 - y as f32 / y_slices; let y_pos = y_proportion * 2.0 - 1.0; let view_y = clip_to_view(view_from_clip, Vec4::new(0.0, y_pos, 1.0, 1.0)).y; let normal = Vec3::Y; let d = view_y * normal.y; y_planes.push(HalfSpace::new(normal.extend(d))); } } else { let x_slices = clusters.dimensions.x as f32; for x in 0..=clusters.dimensions.x { let x_proportion = x as f32 / x_slices; let x_pos = x_proportion * 2.0 - 1.0; let nb = clip_to_view(view_from_clip, Vec4::new(x_pos, -1.0, 1.0, 1.0)).xyz(); let nt = clip_to_view(view_from_clip, Vec4::new(x_pos, 1.0, 1.0, 1.0)).xyz(); let normal = nb.cross(nt); let d = nb.dot(normal); x_planes.push(HalfSpace::new(normal.extend(d))); } let y_slices = clusters.dimensions.y as f32; for y in 0..=clusters.dimensions.y { let y_proportion = 1.0 - y as f32 / y_slices; let y_pos = y_proportion * 2.0 - 1.0; let nl = clip_to_view(view_from_clip, Vec4::new(-1.0, y_pos, 1.0, 1.0)).xyz(); let nr = clip_to_view(view_from_clip, Vec4::new(1.0, y_pos, 1.0, 1.0)).xyz(); let normal = nr.cross(nl); let d = nr.dot(normal); y_planes.push(HalfSpace::new(normal.extend(d))); } } let z_slices = clusters.dimensions.z; for z in 0..=z_slices { let view_z = z_slice_to_view_z(first_slice_depth, far_z, z_slices, z, is_orthographic); let normal = -Vec3::Z; let d = view_z * normal.z; z_planes.push(HalfSpace::new(normal.extend(d))); } let mut update_from_object_intersections = |visible_clusterable_objects: &mut Vec< Entity, >| { for clusterable_object in &clusterable_objects { // check if the clusterable light layers overlap the view layers if !view_layers.intersects(&clusterable_object.render_layers) { continue; } let clusterable_object_sphere = clusterable_object.sphere(); // Check if the clusterable object is within the view frustum if !frustum.intersects_sphere(&clusterable_object_sphere, true) { continue; } // NOTE: The clusterable object intersects the frustum so it // must be visible and part of the global set global_clusterable_objects .entities .insert(clusterable_object.entity); visible_clusterable_objects.push(clusterable_object.entity); // note: caching seems to be slower than calling twice for this aabb calculation let ( clusterable_object_aabb_xy_ndc_z_view_min, clusterable_object_aabb_xy_ndc_z_view_max, ) = cluster_space_clusterable_object_aabb( view_from_world, view_from_world_scale, camera.clip_from_view(), &clusterable_object_sphere, ); let min_cluster = ndc_position_to_cluster( clusters.dimensions, cluster_factors, is_orthographic, clusterable_object_aabb_xy_ndc_z_view_min, clusterable_object_aabb_xy_ndc_z_view_min.z, ); let max_cluster = ndc_position_to_cluster( clusters.dimensions, cluster_factors, is_orthographic, clusterable_object_aabb_xy_ndc_z_view_max, clusterable_object_aabb_xy_ndc_z_view_max.z, ); let (min_cluster, max_cluster) = (min_cluster.min(max_cluster), min_cluster.max(max_cluster)); // What follows is the Iterative Sphere Refinement algorithm from Just Cause 3 // Persson et al, Practical Clustered Shading // http://newq.net/dl/pub/s2015_practical.pdf // NOTE: A sphere under perspective projection is no longer a sphere. It gets // stretched and warped, which prevents simpler algorithms from being correct // as they often assume that the widest part of the sphere under projection is the // center point on the axis of interest plus the radius, and that is not true! let view_clusterable_object_sphere = Sphere { center: Vec3A::from_vec4( view_from_world * clusterable_object_sphere.center.extend(1.0), ), radius: clusterable_object_sphere.radius * view_from_world_scale_max, }; let spot_light_dir_sin_cos = match clusterable_object.object_type { ClusterableObjectType::SpotLight { outer_angle, .. } => { let (angle_sin, angle_cos) = sin_cos(outer_angle); Some(( (view_from_world * clusterable_object.transform.back().extend(0.0)) .truncate() .normalize(), angle_sin, angle_cos, )) } ClusterableObjectType::Decal => { // TODO: cull via a frustum None } ClusterableObjectType::PointLight { .. } | ClusterableObjectType::ReflectionProbe | ClusterableObjectType::IrradianceVolume => None, }; let clusterable_object_center_clip = camera.clip_from_view() * view_clusterable_object_sphere.center.extend(1.0); let object_center_ndc = clusterable_object_center_clip.xyz() / clusterable_object_center_clip.w; let cluster_coordinates = ndc_position_to_cluster( clusters.dimensions, cluster_factors, is_orthographic, object_center_ndc, view_clusterable_object_sphere.center.z, ); let z_center = if object_center_ndc.z <= 1.0 { Some(cluster_coordinates.z) } else { None }; let y_center = if object_center_ndc.y > 1.0 { None } else if object_center_ndc.y < -1.0 { Some(clusters.dimensions.y + 1) } else { Some(cluster_coordinates.y) }; for z in min_cluster.z..=max_cluster.z { let mut z_object = view_clusterable_object_sphere.clone(); if z_center.is_none() || z != z_center.unwrap() { // The z plane closer to the clusterable object has the // larger radius circle where the light sphere // intersects the z plane. let z_plane = if z_center.is_some() && z < z_center.unwrap() { z_planes[(z + 1) as usize] } else { z_planes[z as usize] }; // Project the sphere to this z plane and use its radius as the radius of a // new, refined sphere. if let Some(projected) = project_to_plane_z(z_object, z_plane) { z_object = projected; } else { continue; } } for y in min_cluster.y..=max_cluster.y { let mut y_object = z_object.clone(); if y_center.is_none() || y != y_center.unwrap() { // The y plane closer to the clusterable object has // the larger radius circle where the light sphere // intersects the y plane. let y_plane = if y_center.is_some() && y < y_center.unwrap() { y_planes[(y + 1) as usize] } else { y_planes[y as usize] }; // Project the refined sphere to this y plane and use its radius as the // radius of a new, even more refined sphere. if let Some(projected) = project_to_plane_y(y_object, y_plane, is_orthographic) { y_object = projected; } else { continue; } } // Loop from the left to find the first affected cluster let mut min_x = min_cluster.x; loop { if min_x >= max_cluster.x || -get_distance_x( x_planes[(min_x + 1) as usize], y_object.center, is_orthographic, ) + y_object.radius > 0.0 { break; } min_x += 1; } // Loop from the right to find the last affected cluster let mut max_x = max_cluster.x; loop { if max_x <= min_x || get_distance_x( x_planes[max_x as usize], y_object.center, is_orthographic, ) + y_object.radius > 0.0 { break; } max_x -= 1; } let mut cluster_index = ((y * clusters.dimensions.x + min_x) * clusters.dimensions.z + z) as usize; match clusterable_object.object_type { ClusterableObjectType::SpotLight { .. } => { let (view_light_direction, angle_sin, angle_cos) = spot_light_dir_sin_cos.unwrap(); for x in min_x..=max_x { // further culling for spot lights // get or initialize cluster bounding sphere let cluster_aabb_sphere = &mut cluster_aabb_spheres[cluster_index]; let cluster_aabb_sphere = if let Some(sphere) = cluster_aabb_sphere { &*sphere } else { let aabb = compute_aabb_for_cluster( first_slice_depth, far_z, clusters.tile_size.as_vec2(), screen_size.as_vec2(), view_from_clip, is_orthographic, clusters.dimensions, UVec3::new(x, y, z), ); let sphere = Sphere { center: aabb.center,
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_input/src/lib.rs
crates/bevy_input/src/lib.rs
#![cfg_attr(docsrs, feature(doc_cfg))] #![forbid(unsafe_code)] #![doc( html_logo_url = "https://bevy.org/assets/icon.png", html_favicon_url = "https://bevy.org/assets/icon.png" )] #![no_std] //! Input functionality for the [Bevy game engine](https://bevy.org/). //! //! # Supported input devices //! //! `bevy` currently supports keyboard, mouse, gamepad, and touch inputs. #[cfg(feature = "std")] extern crate std; extern crate alloc; mod axis; mod button_input; /// Common run conditions pub mod common_conditions; #[cfg(feature = "gamepad")] pub mod gamepad; #[cfg(feature = "gestures")] pub mod gestures; #[cfg(feature = "keyboard")] pub mod keyboard; #[cfg(feature = "mouse")] pub mod mouse; #[cfg(feature = "touch")] pub mod touch; pub use axis::*; pub use button_input::*; /// The input prelude. /// /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { #[doc(hidden)] pub use crate::{Axis, ButtonInput}; #[doc(hidden)] #[cfg(feature = "gamepad")] pub use crate::gamepad::{Gamepad, GamepadAxis, GamepadButton, GamepadSettings}; #[doc(hidden)] #[cfg(feature = "keyboard")] pub use crate::keyboard::KeyCode; #[doc(hidden)] #[cfg(feature = "mouse")] pub use crate::mouse::MouseButton; #[doc(hidden)] #[cfg(feature = "touch")] pub use crate::touch::{TouchInput, Touches}; } use bevy_app::prelude::*; use bevy_ecs::prelude::*; #[cfg(feature = "bevy_reflect")] use bevy_reflect::Reflect; #[cfg(feature = "gestures")] use gestures::*; #[cfg(feature = "keyboard")] use keyboard::{keyboard_input_system, Key, KeyCode, KeyboardFocusLost, KeyboardInput}; #[cfg(feature = "mouse")] use mouse::{ accumulate_mouse_motion_system, accumulate_mouse_scroll_system, mouse_button_input_system, AccumulatedMouseMotion, AccumulatedMouseScroll, MouseButton, MouseButtonInput, MouseMotion, MouseWheel, }; #[cfg(feature = "touch")] use touch::{touch_screen_input_system, TouchInput, Touches}; #[cfg(feature = "gamepad")] use gamepad::{ gamepad_connection_system, gamepad_event_processing_system, GamepadAxisChangedEvent, GamepadButtonChangedEvent, GamepadButtonStateChangedEvent, GamepadConnectionEvent, GamepadEvent, GamepadRumbleRequest, RawGamepadAxisChangedEvent, RawGamepadButtonChangedEvent, RawGamepadEvent, }; #[cfg(all(feature = "serialize", feature = "bevy_reflect"))] use bevy_reflect::{ReflectDeserialize, ReflectSerialize}; /// Adds input from various sources to an App #[derive(Default)] pub struct InputPlugin; /// Label for systems that update the input data. #[derive(Debug, PartialEq, Eq, Clone, Hash, SystemSet)] pub struct InputSystems; impl Plugin for InputPlugin { #[expect(clippy::allow_attributes, reason = "this is only sometimes unused")] #[allow(unused, reason = "all features could be disabled")] fn build(&self, app: &mut App) { #[cfg(feature = "keyboard")] app.add_message::<KeyboardInput>() .add_message::<KeyboardFocusLost>() .init_resource::<ButtonInput<KeyCode>>() .init_resource::<ButtonInput<Key>>() .add_systems(PreUpdate, keyboard_input_system.in_set(InputSystems)); #[cfg(feature = "mouse")] app.add_message::<MouseButtonInput>() .add_message::<MouseMotion>() .add_message::<MouseWheel>() .init_resource::<AccumulatedMouseMotion>() .init_resource::<AccumulatedMouseScroll>() .init_resource::<ButtonInput<MouseButton>>() .add_systems( PreUpdate, ( mouse_button_input_system, accumulate_mouse_motion_system, accumulate_mouse_scroll_system, ) .in_set(InputSystems), ); #[cfg(feature = "gestures")] app.add_message::<PinchGesture>() .add_message::<RotationGesture>() .add_message::<DoubleTapGesture>() .add_message::<PanGesture>(); #[cfg(feature = "gamepad")] app.add_message::<GamepadEvent>() .add_message::<GamepadConnectionEvent>() .add_message::<GamepadButtonChangedEvent>() .add_message::<GamepadButtonStateChangedEvent>() .add_message::<GamepadAxisChangedEvent>() .add_message::<RawGamepadEvent>() .add_message::<RawGamepadAxisChangedEvent>() .add_message::<RawGamepadButtonChangedEvent>() .add_message::<GamepadRumbleRequest>() .add_systems( PreUpdate, ( gamepad_connection_system, gamepad_event_processing_system.after(gamepad_connection_system), ) .in_set(InputSystems), ); #[cfg(feature = "touch")] app.add_message::<TouchInput>() .init_resource::<Touches>() .add_systems(PreUpdate, touch_screen_input_system.in_set(InputSystems)); } } /// The current "press" state of an element #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, Hash, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub enum ButtonState { /// The button is pressed. Pressed, /// The button is not pressed. Released, } impl ButtonState { /// Is this button pressed? pub fn is_pressed(&self) -> bool { matches!(self, ButtonState::Pressed) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_input/src/gestures.rs
crates/bevy_input/src/gestures.rs
//! Gestures functionality, from touchscreens and touchpads. use bevy_ecs::message::Message; use bevy_math::Vec2; #[cfg(feature = "bevy_reflect")] use bevy_reflect::Reflect; #[cfg(all(feature = "serialize", feature = "bevy_reflect"))] use bevy_reflect::{ReflectDeserialize, ReflectSerialize}; /// Two-finger pinch gesture, often used for magnifications. /// /// Positive delta values indicate magnification (zooming in) and /// negative delta values indicate shrinking (zooming out). /// /// ## Platform-specific /// /// - Only available on **`macOS`** and **`iOS`**. /// - On **`iOS`**, must be enabled first #[derive(Message, Debug, Clone, Copy, PartialEq)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct PinchGesture(pub f32); /// Two-finger rotation gesture. /// /// Positive delta values indicate rotation counterclockwise and /// negative delta values indicate rotation clockwise. /// /// ## Platform-specific /// /// - Only available on **`macOS`** and **`iOS`**. /// - On **`iOS`**, must be enabled first #[derive(Message, Debug, Clone, Copy, PartialEq)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct RotationGesture(pub f32); /// Double tap gesture. /// /// ## Platform-specific /// /// - Only available on **`macOS`** and **`iOS`**. /// - On **`iOS`**, must be enabled first #[derive(Message, Debug, Clone, Copy, PartialEq)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct DoubleTapGesture; /// Pan gesture. /// /// ## Platform-specific /// /// - On **`iOS`**, must be enabled first #[derive(Message, Debug, Clone, Copy, PartialEq)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct PanGesture(pub Vec2);
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_input/src/mouse.rs
crates/bevy_input/src/mouse.rs
//! The mouse input functionality. use crate::{ButtonInput, ButtonState}; use bevy_ecs::{ change_detection::DetectChangesMut, entity::Entity, message::{Message, MessageReader}, resource::Resource, system::ResMut, }; use bevy_math::Vec2; #[cfg(feature = "bevy_reflect")] use { bevy_ecs::reflect::ReflectResource, bevy_reflect::{std_traits::ReflectDefault, Reflect}, }; #[cfg(all(feature = "serialize", feature = "bevy_reflect"))] use bevy_reflect::{ReflectDeserialize, ReflectSerialize}; /// A mouse button input event. /// /// This event is the translated version of the `WindowEvent::MouseInput` from the `winit` crate. /// /// ## Usage /// /// The event is read inside of the [`mouse_button_input_system`] /// to update the [`ButtonInput<MouseButton>`] resource. #[derive(Message, Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct MouseButtonInput { /// The mouse button assigned to the event. pub button: MouseButton, /// The pressed state of the button. pub state: ButtonState, /// Window that received the input. pub window: Entity, } /// A button on a mouse device. /// /// ## Usage /// /// It is used as the generic `T` value of an [`ButtonInput`] to create a `bevy` /// resource. /// /// ## Updating /// /// The resource is updated inside of the [`mouse_button_input_system`]. #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, Hash, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub enum MouseButton { /// The left mouse button. Left, /// The right mouse button. Right, /// The middle mouse button. Middle, /// The back mouse button. Back, /// The forward mouse button. Forward, /// Another mouse button with the associated number. Other(u16), } /// An event reporting the change in physical position of a pointing device. /// /// This represents raw, unfiltered physical motion. /// It is the translated version of [`DeviceEvent::MouseMotion`] from the `winit` crate. /// /// All pointing devices connected to a single machine at the same time can emit the event independently. /// However, the event data does not make it possible to distinguish which device it is referring to. /// /// [`DeviceEvent::MouseMotion`]: https://docs.rs/winit/latest/winit/event/enum.DeviceEvent.html#variant.MouseMotion #[derive(Message, Debug, Clone, Copy, PartialEq)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct MouseMotion { /// The change in the position of the pointing device since the last event was sent. pub delta: Vec2, } /// The scroll unit. /// /// Describes how a value of a [`MouseWheel`] event has to be interpreted. /// /// The value of the event can either be interpreted as the amount of lines or the amount of pixels /// to scroll. #[derive(Debug, Hash, Clone, Copy, Eq, PartialEq)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub enum MouseScrollUnit { /// The line scroll unit. /// /// The delta of the associated [`MouseWheel`] event corresponds /// to the amount of lines or rows to scroll. Line, /// The pixel scroll unit. /// /// The delta of the associated [`MouseWheel`] event corresponds /// to the amount of pixels to scroll. Pixel, } impl MouseScrollUnit { /// An approximate conversion factor to account for the difference between /// [`MouseScrollUnit::Line`] and [`MouseScrollUnit::Pixel`]. /// /// Each line corresponds to many pixels; this must be corrected for in order to ensure that /// mouse wheel controls are scaled properly regardless of the provided input events for the end user. /// /// This value is correct for Microsoft Edge, but its validity has not been broadly tested. /// Please file an issue if you find that this differs on certain platforms or hardware! pub const SCROLL_UNIT_CONVERSION_FACTOR: f32 = 100.; } /// A mouse wheel event. /// /// This event is the translated version of the `WindowEvent::MouseWheel` from the `winit` crate. #[derive(Message, Debug, Clone, Copy, PartialEq)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct MouseWheel { /// The mouse scroll unit. pub unit: MouseScrollUnit, /// The horizontal scroll value. pub x: f32, /// The vertical scroll value. pub y: f32, /// Window that received the input. pub window: Entity, } /// Updates the [`ButtonInput<MouseButton>`] resource with the latest [`MouseButtonInput`] events. /// /// ## Differences /// /// The main difference between the [`MouseButtonInput`] event and the [`ButtonInput<MouseButton>`] resource is that /// the latter has convenient functions like [`ButtonInput::pressed`], [`ButtonInput::just_pressed`] and [`ButtonInput::just_released`]. pub fn mouse_button_input_system( mut mouse_button_input: ResMut<ButtonInput<MouseButton>>, mut mouse_button_input_events: MessageReader<MouseButtonInput>, ) { mouse_button_input.bypass_change_detection().clear(); for event in mouse_button_input_events.read() { match event.state { ButtonState::Pressed => mouse_button_input.press(event.button), ButtonState::Released => mouse_button_input.release(event.button), } } } /// Tracks how much the mouse has moved every frame. /// /// This resource is reset to zero every frame. /// /// This resource sums the total [`MouseMotion`] events received this frame. #[derive(Resource, Debug, Clone, Copy, PartialEq, Default)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, Default, Resource, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct AccumulatedMouseMotion { /// The change in mouse position. pub delta: Vec2, } /// Tracks how much the mouse has scrolled every frame. /// /// This resource is reset to zero every frame. /// /// This resource sums the total [`MouseWheel`] events received this frame. #[derive(Resource, Debug, Clone, Copy, PartialEq)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, Default, Resource, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct AccumulatedMouseScroll { /// The mouse scroll unit. /// If this value changes while scrolling, then the /// result of the accumulation could be incorrect pub unit: MouseScrollUnit, /// The change in scroll position. pub delta: Vec2, } impl Default for AccumulatedMouseScroll { fn default() -> Self { Self { unit: MouseScrollUnit::Line, delta: Vec2::ZERO, } } } /// Updates the [`AccumulatedMouseMotion`] resource using the [`MouseMotion`] event. /// The value of [`AccumulatedMouseMotion`] is reset to zero every frame pub fn accumulate_mouse_motion_system( mut mouse_motion_event: MessageReader<MouseMotion>, mut accumulated_mouse_motion: ResMut<AccumulatedMouseMotion>, ) { let mut delta = Vec2::ZERO; for event in mouse_motion_event.read() { delta += event.delta; } accumulated_mouse_motion.delta = delta; } /// Updates the [`AccumulatedMouseScroll`] resource using the [`MouseWheel`] event. /// The value of [`AccumulatedMouseScroll`] is reset to zero every frame pub fn accumulate_mouse_scroll_system( mut mouse_scroll_event: MessageReader<MouseWheel>, mut accumulated_mouse_scroll: ResMut<AccumulatedMouseScroll>, ) { let mut delta = Vec2::ZERO; let mut unit = MouseScrollUnit::Line; for event in mouse_scroll_event.read() { if event.unit != unit { unit = event.unit; } delta += Vec2::new(event.x, event.y); } accumulated_mouse_scroll.delta = delta; accumulated_mouse_scroll.unit = unit; }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_input/src/button_input.rs
crates/bevy_input/src/button_input.rs
//! The generic input type. use bevy_ecs::resource::Resource; use bevy_platform::collections::HashSet; use core::hash::Hash; #[cfg(feature = "bevy_reflect")] use { bevy_ecs::reflect::ReflectResource, bevy_reflect::{std_traits::ReflectDefault, Reflect}, }; /// A "press-able" input of type `T`. /// /// ## Usage /// /// This type can be used as a resource to keep the current state of an input, by reacting to /// events from the input. For a given input value: /// /// * [`ButtonInput::pressed`] will return `true` between a press and a release event. /// * [`ButtonInput::just_pressed`] will return `true` for one frame after a press event. /// * [`ButtonInput::just_released`] will return `true` for one frame after a release event. /// /// ## Multiple systems /// /// In case multiple systems are checking for [`ButtonInput::just_pressed`] or [`ButtonInput::just_released`] /// but only one should react, for example when modifying a /// [`Resource`], you should consider clearing the input state, either by: /// /// * Using [`ButtonInput::clear_just_pressed`] or [`ButtonInput::clear_just_released`] instead. /// * Calling [`ButtonInput::clear`] or [`ButtonInput::reset`] immediately after the state change. /// /// ## Performance /// /// For all operations, the following conventions are used: /// - **n** is the number of stored inputs. /// - **m** is the number of input arguments passed to the method. /// - **\***-suffix denotes an amortized cost. /// - **~**-suffix denotes an expected cost. /// /// See Rust's [std::collections doc on performance](https://doc.rust-lang.org/std/collections/index.html#performance) for more details on the conventions used here. /// /// | **[`ButtonInput`] operations** | **Computational complexity** | /// |-----------------------------------|------------------------------------| /// | [`ButtonInput::any_just_pressed`] | *O*(m)~ | /// | [`ButtonInput::any_just_released`] | *O*(m)~ | /// | [`ButtonInput::any_pressed`] | *O*(m)~ | /// | [`ButtonInput::get_just_pressed`] | *O*(n) | /// | [`ButtonInput::get_just_released`] | *O*(n) | /// | [`ButtonInput::get_pressed`] | *O*(n) | /// | [`ButtonInput::just_pressed`] | *O*(1)~ | /// | [`ButtonInput::just_released`] | *O*(1)~ | /// | [`ButtonInput::pressed`] | *O*(1)~ | /// | [`ButtonInput::press`] | *O*(1)~* | /// | [`ButtonInput::release`] | *O*(1)~* | /// | [`ButtonInput::release_all`] | *O*(n)~* | /// | [`ButtonInput::clear_just_pressed`] | *O*(1)~ | /// | [`ButtonInput::clear_just_released`] | *O*(1)~ | /// | [`ButtonInput::reset_all`] | *O*(n) | /// | [`ButtonInput::clear`] | *O*(n) | /// /// ## Window focus /// /// `ButtonInput<KeyCode>` is tied to window focus. For example, if the user holds a button /// while the window loses focus, [`ButtonInput::just_released`] will be triggered. Similarly if the window /// regains focus, [`ButtonInput::just_pressed`] will be triggered. /// /// `ButtonInput<GamepadButton>` is independent of window focus. /// /// ## Examples /// /// Reading and checking against the current set of pressed buttons: /// ```no_run /// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, Update}; /// # use bevy_ecs::{prelude::{IntoScheduleConfigs, Res, Resource, resource_changed}, schedule::SystemCondition}; /// # use bevy_input::{ButtonInput, prelude::{KeyCode, MouseButton}}; /// /// fn main() { /// App::new() /// .add_plugins(DefaultPlugins) /// .add_systems( /// Update, /// print_mouse.run_if(resource_changed::<ButtonInput<MouseButton>>), /// ) /// .add_systems( /// Update, /// print_keyboard.run_if(resource_changed::<ButtonInput<KeyCode>>), /// ) /// .run(); /// } /// /// fn print_mouse(mouse: Res<ButtonInput<MouseButton>>) { /// println!("Mouse: {:?}", mouse.get_pressed().collect::<Vec<_>>()); /// } /// /// fn print_keyboard(keyboard: Res<ButtonInput<KeyCode>>) { /// if keyboard.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight]) /// && keyboard.any_pressed([KeyCode::AltLeft, KeyCode::AltRight]) /// && keyboard.any_pressed([KeyCode::ShiftLeft, KeyCode::ShiftRight]) /// && keyboard.any_pressed([KeyCode::SuperLeft, KeyCode::SuperRight]) /// && keyboard.pressed(KeyCode::KeyL) /// { /// println!("On Windows this opens LinkedIn."); /// } else { /// println!("keyboard: {:?}", keyboard.get_pressed().collect::<Vec<_>>()); /// } /// } /// ``` /// /// ## Note /// /// When adding this resource for a new input type, you should: /// /// * Call the [`ButtonInput::press`] method for each press event. /// * Call the [`ButtonInput::release`] method for each release event. /// * Call the [`ButtonInput::clear`] method at each frame start, before processing events. /// /// Note: Calling `clear` from a [`ResMut`] will trigger change detection. /// It may be preferable to use [`DetectChangesMut::bypass_change_detection`] /// to avoid causing the resource to always be marked as changed. /// /// [`ResMut`]: bevy_ecs::system::ResMut /// [`DetectChangesMut::bypass_change_detection`]: bevy_ecs::change_detection::DetectChangesMut::bypass_change_detection #[derive(Debug, Clone, Resource)] #[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Default, Resource))] pub struct ButtonInput<T: Clone + Eq + Hash + Send + Sync + 'static> { /// A collection of every button that is currently being pressed. pressed: HashSet<T>, /// A collection of every button that has just been pressed. just_pressed: HashSet<T>, /// A collection of every button that has just been released. just_released: HashSet<T>, } impl<T: Clone + Eq + Hash + Send + Sync + 'static> Default for ButtonInput<T> { fn default() -> Self { Self { pressed: Default::default(), just_pressed: Default::default(), just_released: Default::default(), } } } impl<T> ButtonInput<T> where T: Clone + Eq + Hash + Send + Sync + 'static, { /// Registers a press for the given `input`. pub fn press(&mut self, input: T) { // Returns `true` if the `input` wasn't pressed. if self.pressed.insert(input.clone()) { self.just_pressed.insert(input); } } /// Returns `true` if the `input` has been pressed. pub fn pressed(&self, input: T) -> bool { self.pressed.contains(&input) } /// Returns `true` if any item in `inputs` has been pressed. pub fn any_pressed(&self, inputs: impl IntoIterator<Item = T>) -> bool { inputs.into_iter().any(|it| self.pressed(it)) } /// Returns `true` if all items in `inputs` have been pressed. pub fn all_pressed(&self, inputs: impl IntoIterator<Item = T>) -> bool { inputs.into_iter().all(|it| self.pressed(it)) } /// Registers a release for the given `input`. pub fn release(&mut self, input: T) { // Returns `true` if the `input` was pressed. if self.pressed.remove(&input) { self.just_released.insert(input); } } /// Registers a release for all currently pressed inputs. pub fn release_all(&mut self) { // Move all items from pressed into just_released self.just_released.extend(self.pressed.drain()); } /// Returns `true` if the `input` has been pressed during the current frame. /// /// Note: This function does not imply information regarding the current state of [`ButtonInput::pressed`] or [`ButtonInput::just_released`]. pub fn just_pressed(&self, input: T) -> bool { self.just_pressed.contains(&input) } /// Returns `true` if any item in `inputs` has been pressed during the current frame. pub fn any_just_pressed(&self, inputs: impl IntoIterator<Item = T>) -> bool { inputs.into_iter().any(|it| self.just_pressed(it)) } /// Clears the `just_pressed` state of the `input` and returns `true` if the `input` has just been pressed. /// /// Future calls to [`ButtonInput::just_pressed`] for the given input will return false until a new press event occurs. pub fn clear_just_pressed(&mut self, input: T) -> bool { self.just_pressed.remove(&input) } /// Returns `true` if the `input` has been released during the current frame. /// /// Note: This function does not imply information regarding the current state of [`ButtonInput::pressed`] or [`ButtonInput::just_pressed`]. pub fn just_released(&self, input: T) -> bool { self.just_released.contains(&input) } /// Returns `true` if any item in `inputs` has just been released. pub fn any_just_released(&self, inputs: impl IntoIterator<Item = T>) -> bool { inputs.into_iter().any(|input| self.just_released(input)) } /// Returns `true` if all items in `inputs` have just been released. pub fn all_just_released(&self, inputs: impl IntoIterator<Item = T>) -> bool { inputs.into_iter().all(|input| self.just_released(input)) } /// Returns `true` if all items in `inputs` have been just pressed. pub fn all_just_pressed(&self, inputs: impl IntoIterator<Item = T>) -> bool { inputs.into_iter().all(|input| self.just_pressed(input)) } /// Clears the `just_released` state of the `input` and returns `true` if the `input` has just been released. /// /// Future calls to [`ButtonInput::just_released`] for the given input will return false until a new release event occurs. pub fn clear_just_released(&mut self, input: T) -> bool { self.just_released.remove(&input) } /// Clears the `pressed`, `just_pressed` and `just_released` data of the `input`. pub fn reset(&mut self, input: T) { self.pressed.remove(&input); self.just_pressed.remove(&input); self.just_released.remove(&input); } /// Clears the `pressed`, `just_pressed`, and `just_released` data for every input. /// /// See also [`ButtonInput::clear`] for simulating elapsed time steps. pub fn reset_all(&mut self) { self.pressed.clear(); self.just_pressed.clear(); self.just_released.clear(); } /// Clears the `just pressed` and `just released` data for every input. /// /// See also [`ButtonInput::reset_all`] for a full reset. pub fn clear(&mut self) { self.just_pressed.clear(); self.just_released.clear(); } /// An iterator visiting every pressed input in arbitrary order. pub fn get_pressed(&self) -> impl ExactSizeIterator<Item = &T> { self.pressed.iter() } /// An iterator visiting every just pressed input in arbitrary order. /// /// Note: Returned elements do not imply information regarding the current state of [`ButtonInput::pressed`] or [`ButtonInput::just_released`]. pub fn get_just_pressed(&self) -> impl ExactSizeIterator<Item = &T> { self.just_pressed.iter() } /// An iterator visiting every just released input in arbitrary order. /// /// Note: Returned elements do not imply information regarding the current state of [`ButtonInput::pressed`] or [`ButtonInput::just_pressed`]. pub fn get_just_released(&self) -> impl ExactSizeIterator<Item = &T> { self.just_released.iter() } } #[cfg(test)] mod test { use crate::ButtonInput; /// Used for testing the functionality of [`ButtonInput`]. #[derive(Copy, Clone, Eq, PartialEq, Hash)] enum DummyInput { Input1, Input2, } #[test] fn test_press() { let mut input = ButtonInput::default(); assert!(!input.pressed.contains(&DummyInput::Input1)); assert!(!input.just_pressed.contains(&DummyInput::Input1)); input.press(DummyInput::Input1); assert!(input.just_pressed.contains(&DummyInput::Input1)); assert!(input.pressed.contains(&DummyInput::Input1)); } #[test] fn test_pressed() { let mut input = ButtonInput::default(); assert!(!input.pressed(DummyInput::Input1)); input.press(DummyInput::Input1); assert!(input.pressed(DummyInput::Input1)); } #[test] fn test_any_pressed() { let mut input = ButtonInput::default(); assert!(!input.any_pressed([DummyInput::Input1])); assert!(!input.any_pressed([DummyInput::Input2])); assert!(!input.any_pressed([DummyInput::Input1, DummyInput::Input2])); input.press(DummyInput::Input1); assert!(input.any_pressed([DummyInput::Input1])); assert!(!input.any_pressed([DummyInput::Input2])); assert!(input.any_pressed([DummyInput::Input1, DummyInput::Input2])); } #[test] fn test_all_pressed() { let mut input = ButtonInput::default(); assert!(!input.all_pressed([DummyInput::Input1])); assert!(!input.all_pressed([DummyInput::Input2])); assert!(!input.all_pressed([DummyInput::Input1, DummyInput::Input2])); input.press(DummyInput::Input1); assert!(input.all_pressed([DummyInput::Input1])); assert!(!input.all_pressed([DummyInput::Input1, DummyInput::Input2])); input.press(DummyInput::Input2); assert!(input.all_pressed([DummyInput::Input1, DummyInput::Input2])); } #[test] fn test_release() { let mut input = ButtonInput::default(); input.press(DummyInput::Input1); assert!(input.pressed.contains(&DummyInput::Input1)); assert!(!input.just_released.contains(&DummyInput::Input1)); input.release(DummyInput::Input1); assert!(!input.pressed.contains(&DummyInput::Input1)); assert!(input.just_released.contains(&DummyInput::Input1)); } #[test] fn test_release_all() { let mut input = ButtonInput::default(); input.press(DummyInput::Input1); input.press(DummyInput::Input2); input.release_all(); assert!(input.pressed.is_empty()); assert!(input.just_released.contains(&DummyInput::Input1)); assert!(input.just_released.contains(&DummyInput::Input2)); } #[test] fn test_just_pressed() { let mut input = ButtonInput::default(); assert!(!input.just_pressed(DummyInput::Input1)); input.press(DummyInput::Input1); assert!(input.just_pressed(DummyInput::Input1)); } #[test] fn test_any_just_pressed() { let mut input = ButtonInput::default(); assert!(!input.any_just_pressed([DummyInput::Input1])); assert!(!input.any_just_pressed([DummyInput::Input2])); assert!(!input.any_just_pressed([DummyInput::Input1, DummyInput::Input2])); input.press(DummyInput::Input1); assert!(input.any_just_pressed([DummyInput::Input1])); assert!(!input.any_just_pressed([DummyInput::Input2])); assert!(input.any_just_pressed([DummyInput::Input1, DummyInput::Input2])); } #[test] fn test_clear_just_pressed() { let mut input = ButtonInput::default(); input.press(DummyInput::Input1); assert!(input.just_pressed(DummyInput::Input1)); input.clear_just_pressed(DummyInput::Input1); assert!(!input.just_pressed(DummyInput::Input1)); } #[test] fn test_just_released() { let mut input = ButtonInput::default(); input.press(DummyInput::Input1); assert!(!input.just_released(DummyInput::Input1)); input.release(DummyInput::Input1); assert!(input.just_released(DummyInput::Input1)); } #[test] fn test_any_just_released() { let mut input = ButtonInput::default(); input.press(DummyInput::Input1); assert!(!input.any_just_released([DummyInput::Input1])); assert!(!input.any_just_released([DummyInput::Input2])); assert!(!input.any_just_released([DummyInput::Input1, DummyInput::Input2])); input.release(DummyInput::Input1); assert!(input.any_just_released([DummyInput::Input1])); assert!(!input.any_just_released([DummyInput::Input2])); assert!(input.any_just_released([DummyInput::Input1, DummyInput::Input2])); } #[test] fn test_clear_just_released() { let mut input = ButtonInput::default(); input.press(DummyInput::Input1); input.release(DummyInput::Input1); assert!(input.just_released(DummyInput::Input1)); input.clear_just_released(DummyInput::Input1); assert!(!input.just_released(DummyInput::Input1)); } #[test] fn test_reset() { let mut input = ButtonInput::default(); // Pressed input.press(DummyInput::Input1); assert!(input.pressed(DummyInput::Input1)); assert!(input.just_pressed(DummyInput::Input1)); assert!(!input.just_released(DummyInput::Input1)); input.reset(DummyInput::Input1); assert!(!input.pressed(DummyInput::Input1)); assert!(!input.just_pressed(DummyInput::Input1)); assert!(!input.just_released(DummyInput::Input1)); // Released input.press(DummyInput::Input1); input.release(DummyInput::Input1); assert!(!input.pressed(DummyInput::Input1)); assert!(input.just_pressed(DummyInput::Input1)); assert!(input.just_released(DummyInput::Input1)); input.reset(DummyInput::Input1); assert!(!input.pressed(DummyInput::Input1)); assert!(!input.just_pressed(DummyInput::Input1)); assert!(!input.just_released(DummyInput::Input1)); } #[test] fn test_reset_all() { let mut input = ButtonInput::default(); input.press(DummyInput::Input1); input.press(DummyInput::Input2); input.release(DummyInput::Input2); assert!(input.pressed.contains(&DummyInput::Input1)); assert!(input.just_pressed.contains(&DummyInput::Input1)); assert!(input.just_released.contains(&DummyInput::Input2)); input.reset_all(); assert!(input.pressed.is_empty()); assert!(input.just_pressed.is_empty()); assert!(input.just_released.is_empty()); } #[test] fn test_clear() { let mut input = ButtonInput::default(); // Pressed input.press(DummyInput::Input1); assert!(input.pressed(DummyInput::Input1)); assert!(input.just_pressed(DummyInput::Input1)); assert!(!input.just_released(DummyInput::Input1)); input.clear(); assert!(input.pressed(DummyInput::Input1)); assert!(!input.just_pressed(DummyInput::Input1)); assert!(!input.just_released(DummyInput::Input1)); // Released input.press(DummyInput::Input1); input.release(DummyInput::Input1); assert!(!input.pressed(DummyInput::Input1)); assert!(!input.just_pressed(DummyInput::Input1)); assert!(input.just_released(DummyInput::Input1)); input.clear(); assert!(!input.pressed(DummyInput::Input1)); assert!(!input.just_pressed(DummyInput::Input1)); assert!(!input.just_released(DummyInput::Input1)); } #[test] fn test_get_pressed() { let mut input = ButtonInput::default(); input.press(DummyInput::Input1); input.press(DummyInput::Input2); let pressed = input.get_pressed(); assert_eq!(pressed.len(), 2); for pressed_input in pressed { assert!(input.pressed.contains(pressed_input)); } } #[test] fn test_get_just_pressed() { let mut input = ButtonInput::default(); input.press(DummyInput::Input1); input.press(DummyInput::Input2); let just_pressed = input.get_just_pressed(); assert_eq!(just_pressed.len(), 2); for just_pressed_input in just_pressed { assert!(input.just_pressed.contains(just_pressed_input)); } } #[test] fn test_get_just_released() { let mut input = ButtonInput::default(); input.press(DummyInput::Input1); input.press(DummyInput::Input2); input.release(DummyInput::Input1); input.release(DummyInput::Input2); let just_released = input.get_just_released(); assert_eq!(just_released.len(), 2); for just_released_input in just_released { assert!(input.just_released.contains(just_released_input)); } } #[test] fn test_general_input_handling() { let mut input = ButtonInput::default(); // Test pressing input.press(DummyInput::Input1); input.press(DummyInput::Input2); // Check if they were `just_pressed` (pressed on this update) assert!(input.just_pressed(DummyInput::Input1)); assert!(input.just_pressed(DummyInput::Input2)); // Check if they are also marked as pressed assert!(input.pressed(DummyInput::Input1)); assert!(input.pressed(DummyInput::Input2)); // Clear the `input`, removing `just_pressed` and `just_released` input.clear(); // Check if they're marked `just_pressed` assert!(!input.just_pressed(DummyInput::Input1)); assert!(!input.just_pressed(DummyInput::Input2)); // Check if they're marked as pressed assert!(input.pressed(DummyInput::Input1)); assert!(input.pressed(DummyInput::Input2)); // Release the inputs and check state input.release(DummyInput::Input1); input.release(DummyInput::Input2); // Check if they're marked as `just_released` (released on this update) assert!(input.just_released(DummyInput::Input1)); assert!(input.just_released(DummyInput::Input2)); // Check that they're not incorrectly marked as pressed assert!(!input.pressed(DummyInput::Input1)); assert!(!input.pressed(DummyInput::Input2)); // Clear the `Input` and check for removal from `just_released` input.clear(); // Check that they're not incorrectly marked as just released assert!(!input.just_released(DummyInput::Input1)); assert!(!input.just_released(DummyInput::Input2)); // Set up an `Input` to test resetting let mut input = ButtonInput::default(); input.press(DummyInput::Input1); input.release(DummyInput::Input2); // Reset the `Input` and test if it was reset correctly input.reset(DummyInput::Input1); input.reset(DummyInput::Input2); assert!(!input.just_pressed(DummyInput::Input1)); assert!(!input.pressed(DummyInput::Input1)); assert!(!input.just_released(DummyInput::Input2)); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_input/src/gamepad.rs
crates/bevy_input/src/gamepad.rs
//! The gamepad input functionality. use core::{ops::RangeInclusive, time::Duration}; use crate::{Axis, ButtonInput, ButtonState}; use alloc::string::String; #[cfg(feature = "bevy_reflect")] use bevy_ecs::prelude::ReflectComponent; use bevy_ecs::{ change_detection::DetectChangesMut, component::Component, entity::Entity, message::{Message, MessageReader, MessageWriter}, name::Name, system::{Commands, Query}, }; use bevy_math::ops; use bevy_math::Vec2; use bevy_platform::collections::HashMap; #[cfg(feature = "bevy_reflect")] use bevy_reflect::{std_traits::ReflectDefault, Reflect}; #[cfg(all(feature = "serialize", feature = "bevy_reflect"))] use bevy_reflect::{ReflectDeserialize, ReflectSerialize}; use derive_more::derive::From; use log::{info, warn}; use thiserror::Error; /// A gamepad event. /// /// This event type is used over the [`GamepadConnectionEvent`], /// [`GamepadButtonChangedEvent`] and [`GamepadAxisChangedEvent`] when /// the in-frame relative ordering of events is important. /// /// This event is produced by `bevy_input`. #[derive(Message, Debug, Clone, PartialEq, From)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub enum GamepadEvent { /// A gamepad has been connected or disconnected. Connection(GamepadConnectionEvent), /// A button of the gamepad has been triggered. Button(GamepadButtonChangedEvent), /// An axis of the gamepad has been triggered. Axis(GamepadAxisChangedEvent), } /// A raw gamepad event. /// /// This event type is used over the [`GamepadConnectionEvent`], /// [`RawGamepadButtonChangedEvent`] and [`RawGamepadAxisChangedEvent`] when /// the in-frame relative ordering of events is important. /// /// This event type is used by `bevy_input` to feed its components. #[derive(Message, Debug, Clone, PartialEq, From)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub enum RawGamepadEvent { /// A gamepad has been connected or disconnected. Connection(GamepadConnectionEvent), /// A button of the gamepad has been triggered. Button(RawGamepadButtonChangedEvent), /// An axis of the gamepad has been triggered. Axis(RawGamepadAxisChangedEvent), } /// [`GamepadButton`] changed event unfiltered by [`GamepadSettings`]. #[derive(Message, Debug, Copy, Clone, PartialEq)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct RawGamepadButtonChangedEvent { /// The gamepad on which the button is triggered. pub gamepad: Entity, /// The type of the triggered button. pub button: GamepadButton, /// The value of the button. pub value: f32, } impl RawGamepadButtonChangedEvent { /// Creates a [`RawGamepadButtonChangedEvent`]. pub fn new(gamepad: Entity, button_type: GamepadButton, value: f32) -> Self { Self { gamepad, button: button_type, value, } } } /// [`GamepadAxis`] changed event unfiltered by [`GamepadSettings`]. #[derive(Message, Debug, Copy, Clone, PartialEq)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct RawGamepadAxisChangedEvent { /// The gamepad on which the axis is triggered. pub gamepad: Entity, /// The type of the triggered axis. pub axis: GamepadAxis, /// The value of the axis. pub value: f32, } impl RawGamepadAxisChangedEvent { /// Creates a [`RawGamepadAxisChangedEvent`]. pub fn new(gamepad: Entity, axis_type: GamepadAxis, value: f32) -> Self { Self { gamepad, axis: axis_type, value, } } } /// A [`Gamepad`] connection event. Created when a connection to a gamepad /// is established and when a gamepad is disconnected. #[derive(Message, Debug, Clone, PartialEq)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct GamepadConnectionEvent { /// The gamepad whose connection status changed. pub gamepad: Entity, /// The change in the gamepads connection. pub connection: GamepadConnection, } impl GamepadConnectionEvent { /// Creates a [`GamepadConnectionEvent`]. pub fn new(gamepad: Entity, connection: GamepadConnection) -> Self { Self { gamepad, connection, } } /// Whether the gamepad is connected. pub fn connected(&self) -> bool { matches!(self.connection, GamepadConnection::Connected { .. }) } /// Whether the gamepad is disconnected. pub fn disconnected(&self) -> bool { !self.connected() } } /// [`GamepadButton`] event triggered by a digital state change. #[derive(Message, Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct GamepadButtonStateChangedEvent { /// The entity that represents this gamepad. pub entity: Entity, /// The gamepad button assigned to the event. pub button: GamepadButton, /// The pressed state of the button. pub state: ButtonState, } impl GamepadButtonStateChangedEvent { /// Creates a new [`GamepadButtonStateChangedEvent`]. pub fn new(entity: Entity, button: GamepadButton, state: ButtonState) -> Self { Self { entity, button, state, } } } /// [`GamepadButton`] event triggered by an analog state change. #[derive(Message, Debug, Clone, Copy, PartialEq)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct GamepadButtonChangedEvent { /// The entity that represents this gamepad. pub entity: Entity, /// The gamepad button assigned to the event. pub button: GamepadButton, /// The pressed state of the button. pub state: ButtonState, /// The analog value of the button (rescaled to be in the 0.0..=1.0 range). pub value: f32, } impl GamepadButtonChangedEvent { /// Creates a new [`GamepadButtonChangedEvent`]. pub fn new(entity: Entity, button: GamepadButton, state: ButtonState, value: f32) -> Self { Self { entity, button, state, value, } } } /// [`GamepadAxis`] event triggered by an analog state change. #[derive(Message, Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr( all(feature = "bevy_reflect", feature = "serialize"), reflect(Serialize, Deserialize) )] pub struct GamepadAxisChangedEvent { /// The entity that represents this gamepad. pub entity: Entity, /// The gamepad axis assigned to the event. pub axis: GamepadAxis, /// The value of this axis (rescaled to account for axis settings). pub value: f32, } impl GamepadAxisChangedEvent { /// Creates a new [`GamepadAxisChangedEvent`]. pub fn new(entity: Entity, axis: GamepadAxis, value: f32) -> Self { Self { entity, axis, value, } } } /// Errors that occur when setting axis settings for gamepad input. #[derive(Error, Debug, PartialEq)] pub enum AxisSettingsError { /// The given parameter `livezone_lowerbound` was not in range -1.0..=0.0. #[error("invalid livezone_lowerbound {0}, expected value [-1.0..=0.0]")] LiveZoneLowerBoundOutOfRange(f32), /// The given parameter `deadzone_lowerbound` was not in range -1.0..=0.0. #[error("invalid deadzone_lowerbound {0}, expected value [-1.0..=0.0]")] DeadZoneLowerBoundOutOfRange(f32), /// The given parameter `deadzone_lowerbound` was not in range -1.0..=0.0. #[error("invalid deadzone_upperbound {0}, expected value [0.0..=1.0]")] DeadZoneUpperBoundOutOfRange(f32), /// The given parameter `deadzone_lowerbound` was not in range -1.0..=0.0. #[error("invalid livezone_upperbound {0}, expected value [0.0..=1.0]")] LiveZoneUpperBoundOutOfRange(f32), /// Parameter `livezone_lowerbound` was not less than or equal to parameter `deadzone_lowerbound`. #[error("invalid parameter values livezone_lowerbound {} deadzone_lowerbound {}, expected livezone_lowerbound <= deadzone_lowerbound", livezone_lowerbound, deadzone_lowerbound)] LiveZoneLowerBoundGreaterThanDeadZoneLowerBound { /// The value of the `livezone_lowerbound` parameter. livezone_lowerbound: f32, /// The value of the `deadzone_lowerbound` parameter. deadzone_lowerbound: f32, }, /// Parameter `deadzone_upperbound` was not less than or equal to parameter `livezone_upperbound`. #[error("invalid parameter values livezone_upperbound {} deadzone_upperbound {}, expected deadzone_upperbound <= livezone_upperbound", livezone_upperbound, deadzone_upperbound)] DeadZoneUpperBoundGreaterThanLiveZoneUpperBound { /// The value of the `livezone_upperbound` parameter. livezone_upperbound: f32, /// The value of the `deadzone_upperbound` parameter. deadzone_upperbound: f32, }, /// The given parameter was not in range 0.0..=2.0. #[error("invalid threshold {0}, expected 0.0 <= threshold <= 2.0")] Threshold(f32), } /// Errors that occur when setting button settings for gamepad input. #[derive(Error, Debug, PartialEq)] pub enum ButtonSettingsError { /// The given parameter was not in range 0.0..=1.0. #[error("invalid release_threshold {0}, expected value [0.0..=1.0]")] ReleaseThresholdOutOfRange(f32), /// The given parameter was not in range 0.0..=1.0. #[error("invalid press_threshold {0}, expected [0.0..=1.0]")] PressThresholdOutOfRange(f32), /// Parameter `release_threshold` was not less than or equal to `press_threshold`. #[error("invalid parameter values release_threshold {} press_threshold {}, expected release_threshold <= press_threshold", release_threshold, press_threshold)] ReleaseThresholdGreaterThanPressThreshold { /// The value of the `press_threshold` parameter. press_threshold: f32, /// The value of the `release_threshold` parameter. release_threshold: f32, }, } /// Stores a connected gamepad's metadata such as the name and its [`GamepadButton`] and [`GamepadAxis`]. /// /// An entity with this component is spawned automatically after [`GamepadConnectionEvent`] /// and updated by [`gamepad_event_processing_system`]. /// /// See also [`GamepadSettings`] for configuration. /// /// # Examples /// /// ``` /// # use bevy_input::gamepad::{Gamepad, GamepadAxis, GamepadButton}; /// # use bevy_ecs::system::Query; /// # use bevy_ecs::name::Name; /// # /// fn gamepad_usage_system(gamepads: Query<(&Name, &Gamepad)>) { /// for (name, gamepad) in &gamepads { /// println!("{name}"); /// /// if gamepad.just_pressed(GamepadButton::North) { /// println!("{} just pressed North", name) /// } /// /// if let Some(left_stick_x) = gamepad.get(GamepadAxis::LeftStickX) { /// println!("left stick X: {}", left_stick_x) /// } /// } /// } /// ``` #[derive(Component, Debug)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, Component, Default) )] #[require(GamepadSettings)] pub struct Gamepad { /// The USB vendor ID as assigned by the USB-IF, if available. pub(crate) vendor_id: Option<u16>, /// The USB product ID as assigned by the [vendor][Self::vendor_id], if available. pub(crate) product_id: Option<u16>, /// [`ButtonInput`] of [`GamepadButton`] representing their digital state. pub(crate) digital: ButtonInput<GamepadButton>, /// [`Axis`] of [`GamepadButton`] representing their analog state. pub(crate) analog: Axis<GamepadInput>, } impl Gamepad { /// Returns the USB vendor ID as assigned by the USB-IF, if available. pub fn vendor_id(&self) -> Option<u16> { self.vendor_id } /// Returns the USB product ID as assigned by the [vendor], if available. /// /// [vendor]: Self::vendor_id pub fn product_id(&self) -> Option<u16> { self.product_id } /// Returns the analog data of the provided [`GamepadAxis`] or [`GamepadButton`]. /// /// This will be clamped between [[`Axis::MIN`],[`Axis::MAX`]]. pub fn get(&self, input: impl Into<GamepadInput>) -> Option<f32> { self.analog.get(input.into()) } /// Returns the unclamped analog data of the provided [`GamepadAxis`] or [`GamepadButton`]. /// /// This value may be outside the [`Axis::MIN`] and [`Axis::MAX`] range. pub fn get_unclamped(&self, input: impl Into<GamepadInput>) -> Option<f32> { self.analog.get_unclamped(input.into()) } /// Returns the left stick as a [`Vec2`]. pub fn left_stick(&self) -> Vec2 { Vec2 { x: self.get(GamepadAxis::LeftStickX).unwrap_or(0.0), y: self.get(GamepadAxis::LeftStickY).unwrap_or(0.0), } } /// Returns the right stick as a [`Vec2`]. pub fn right_stick(&self) -> Vec2 { Vec2 { x: self.get(GamepadAxis::RightStickX).unwrap_or(0.0), y: self.get(GamepadAxis::RightStickY).unwrap_or(0.0), } } /// Returns the directional pad as a [`Vec2`]. pub fn dpad(&self) -> Vec2 { Vec2 { x: self.get(GamepadButton::DPadRight).unwrap_or(0.0) - self.get(GamepadButton::DPadLeft).unwrap_or(0.0), y: self.get(GamepadButton::DPadUp).unwrap_or(0.0) - self.get(GamepadButton::DPadDown).unwrap_or(0.0), } } /// Returns `true` if the [`GamepadButton`] has been pressed. pub fn pressed(&self, button_type: GamepadButton) -> bool { self.digital.pressed(button_type) } /// Returns `true` if any item in the [`GamepadButton`] iterator has been pressed. pub fn any_pressed(&self, button_inputs: impl IntoIterator<Item = GamepadButton>) -> bool { self.digital.any_pressed(button_inputs) } /// Returns `true` if all items in the [`GamepadButton`] iterator have been pressed. pub fn all_pressed(&self, button_inputs: impl IntoIterator<Item = GamepadButton>) -> bool { self.digital.all_pressed(button_inputs) } /// Returns `true` if the [`GamepadButton`] has been pressed during the current frame. /// /// Note: This function does not imply information regarding the current state of [`ButtonInput::pressed`] or [`ButtonInput::just_released`]. pub fn just_pressed(&self, button_type: GamepadButton) -> bool { self.digital.just_pressed(button_type) } /// Returns `true` if any item in the [`GamepadButton`] iterator has been pressed during the current frame. pub fn any_just_pressed(&self, button_inputs: impl IntoIterator<Item = GamepadButton>) -> bool { self.digital.any_just_pressed(button_inputs) } /// Returns `true` if all items in the [`GamepadButton`] iterator have been just pressed. pub fn all_just_pressed(&self, button_inputs: impl IntoIterator<Item = GamepadButton>) -> bool { self.digital.all_just_pressed(button_inputs) } /// Returns `true` if the [`GamepadButton`] has been released during the current frame. /// /// Note: This function does not imply information regarding the current state of [`ButtonInput::pressed`] or [`ButtonInput::just_pressed`]. pub fn just_released(&self, button_type: GamepadButton) -> bool { self.digital.just_released(button_type) } /// Returns `true` if any item in the [`GamepadButton`] iterator has just been released. pub fn any_just_released( &self, button_inputs: impl IntoIterator<Item = GamepadButton>, ) -> bool { self.digital.any_just_released(button_inputs) } /// Returns `true` if all items in the [`GamepadButton`] iterator have just been released. pub fn all_just_released( &self, button_inputs: impl IntoIterator<Item = GamepadButton>, ) -> bool { self.digital.all_just_released(button_inputs) } /// Returns an iterator over all digital [button]s that are pressed. /// /// [button]: GamepadButton pub fn get_pressed(&self) -> impl Iterator<Item = &GamepadButton> { self.digital.get_pressed() } /// Returns an iterator over all digital [button]s that were just pressed. /// /// [button]: GamepadButton pub fn get_just_pressed(&self) -> impl Iterator<Item = &GamepadButton> { self.digital.get_just_pressed() } /// Returns an iterator over all digital [button]s that were just released. /// /// [button]: GamepadButton pub fn get_just_released(&self) -> impl Iterator<Item = &GamepadButton> { self.digital.get_just_released() } /// Returns an iterator over all analog [axes][GamepadInput]. pub fn get_analog_axes(&self) -> impl Iterator<Item = &GamepadInput> { self.analog.all_axes() } /// [`ButtonInput`] of [`GamepadButton`] representing their digital state. pub fn digital(&self) -> &ButtonInput<GamepadButton> { &self.digital } /// Mutable [`ButtonInput`] of [`GamepadButton`] representing their digital state. Useful for mocking inputs. pub fn digital_mut(&mut self) -> &mut ButtonInput<GamepadButton> { &mut self.digital } /// [`Axis`] of [`GamepadButton`] representing their analog state. pub fn analog(&self) -> &Axis<GamepadInput> { &self.analog } /// Mutable [`Axis`] of [`GamepadButton`] representing their analog state. Useful for mocking inputs. pub fn analog_mut(&mut self) -> &mut Axis<GamepadInput> { &mut self.analog } } impl Default for Gamepad { fn default() -> Self { let mut analog = Axis::default(); for button in GamepadButton::all().iter().copied() { analog.set(button, 0.0); } for axis_type in GamepadAxis::all().iter().copied() { analog.set(axis_type, 0.0); } Self { vendor_id: None, product_id: None, digital: Default::default(), analog, } } } /// Represents gamepad input types that are mapped in the range [0.0, 1.0]. /// /// ## Usage /// /// This is used to determine which button has changed its value when receiving gamepad button events. /// It is also used in the [`Gamepad`] component. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, Hash, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub enum GamepadButton { /// The bottom action button of the action pad (i.e. PS: Cross, Xbox: A). South, /// The right action button of the action pad (i.e. PS: Circle, Xbox: B). East, /// The upper action button of the action pad (i.e. PS: Triangle, Xbox: Y). North, /// The left action button of the action pad (i.e. PS: Square, Xbox: X). West, /// The C button. C, /// The Z button. Z, /// The first left trigger. LeftTrigger, /// The second left trigger. LeftTrigger2, /// The first right trigger. RightTrigger, /// The second right trigger. RightTrigger2, /// The select button. Select, /// The start button. Start, /// The mode button. Mode, /// The left thumb stick button. LeftThumb, /// The right thumb stick button. RightThumb, /// The up button of the D-Pad. DPadUp, /// The down button of the D-Pad. DPadDown, /// The left button of the D-Pad. DPadLeft, /// The right button of the D-Pad. DPadRight, /// Miscellaneous buttons, considered non-standard (i.e. Extra buttons on a flight stick that do not have a gamepad equivalent). Other(u8), } impl GamepadButton { /// Returns an array of all the standard [`GamepadButton`]. pub const fn all() -> [GamepadButton; 19] { [ GamepadButton::South, GamepadButton::East, GamepadButton::North, GamepadButton::West, GamepadButton::C, GamepadButton::Z, GamepadButton::LeftTrigger, GamepadButton::LeftTrigger2, GamepadButton::RightTrigger, GamepadButton::RightTrigger2, GamepadButton::Select, GamepadButton::Start, GamepadButton::Mode, GamepadButton::LeftThumb, GamepadButton::RightThumb, GamepadButton::DPadUp, GamepadButton::DPadDown, GamepadButton::DPadLeft, GamepadButton::DPadRight, ] } } /// Represents gamepad input types that are mapped in the range [-1.0, 1.0]. /// /// ## Usage /// /// This is used to determine which axis has changed its value when receiving a /// gamepad axis event. It is also used in the [`Gamepad`] component. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Hash, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub enum GamepadAxis { /// The horizontal value of the left stick. LeftStickX, /// The vertical value of the left stick. LeftStickY, /// Generally the throttle axis of a HOTAS setup. /// Refer to [`GamepadButton::LeftTrigger2`] for the analog trigger on a gamepad controller. LeftZ, /// The horizontal value of the right stick. RightStickX, /// The vertical value of the right stick. RightStickY, /// The yaw of the main joystick, not supported on common gamepads. /// Refer to [`GamepadButton::RightTrigger2`] for the analog trigger on a gamepad controller. RightZ, /// Non-standard support for other axis types (i.e. HOTAS sliders, potentiometers, etc). Other(u8), } impl GamepadAxis { /// Returns an array of all the standard [`GamepadAxis`]. pub const fn all() -> [GamepadAxis; 6] { [ GamepadAxis::LeftStickX, GamepadAxis::LeftStickY, GamepadAxis::LeftZ, GamepadAxis::RightStickX, GamepadAxis::RightStickY, GamepadAxis::RightZ, ] } } /// Encapsulation over [`GamepadAxis`] and [`GamepadButton`]. // This is done so Gamepad can share a single Axis<T> and simplifies the API by having only one get/get_unclamped method #[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, From)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, Hash, PartialEq, Clone) )] pub enum GamepadInput { /// A [`GamepadAxis`]. Axis(GamepadAxis), /// A [`GamepadButton`]. Button(GamepadButton), } /// Gamepad settings component. /// /// ## Usage /// /// It is used to create a `bevy` component that stores the settings of [`GamepadButton`] and [`GamepadAxis`] in [`Gamepad`]. /// If no user defined [`ButtonSettings`], [`AxisSettings`], or [`ButtonAxisSettings`] /// are defined, the default settings of each are used as a fallback accordingly. /// /// ## Note /// /// The [`GamepadSettings`] are used to determine when raw gamepad events /// should register. Events that don't meet the change thresholds defined in [`GamepadSettings`] /// will not register. To modify these settings, mutate the corresponding component. #[derive(Component, Clone, Default, Debug)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, Default, Component, Clone) )] pub struct GamepadSettings { /// The default button settings. pub default_button_settings: ButtonSettings, /// The default axis settings. pub default_axis_settings: AxisSettings, /// The default button axis settings. pub default_button_axis_settings: ButtonAxisSettings, /// The user defined button settings. pub button_settings: HashMap<GamepadButton, ButtonSettings>, /// The user defined axis settings. pub axis_settings: HashMap<GamepadAxis, AxisSettings>, /// The user defined button axis settings. pub button_axis_settings: HashMap<GamepadButton, ButtonAxisSettings>, } impl GamepadSettings { /// Returns the [`ButtonSettings`] of the [`GamepadButton`]. /// /// If no user defined [`ButtonSettings`] are specified the default [`ButtonSettings`] get returned. /// /// # Examples /// /// ``` /// # use bevy_input::gamepad::{GamepadSettings, GamepadButton}; /// # /// # let settings = GamepadSettings::default(); /// let button_settings = settings.get_button_settings(GamepadButton::South); /// ``` pub fn get_button_settings(&self, button: GamepadButton) -> &ButtonSettings { self.button_settings .get(&button) .unwrap_or(&self.default_button_settings) } /// Returns the [`AxisSettings`] of the [`GamepadAxis`]. /// /// If no user defined [`AxisSettings`] are specified the default [`AxisSettings`] get returned. /// /// # Examples /// /// ``` /// # use bevy_input::gamepad::{GamepadSettings, GamepadAxis}; /// # /// # let settings = GamepadSettings::default(); /// let axis_settings = settings.get_axis_settings(GamepadAxis::LeftStickX); /// ``` pub fn get_axis_settings(&self, axis: GamepadAxis) -> &AxisSettings { self.axis_settings .get(&axis) .unwrap_or(&self.default_axis_settings) } /// Returns the [`ButtonAxisSettings`] of the [`GamepadButton`]. /// /// If no user defined [`ButtonAxisSettings`] are specified the default [`ButtonAxisSettings`] get returned. /// /// # Examples /// /// ``` /// # use bevy_input::gamepad::{GamepadSettings, GamepadButton}; /// # /// # let settings = GamepadSettings::default(); /// let button_axis_settings = settings.get_button_axis_settings(GamepadButton::South); /// ``` pub fn get_button_axis_settings(&self, button: GamepadButton) -> &ButtonAxisSettings { self.button_axis_settings .get(&button) .unwrap_or(&self.default_button_axis_settings) } } /// Manages settings for gamepad buttons. /// /// It is used inside [`GamepadSettings`] to define the threshold for a [`GamepadButton`] /// to be considered pressed or released. A button is considered pressed if the `press_threshold` /// value is surpassed and released if the `release_threshold` value is undercut. /// /// Allowed values: `0.0 <= ``release_threshold`` <= ``press_threshold`` <= 1.0` #[derive(Debug, PartialEq, Clone)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, Default, Clone) )] pub struct ButtonSettings { press_threshold: f32, release_threshold: f32, } impl Default for ButtonSettings { fn default() -> Self { ButtonSettings { press_threshold: 0.75, release_threshold: 0.65, } } } impl ButtonSettings { /// Creates a new [`ButtonSettings`] instance. /// /// # Parameters /// /// + `press_threshold` is the button input value above which the button is considered pressed. /// + `release_threshold` is the button input value below which the button is considered released. /// /// Restrictions: /// + `0.0 <= ``release_threshold`` <= ``press_threshold`` <= 1.0` /// /// # Errors /// /// If the restrictions are not met, returns one of /// `GamepadSettingsError::ButtonReleaseThresholdOutOfRange`, /// `GamepadSettingsError::ButtonPressThresholdOutOfRange`, or /// `GamepadSettingsError::ButtonReleaseThresholdGreaterThanPressThreshold`. pub fn new( press_threshold: f32, release_threshold: f32, ) -> Result<ButtonSettings, ButtonSettingsError> { if !(0.0..=1.0).contains(&release_threshold) { Err(ButtonSettingsError::ReleaseThresholdOutOfRange( release_threshold, )) } else if !(0.0..=1.0).contains(&press_threshold) { Err(ButtonSettingsError::PressThresholdOutOfRange( press_threshold, )) } else if release_threshold > press_threshold { Err( ButtonSettingsError::ReleaseThresholdGreaterThanPressThreshold { press_threshold, release_threshold, }, ) } else { Ok(ButtonSettings { press_threshold, release_threshold, }) } } /// Returns `true` if the button is pressed. /// /// A button is considered pressed if the `value` passed is greater than or equal to the press threshold. pub fn is_pressed(&self, value: f32) -> bool { value >= self.press_threshold } /// Returns `true` if the button is released. /// /// A button is considered released if the `value` passed is lower than or equal to the release threshold. pub fn is_released(&self, value: f32) -> bool { value <= self.release_threshold } /// Get the button input threshold above which the button is considered pressed. pub fn press_threshold(&self) -> f32 { self.press_threshold } /// Try to set the button input threshold above which the button is considered pressed. /// /// # Errors /// /// If the value passed is outside the range [release threshold..=1.0], returns either /// `GamepadSettingsError::ButtonPressThresholdOutOfRange` or /// `GamepadSettingsError::ButtonReleaseThresholdGreaterThanPressThreshold`. pub fn try_set_press_threshold(&mut self, value: f32) -> Result<(), ButtonSettingsError> { if (self.release_threshold..=1.0).contains(&value) { self.press_threshold = value; Ok(()) } else if !(0.0..1.0).contains(&value) { Err(ButtonSettingsError::PressThresholdOutOfRange(value)) } else { Err( ButtonSettingsError::ReleaseThresholdGreaterThanPressThreshold { press_threshold: value, release_threshold: self.release_threshold, }, ) } } /// Try to set the button input threshold above which the button is considered pressed. /// If the value passed is outside the range [release threshold..=1.0], the value will not be changed. /// /// Returns the new value of the press threshold. pub fn set_press_threshold(&mut self, value: f32) -> f32 { self.try_set_press_threshold(value).ok(); self.press_threshold } /// Get the button input threshold below which the button is considered released. pub fn release_threshold(&self) -> f32 { self.release_threshold }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_input/src/common_conditions.rs
crates/bevy_input/src/common_conditions.rs
use crate::ButtonInput; use bevy_ecs::system::Res; use core::hash::Hash; /// 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}; /// # use bevy_ecs::prelude::IntoScheduleConfigs; /// # use bevy_input::{common_conditions::input_toggle_active, prelude::KeyCode}; /// /// fn main() { /// App::new() /// .add_plugins(DefaultPlugins) /// .add_systems(Update, pause_menu.run_if(input_toggle_active(false, KeyCode::Escape))) /// .run(); /// } /// /// fn pause_menu() { /// println!("in pause menu"); /// } /// ``` /// /// If you want other systems to be able to access whether the toggled state is active, /// you should use a custom resource or a state for that: /// ```no_run /// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, Update}; /// # use bevy_ecs::prelude::{IntoScheduleConfigs, Res, ResMut, Resource}; /// # use bevy_input::{common_conditions::input_just_pressed, prelude::KeyCode}; /// /// #[derive(Resource, Default)] /// struct Paused(bool); /// /// fn main() { /// App::new() /// .add_plugins(DefaultPlugins) /// .init_resource::<Paused>() /// .add_systems(Update, toggle_pause_state.run_if(input_just_pressed(KeyCode::Escape))) /// .add_systems(Update, pause_menu.run_if(|paused: Res<Paused>| paused.0)) /// .run(); /// } /// /// fn toggle_pause_state(mut paused: ResMut<Paused>) { /// paused.0 = !paused.0; /// } /// /// fn pause_menu() { /// println!("in pause menu"); /// } /// ``` pub fn input_toggle_active<T>( default: bool, input: T, ) -> impl FnMut(Res<ButtonInput<T>>) -> bool + Clone where T: Clone + Eq + Hash + Send + Sync + 'static, { let mut active = default; move |inputs: Res<ButtonInput<T>>| { active ^= inputs.just_pressed(input.clone()); active } } /// Run condition that is active if [`ButtonInput::pressed`] is true for the given input. pub fn input_pressed<T>(input: T) -> impl FnMut(Res<ButtonInput<T>>) -> bool + Clone where T: Clone + Eq + Hash + Send + Sync + 'static, { move |inputs: Res<ButtonInput<T>>| inputs.pressed(input.clone()) } /// Run condition that is active if [`ButtonInput::just_pressed`] is true for the given input. /// /// ```no_run /// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, Update}; /// # use bevy_ecs::prelude::IntoScheduleConfigs; /// # use bevy_input::{common_conditions::input_just_pressed, prelude::KeyCode}; /// fn main() { /// App::new() /// .add_plugins(DefaultPlugins) /// .add_systems(Update, jump.run_if(input_just_pressed(KeyCode::Space))) /// .run(); /// } /// /// # fn jump() {} /// ``` pub fn input_just_pressed<T>(input: T) -> impl FnMut(Res<ButtonInput<T>>) -> bool + Clone where T: Clone + Eq + Hash + Send + Sync + 'static, { move |inputs: Res<ButtonInput<T>>| inputs.just_pressed(input.clone()) } /// Run condition that is active if [`ButtonInput::just_released`] is true for the given input. pub fn input_just_released<T>(input: T) -> impl FnMut(Res<ButtonInput<T>>) -> bool + Clone where T: Clone + Eq + Hash + Send + Sync + 'static, { move |inputs: Res<ButtonInput<T>>| inputs.just_released(input.clone()) } #[cfg(test)] mod tests { use super::*; use crate::prelude::KeyCode; use bevy_ecs::schedule::{IntoScheduleConfigs, Schedule}; fn test_system() {} // Ensure distributive_run_if compiles with the common conditions. #[test] fn distributive_run_if_compiles() { Schedule::default().add_systems( (test_system, test_system) .distributive_run_if(input_toggle_active(false, KeyCode::Escape)) .distributive_run_if(input_pressed(KeyCode::Escape)) .distributive_run_if(input_just_pressed(KeyCode::Escape)) .distributive_run_if(input_just_released(KeyCode::Escape)), ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_input/src/axis.rs
crates/bevy_input/src/axis.rs
//! The generic axis type. use bevy_ecs::resource::Resource; use bevy_platform::collections::HashMap; use core::hash::Hash; #[cfg(feature = "bevy_reflect")] use bevy_reflect::Reflect; /// Stores the position data of the input devices of type `T`. /// /// The values are stored as `f32`s, using [`Axis::set`]. /// Use [`Axis::get`] to retrieve the value clamped between [`Axis::MIN`] and [`Axis::MAX`] /// inclusive, or unclamped using [`Axis::get_unclamped`]. #[derive(Debug, Resource)] #[cfg_attr(feature = "bevy_reflect", derive(Reflect))] pub struct Axis<T> { /// The position data of the input devices. axis_data: HashMap<T, f32>, } impl<T> Default for Axis<T> where T: Copy + Eq + Hash, { fn default() -> Self { Axis { axis_data: HashMap::default(), } } } impl<T> Axis<T> where T: Copy + Eq + Hash, { /// The smallest possible axis value. pub const MIN: f32 = -1.0; /// The largest possible axis value. pub const MAX: f32 = 1.0; /// Sets the position data of the `input_device` to `position_data`. /// /// If the `input_device`: /// - was present before, the position data is updated, and the old value is returned. /// - wasn't present before, `None` is returned. pub fn set(&mut self, input_device: impl Into<T>, position_data: f32) -> Option<f32> { self.axis_data.insert(input_device.into(), position_data) } /// Returns the position data of the provided `input_device`. /// /// This will be clamped between [`Axis::MIN`] and [`Axis::MAX`] inclusive. pub fn get(&self, input_device: impl Into<T>) -> Option<f32> { self.axis_data .get(&input_device.into()) .copied() .map(|value| value.clamp(Self::MIN, Self::MAX)) } /// Returns the unclamped position data of the provided `input_device`. /// /// This value may be outside the [`Axis::MIN`] and [`Axis::MAX`] range. /// /// Use for things like camera zoom, where you want devices like mouse wheels to be able to /// exceed the normal range. If being able to move faster on one input device /// than another would give an unfair advantage, you should likely use [`Axis::get`] instead. pub fn get_unclamped(&self, input_device: impl Into<T>) -> Option<f32> { self.axis_data.get(&input_device.into()).copied() } /// Removes the position data of the `input_device`, returning the position data if the input device was previously set. pub fn remove(&mut self, input_device: impl Into<T>) -> Option<f32> { self.axis_data.remove(&input_device.into()) } /// Returns an iterator over all axes. pub fn all_axes(&self) -> impl Iterator<Item = &T> { self.axis_data.keys() } /// Returns an iterator over all axes and their values. pub fn all_axes_and_values(&self) -> impl Iterator<Item = (&T, f32)> { self.axis_data.iter().map(|(axis, value)| (axis, *value)) } } #[cfg(test)] mod tests { use crate::{gamepad::GamepadButton, Axis}; #[test] fn test_axis_set() { let cases = [ (-1.5, Some(-1.0)), (-1.1, Some(-1.0)), (-1.0, Some(-1.0)), (-0.9, Some(-0.9)), (-0.1, Some(-0.1)), (0.0, Some(0.0)), (0.1, Some(0.1)), (0.9, Some(0.9)), (1.0, Some(1.0)), (1.1, Some(1.0)), (1.6, Some(1.0)), ]; for (value, expected) in cases { let mut axis = Axis::<GamepadButton>::default(); axis.set(GamepadButton::RightTrigger, value); let actual = axis.get(GamepadButton::RightTrigger); assert_eq!(expected, actual); } } #[test] fn test_axis_remove() { let cases = [-1.0, -0.9, -0.1, 0.0, 0.1, 0.9, 1.0]; for value in cases { let mut axis = Axis::<GamepadButton>::default(); axis.set(GamepadButton::RightTrigger, value); assert!(axis.get(GamepadButton::RightTrigger).is_some()); axis.remove(GamepadButton::RightTrigger); let actual = axis.get(GamepadButton::RightTrigger); let expected = None; assert_eq!(expected, actual); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_input/src/keyboard.rs
crates/bevy_input/src/keyboard.rs
//! The keyboard input functionality. // This file contains a substantial portion of the UI Events Specification by the W3C. In // particular, the variant names within `KeyCode` and their documentation are modified // versions of contents of the aforementioned specification. // // The original documents are: // // // ### For `KeyCode` // UI Events KeyboardEvent code Values // https://www.w3.org/TR/2017/CR-uievents-code-20170601/ // Copyright © 2017 W3C® (MIT, ERCIM, Keio, Beihang). // // These documents were used under the terms of the following license. This W3C license as well as // the W3C short notice apply to the `KeyCode` enums and their variants and the // documentation attached to their variants. // --------- BEGINNING OF W3C LICENSE -------------------------------------------------------------- // // License // // By obtaining and/or copying this work, you (the licensee) agree that you have read, understood, // and will comply with the following terms and conditions. // // Permission to copy, modify, and distribute this work, with or without modification, for any // purpose and without fee or royalty is hereby granted, provided that you include the following on // ALL copies of the work or portions thereof, including modifications: // // - The full text of this NOTICE in a location viewable to users of the redistributed or derivative // work. // - Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none // exist, the W3C Software and Document Short Notice should be included. // - Notice of any changes or modifications, through a copyright statement on the new code or // document such as "This software or document includes material copied from or derived from // [title and URI of the W3C document]. Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang)." // // Disclaimers // // THIS WORK IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR // ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENT WILL NOT INFRINGE ANY THIRD // PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. // // COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES // ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENT. // // The name and trademarks of copyright holders may NOT be used in advertising or publicity // pertaining to the work without specific, written prior permission. Title to copyright in this // work will at all times remain with copyright holders. // // --------- END OF W3C LICENSE -------------------------------------------------------------------- // --------- BEGINNING OF W3C SHORT NOTICE --------------------------------------------------------- // // winit: https://github.com/rust-windowing/winit // // Copyright © 2021 World Wide Web Consortium, (Massachusetts Institute of Technology, European // Research Consortium for Informatics and Mathematics, Keio University, Beihang). All Rights // Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will // be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. // // [1] http://www.w3.org/Consortium/Legal/copyright-software // // --------- END OF W3C SHORT NOTICE --------------------------------------------------------------- use crate::{ButtonInput, ButtonState}; use bevy_ecs::{ change_detection::DetectChangesMut, entity::Entity, message::{Message, MessageReader}, system::ResMut, }; #[cfg(feature = "bevy_reflect")] use bevy_reflect::Reflect; #[cfg(not(feature = "smol_str"))] use alloc::string::String as SmolStr; #[cfg(feature = "smol_str")] use smol_str::SmolStr; #[cfg(all(feature = "serialize", feature = "bevy_reflect"))] use bevy_reflect::{ReflectDeserialize, ReflectSerialize}; /// A keyboard input event. /// /// This event is the translated version of the `WindowEvent::KeyboardInput` from the `winit` crate. /// It is available to the end user and can be used for game logic. /// /// ## Usage /// /// The event is consumed inside of the [`keyboard_input_system`] to update the /// [`ButtonInput<KeyCode>`](ButtonInput<KeyCode>) and /// [`ButtonInput<Key>`](ButtonInput<Key>) resources. #[derive(Message, Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Hash, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct KeyboardInput { /// The physical key code of the key. /// /// This corresponds to the location of the key independent of the keyboard layout. pub key_code: KeyCode, /// The logical key of the input. /// /// This corresponds to the actual key taking keyboard layout into account. pub logical_key: Key, /// The press state of the key. pub state: ButtonState, /// Contains the text produced by this keypress. /// /// In most cases this is identical to the content /// of the `Character` variant of `logical_key`. /// However, on Windows when a dead key was pressed earlier /// but cannot be combined with the character from this /// keypress, the produced text will consist of two characters: /// the dead-key-character followed by the character resulting /// from this keypress. /// /// This is `None` if the current keypress cannot /// be interpreted as text. pub text: Option<SmolStr>, /// On some systems, holding down a key for some period of time causes that key to be repeated /// as though it were being pressed and released repeatedly. This field is [`true`] if this /// event is the result of one of those repeats. pub repeat: bool, /// Window that received the input. pub window: Entity, } /// Gets generated from `bevy_winit::winit_runner` /// /// Used for clearing all cached states to avoid having 'stuck' key presses /// when, for example, switching between windows with 'Alt-Tab' or using any other /// OS specific key combination that leads to Bevy window losing focus and not receiving any /// input events #[derive(Message, Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Clone, PartialEq))] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct KeyboardFocusLost; /// Updates the [`ButtonInput<KeyCode>`] and [`ButtonInput<Key>`] resources with the latest [`KeyboardInput`] events. /// /// ## Differences /// /// The main difference between the [`KeyboardInput`] event and the [`ButtonInput`] resources are that /// the latter has convenient functions such as [`ButtonInput::pressed`], [`ButtonInput::just_pressed`] and [`ButtonInput::just_released`] and is window id agnostic. /// /// There is a [`ButtonInput`] for both [`KeyCode`] and [`Key`] as they are both useful in different situations, see their documentation for the details. pub fn keyboard_input_system( mut keycode_input: ResMut<ButtonInput<KeyCode>>, mut key_input: ResMut<ButtonInput<Key>>, mut keyboard_input_reader: MessageReader<KeyboardInput>, mut keyboard_focus_lost_reader: MessageReader<KeyboardFocusLost>, ) { // Avoid clearing if not empty to ensure change detection is not triggered. keycode_input.bypass_change_detection().clear(); key_input.bypass_change_detection().clear(); for event in keyboard_input_reader.read() { let KeyboardInput { key_code, logical_key, state, .. } = event; match state { ButtonState::Pressed => { keycode_input.press(*key_code); key_input.press(logical_key.clone()); } ButtonState::Released => { keycode_input.release(*key_code); key_input.release(logical_key.clone()); } } } // Release all cached input to avoid having stuck input when switching between windows in os if !keyboard_focus_lost_reader.is_empty() { keycode_input.release_all(); keyboard_focus_lost_reader.clear(); } } /// Contains the platform-native physical key identifier /// /// The exact values vary from platform to platform (which is part of why this is a per-platform /// enum), but the values are primarily tied to the key's physical location on the keyboard. /// /// This enum is primarily used to store raw keycodes when Winit doesn't map a given native /// physical key identifier to a meaningful [`KeyCode`] variant. In the presence of identifiers we /// haven't mapped for you yet, this lets you use [`KeyCode`] to: /// /// - Correctly match key press and release events. /// - On non-web platforms, support assigning keybinds to virtually any key through a UI. #[derive(Debug, Clone, Ord, PartialOrd, Copy, PartialEq, Eq, Hash)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Clone, PartialEq, Hash) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub enum NativeKeyCode { /// Unidentified Unidentified, /// An Android "scancode". Android(u32), /// A macOS "scancode". MacOS(u16), /// A Windows "scancode". Windows(u16), /// An XKB "keycode". Xkb(u32), } /// The key code of a [`KeyboardInput`]. /// /// ## Usage /// /// It is used as the generic `T` value of an [`ButtonInput`] to create a `Res<ButtonInput<KeyCode>>`. /// /// Code representing the location of a physical key /// This mostly conforms to the [`UI Events Specification's KeyboardEvent.code`] with a few /// exceptions: /// - The keys that the specification calls `MetaLeft` and `MetaRight` are named `SuperLeft` and /// `SuperRight` here. /// - The key that the specification calls "Super" is reported as `Unidentified` here. /// /// [`UI Events Specification's KeyboardEvent.code`]: https://w3c.github.io/uievents-code/#code-value-tables /// /// ## Updating /// /// The resource is updated inside of the [`keyboard_input_system`]. #[derive(Debug, Hash, Ord, PartialOrd, PartialEq, Eq, Clone, Copy)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, Hash, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] #[expect( clippy::doc_markdown, reason = "We use camel-case words inside `<kbd>` tags to represent keyboard keys, which are not identifiers that we should be putting inside backticks." )] #[repr(u32)] pub enum KeyCode { /// This variant is used when the key cannot be translated to any other variant. /// /// The native keycode is provided (if available) so you're able to more reliably match /// key-press and key-release events by hashing the [`KeyCode`]. It is also possible to use /// this for keybinds for non-standard keys, but such keybinds are tied to a given platform. Unidentified(NativeKeyCode), /// <kbd>\`</kbd> on a US keyboard. This is also called a backtick or grave. /// This is the <kbd>半角</kbd>/<kbd>全角</kbd>/<kbd>漢字</kbd> /// (hankaku/zenkaku/kanji) key on Japanese keyboards Backquote, /// Used for both the US <kbd>\\</kbd> (on the 101-key layout) and also for the key /// located between the <kbd>"</kbd> and <kbd>Enter</kbd> keys on row C of the 102-, /// 104- and 106-key layouts. /// Labeled <kbd>#</kbd> on a UK (102) keyboard. Backslash, /// <kbd>[</kbd> on a US keyboard. BracketLeft, /// <kbd>]</kbd> on a US keyboard. BracketRight, /// <kbd>,</kbd> on a US keyboard. Comma, /// <kbd>0</kbd> on a US keyboard. Digit0, /// <kbd>1</kbd> on a US keyboard. Digit1, /// <kbd>2</kbd> on a US keyboard. Digit2, /// <kbd>3</kbd> on a US keyboard. Digit3, /// <kbd>4</kbd> on a US keyboard. Digit4, /// <kbd>5</kbd> on a US keyboard. Digit5, /// <kbd>6</kbd> on a US keyboard. Digit6, /// <kbd>7</kbd> on a US keyboard. Digit7, /// <kbd>8</kbd> on a US keyboard. Digit8, /// <kbd>9</kbd> on a US keyboard. Digit9, /// <kbd>=</kbd> on a US keyboard. Equal, /// Located between the left <kbd>Shift</kbd> and <kbd>Z</kbd> keys. /// Labeled <kbd>\\</kbd> on a UK keyboard. IntlBackslash, /// Located between the <kbd>/</kbd> and right <kbd>Shift</kbd> keys. /// Labeled <kbd>\\</kbd> (ro) on a Japanese keyboard. IntlRo, /// Located between the <kbd>=</kbd> and <kbd>Backspace</kbd> keys. /// Labeled <kbd>¥</kbd> (yen) on a Japanese keyboard. <kbd>\\</kbd> on a /// Russian keyboard. IntlYen, /// <kbd>a</kbd> on a US keyboard. /// Labeled <kbd>q</kbd> on an AZERTY (e.g., French) keyboard. KeyA, /// <kbd>b</kbd> on a US keyboard. KeyB, /// <kbd>c</kbd> on a US keyboard. KeyC, /// <kbd>d</kbd> on a US keyboard. KeyD, /// <kbd>e</kbd> on a US keyboard. KeyE, /// <kbd>f</kbd> on a US keyboard. KeyF, /// <kbd>g</kbd> on a US keyboard. KeyG, /// <kbd>h</kbd> on a US keyboard. KeyH, /// <kbd>i</kbd> on a US keyboard. KeyI, /// <kbd>j</kbd> on a US keyboard. KeyJ, /// <kbd>k</kbd> on a US keyboard. KeyK, /// <kbd>l</kbd> on a US keyboard. KeyL, /// <kbd>m</kbd> on a US keyboard. KeyM, /// <kbd>n</kbd> on a US keyboard. KeyN, /// <kbd>o</kbd> on a US keyboard. KeyO, /// <kbd>p</kbd> on a US keyboard. KeyP, /// <kbd>q</kbd> on a US keyboard. /// Labeled <kbd>a</kbd> on an AZERTY (e.g., French) keyboard. KeyQ, /// <kbd>r</kbd> on a US keyboard. KeyR, /// <kbd>s</kbd> on a US keyboard. KeyS, /// <kbd>t</kbd> on a US keyboard. KeyT, /// <kbd>u</kbd> on a US keyboard. KeyU, /// <kbd>v</kbd> on a US keyboard. KeyV, /// <kbd>w</kbd> on a US keyboard. /// Labeled <kbd>z</kbd> on an AZERTY (e.g., French) keyboard. KeyW, /// <kbd>x</kbd> on a US keyboard. KeyX, /// <kbd>y</kbd> on a US keyboard. /// Labeled <kbd>z</kbd> on a QWERTZ (e.g., German) keyboard. KeyY, /// <kbd>z</kbd> on a US keyboard. /// Labeled <kbd>w</kbd> on an AZERTY (e.g., French) keyboard, and <kbd>y</kbd> on a /// QWERTZ (e.g., German) keyboard. KeyZ, /// <kbd>-</kbd> on a US keyboard. Minus, /// <kbd>.</kbd> on a US keyboard. Period, /// <kbd>'</kbd> on a US keyboard. Quote, /// <kbd>;</kbd> on a US keyboard. Semicolon, /// <kbd>/</kbd> on a US keyboard. Slash, /// <kbd>Alt</kbd>, <kbd>Option</kbd>, or <kbd>⌥</kbd>. AltLeft, /// <kbd>Alt</kbd>, <kbd>Option</kbd>, or <kbd>⌥</kbd>. /// This is labeled <kbd>AltGr</kbd> on many keyboard layouts. AltRight, /// <kbd>Backspace</kbd> or <kbd>⌫</kbd>. /// Labeled <kbd>Delete</kbd> on Apple keyboards. Backspace, /// <kbd>CapsLock</kbd> or <kbd>⇪</kbd> CapsLock, /// The application context menu key, which is typically found between the right /// <kbd>Super</kbd> key and the right <kbd>Control</kbd> key. ContextMenu, /// <kbd>Control</kbd> or <kbd>⌃</kbd> ControlLeft, /// <kbd>Control</kbd> or <kbd>⌃</kbd> ControlRight, /// <kbd>Enter</kbd> or <kbd>↵</kbd>. Labeled <kbd>Return</kbd> on Apple keyboards. Enter, /// The Windows, <kbd>⌘</kbd>, <kbd>Command</kbd>, or other OS symbol key. SuperLeft, /// The Windows, <kbd>⌘</kbd>, <kbd>Command</kbd>, or other OS symbol key. SuperRight, /// <kbd>Shift</kbd> or <kbd>⇧</kbd> ShiftLeft, /// <kbd>Shift</kbd> or <kbd>⇧</kbd> ShiftRight, /// <kbd> </kbd> (space) Space, /// <kbd>Tab</kbd> or <kbd>⇥</kbd> Tab, /// Japanese: <kbd>変</kbd> (henkan) Convert, /// Japanese: <kbd>カタカナ</kbd>/<kbd>ひらがな</kbd>/<kbd>ローマ字</kbd> (katakana/hiragana/romaji) KanaMode, /// Korean: HangulMode <kbd>한/영</kbd> (han/yeong) /// /// Japanese (Mac keyboard): <kbd>か</kbd> (kana) Lang1, /// Korean: Hanja <kbd>한</kbd> (hanja) /// /// Japanese (Mac keyboard): <kbd>英</kbd> (eisu) Lang2, /// Japanese (word-processing keyboard): Katakana Lang3, /// Japanese (word-processing keyboard): Hiragana Lang4, /// Japanese (word-processing keyboard): Zenkaku/Hankaku Lang5, /// Japanese: <kbd>無変換</kbd> (muhenkan) NonConvert, /// <kbd>⌦</kbd>. The forward delete key. /// Note that on Apple keyboards, the key labeled <kbd>Delete</kbd> on the main part of /// the keyboard is encoded as [`Backspace`]. /// /// [`Backspace`]: Self::Backspace Delete, /// <kbd>Page Down</kbd>, <kbd>End</kbd>, or <kbd>↘</kbd> End, /// <kbd>Help</kbd>. Not present on standard PC keyboards. Help, /// <kbd>Home</kbd> or <kbd>↖</kbd> Home, /// <kbd>Insert</kbd> or <kbd>Ins</kbd>. Not present on Apple keyboards. Insert, /// <kbd>Page Down</kbd>, <kbd>PgDn</kbd>, or <kbd>⇟</kbd> PageDown, /// <kbd>Page Up</kbd>, <kbd>PgUp</kbd>, or <kbd>⇞</kbd> PageUp, /// <kbd>↓</kbd> ArrowDown, /// <kbd>←</kbd> ArrowLeft, /// <kbd>→</kbd> ArrowRight, /// <kbd>↑</kbd> ArrowUp, /// On the Mac, this is used for the numpad <kbd>Clear</kbd> key. NumLock, /// <kbd>0 Ins</kbd> on a keyboard. <kbd>0</kbd> on a phone or remote control Numpad0, /// <kbd>1 End</kbd> on a keyboard. <kbd>1</kbd> or <kbd>1 QZ</kbd> on a phone or remote control Numpad1, /// <kbd>2 ↓</kbd> on a keyboard. <kbd>2 ABC</kbd> on a phone or remote control Numpad2, /// <kbd>3 PgDn</kbd> on a keyboard. <kbd>3 DEF</kbd> on a phone or remote control Numpad3, /// <kbd>4 ←</kbd> on a keyboard. <kbd>4 GHI</kbd> on a phone or remote control Numpad4, /// <kbd>5</kbd> on a keyboard. <kbd>5 JKL</kbd> on a phone or remote control Numpad5, /// <kbd>6 →</kbd> on a keyboard. <kbd>6 MNO</kbd> on a phone or remote control Numpad6, /// <kbd>7 Home</kbd> on a keyboard. <kbd>7 PQRS</kbd> or <kbd>7 PRS</kbd> on a phone /// or remote control Numpad7, /// <kbd>8 ↑</kbd> on a keyboard. <kbd>8 TUV</kbd> on a phone or remote control Numpad8, /// <kbd>9 PgUp</kbd> on a keyboard. <kbd>9 WXYZ</kbd> or <kbd>9 WXY</kbd> on a phone /// or remote control Numpad9, /// <kbd>+</kbd> NumpadAdd, /// Found on the Microsoft Natural Keyboard. NumpadBackspace, /// <kbd>C</kbd> or <kbd>A</kbd> (All Clear). Also for use with numpads that have a /// <kbd>Clear</kbd> key that is separate from the <kbd>NumLock</kbd> key. On the Mac, the /// numpad <kbd>Clear</kbd> key is encoded as [`NumLock`]. /// /// [`NumLock`]: Self::NumLock NumpadClear, /// <kbd>C</kbd> (Clear Entry) NumpadClearEntry, /// <kbd>,</kbd> (thousands separator). For locales where the thousands separator /// is a "." (e.g., Brazil), this key may generate a <kbd>.</kbd>. NumpadComma, /// <kbd>. Del</kbd>. For locales where the decimal separator is "," (e.g., /// Brazil), this key may generate a <kbd>,</kbd>. NumpadDecimal, /// <kbd>/</kbd> NumpadDivide, /// The Enter key on the numpad. NumpadEnter, /// <kbd>=</kbd> NumpadEqual, /// <kbd>#</kbd> on a phone or remote control device. This key is typically found /// below the <kbd>9</kbd> key and to the right of the <kbd>0</kbd> key. NumpadHash, /// <kbd>M</kbd> Add current entry to the value stored in memory. NumpadMemoryAdd, /// <kbd>M</kbd> Clear the value stored in memory. NumpadMemoryClear, /// <kbd>M</kbd> Replace the current entry with the value stored in memory. NumpadMemoryRecall, /// <kbd>M</kbd> Replace the value stored in memory with the current entry. NumpadMemoryStore, /// <kbd>M</kbd> Subtract current entry from the value stored in memory. NumpadMemorySubtract, /// <kbd>*</kbd> on a keyboard. For use with numpads that provide mathematical /// operations (<kbd>+</kbd>, <kbd>-</kbd> <kbd>*</kbd> and <kbd>/</kbd>). /// /// Use `NumpadStar` for the <kbd>*</kbd> key on phones and remote controls. NumpadMultiply, /// <kbd>(</kbd> Found on the Microsoft Natural Keyboard. NumpadParenLeft, /// <kbd>)</kbd> Found on the Microsoft Natural Keyboard. NumpadParenRight, /// <kbd>*</kbd> on a phone or remote control device. /// /// This key is typically found below the <kbd>7</kbd> key and to the left of /// the <kbd>0</kbd> key. /// /// Use <kbd>"NumpadMultiply"</kbd> for the <kbd>*</kbd> key on /// numeric keypads. NumpadStar, /// <kbd>-</kbd> NumpadSubtract, /// <kbd>Esc</kbd> or <kbd>⎋</kbd> Escape, /// <kbd>Fn</kbd> This is typically a hardware key that does not generate a separate code. Fn, /// <kbd>FLock</kbd> or <kbd>FnLock</kbd>. Function Lock key. Found on the Microsoft /// Natural Keyboard. FnLock, /// <kbd>PrtScr SysRq</kbd> or <kbd>Print Screen</kbd> PrintScreen, /// <kbd>Scroll Lock</kbd> ScrollLock, /// <kbd>Pause Break</kbd> Pause, /// Some laptops place this key to the left of the <kbd>↑</kbd> key. /// /// This also the "back" button (triangle) on Android. BrowserBack, /// BrowserFavorites BrowserFavorites, /// Some laptops place this key to the right of the <kbd>↑</kbd> key. BrowserForward, /// The "home" button on Android. BrowserHome, /// BrowserRefresh BrowserRefresh, /// BrowserSearch BrowserSearch, /// BrowserStop BrowserStop, /// <kbd>Eject</kbd> or <kbd>⏏</kbd>. This key is placed in the function section on some Apple /// keyboards. Eject, /// Sometimes labeled <kbd>My Computer</kbd> on the keyboard LaunchApp1, /// Sometimes labeled <kbd>Calculator</kbd> on the keyboard LaunchApp2, /// LaunchMail LaunchMail, /// MediaPlayPause MediaPlayPause, /// MediaSelect MediaSelect, /// MediaStop MediaStop, /// MediaTrackNext MediaTrackNext, /// MediaTrackPrevious MediaTrackPrevious, /// This key is placed in the function section on some Apple keyboards, replacing the /// <kbd>Eject</kbd> key. Power, /// Sleep Sleep, /// AudioVolumeDown AudioVolumeDown, /// AudioVolumeMute AudioVolumeMute, /// AudioVolumeUp AudioVolumeUp, /// WakeUp WakeUp, /// Legacy modifier key. Also called "Super" in certain places. Meta, /// Legacy modifier key. Hyper, /// Turbo Turbo, /// Abort Abort, /// Resume Resume, /// Suspend Suspend, /// Found on Sun’s USB keyboard. Again, /// Found on Sun’s USB keyboard. Copy, /// Found on Sun’s USB keyboard. Cut, /// Found on Sun’s USB keyboard. Find, /// Found on Sun’s USB keyboard. Open, /// Found on Sun’s USB keyboard. Paste, /// Found on Sun’s USB keyboard. Props, /// Found on Sun’s USB keyboard. Select, /// Found on Sun’s USB keyboard. Undo, /// Use for dedicated <kbd>ひらがな</kbd> key found on some Japanese word processing keyboards. Hiragana, /// Use for dedicated <kbd>カタカナ</kbd> key found on some Japanese word processing keyboards. Katakana, /// General-purpose function key. /// Usually found at the top of the keyboard. F1, /// General-purpose function key. /// Usually found at the top of the keyboard. F2, /// General-purpose function key. /// Usually found at the top of the keyboard. F3, /// General-purpose function key. /// Usually found at the top of the keyboard. F4, /// General-purpose function key. /// Usually found at the top of the keyboard. F5, /// General-purpose function key. /// Usually found at the top of the keyboard. F6, /// General-purpose function key. /// Usually found at the top of the keyboard. F7, /// General-purpose function key. /// Usually found at the top of the keyboard. F8, /// General-purpose function key. /// Usually found at the top of the keyboard. F9, /// General-purpose function key. /// Usually found at the top of the keyboard. F10, /// General-purpose function key. /// Usually found at the top of the keyboard. F11, /// General-purpose function key. /// Usually found at the top of the keyboard. F12, /// General-purpose function key. /// Usually found at the top of the keyboard. F13, /// General-purpose function key. /// Usually found at the top of the keyboard. F14, /// General-purpose function key. /// Usually found at the top of the keyboard. F15, /// General-purpose function key. /// Usually found at the top of the keyboard. F16, /// General-purpose function key. /// Usually found at the top of the keyboard. F17, /// General-purpose function key. /// Usually found at the top of the keyboard. F18, /// General-purpose function key. /// Usually found at the top of the keyboard. F19, /// General-purpose function key. /// Usually found at the top of the keyboard. F20, /// General-purpose function key. /// Usually found at the top of the keyboard. F21, /// General-purpose function key. /// Usually found at the top of the keyboard. F22, /// General-purpose function key. /// Usually found at the top of the keyboard. F23, /// General-purpose function key. /// Usually found at the top of the keyboard. F24, /// General-purpose function key. F25, /// General-purpose function key. F26, /// General-purpose function key. F27, /// General-purpose function key. F28, /// General-purpose function key. F29, /// General-purpose function key. F30, /// General-purpose function key. F31, /// General-purpose function key. F32, /// General-purpose function key. F33, /// General-purpose function key. F34, /// General-purpose function key. F35, } /// Contains the platform-native logical key identifier, known as keysym. /// /// Exactly what that means differs from platform to platform, but the values are to some degree /// tied to the currently active keyboard layout. The same key on the same keyboard may also report /// different values on different platforms, which is one of the reasons this is a per-platform /// enum. /// /// This enum is primarily used to store raw keysym when Winit doesn't map a given native logical /// key identifier to a meaningful [`Key`] variant. This lets you use [`Key`], and let the user /// define keybinds which work in the presence of identifiers we haven't mapped for you yet. #[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq, Hash)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, Hash, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub enum NativeKey { /// Unidentified Unidentified, /// An Android "keycode", which is similar to a "virtual-key code" on Windows. Android(u32), /// A macOS "scancode". There does not appear to be any direct analogue to either keysyms or /// "virtual-key" codes in macOS, so we report the scancode instead. MacOS(u16), /// A Windows "virtual-key code". Windows(u16), /// An XKB "keysym". Xkb(u32), /// A "key value string". Web(SmolStr), } /// The logical key code of a [`KeyboardInput`]. /// /// This contains the actual value that is produced by pressing the key. This is /// useful when you need the actual letters, and for symbols like `+` and `-` /// when implementing zoom, as they can be in different locations depending on /// the keyboard layout. /// /// In many cases you want the key location instead, for example when /// implementing WASD controls so the keys are located the same place on QWERTY /// and other layouts. In that case use [`KeyCode`] instead. /// /// ## Usage /// /// It is used as the generic `T` value of an [`ButtonInput`] to create a `Res<ButtonInput<Key>>`. /// /// ## Technical /// /// Its values map 1 to 1 to winit's Key. #[non_exhaustive] #[derive(Debug, Hash, Ord, PartialOrd, PartialEq, Eq, Clone)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, Hash, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] #[expect( clippy::doc_markdown, reason = "We use camel-case words inside `<kbd>` tags to represent keyboard keys, which are not identifiers that we should be putting inside backticks." )] pub enum Key { /// A key string that corresponds to the character typed by the user, taking into account the /// user’s current locale setting, and any system-level keyboard mapping overrides that are in /// effect. /// /// Note that behavior may vary across platforms and keyboard layouts. /// See the `text` field of [`KeyboardInput`] for more information. Character(SmolStr), /// This variant is used when the key cannot be translated to any other variant. /// /// The native key is provided (if available) in order to allow the user to specify keybindings /// for keys which are not defined by this API, mainly through some sort of UI. Unidentified(NativeKey), /// Contains the text representation of the dead-key when available. /// /// ## Platform-specific /// - **Web:** Always contains `None` Dead(Option<char>), /// The `Alt` (Alternative) key. /// /// This key enables the alternate modifier function for interpreting concurrent or subsequent /// keyboard input. This key value is also used for the Apple <kbd>Option</kbd> key. Alt, /// The Alternate Graphics (<kbd>AltGr</kbd> or <kbd>AltGraph</kbd>) key. /// /// This key is used enable the ISO Level 3 shift modifier (the standard `Shift` key is the /// level 2 modifier). AltGraph, /// The `Caps Lock` (Capital) key. /// /// Toggle capital character lock function for interpreting subsequent keyboard input event. CapsLock, /// The `Control` or `Ctrl` key. /// /// Used to enable control modifier function for interpreting concurrent or subsequent keyboard /// input. Control, /// The Function switch `Fn` key. Activating this key simultaneously with another key changes /// that key’s value to an alternate character or function. This key is often handled directly /// in the keyboard hardware and does not usually generate key events. Fn, /// The Function-Lock (`FnLock` or `F-Lock`) key. Activating this key switches the mode of the /// keyboard to changes some keys' values to an alternate character or function. This key is /// often handled directly in the keyboard hardware and does not usually generate key events. FnLock, /// The `NumLock` or Number Lock key. Used to toggle numpad mode function for interpreting /// subsequent keyboard input. NumLock, /// Toggle between scrolling and cursor movement modes. ScrollLock, /// Used to enable shift modifier function for interpreting concurrent or subsequent keyboard /// input. Shift, /// The Symbol modifier key (used on some virtual keyboards). Symbol, /// The SymbolLock key, only on web. SymbolLock, /// Legacy modifier key. Also called "Super" in certain places. Meta, /// Legacy modifier key. Hyper, /// Used to enable "super" modifier function for interpreting concurrent or subsequent keyboard
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_input/src/touch.rs
crates/bevy_input/src/touch.rs
//! The touch input functionality. use bevy_ecs::{ entity::Entity, message::{Message, MessageReader}, resource::Resource, system::ResMut, }; use bevy_math::Vec2; use bevy_platform::collections::HashMap; #[cfg(feature = "bevy_reflect")] use bevy_reflect::Reflect; #[cfg(all(feature = "serialize", feature = "bevy_reflect"))] use bevy_reflect::{ReflectDeserialize, ReflectSerialize}; /// A touch input event. /// /// ## Logic /// /// Every time the user touches the screen, a new [`TouchPhase::Started`] event with an unique /// identifier for the finger is generated. When the finger is lifted, the [`TouchPhase::Ended`] /// event is generated with the same finger id. /// /// After a [`TouchPhase::Started`] event has been emitted, there may be zero or more [`TouchPhase::Moved`] /// events when the finger is moved or the touch pressure changes. /// /// The finger id may be reused by the system after an [`TouchPhase::Ended`] event. The user /// should assume that a new [`TouchPhase::Started`] event received with the same id has nothing /// to do with the old finger and is a new finger. /// /// A [`TouchPhase::Canceled`] event is emitted when the system has canceled tracking this /// touch, such as when the window loses focus, or on iOS if the user moves the /// device against their face. /// /// ## Note /// /// This event is the translated version of the `WindowEvent::Touch` from the `winit` crate. /// It is available to the end user and can be used for game logic. #[derive(Message, Debug, Clone, Copy, PartialEq)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub struct TouchInput { /// The phase of the touch input. pub phase: TouchPhase, /// The position of the finger on the touchscreen. pub position: Vec2, /// The window entity registering the touch. pub window: Entity, /// Describes how hard the screen was pressed. /// /// May be [`None`] if the platform does not support pressure sensitivity. /// This feature is only available on **iOS** 9.0+ and **Windows** 8+. pub force: Option<ForceTouch>, /// The unique identifier of the finger. pub id: u64, } /// A force description of a [`Touch`] input. #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub enum ForceTouch { /// On iOS, the force is calibrated so that the same number corresponds to /// roughly the same amount of pressure on the screen regardless of the /// device. Calibrated { /// The force of the touch, where a value of 1.0 represents the force of /// an average touch (predetermined by the system, not user-specific). /// /// The force reported by Apple Pencil is measured along the axis of the /// pencil. If you want a force perpendicular to the device, you need to /// calculate this value using the `altitude_angle` value. force: f64, /// The maximum possible force for a touch. /// /// The value of this field is sufficiently high to provide a wide /// dynamic range for values of the `force` field. max_possible_force: f64, /// The altitude (in radians) of the stylus. /// /// A value of 0 radians indicates that the stylus is parallel to the /// surface. The value of this property is Pi/2 when the stylus is /// perpendicular to the surface. altitude_angle: Option<f64>, }, /// If the platform reports the force as normalized, we have no way of /// knowing how much pressure 1.0 corresponds to – we know it's the maximum /// amount of force, but as to how much force, you might either have to /// press really hard, or not hard at all, depending on the device. Normalized(f64), } /// A phase of a [`TouchInput`]. /// /// ## Usage /// /// It is used to describe the phase of the touch input that is currently active. /// This includes a phase that indicates that a touch input has started or ended, /// or that a finger has moved. There is also a canceled phase that indicates that /// the system canceled the tracking of the finger. #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] #[cfg_attr( feature = "bevy_reflect", derive(Reflect), reflect(Debug, Hash, PartialEq, Clone) )] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( all(feature = "serialize", feature = "bevy_reflect"), reflect(Serialize, Deserialize) )] pub enum TouchPhase { /// A finger started to touch the touchscreen. Started, /// A finger moved over the touchscreen. Moved, /// A finger stopped touching the touchscreen. Ended, /// The system canceled the tracking of the finger. /// /// This occurs when the window loses focus, or on iOS if the user moves the /// device against their face. Canceled, } /// A touch input. /// /// ## Usage /// /// It is used to store the position and force of a touch input and also the `id` of the finger. /// The data of the touch input comes from the [`TouchInput`] event and is being stored /// inside of the [`Touches`] `bevy` resource. #[derive(Debug, Clone, Copy)] pub struct Touch { /// The id of the touch input. id: u64, /// The starting position of the touch input. start_position: Vec2, /// The starting force of the touch input. start_force: Option<ForceTouch>, /// The previous position of the touch input. previous_position: Vec2, /// The previous force of the touch input. previous_force: Option<ForceTouch>, /// The current position of the touch input. position: Vec2, /// The current force of the touch input. force: Option<ForceTouch>, } impl Touch { /// The delta of the current `position` and the `previous_position`. pub fn delta(&self) -> Vec2 { self.position - self.previous_position } /// The distance of the `start_position` and the current `position`. pub fn distance(&self) -> Vec2 { self.position - self.start_position } /// Returns the `id` of the touch. #[inline] pub fn id(&self) -> u64 { self.id } /// Returns the `start_position` of the touch. #[inline] pub fn start_position(&self) -> Vec2 { self.start_position } /// Returns the `start_force` of the touch. #[inline] pub fn start_force(&self) -> Option<ForceTouch> { self.start_force } /// Returns the `previous_position` of the touch. #[inline] pub fn previous_position(&self) -> Vec2 { self.previous_position } /// Returns the `previous_force` of the touch. #[inline] pub fn previous_force(&self) -> Option<ForceTouch> { self.previous_force } /// Returns the current `position` of the touch. #[inline] pub fn position(&self) -> Vec2 { self.position } /// Returns the current `force` of the touch. #[inline] pub fn force(&self) -> Option<ForceTouch> { self.force } } impl From<&TouchInput> for Touch { fn from(input: &TouchInput) -> Touch { Touch { id: input.id, start_position: input.position, start_force: input.force, previous_position: input.position, previous_force: input.force, position: input.position, force: input.force, } } } /// A collection of [`Touch`]es. /// /// ## Usage /// /// It is used to create a `bevy` resource that stores the data of the touches on a touchscreen /// and can be accessed inside of a system. /// /// ## Updating /// /// The resource is updated inside of the [`touch_screen_input_system`]. #[derive(Debug, Clone, Default, Resource)] pub struct Touches { /// A collection of every [`Touch`] that is currently being pressed. pressed: HashMap<u64, Touch>, /// A collection of every [`Touch`] that just got pressed. just_pressed: HashMap<u64, Touch>, /// A collection of every [`Touch`] that just got released. just_released: HashMap<u64, Touch>, /// A collection of every [`Touch`] that just got canceled. just_canceled: HashMap<u64, Touch>, } impl Touches { /// An iterator visiting every pressed [`Touch`] input in arbitrary order. pub fn iter(&self) -> impl Iterator<Item = &Touch> + '_ { self.pressed.values() } /// Returns the [`Touch`] input corresponding to the `id` if it is being pressed. pub fn get_pressed(&self, id: u64) -> Option<&Touch> { self.pressed.get(&id) } /// Checks if any touch input was just pressed. pub fn any_just_pressed(&self) -> bool { !self.just_pressed.is_empty() } /// Register a release for a given touch input. pub fn release(&mut self, id: u64) { if let Some(touch) = self.pressed.remove(&id) { self.just_released.insert(id, touch); } } /// Registers a release for all currently pressed touch inputs. pub fn release_all(&mut self) { self.just_released.extend(self.pressed.drain()); } /// Returns `true` if the input corresponding to the `id` has just been pressed. pub fn just_pressed(&self, id: u64) -> bool { self.just_pressed.contains_key(&id) } /// Clears the `just_pressed` state of the touch input and returns `true` if the touch input has just been pressed. /// /// Future calls to [`Touches::just_pressed`] for the given touch input will return false until a new press event occurs. pub fn clear_just_pressed(&mut self, id: u64) -> bool { self.just_pressed.remove(&id).is_some() } /// An iterator visiting every just pressed [`Touch`] input in arbitrary order. pub fn iter_just_pressed(&self) -> impl Iterator<Item = &Touch> { self.just_pressed.values() } /// Returns the [`Touch`] input corresponding to the `id` if it has just been released. pub fn get_released(&self, id: u64) -> Option<&Touch> { self.just_released.get(&id) } /// Checks if any touch input was just released. pub fn any_just_released(&self) -> bool { !self.just_released.is_empty() } /// Returns `true` if the input corresponding to the `id` has just been released. pub fn just_released(&self, id: u64) -> bool { self.just_released.contains_key(&id) } /// Clears the `just_released` state of the touch input and returns `true` if the touch input has just been released. /// /// Future calls to [`Touches::just_released`] for the given touch input will return false until a new release event occurs. pub fn clear_just_released(&mut self, id: u64) -> bool { self.just_released.remove(&id).is_some() } /// An iterator visiting every just released [`Touch`] input in arbitrary order. pub fn iter_just_released(&self) -> impl Iterator<Item = &Touch> { self.just_released.values() } /// Checks if any touch input was just canceled. pub fn any_just_canceled(&self) -> bool { !self.just_canceled.is_empty() } /// Returns `true` if the input corresponding to the `id` has just been canceled. pub fn just_canceled(&self, id: u64) -> bool { self.just_canceled.contains_key(&id) } /// Clears the `just_canceled` state of the touch input and returns `true` if the touch input has just been canceled. /// /// Future calls to [`Touches::just_canceled`] for the given touch input will return false until a new cancel event occurs. pub fn clear_just_canceled(&mut self, id: u64) -> bool { self.just_canceled.remove(&id).is_some() } /// An iterator visiting every just canceled [`Touch`] input in arbitrary order. pub fn iter_just_canceled(&self) -> impl Iterator<Item = &Touch> { self.just_canceled.values() } /// Retrieves the position of the first currently pressed touch, if any pub fn first_pressed_position(&self) -> Option<Vec2> { // Looking for the position in `pressed`. If nothing is found, also look into `just_pressed` // A touch can be in `just_pressed` but not in `pressed` if it ended in the same frame it started self.pressed .values() .next() .or_else(|| self.just_pressed.values().next()) .map(|t| t.position) } /// Clears `just_pressed`, `just_released`, and `just_canceled` data for every touch input. /// /// See also [`Touches::reset_all`] for a full reset. pub fn clear(&mut self) { self.just_pressed.clear(); self.just_released.clear(); self.just_canceled.clear(); } /// Clears `pressed`, `just_pressed`, `just_released`, and `just_canceled` data for every touch input. /// /// See also [`Touches::clear`] for clearing only touches that have just been pressed, released or canceled. pub fn reset_all(&mut self) { self.pressed.clear(); self.just_pressed.clear(); self.just_released.clear(); self.just_canceled.clear(); } /// Processes a [`TouchInput`] event by updating the `pressed`, `just_pressed`, /// `just_released`, and `just_canceled` collections. fn process_touch_event(&mut self, event: &TouchInput) { match event.phase { TouchPhase::Started => { self.pressed.insert(event.id, event.into()); self.just_pressed.insert(event.id, event.into()); } TouchPhase::Moved => { if let Some(mut new_touch) = self.pressed.get(&event.id).cloned() { // NOTE: This does not update the previous_force / previous_position field; // they should be updated once per frame, not once per event // See https://github.com/bevyengine/bevy/issues/12442 new_touch.position = event.position; new_touch.force = event.force; self.pressed.insert(event.id, new_touch); } } TouchPhase::Ended => { // if touch `just_released`, add related event to it // the event position info is inside `pressed`, so use it unless not found if let Some((_, v)) = self.pressed.remove_entry(&event.id) { self.just_released.insert(event.id, v); } else { self.just_released.insert(event.id, event.into()); } } TouchPhase::Canceled => { // if touch `just_canceled`, add related event to it // the event position info is inside `pressed`, so use it unless not found if let Some((_, v)) = self.pressed.remove_entry(&event.id) { self.just_canceled.insert(event.id, v); } else { self.just_canceled.insert(event.id, event.into()); } } }; } } /// Updates the [`Touches`] resource with the latest [`TouchInput`] events. /// /// This is not clearing the `pressed` collection, because it could incorrectly mark a touch input /// as not pressed even though it is pressed. This could happen if the touch input is not moving /// for a single frame and would therefore be marked as not pressed, because this function is /// called on every single frame no matter if there was an event or not. /// /// ## Differences /// /// The main difference between the [`TouchInput`] event and the [`Touches`] resource is that /// the latter has convenient functions like [`Touches::just_pressed`] and [`Touches::just_released`]. pub fn touch_screen_input_system( mut touch_state: ResMut<Touches>, mut touch_input_reader: MessageReader<TouchInput>, ) { if !touch_state.just_pressed.is_empty() { touch_state.just_pressed.clear(); } if !touch_state.just_released.is_empty() { touch_state.just_released.clear(); } if !touch_state.just_canceled.is_empty() { touch_state.just_canceled.clear(); } if !touch_input_reader.is_empty() { for touch in touch_state.pressed.values_mut() { touch.previous_position = touch.position; touch.previous_force = touch.force; } for event in touch_input_reader.read() { touch_state.process_touch_event(event); } } } #[cfg(test)] mod test { use super::Touches; #[test] fn touch_update() { use crate::{touch::Touch, Touches}; use bevy_math::Vec2; let mut touches = Touches::default(); let touch_event = Touch { id: 4, start_position: Vec2::ZERO, start_force: None, previous_position: Vec2::ZERO, previous_force: None, position: Vec2::ZERO, force: None, }; // Add a touch to `just_pressed`, 'just_released', and 'just canceled' touches.just_pressed.insert(4, touch_event); touches.just_released.insert(4, touch_event); touches.just_canceled.insert(4, touch_event); clear_all(&mut touches); // Verify that all the `just_x` maps are cleared assert!(touches.just_pressed.is_empty()); assert!(touches.just_released.is_empty()); assert!(touches.just_canceled.is_empty()); } #[test] fn touch_process() { use crate::{touch::TouchPhase, TouchInput, Touches}; use bevy_ecs::entity::Entity; use bevy_math::Vec2; let mut touches = Touches::default(); // Test adding a `TouchPhase::Started` let touch_event = TouchInput { phase: TouchPhase::Started, position: Vec2::splat(4.0), window: Entity::PLACEHOLDER, force: None, id: 4, }; clear_all(&mut touches); touches.process_touch_event(&touch_event); assert!(touches.pressed.get(&touch_event.id).is_some()); assert!(touches.just_pressed.get(&touch_event.id).is_some()); // Test adding a `TouchPhase::Moved` let moved_touch_event = TouchInput { phase: TouchPhase::Moved, position: Vec2::splat(5.0), window: Entity::PLACEHOLDER, force: None, id: touch_event.id, }; clear_all(&mut touches); touches.process_touch_event(&moved_touch_event); assert_eq!( touches .pressed .get(&moved_touch_event.id) .expect("Missing from pressed after move.") .previous_position, touch_event.position ); // Test cancelling an event let cancel_touch_event = TouchInput { phase: TouchPhase::Canceled, position: Vec2::ONE, window: Entity::PLACEHOLDER, force: None, id: touch_event.id, }; clear_all(&mut touches); touches.process_touch_event(&cancel_touch_event); assert!(touches.just_canceled.get(&touch_event.id).is_some()); assert!(touches.pressed.get(&touch_event.id).is_none()); // Test ending an event let end_touch_event = TouchInput { phase: TouchPhase::Ended, position: Vec2::splat(4.0), window: Entity::PLACEHOLDER, force: None, id: touch_event.id, }; clear_all(&mut touches); touches.process_touch_event(&touch_event); touches.process_touch_event(&moved_touch_event); touches.process_touch_event(&end_touch_event); assert!(touches.just_released.get(&touch_event.id).is_some()); assert!(touches.pressed.get(&touch_event.id).is_none()); let touch = touches.just_released.get(&touch_event.id).unwrap(); // Make sure the position is updated from TouchPhase::Moved and TouchPhase::Ended assert_ne!(touch.previous_position, touch.position); } // See https://github.com/bevyengine/bevy/issues/12442 #[test] fn touch_process_multi_event() { use crate::{touch::TouchPhase, TouchInput, Touches}; use bevy_ecs::entity::Entity; use bevy_math::Vec2; let mut touches = Touches::default(); let started_touch_event = TouchInput { phase: TouchPhase::Started, position: Vec2::splat(4.0), window: Entity::PLACEHOLDER, force: None, id: 4, }; let moved_touch_event1 = TouchInput { phase: TouchPhase::Moved, position: Vec2::splat(5.0), window: Entity::PLACEHOLDER, force: None, id: started_touch_event.id, }; let moved_touch_event2 = TouchInput { phase: TouchPhase::Moved, position: Vec2::splat(6.0), window: Entity::PLACEHOLDER, force: None, id: started_touch_event.id, }; // tick 1: touch is started during frame for touch in touches.pressed.values_mut() { // update ONCE, at start of frame touch.previous_position = touch.position; } touches.process_touch_event(&started_touch_event); touches.process_touch_event(&moved_touch_event1); touches.process_touch_event(&moved_touch_event2); { let touch = touches.get_pressed(started_touch_event.id).unwrap(); assert_eq!(touch.previous_position, started_touch_event.position); assert_eq!(touch.position, moved_touch_event2.position); } // tick 2: touch was started before frame for touch in touches.pressed.values_mut() { touch.previous_position = touch.position; } touches.process_touch_event(&moved_touch_event1); touches.process_touch_event(&moved_touch_event2); touches.process_touch_event(&moved_touch_event1); { let touch = touches.get_pressed(started_touch_event.id).unwrap(); assert_eq!(touch.previous_position, moved_touch_event2.position); assert_eq!(touch.position, moved_touch_event1.position); } } #[test] fn touch_pressed() { use crate::{touch::TouchPhase, TouchInput, Touches}; use bevy_ecs::entity::Entity; use bevy_math::Vec2; let mut touches = Touches::default(); let touch_event = TouchInput { phase: TouchPhase::Started, position: Vec2::splat(4.0), window: Entity::PLACEHOLDER, force: None, id: 4, }; // Register the touch and test that it was registered correctly touches.process_touch_event(&touch_event); assert!(touches.get_pressed(touch_event.id).is_some()); assert!(touches.just_pressed(touch_event.id)); assert_eq!(touches.iter().count(), 1); touches.clear_just_pressed(touch_event.id); assert!(!touches.just_pressed(touch_event.id)); } #[test] fn touch_released() { use crate::{touch::TouchPhase, TouchInput, Touches}; use bevy_ecs::entity::Entity; use bevy_math::Vec2; let mut touches = Touches::default(); let touch_event = TouchInput { phase: TouchPhase::Ended, position: Vec2::splat(4.0), window: Entity::PLACEHOLDER, force: None, id: 4, }; // Register the touch and test that it was registered correctly touches.process_touch_event(&touch_event); assert!(touches.get_released(touch_event.id).is_some()); assert!(touches.just_released(touch_event.id)); assert_eq!(touches.iter_just_released().count(), 1); touches.clear_just_released(touch_event.id); assert!(!touches.just_released(touch_event.id)); } #[test] fn touch_canceled() { use crate::{touch::TouchPhase, TouchInput, Touches}; use bevy_ecs::entity::Entity; use bevy_math::Vec2; let mut touches = Touches::default(); let touch_event = TouchInput { phase: TouchPhase::Canceled, position: Vec2::splat(4.0), window: Entity::PLACEHOLDER, force: None, id: 4, }; // Register the touch and test that it was registered correctly touches.process_touch_event(&touch_event); assert!(touches.just_canceled(touch_event.id)); assert_eq!(touches.iter_just_canceled().count(), 1); touches.clear_just_canceled(touch_event.id); assert!(!touches.just_canceled(touch_event.id)); } #[test] fn release_touch() { use crate::{touch::TouchPhase, TouchInput, Touches}; use bevy_ecs::entity::Entity; use bevy_math::Vec2; let mut touches = Touches::default(); let touch_event = TouchInput { phase: TouchPhase::Started, position: Vec2::splat(4.0), window: Entity::PLACEHOLDER, force: None, id: 4, }; // Register the touch and test that it was registered correctly touches.process_touch_event(&touch_event); assert!(touches.get_pressed(touch_event.id).is_some()); touches.release(touch_event.id); assert!(touches.get_pressed(touch_event.id).is_none()); assert!(touches.just_released(touch_event.id)); } #[test] fn release_all_touches() { use crate::{touch::TouchPhase, TouchInput, Touches}; use bevy_ecs::entity::Entity; use bevy_math::Vec2; let mut touches = Touches::default(); let touch_pressed_event = TouchInput { phase: TouchPhase::Started, position: Vec2::splat(4.0), window: Entity::PLACEHOLDER, force: None, id: 4, }; let touch_moved_event = TouchInput { phase: TouchPhase::Moved, position: Vec2::splat(4.0), window: Entity::PLACEHOLDER, force: None, id: 4, }; touches.process_touch_event(&touch_pressed_event); touches.process_touch_event(&touch_moved_event); assert!(touches.get_pressed(touch_pressed_event.id).is_some()); assert!(touches.get_pressed(touch_moved_event.id).is_some()); touches.release_all(); assert!(touches.get_pressed(touch_pressed_event.id).is_none()); assert!(touches.just_released(touch_pressed_event.id)); assert!(touches.get_pressed(touch_moved_event.id).is_none()); assert!(touches.just_released(touch_moved_event.id)); } #[test] fn clear_touches() { use crate::{touch::TouchPhase, TouchInput, Touches}; use bevy_ecs::entity::Entity; use bevy_math::Vec2; let mut touches = Touches::default(); let touch_press_event = TouchInput { phase: TouchPhase::Started, position: Vec2::splat(4.0), window: Entity::PLACEHOLDER, force: None, id: 4, }; let touch_canceled_event = TouchInput { phase: TouchPhase::Canceled, position: Vec2::splat(4.0), window: Entity::PLACEHOLDER, force: None, id: 5, }; let touch_released_event = TouchInput { phase: TouchPhase::Ended, position: Vec2::splat(4.0), window: Entity::PLACEHOLDER, force: None, id: 6, }; // Register the touches and test that it was registered correctly touches.process_touch_event(&touch_press_event); touches.process_touch_event(&touch_canceled_event); touches.process_touch_event(&touch_released_event); assert!(touches.get_pressed(touch_press_event.id).is_some()); assert!(touches.just_pressed(touch_press_event.id)); assert!(touches.just_canceled(touch_canceled_event.id)); assert!(touches.just_released(touch_released_event.id)); touches.clear(); assert!(touches.get_pressed(touch_press_event.id).is_some()); assert!(!touches.just_pressed(touch_press_event.id)); assert!(!touches.just_canceled(touch_canceled_event.id)); assert!(!touches.just_released(touch_released_event.id)); } #[test] fn reset_all_touches() { use crate::{touch::TouchPhase, TouchInput, Touches}; use bevy_ecs::entity::Entity; use bevy_math::Vec2; let mut touches = Touches::default(); let touch_press_event = TouchInput { phase: TouchPhase::Started, position: Vec2::splat(4.0), window: Entity::PLACEHOLDER, force: None, id: 4, }; let touch_canceled_event = TouchInput { phase: TouchPhase::Canceled, position: Vec2::splat(4.0), window: Entity::PLACEHOLDER, force: None, id: 5, }; let touch_released_event = TouchInput { phase: TouchPhase::Ended, position: Vec2::splat(4.0), window: Entity::PLACEHOLDER, force: None, id: 6, }; // Register the touches and test that it was registered correctly touches.process_touch_event(&touch_press_event); touches.process_touch_event(&touch_canceled_event); touches.process_touch_event(&touch_released_event); assert!(touches.get_pressed(touch_press_event.id).is_some()); assert!(touches.just_pressed(touch_press_event.id)); assert!(touches.just_canceled(touch_canceled_event.id)); assert!(touches.just_released(touch_released_event.id)); touches.reset_all(); assert!(touches.get_pressed(touch_press_event.id).is_none()); assert!(!touches.just_pressed(touch_press_event.id)); assert!(!touches.just_canceled(touch_canceled_event.id)); assert!(!touches.just_released(touch_released_event.id)); } fn clear_all(touch_state: &mut Touches) { touch_state.just_pressed.clear(); touch_state.just_released.clear(); touch_state.just_canceled.clear(); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_solari/src/lib.rs
crates/bevy_solari/src/lib.rs
#![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")] //! Provides raytraced lighting. //! //! See [`SolariPlugins`] for more info. //! //! ![`bevy_solari` logo](https://raw.githubusercontent.com/bevyengine/bevy/refs/heads/main/assets/branding/bevy_solari.svg) extern crate alloc; pub mod pathtracer; pub mod realtime; pub mod scene; /// The solari prelude. /// /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { pub use super::SolariPlugins; pub use crate::realtime::SolariLighting; pub use crate::scene::RaytracingMesh3d; } use crate::realtime::SolariLightingPlugin; use crate::scene::RaytracingScenePlugin; use bevy_app::{PluginGroup, PluginGroupBuilder}; use bevy_render::settings::WgpuFeatures; /// An experimental set of plugins for raytraced lighting. /// /// This plugin group provides: /// * [`SolariLightingPlugin`] - Raytraced direct and indirect lighting. /// * [`RaytracingScenePlugin`] - BLAS building, resource and lighting binding. /// /// There's also: /// * [`pathtracer::PathtracingPlugin`] - A non-realtime pathtracer for validation purposes (not added by default). /// /// To get started, add this plugin to your app, and then add `RaytracingMesh3d` and `MeshMaterial3d::<StandardMaterial>` to your entities. pub struct SolariPlugins; impl PluginGroup for SolariPlugins { fn build(self) -> PluginGroupBuilder { PluginGroupBuilder::start::<Self>() .add(RaytracingScenePlugin) .add(SolariLightingPlugin) } } impl SolariPlugins { /// [`WgpuFeatures`] required for these plugins to function. pub fn required_wgpu_features() -> WgpuFeatures { WgpuFeatures::EXPERIMENTAL_RAY_QUERY | WgpuFeatures::BUFFER_BINDING_ARRAY | WgpuFeatures::TEXTURE_BINDING_ARRAY | WgpuFeatures::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING | WgpuFeatures::PARTIALLY_BOUND_BINDING_ARRAY } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_solari/src/scene/blas.rs
crates/bevy_solari/src/scene/blas.rs
use alloc::collections::VecDeque; use bevy_asset::AssetId; use bevy_ecs::{ resource::Resource, system::{Res, ResMut}, }; use bevy_mesh::{Indices, Mesh}; use bevy_platform::collections::HashMap; use bevy_render::{ mesh::{ allocator::{MeshAllocator, MeshBufferSlice}, RenderMesh, }, render_asset::ExtractedAssets, render_resource::*, renderer::{RenderDevice, RenderQueue}, }; /// After compacting this many vertices worth of meshes per frame, no further BLAS will be compacted. /// Lower this number to distribute the work across more frames. const MAX_COMPACTION_VERTICES_PER_FRAME: u32 = 400_000; #[derive(Resource, Default)] pub struct BlasManager { blas: HashMap<AssetId<Mesh>, Blas>, compaction_queue: VecDeque<(AssetId<Mesh>, u32, bool)>, } impl BlasManager { pub fn get(&self, mesh: &AssetId<Mesh>) -> Option<&Blas> { self.blas.get(mesh) } } pub fn prepare_raytracing_blas( mut blas_manager: ResMut<BlasManager>, extracted_meshes: Res<ExtractedAssets<RenderMesh>>, mesh_allocator: Res<MeshAllocator>, render_device: Res<RenderDevice>, render_queue: Res<RenderQueue>, ) { // Delete BLAS for deleted or modified meshes for asset_id in extracted_meshes .removed .iter() .chain(extracted_meshes.modified.iter()) { blas_manager.blas.remove(asset_id); } if extracted_meshes.extracted.is_empty() { return; } // Create new BLAS for added or changed meshes let blas_resources = extracted_meshes .extracted .iter() .filter(|(_, mesh)| is_mesh_raytracing_compatible(mesh)) .map(|(asset_id, _)| { let vertex_slice = mesh_allocator.mesh_vertex_slice(asset_id).unwrap(); let index_slice = mesh_allocator.mesh_index_slice(asset_id).unwrap(); let (blas, blas_size) = allocate_blas(&vertex_slice, &index_slice, asset_id, &render_device); blas_manager.blas.insert(*asset_id, blas); blas_manager .compaction_queue .push_back((*asset_id, blas_size.vertex_count, false)); (*asset_id, vertex_slice, index_slice, blas_size) }) .collect::<Vec<_>>(); // Build geometry into each BLAS let build_entries = blas_resources .iter() .map(|(asset_id, vertex_slice, index_slice, blas_size)| { let geometry = BlasTriangleGeometry { size: blas_size, vertex_buffer: vertex_slice.buffer, first_vertex: vertex_slice.range.start, vertex_stride: 48, index_buffer: Some(index_slice.buffer), first_index: Some(index_slice.range.start), transform_buffer: None, transform_buffer_offset: None, }; BlasBuildEntry { blas: &blas_manager.blas[asset_id], geometry: BlasGeometries::TriangleGeometries(vec![geometry]), } }) .collect::<Vec<_>>(); let mut command_encoder = render_device.create_command_encoder(&CommandEncoderDescriptor { label: Some("build_blas_command_encoder"), }); command_encoder.build_acceleration_structures(&build_entries, &[]); render_queue.submit([command_encoder.finish()]); } pub fn compact_raytracing_blas( mut blas_manager: ResMut<BlasManager>, render_queue: Res<RenderQueue>, ) { let queue_size = blas_manager.compaction_queue.len(); let mut meshes_processed = 0; let mut vertices_compacted = 0; while !blas_manager.compaction_queue.is_empty() && vertices_compacted < MAX_COMPACTION_VERTICES_PER_FRAME && meshes_processed < queue_size { meshes_processed += 1; let (mesh, vertex_count, compaction_started) = blas_manager.compaction_queue.pop_front().unwrap(); let Some(blas) = blas_manager.get(&mesh) else { continue; }; if !compaction_started { blas.prepare_compaction_async(|_| {}); } if blas.ready_for_compaction() { let compacted_blas = render_queue.compact_blas(blas); blas_manager.blas.insert(mesh, compacted_blas); vertices_compacted += vertex_count; continue; } // BLAS not ready for compaction, put back in queue blas_manager .compaction_queue .push_back((mesh, vertex_count, true)); } } fn allocate_blas( vertex_slice: &MeshBufferSlice, index_slice: &MeshBufferSlice, asset_id: &AssetId<Mesh>, render_device: &RenderDevice, ) -> (Blas, BlasTriangleGeometrySizeDescriptor) { let blas_size = BlasTriangleGeometrySizeDescriptor { vertex_format: Mesh::ATTRIBUTE_POSITION.format, vertex_count: vertex_slice.range.len() as u32, index_format: Some(IndexFormat::Uint32), index_count: Some(index_slice.range.len() as u32), flags: AccelerationStructureGeometryFlags::OPAQUE, }; let blas = render_device.wgpu_device().create_blas( &CreateBlasDescriptor { label: Some(&asset_id.to_string()), flags: AccelerationStructureFlags::PREFER_FAST_TRACE | AccelerationStructureFlags::ALLOW_COMPACTION, update_mode: AccelerationStructureUpdateMode::Build, }, BlasGeometrySizeDescriptors::Triangles { descriptors: vec![blas_size.clone()], }, ); (blas, blas_size) } fn is_mesh_raytracing_compatible(mesh: &Mesh) -> bool { let triangle_list = mesh.primitive_topology() == PrimitiveTopology::TriangleList; let vertex_attributes = mesh.attributes().map(|(attribute, _)| attribute.id).eq([ Mesh::ATTRIBUTE_POSITION.id, Mesh::ATTRIBUTE_NORMAL.id, Mesh::ATTRIBUTE_UV_0.id, Mesh::ATTRIBUTE_TANGENT.id, ]); let indexed_32 = matches!(mesh.indices(), Some(Indices::U32(..))); mesh.enable_raytracing && triangle_list && vertex_attributes && indexed_32 }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_solari/src/scene/types.rs
crates/bevy_solari/src/scene/types.rs
use bevy_asset::Handle; use bevy_derive::{Deref, DerefMut}; use bevy_ecs::{component::Component, prelude::ReflectComponent}; use bevy_mesh::Mesh; use bevy_pbr::{MeshMaterial3d, StandardMaterial}; use bevy_reflect::{prelude::ReflectDefault, Reflect}; use bevy_render::sync_world::SyncToRenderWorld; use bevy_transform::components::Transform; use derive_more::derive::From; /// A mesh component used for raytracing. /// /// The mesh used in this component must have [`Mesh::enable_raytracing`] set to true, /// use the following set of vertex attributes: `{POSITION, NORMAL, UV_0, TANGENT}`, use [`bevy_mesh::PrimitiveTopology::TriangleList`], /// and use [`bevy_mesh::Indices::U32`]. /// /// The material used for this entity must be [`MeshMaterial3d<StandardMaterial>`]. #[derive(Component, Clone, Debug, Default, Deref, DerefMut, Reflect, PartialEq, Eq, From)] #[reflect(Component, Default, Clone, PartialEq)] #[require(MeshMaterial3d<StandardMaterial>, Transform, SyncToRenderWorld)] pub struct RaytracingMesh3d(pub Handle<Mesh>);
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_solari/src/scene/mod.rs
crates/bevy_solari/src/scene/mod.rs
mod binder; mod blas; mod extract; mod types; use bevy_shader::load_shader_library; pub use binder::RaytracingSceneBindings; pub use types::RaytracingMesh3d; use crate::SolariPlugins; use bevy_app::{App, Plugin}; use bevy_ecs::schedule::IntoScheduleConfigs; use bevy_render::{ extract_resource::ExtractResourcePlugin, mesh::{ allocator::{allocate_and_free_meshes, MeshAllocator}, RenderMesh, }, render_asset::prepare_assets, render_resource::BufferUsages, renderer::RenderDevice, ExtractSchedule, Render, RenderApp, RenderSystems, }; use binder::prepare_raytracing_scene_bindings; use blas::{compact_raytracing_blas, prepare_raytracing_blas, BlasManager}; use extract::{extract_raytracing_scene, StandardMaterialAssets}; use tracing::warn; /// Creates acceleration structures and binding arrays of resources for raytracing. pub struct RaytracingScenePlugin; impl Plugin for RaytracingScenePlugin { fn build(&self, app: &mut App) { load_shader_library!(app, "brdf.wgsl"); load_shader_library!(app, "raytracing_scene_bindings.wgsl"); load_shader_library!(app, "sampling.wgsl"); } fn finish(&self, app: &mut App) { let render_app = app.sub_app_mut(RenderApp); let render_device = render_app.world().resource::<RenderDevice>(); let features = render_device.features(); if !features.contains(SolariPlugins::required_wgpu_features()) { warn!( "RaytracingScenePlugin not loaded. GPU lacks support for required features: {:?}.", SolariPlugins::required_wgpu_features().difference(features) ); return; } app.add_plugins(ExtractResourcePlugin::<StandardMaterialAssets>::default()); let render_app = app.sub_app_mut(RenderApp); render_app .world_mut() .resource_mut::<MeshAllocator>() .extra_buffer_usages |= BufferUsages::BLAS_INPUT | BufferUsages::STORAGE; render_app .init_resource::<BlasManager>() .init_resource::<StandardMaterialAssets>() .insert_resource(RaytracingSceneBindings::new()) .add_systems(ExtractSchedule, extract_raytracing_scene) .add_systems( Render, ( prepare_raytracing_blas .in_set(RenderSystems::PrepareAssets) .before(prepare_assets::<RenderMesh>) .after(allocate_and_free_meshes), compact_raytracing_blas .in_set(RenderSystems::PrepareAssets) .after(prepare_raytracing_blas), prepare_raytracing_scene_bindings.in_set(RenderSystems::PrepareBindGroups), ), ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_solari/src/scene/extract.rs
crates/bevy_solari/src/scene/extract.rs
use super::RaytracingMesh3d; use bevy_asset::{AssetId, Assets}; use bevy_derive::Deref; use bevy_ecs::{ resource::Resource, system::{Commands, Query}, }; use bevy_pbr::{MeshMaterial3d, StandardMaterial}; use bevy_platform::collections::HashMap; use bevy_render::{extract_resource::ExtractResource, sync_world::RenderEntity, Extract}; use bevy_transform::components::GlobalTransform; pub fn extract_raytracing_scene( instances: Extract< Query<( RenderEntity, &RaytracingMesh3d, &MeshMaterial3d<StandardMaterial>, &GlobalTransform, )>, >, mut commands: Commands, ) { for (render_entity, mesh, material, transform) in &instances { commands .entity(render_entity) .insert((mesh.clone(), material.clone(), *transform)); } } #[derive(Resource, Deref, Default)] pub struct StandardMaterialAssets(HashMap<AssetId<StandardMaterial>, StandardMaterial>); impl ExtractResource for StandardMaterialAssets { type Source = Assets<StandardMaterial>; fn extract_resource(source: &Self::Source) -> Self { Self( source .iter() .map(|(asset_id, material)| (asset_id, material.clone())) .collect(), ) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_solari/src/scene/binder.rs
crates/bevy_solari/src/scene/binder.rs
use super::{blas::BlasManager, extract::StandardMaterialAssets, RaytracingMesh3d}; use bevy_asset::{AssetId, Handle}; use bevy_color::{ColorToComponents, LinearRgba}; use bevy_ecs::{ entity::{Entity, EntityHashMap}, resource::Resource, system::{Query, Res, ResMut}, }; use bevy_math::{ops::cos, Mat4, Vec3}; use bevy_pbr::{ExtractedDirectionalLight, MeshMaterial3d, StandardMaterial}; use bevy_platform::{collections::HashMap, hash::FixedHasher}; use bevy_render::{ mesh::allocator::MeshAllocator, render_asset::RenderAssets, render_resource::{binding_types::*, *}, renderer::{RenderDevice, RenderQueue}, texture::{FallbackImage, GpuImage}, }; use bevy_transform::components::GlobalTransform; use core::{f32::consts::TAU, hash::Hash, num::NonZeroU32, ops::Deref}; const MAX_MESH_SLAB_COUNT: NonZeroU32 = NonZeroU32::new(500).unwrap(); const MAX_TEXTURE_COUNT: NonZeroU32 = NonZeroU32::new(5_000).unwrap(); const TEXTURE_MAP_NONE: u32 = u32::MAX; const LIGHT_NOT_PRESENT_THIS_FRAME: u32 = u32::MAX; #[derive(Resource)] pub struct RaytracingSceneBindings { pub bind_group: Option<BindGroup>, pub bind_group_layout: BindGroupLayoutDescriptor, previous_frame_light_entities: Vec<Entity>, } pub fn prepare_raytracing_scene_bindings( instances_query: Query<( Entity, &RaytracingMesh3d, &MeshMaterial3d<StandardMaterial>, &GlobalTransform, )>, directional_lights_query: Query<(Entity, &ExtractedDirectionalLight)>, mesh_allocator: Res<MeshAllocator>, blas_manager: Res<BlasManager>, material_assets: Res<StandardMaterialAssets>, texture_assets: Res<RenderAssets<GpuImage>>, fallback_texture: Res<FallbackImage>, render_device: Res<RenderDevice>, pipeline_cache: Res<PipelineCache>, render_queue: Res<RenderQueue>, mut raytracing_scene_bindings: ResMut<RaytracingSceneBindings>, ) { raytracing_scene_bindings.bind_group = None; let mut this_frame_entity_to_light_id = EntityHashMap::<u32>::default(); let previous_frame_light_entities: Vec<_> = raytracing_scene_bindings .previous_frame_light_entities .drain(..) .collect(); if instances_query.iter().len() == 0 { return; } let mut vertex_buffers = CachedBindingArray::new(); let mut index_buffers = CachedBindingArray::new(); let mut textures = CachedBindingArray::new(); let mut samplers = Vec::new(); let mut materials = StorageBufferList::<GpuMaterial>::default(); let mut tlas = render_device .wgpu_device() .create_tlas(&CreateTlasDescriptor { label: Some("tlas"), flags: AccelerationStructureFlags::PREFER_FAST_TRACE, update_mode: AccelerationStructureUpdateMode::Build, max_instances: instances_query.iter().len() as u32, }); let mut transforms = StorageBufferList::<Mat4>::default(); let mut geometry_ids = StorageBufferList::<GpuInstanceGeometryIds>::default(); let mut material_ids = StorageBufferList::<u32>::default(); let mut light_sources = StorageBufferList::<GpuLightSource>::default(); let mut directional_lights = StorageBufferList::<GpuDirectionalLight>::default(); let mut previous_frame_light_id_translations = StorageBufferList::<u32>::default(); let mut material_id_map: HashMap<AssetId<StandardMaterial>, u32, FixedHasher> = HashMap::default(); let mut material_id = 0; let mut process_texture = |texture_handle: &Option<Handle<_>>| -> Option<u32> { match texture_handle { Some(texture_handle) => match texture_assets.get(texture_handle.id()) { Some(texture) => { let (texture_id, is_new) = textures.push_if_absent(texture.texture_view.deref(), texture_handle.id()); if is_new { samplers.push(texture.sampler.deref()); } Some(texture_id) } None => None, }, None => Some(TEXTURE_MAP_NONE), } }; for (asset_id, material) in material_assets.iter() { let Some(base_color_texture_id) = process_texture(&material.base_color_texture) else { continue; }; let Some(normal_map_texture_id) = process_texture(&material.normal_map_texture) else { continue; }; let Some(emissive_texture_id) = process_texture(&material.emissive_texture) else { continue; }; let Some(metallic_roughness_texture_id) = process_texture(&material.metallic_roughness_texture) else { continue; }; materials.get_mut().push(GpuMaterial { normal_map_texture_id, base_color_texture_id, emissive_texture_id, metallic_roughness_texture_id, base_color: LinearRgba::from(material.base_color).to_vec3(), perceptual_roughness: material.perceptual_roughness, emissive: material.emissive.to_vec3(), metallic: material.metallic, reflectance: LinearRgba::from(material.specular_tint).to_vec3() * material.reflectance, _padding: Default::default(), }); material_id_map.insert(*asset_id, material_id); material_id += 1; } if material_id == 0 { return; } if textures.is_empty() { textures.vec.push(fallback_texture.d2.texture_view.deref()); samplers.push(fallback_texture.d2.sampler.deref()); } let mut instance_id = 0; for (entity, mesh, material, transform) in &instances_query { let Some(blas) = blas_manager.get(&mesh.id()) else { continue; }; let Some(vertex_slice) = mesh_allocator.mesh_vertex_slice(&mesh.id()) else { continue; }; let Some(index_slice) = mesh_allocator.mesh_index_slice(&mesh.id()) else { continue; }; let Some(material_id) = material_id_map.get(&material.id()).copied() else { continue; }; let Some(material) = materials.get().get(material_id as usize) else { continue; }; let transform = transform.to_matrix(); *tlas.get_mut_single(instance_id).unwrap() = Some(TlasInstance::new( blas, tlas_transform(&transform), Default::default(), 0xFF, )); transforms.get_mut().push(transform); let (vertex_buffer_id, _) = vertex_buffers.push_if_absent( vertex_slice.buffer.as_entire_buffer_binding(), vertex_slice.buffer.id(), ); let (index_buffer_id, _) = index_buffers.push_if_absent( index_slice.buffer.as_entire_buffer_binding(), index_slice.buffer.id(), ); geometry_ids.get_mut().push(GpuInstanceGeometryIds { vertex_buffer_id, vertex_buffer_offset: vertex_slice.range.start, index_buffer_id, index_buffer_offset: index_slice.range.start, triangle_count: (index_slice.range.len() / 3) as u32, }); material_ids.get_mut().push(material_id); if material.emissive != Vec3::ZERO { light_sources .get_mut() .push(GpuLightSource::new_emissive_mesh_light( instance_id as u32, (index_slice.range.len() / 3) as u32, )); this_frame_entity_to_light_id.insert(entity, light_sources.get().len() as u32 - 1); raytracing_scene_bindings .previous_frame_light_entities .push(entity); } instance_id += 1; } if instance_id == 0 { return; } for (entity, directional_light) in &directional_lights_query { let directional_lights = directional_lights.get_mut(); let directional_light_id = directional_lights.len() as u32; directional_lights.push(GpuDirectionalLight::new(directional_light)); light_sources .get_mut() .push(GpuLightSource::new_directional_light(directional_light_id)); this_frame_entity_to_light_id.insert(entity, light_sources.get().len() as u32 - 1); raytracing_scene_bindings .previous_frame_light_entities .push(entity); } for previous_frame_light_entity in previous_frame_light_entities { let current_frame_index = this_frame_entity_to_light_id .get(&previous_frame_light_entity) .copied() .unwrap_or(LIGHT_NOT_PRESENT_THIS_FRAME); previous_frame_light_id_translations .get_mut() .push(current_frame_index); } if light_sources.get().len() > u16::MAX as usize { panic!("Too many light sources in the scene, maximum is 65536."); } materials.write_buffer(&render_device, &render_queue); transforms.write_buffer(&render_device, &render_queue); geometry_ids.write_buffer(&render_device, &render_queue); material_ids.write_buffer(&render_device, &render_queue); light_sources.write_buffer(&render_device, &render_queue); directional_lights.write_buffer(&render_device, &render_queue); previous_frame_light_id_translations.write_buffer(&render_device, &render_queue); let mut command_encoder = render_device.create_command_encoder(&CommandEncoderDescriptor { label: Some("build_tlas_command_encoder"), }); command_encoder.build_acceleration_structures(&[], [&tlas]); render_queue.submit([command_encoder.finish()]); raytracing_scene_bindings.bind_group = Some(render_device.create_bind_group( "raytracing_scene_bind_group", &pipeline_cache.get_bind_group_layout(&raytracing_scene_bindings.bind_group_layout), &BindGroupEntries::sequential(( vertex_buffers.as_slice(), index_buffers.as_slice(), textures.as_slice(), samplers.as_slice(), materials.binding().unwrap(), tlas.as_binding(), transforms.binding().unwrap(), geometry_ids.binding().unwrap(), material_ids.binding().unwrap(), light_sources.binding().unwrap(), directional_lights.binding().unwrap(), previous_frame_light_id_translations.binding().unwrap(), )), )); } impl RaytracingSceneBindings { pub fn new() -> Self { Self { bind_group: None, bind_group_layout: BindGroupLayoutDescriptor::new( "raytracing_scene_bind_group_layout", &BindGroupLayoutEntries::sequential( ShaderStages::COMPUTE, ( storage_buffer_read_only_sized(false, None).count(MAX_MESH_SLAB_COUNT), storage_buffer_read_only_sized(false, None).count(MAX_MESH_SLAB_COUNT), texture_2d(TextureSampleType::Float { filterable: true }) .count(MAX_TEXTURE_COUNT), sampler(SamplerBindingType::Filtering).count(MAX_TEXTURE_COUNT), storage_buffer_read_only_sized(false, None), acceleration_structure(), storage_buffer_read_only_sized(false, None), storage_buffer_read_only_sized(false, None), storage_buffer_read_only_sized(false, None), storage_buffer_read_only_sized(false, None), storage_buffer_read_only_sized(false, None), storage_buffer_read_only_sized(false, None), ), ), ), previous_frame_light_entities: Vec::new(), } } } impl Default for RaytracingSceneBindings { fn default() -> Self { Self::new() } } struct CachedBindingArray<T, I: Eq + Hash> { map: HashMap<I, u32>, vec: Vec<T>, } impl<T, I: Eq + Hash> CachedBindingArray<T, I> { fn new() -> Self { Self { map: HashMap::default(), vec: Vec::default(), } } fn push_if_absent(&mut self, item: T, item_id: I) -> (u32, bool) { let mut is_new = false; let i = *self.map.entry(item_id).or_insert_with(|| { is_new = true; let i = self.vec.len() as u32; self.vec.push(item); i }); (i, is_new) } fn is_empty(&self) -> bool { self.vec.is_empty() } fn as_slice(&self) -> &[T] { self.vec.as_slice() } } type StorageBufferList<T> = StorageBuffer<Vec<T>>; #[derive(ShaderType)] struct GpuInstanceGeometryIds { vertex_buffer_id: u32, vertex_buffer_offset: u32, index_buffer_id: u32, index_buffer_offset: u32, triangle_count: u32, } #[derive(ShaderType)] struct GpuMaterial { normal_map_texture_id: u32, base_color_texture_id: u32, emissive_texture_id: u32, metallic_roughness_texture_id: u32, base_color: Vec3, perceptual_roughness: f32, emissive: Vec3, metallic: f32, reflectance: Vec3, _padding: f32, } #[derive(ShaderType)] struct GpuLightSource { kind: u32, id: u32, } impl GpuLightSource { fn new_emissive_mesh_light(instance_id: u32, triangle_count: u32) -> GpuLightSource { if triangle_count > u16::MAX as u32 { panic!("Too many triangles ({triangle_count}) in an emissive mesh, maximum is 65535."); } Self { kind: triangle_count << 1, id: instance_id, } } fn new_directional_light(directional_light_id: u32) -> GpuLightSource { Self { kind: 1, id: directional_light_id, } } } #[derive(ShaderType, Default)] struct GpuDirectionalLight { direction_to_light: Vec3, cos_theta_max: f32, luminance: Vec3, inverse_pdf: f32, } impl GpuDirectionalLight { fn new(directional_light: &ExtractedDirectionalLight) -> Self { let cos_theta_max = cos(directional_light.sun_disk_angular_size / 2.0); let solid_angle = TAU * (1.0 - cos_theta_max); let luminance = (directional_light.color.to_vec3() * directional_light.illuminance) / solid_angle; Self { direction_to_light: directional_light.transform.back().into(), cos_theta_max, luminance, inverse_pdf: solid_angle, } } } fn tlas_transform(transform: &Mat4) -> [f32; 12] { transform.transpose().to_cols_array()[..12] .try_into() .unwrap() }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_solari/src/pathtracer/node.rs
crates/bevy_solari/src/pathtracer/node.rs
use super::{prepare::PathtracerAccumulationTexture, Pathtracer}; use crate::scene::RaytracingSceneBindings; use bevy_asset::load_embedded_asset; use bevy_ecs::{ query::QueryItem, world::{FromWorld, World}, }; use bevy_render::{ camera::ExtractedCamera, render_graph::{NodeRunError, RenderGraphContext, ViewNode}, render_resource::{ binding_types::{texture_storage_2d, uniform_buffer}, BindGroupEntries, BindGroupLayoutDescriptor, BindGroupLayoutEntries, CachedComputePipelineId, ComputePassDescriptor, ComputePipelineDescriptor, ImageSubresourceRange, PipelineCache, ShaderStages, StorageTextureAccess, TextureFormat, }, renderer::RenderContext, view::{ViewTarget, ViewUniform, ViewUniformOffset, ViewUniforms}, }; use bevy_utils::default; pub mod graph { use bevy_render::render_graph::RenderLabel; #[derive(Debug, Hash, PartialEq, Eq, Clone, RenderLabel)] pub struct PathtracerNode; } pub struct PathtracerNode { bind_group_layout: BindGroupLayoutDescriptor, pipeline: CachedComputePipelineId, } impl ViewNode for PathtracerNode { type ViewQuery = ( &'static Pathtracer, &'static PathtracerAccumulationTexture, &'static ExtractedCamera, &'static ViewTarget, &'static ViewUniformOffset, ); fn run( &self, _graph: &mut RenderGraphContext, render_context: &mut RenderContext, (pathtracer, accumulation_texture, camera, view_target, view_uniform_offset): QueryItem< Self::ViewQuery, >, world: &World, ) -> Result<(), NodeRunError> { let pipeline_cache = world.resource::<PipelineCache>(); let scene_bindings = world.resource::<RaytracingSceneBindings>(); let view_uniforms = world.resource::<ViewUniforms>(); let (Some(pipeline), Some(scene_bindings), Some(viewport), Some(view_uniforms)) = ( pipeline_cache.get_compute_pipeline(self.pipeline), &scene_bindings.bind_group, camera.physical_viewport_size, view_uniforms.uniforms.binding(), ) else { return Ok(()); }; let bind_group = render_context.render_device().create_bind_group( "pathtracer_bind_group", &pipeline_cache.get_bind_group_layout(&self.bind_group_layout), &BindGroupEntries::sequential(( &accumulation_texture.0.default_view, view_target.get_unsampled_color_attachment().view, view_uniforms, )), ); let command_encoder = render_context.command_encoder(); if pathtracer.reset { command_encoder.clear_texture( &accumulation_texture.0.texture, &ImageSubresourceRange::default(), ); } let mut pass = command_encoder.begin_compute_pass(&ComputePassDescriptor { label: Some("pathtracer"), timestamp_writes: None, }); pass.set_pipeline(pipeline); pass.set_bind_group(0, scene_bindings, &[]); pass.set_bind_group(1, &bind_group, &[view_uniform_offset.offset]); pass.dispatch_workgroups(viewport.x.div_ceil(8), viewport.y.div_ceil(8), 1); Ok(()) } } impl FromWorld for PathtracerNode { fn from_world(world: &mut World) -> Self { let pipeline_cache = world.resource::<PipelineCache>(); let scene_bindings = world.resource::<RaytracingSceneBindings>(); let bind_group_layout = BindGroupLayoutDescriptor::new( "pathtracer_bind_group_layout", &BindGroupLayoutEntries::sequential( ShaderStages::COMPUTE, ( texture_storage_2d(TextureFormat::Rgba32Float, StorageTextureAccess::ReadWrite), texture_storage_2d( ViewTarget::TEXTURE_FORMAT_HDR, StorageTextureAccess::WriteOnly, ), uniform_buffer::<ViewUniform>(true), ), ), ); let pipeline = pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor { label: Some("pathtracer_pipeline".into()), layout: vec![ scene_bindings.bind_group_layout.clone(), bind_group_layout.clone(), ], shader: load_embedded_asset!(world, "pathtracer.wgsl"), ..default() }); Self { bind_group_layout, pipeline, } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_solari/src/pathtracer/mod.rs
crates/bevy_solari/src/pathtracer/mod.rs
mod extract; mod node; mod prepare; use crate::SolariPlugins; use bevy_app::{App, Plugin}; use bevy_asset::embedded_asset; use bevy_core_pipeline::core_3d::graph::{Core3d, Node3d}; use bevy_ecs::{component::Component, reflect::ReflectComponent, schedule::IntoScheduleConfigs}; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{ render_graph::{RenderGraphExt, ViewNodeRunner}, renderer::RenderDevice, view::Hdr, ExtractSchedule, Render, RenderApp, RenderSystems, }; use extract::extract_pathtracer; use node::PathtracerNode; use prepare::prepare_pathtracer_accumulation_texture; use tracing::warn; /// Non-realtime pathtracing. /// /// This plugin is meant to generate reference screenshots to compare against, /// and is not intended to be used by games. pub struct PathtracingPlugin; impl Plugin for PathtracingPlugin { fn build(&self, app: &mut App) { embedded_asset!(app, "pathtracer.wgsl"); } fn finish(&self, app: &mut App) { let render_app = app.sub_app_mut(RenderApp); let render_device = render_app.world().resource::<RenderDevice>(); let features = render_device.features(); if !features.contains(SolariPlugins::required_wgpu_features()) { warn!( "PathtracingPlugin not loaded. GPU lacks support for required features: {:?}.", SolariPlugins::required_wgpu_features().difference(features) ); return; } render_app .add_systems(ExtractSchedule, extract_pathtracer) .add_systems( Render, prepare_pathtracer_accumulation_texture.in_set(RenderSystems::PrepareResources), ) .add_render_graph_node::<ViewNodeRunner<PathtracerNode>>( Core3d, node::graph::PathtracerNode, ) .add_render_graph_edges(Core3d, (Node3d::EndMainPass, node::graph::PathtracerNode)); } } #[derive(Component, Reflect, Default, Clone)] #[reflect(Component, Default, Clone)] #[require(Hdr)] pub struct Pathtracer { pub reset: bool, }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_solari/src/pathtracer/extract.rs
crates/bevy_solari/src/pathtracer/extract.rs
use super::{prepare::PathtracerAccumulationTexture, Pathtracer}; use bevy_camera::Camera; use bevy_ecs::{ change_detection::DetectChanges, system::{Commands, Query}, world::Ref, }; use bevy_render::{sync_world::RenderEntity, Extract}; use bevy_transform::components::GlobalTransform; pub fn extract_pathtracer( cameras_3d: Extract< Query<( RenderEntity, &Camera, Ref<GlobalTransform>, Option<&Pathtracer>, )>, >, mut commands: Commands, ) { for (entity, camera, global_transform, pathtracer) in &cameras_3d { let mut entity_commands = commands .get_entity(entity) .expect("Camera entity wasn't synced."); if let Some(pathtracer) = pathtracer && camera.is_active { let mut pathtracer = pathtracer.clone(); pathtracer.reset |= global_transform.is_changed(); entity_commands.insert(pathtracer); } else { entity_commands.remove::<(Pathtracer, PathtracerAccumulationTexture)>(); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_solari/src/pathtracer/prepare.rs
crates/bevy_solari/src/pathtracer/prepare.rs
use super::Pathtracer; use bevy_ecs::{ component::Component, entity::Entity, query::With, system::{Commands, Query, Res, ResMut}, }; use bevy_image::ToExtents; use bevy_render::{ camera::ExtractedCamera, render_resource::{TextureDescriptor, TextureDimension, TextureFormat, TextureUsages}, renderer::RenderDevice, texture::{CachedTexture, TextureCache}, }; #[derive(Component)] pub struct PathtracerAccumulationTexture(pub CachedTexture); pub fn prepare_pathtracer_accumulation_texture( query: Query<(Entity, &ExtractedCamera), With<Pathtracer>>, mut texture_cache: ResMut<TextureCache>, render_device: Res<RenderDevice>, mut commands: Commands, ) { for (entity, camera) in &query { let Some(viewport) = camera.physical_viewport_size else { continue; }; let descriptor = TextureDescriptor { label: Some("pathtracer_accumulation_texture"), size: viewport.to_extents(), mip_level_count: 1, sample_count: 1, dimension: TextureDimension::D2, format: TextureFormat::Rgba32Float, usage: TextureUsages::STORAGE_BINDING, view_formats: &[], }; commands .entity(entity) .insert(PathtracerAccumulationTexture( texture_cache.get(&render_device, descriptor), )); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_solari/src/realtime/node.rs
crates/bevy_solari/src/realtime/node.rs
use super::{ prepare::{SolariLightingResources, LIGHT_TILE_BLOCKS, WORLD_CACHE_SIZE}, SolariLighting, }; use crate::scene::RaytracingSceneBindings; #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] use bevy_anti_alias::dlss::ViewDlssRayReconstructionTextures; use bevy_asset::{load_embedded_asset, Handle}; use bevy_core_pipeline::prepass::{ PreviousViewData, PreviousViewUniformOffset, PreviousViewUniforms, ViewPrepassTextures, }; use bevy_diagnostic::FrameCount; use bevy_ecs::{ query::QueryItem, world::{FromWorld, World}, }; use bevy_render::{ diagnostic::RecordDiagnostics, render_graph::{NodeRunError, RenderGraphContext, ViewNode}, render_resource::{ binding_types::{ storage_buffer_sized, texture_2d, texture_depth_2d, texture_storage_2d, uniform_buffer, }, BindGroupEntries, BindGroupLayoutDescriptor, BindGroupLayoutEntries, CachedComputePipelineId, ComputePassDescriptor, ComputePipelineDescriptor, LoadOp, PipelineCache, PushConstantRange, RenderPassDescriptor, ShaderStages, StorageTextureAccess, TextureFormat, TextureSampleType, }, renderer::RenderContext, view::{ViewTarget, ViewUniform, ViewUniformOffset, ViewUniforms}, }; use bevy_shader::{Shader, ShaderDefVal}; use bevy_utils::default; pub mod graph { use bevy_render::render_graph::RenderLabel; #[derive(Debug, Hash, PartialEq, Eq, Clone, RenderLabel)] pub struct SolariLightingNode; } pub struct SolariLightingNode { bind_group_layout: BindGroupLayoutDescriptor, bind_group_layout_world_cache_active_cells_dispatch: BindGroupLayoutDescriptor, #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] bind_group_layout_resolve_dlss_rr_textures: BindGroupLayoutDescriptor, decay_world_cache_pipeline: CachedComputePipelineId, compact_world_cache_single_block_pipeline: CachedComputePipelineId, compact_world_cache_blocks_pipeline: CachedComputePipelineId, compact_world_cache_write_active_cells_pipeline: CachedComputePipelineId, sample_for_world_cache_pipeline: CachedComputePipelineId, blend_new_world_cache_samples_pipeline: CachedComputePipelineId, presample_light_tiles_pipeline: CachedComputePipelineId, di_initial_and_temporal_pipeline: CachedComputePipelineId, di_spatial_and_shade_pipeline: CachedComputePipelineId, gi_initial_and_temporal_pipeline: CachedComputePipelineId, gi_spatial_and_shade_pipeline: CachedComputePipelineId, specular_gi_pipeline: CachedComputePipelineId, #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] resolve_dlss_rr_textures_pipeline: CachedComputePipelineId, } impl ViewNode for SolariLightingNode { #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))] type ViewQuery = ( &'static SolariLighting, &'static SolariLightingResources, &'static ViewTarget, &'static ViewPrepassTextures, &'static ViewUniformOffset, &'static PreviousViewUniformOffset, ); #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] type ViewQuery = ( &'static SolariLighting, &'static SolariLightingResources, &'static ViewTarget, &'static ViewPrepassTextures, &'static ViewUniformOffset, &'static PreviousViewUniformOffset, Option<&'static ViewDlssRayReconstructionTextures>, ); fn run( &self, _graph: &mut RenderGraphContext, render_context: &mut RenderContext, #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))] ( solari_lighting, solari_lighting_resources, view_target, view_prepass_textures, view_uniform_offset, previous_view_uniform_offset, ): QueryItem<Self::ViewQuery>, #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] ( solari_lighting, solari_lighting_resources, view_target, view_prepass_textures, view_uniform_offset, previous_view_uniform_offset, view_dlss_rr_textures, ): QueryItem<Self::ViewQuery>, world: &World, ) -> Result<(), NodeRunError> { let pipeline_cache = world.resource::<PipelineCache>(); let scene_bindings = world.resource::<RaytracingSceneBindings>(); let view_uniforms = world.resource::<ViewUniforms>(); let previous_view_uniforms = world.resource::<PreviousViewUniforms>(); let frame_count = world.resource::<FrameCount>(); let ( Some(decay_world_cache_pipeline), Some(compact_world_cache_single_block_pipeline), Some(compact_world_cache_blocks_pipeline), Some(compact_world_cache_write_active_cells_pipeline), Some(sample_for_world_cache_pipeline), Some(blend_new_world_cache_samples_pipeline), Some(presample_light_tiles_pipeline), Some(di_initial_and_temporal_pipeline), Some(di_spatial_and_shade_pipeline), Some(gi_initial_and_temporal_pipeline), Some(gi_spatial_and_shade_pipeline), Some(specular_gi_pipeline), Some(scene_bindings), Some(gbuffer), Some(depth_buffer), Some(motion_vectors), Some(previous_gbuffer), Some(previous_depth_buffer), Some(view_uniforms), Some(previous_view_uniforms), ) = ( pipeline_cache.get_compute_pipeline(self.decay_world_cache_pipeline), pipeline_cache.get_compute_pipeline(self.compact_world_cache_single_block_pipeline), pipeline_cache.get_compute_pipeline(self.compact_world_cache_blocks_pipeline), pipeline_cache .get_compute_pipeline(self.compact_world_cache_write_active_cells_pipeline), pipeline_cache.get_compute_pipeline(self.sample_for_world_cache_pipeline), pipeline_cache.get_compute_pipeline(self.blend_new_world_cache_samples_pipeline), pipeline_cache.get_compute_pipeline(self.presample_light_tiles_pipeline), pipeline_cache.get_compute_pipeline(self.di_initial_and_temporal_pipeline), pipeline_cache.get_compute_pipeline(self.di_spatial_and_shade_pipeline), pipeline_cache.get_compute_pipeline(self.gi_initial_and_temporal_pipeline), pipeline_cache.get_compute_pipeline(self.gi_spatial_and_shade_pipeline), pipeline_cache.get_compute_pipeline(self.specular_gi_pipeline), &scene_bindings.bind_group, view_prepass_textures.deferred_view(), view_prepass_textures.depth_view(), view_prepass_textures.motion_vectors_view(), view_prepass_textures.previous_deferred_view(), view_prepass_textures.previous_depth_view(), view_uniforms.uniforms.binding(), previous_view_uniforms.uniforms.binding(), ) else { return Ok(()); }; #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] let Some(resolve_dlss_rr_textures_pipeline) = pipeline_cache.get_compute_pipeline(self.resolve_dlss_rr_textures_pipeline) else { return Ok(()); }; let view_target = view_target.get_unsampled_color_attachment(); let s = solari_lighting_resources; let bind_group = render_context.render_device().create_bind_group( "solari_lighting_bind_group", &pipeline_cache.get_bind_group_layout(&self.bind_group_layout), &BindGroupEntries::sequential(( view_target.view, s.light_tile_samples.as_entire_binding(), s.light_tile_resolved_samples.as_entire_binding(), &s.di_reservoirs_a, &s.di_reservoirs_b, s.gi_reservoirs_a.as_entire_binding(), s.gi_reservoirs_b.as_entire_binding(), gbuffer, depth_buffer, motion_vectors, previous_gbuffer, previous_depth_buffer, view_uniforms, previous_view_uniforms, s.world_cache_checksums.as_entire_binding(), s.world_cache_life.as_entire_binding(), s.world_cache_radiance.as_entire_binding(), s.world_cache_geometry_data.as_entire_binding(), s.world_cache_luminance_deltas.as_entire_binding(), s.world_cache_active_cells_new_radiance.as_entire_binding(), s.world_cache_a.as_entire_binding(), s.world_cache_b.as_entire_binding(), s.world_cache_active_cell_indices.as_entire_binding(), s.world_cache_active_cells_count.as_entire_binding(), )), ); let bind_group_world_cache_active_cells_dispatch = render_context.render_device().create_bind_group( "solari_lighting_bind_group_world_cache_active_cells_dispatch", &pipeline_cache.get_bind_group_layout( &self.bind_group_layout_world_cache_active_cells_dispatch, ), &BindGroupEntries::single(s.world_cache_active_cells_dispatch.as_entire_binding()), ); #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] let bind_group_resolve_dlss_rr_textures = view_dlss_rr_textures.map(|d| { render_context.render_device().create_bind_group( "solari_lighting_bind_group_resolve_dlss_rr_textures", &pipeline_cache .get_bind_group_layout(&self.bind_group_layout_resolve_dlss_rr_textures), &BindGroupEntries::sequential(( &d.diffuse_albedo.default_view, &d.specular_albedo.default_view, &d.normal_roughness.default_view, &d.specular_motion_vectors.default_view, )), ) }); // Choice of number here is arbitrary let frame_index = frame_count.0.wrapping_mul(5782582); let diagnostics = render_context.diagnostic_recorder(); let command_encoder = render_context.command_encoder(); // Clear the view target if we're the first node to write to it if matches!(view_target.ops.load, LoadOp::Clear(_)) { command_encoder.begin_render_pass(&RenderPassDescriptor { label: Some("solari_lighting_clear"), color_attachments: &[Some(view_target)], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, }); } let mut pass = command_encoder.begin_compute_pass(&ComputePassDescriptor { label: Some("solari_lighting"), timestamp_writes: None, }); let dx = solari_lighting_resources.view_size.x.div_ceil(8); let dy = solari_lighting_resources.view_size.y.div_ceil(8); pass.set_bind_group(0, scene_bindings, &[]); pass.set_bind_group( 1, &bind_group, &[ view_uniform_offset.offset, previous_view_uniform_offset.offset, ], ); #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] if let Some(bind_group_resolve_dlss_rr_textures) = bind_group_resolve_dlss_rr_textures { pass.set_bind_group(2, &bind_group_resolve_dlss_rr_textures, &[]); pass.set_pipeline(resolve_dlss_rr_textures_pipeline); pass.dispatch_workgroups(dx, dy, 1); } let d = diagnostics.time_span(&mut pass, "solari_lighting/presample_light_tiles"); pass.set_pipeline(presample_light_tiles_pipeline); pass.set_push_constants( 0, bytemuck::cast_slice(&[frame_index, solari_lighting.reset as u32]), ); pass.dispatch_workgroups(LIGHT_TILE_BLOCKS as u32, 1, 1); d.end(&mut pass); let d = diagnostics.time_span(&mut pass, "solari_lighting/world_cache"); pass.set_bind_group(2, &bind_group_world_cache_active_cells_dispatch, &[]); pass.set_pipeline(decay_world_cache_pipeline); pass.dispatch_workgroups((WORLD_CACHE_SIZE / 1024) as u32, 1, 1); pass.set_pipeline(compact_world_cache_single_block_pipeline); pass.dispatch_workgroups((WORLD_CACHE_SIZE / 1024) as u32, 1, 1); pass.set_pipeline(compact_world_cache_blocks_pipeline); pass.dispatch_workgroups(1, 1, 1); pass.set_pipeline(compact_world_cache_write_active_cells_pipeline); pass.dispatch_workgroups((WORLD_CACHE_SIZE / 1024) as u32, 1, 1); pass.set_bind_group(2, None, &[]); pass.set_pipeline(sample_for_world_cache_pipeline); pass.set_push_constants( 0, bytemuck::cast_slice(&[frame_index, solari_lighting.reset as u32]), ); pass.dispatch_workgroups_indirect( &solari_lighting_resources.world_cache_active_cells_dispatch, 0, ); pass.set_pipeline(blend_new_world_cache_samples_pipeline); pass.dispatch_workgroups_indirect( &solari_lighting_resources.world_cache_active_cells_dispatch, 0, ); d.end(&mut pass); let d = diagnostics.time_span(&mut pass, "solari_lighting/direct_lighting"); pass.set_pipeline(di_initial_and_temporal_pipeline); pass.set_push_constants( 0, bytemuck::cast_slice(&[frame_index, solari_lighting.reset as u32]), ); pass.dispatch_workgroups(dx, dy, 1); pass.set_pipeline(di_spatial_and_shade_pipeline); pass.set_push_constants( 0, bytemuck::cast_slice(&[frame_index, solari_lighting.reset as u32]), ); pass.dispatch_workgroups(dx, dy, 1); d.end(&mut pass); let d = diagnostics.time_span(&mut pass, "solari_lighting/diffuse_indirect_lighting"); pass.set_pipeline(gi_initial_and_temporal_pipeline); pass.set_push_constants( 0, bytemuck::cast_slice(&[frame_index, solari_lighting.reset as u32]), ); pass.dispatch_workgroups(dx, dy, 1); pass.set_pipeline(gi_spatial_and_shade_pipeline); pass.set_push_constants( 0, bytemuck::cast_slice(&[frame_index, solari_lighting.reset as u32]), ); pass.dispatch_workgroups(dx, dy, 1); d.end(&mut pass); let d = diagnostics.time_span(&mut pass, "solari_lighting/specular_indirect_lighting"); pass.set_pipeline(specular_gi_pipeline); pass.set_push_constants( 0, bytemuck::cast_slice(&[frame_index, solari_lighting.reset as u32]), ); pass.dispatch_workgroups(dx, dy, 1); d.end(&mut pass); Ok(()) } } impl FromWorld for SolariLightingNode { fn from_world(world: &mut World) -> Self { let pipeline_cache = world.resource::<PipelineCache>(); let scene_bindings = world.resource::<RaytracingSceneBindings>(); let bind_group_layout = BindGroupLayoutDescriptor::new( "solari_lighting_bind_group_layout", &BindGroupLayoutEntries::sequential( ShaderStages::COMPUTE, ( texture_storage_2d( ViewTarget::TEXTURE_FORMAT_HDR, StorageTextureAccess::ReadWrite, ), storage_buffer_sized(false, None), storage_buffer_sized(false, None), texture_storage_2d(TextureFormat::Rgba32Uint, StorageTextureAccess::ReadWrite), texture_storage_2d(TextureFormat::Rgba32Uint, StorageTextureAccess::ReadWrite), storage_buffer_sized(false, None), storage_buffer_sized(false, None), texture_2d(TextureSampleType::Uint), texture_depth_2d(), texture_2d(TextureSampleType::Float { filterable: true }), texture_2d(TextureSampleType::Uint), texture_depth_2d(), uniform_buffer::<ViewUniform>(true), uniform_buffer::<PreviousViewData>(true), storage_buffer_sized(false, None), storage_buffer_sized(false, None), storage_buffer_sized(false, None), storage_buffer_sized(false, None), storage_buffer_sized(false, None), storage_buffer_sized(false, None), storage_buffer_sized(false, None), storage_buffer_sized(false, None), storage_buffer_sized(false, None), storage_buffer_sized(false, None), ), ), ); let bind_group_layout_world_cache_active_cells_dispatch = BindGroupLayoutDescriptor::new( "solari_lighting_bind_group_layout_world_cache_active_cells_dispatch", &BindGroupLayoutEntries::single( ShaderStages::COMPUTE, storage_buffer_sized(false, None), ), ); #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] let bind_group_layout_resolve_dlss_rr_textures = BindGroupLayoutDescriptor::new( "solari_lighting_bind_group_layout_resolve_dlss_rr_textures", &BindGroupLayoutEntries::sequential( ShaderStages::COMPUTE, ( texture_storage_2d(TextureFormat::Rgba8Unorm, StorageTextureAccess::WriteOnly), texture_storage_2d(TextureFormat::Rgba8Unorm, StorageTextureAccess::WriteOnly), texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly), texture_storage_2d(TextureFormat::Rg16Float, StorageTextureAccess::WriteOnly), ), ), ); let create_pipeline = |label: &'static str, entry_point: &'static str, shader: Handle<Shader>, extra_bind_group_layout: Option<&BindGroupLayoutDescriptor>, extra_shader_defs: Vec<ShaderDefVal>| { let mut layout = vec![ scene_bindings.bind_group_layout.clone(), bind_group_layout.clone(), ]; if let Some(extra_bind_group_layout) = extra_bind_group_layout { layout.push(extra_bind_group_layout.clone()); } let mut shader_defs = vec![ShaderDefVal::UInt( "WORLD_CACHE_SIZE".into(), WORLD_CACHE_SIZE as u32, )]; shader_defs.extend_from_slice(&extra_shader_defs); pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor { label: Some(label.into()), layout, push_constant_ranges: vec![PushConstantRange { stages: ShaderStages::COMPUTE, range: 0..8, }], shader, shader_defs, entry_point: Some(entry_point.into()), ..default() }) }; Self { bind_group_layout: bind_group_layout.clone(), bind_group_layout_world_cache_active_cells_dispatch: bind_group_layout_world_cache_active_cells_dispatch.clone(), #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] bind_group_layout_resolve_dlss_rr_textures: bind_group_layout_resolve_dlss_rr_textures .clone(), decay_world_cache_pipeline: create_pipeline( "solari_lighting_decay_world_cache_pipeline", "decay_world_cache", load_embedded_asset!(world, "world_cache_compact.wgsl"), Some(&bind_group_layout_world_cache_active_cells_dispatch), vec!["WORLD_CACHE_NON_ATOMIC_LIFE_BUFFER".into()], ), compact_world_cache_single_block_pipeline: create_pipeline( "solari_lighting_compact_world_cache_single_block_pipeline", "compact_world_cache_single_block", load_embedded_asset!(world, "world_cache_compact.wgsl"), Some(&bind_group_layout_world_cache_active_cells_dispatch), vec!["WORLD_CACHE_NON_ATOMIC_LIFE_BUFFER".into()], ), compact_world_cache_blocks_pipeline: create_pipeline( "solari_lighting_compact_world_cache_blocks_pipeline", "compact_world_cache_blocks", load_embedded_asset!(world, "world_cache_compact.wgsl"), Some(&bind_group_layout_world_cache_active_cells_dispatch), vec![], ), compact_world_cache_write_active_cells_pipeline: create_pipeline( "solari_lighting_compact_world_cache_write_active_cells_pipeline", "compact_world_cache_write_active_cells", load_embedded_asset!(world, "world_cache_compact.wgsl"), Some(&bind_group_layout_world_cache_active_cells_dispatch), vec!["WORLD_CACHE_NON_ATOMIC_LIFE_BUFFER".into()], ), sample_for_world_cache_pipeline: create_pipeline( "solari_lighting_sample_for_world_cache_pipeline", "sample_radiance", load_embedded_asset!(world, "world_cache_update.wgsl"), None, vec!["WORLD_CACHE_QUERY_ATOMIC_MAX_LIFETIME".into()], ), blend_new_world_cache_samples_pipeline: create_pipeline( "solari_lighting_blend_new_world_cache_samples_pipeline", "blend_new_samples", load_embedded_asset!(world, "world_cache_update.wgsl"), None, vec![], ), presample_light_tiles_pipeline: create_pipeline( "solari_lighting_presample_light_tiles_pipeline", "presample_light_tiles", load_embedded_asset!(world, "presample_light_tiles.wgsl"), None, vec![], ), di_initial_and_temporal_pipeline: create_pipeline( "solari_lighting_di_initial_and_temporal_pipeline", "initial_and_temporal", load_embedded_asset!(world, "restir_di.wgsl"), None, vec![], ), di_spatial_and_shade_pipeline: create_pipeline( "solari_lighting_di_spatial_and_shade_pipeline", "spatial_and_shade", load_embedded_asset!(world, "restir_di.wgsl"), None, vec![], ), gi_initial_and_temporal_pipeline: create_pipeline( "solari_lighting_gi_initial_and_temporal_pipeline", "initial_and_temporal", load_embedded_asset!(world, "restir_gi.wgsl"), None, vec![], ), gi_spatial_and_shade_pipeline: create_pipeline( "solari_lighting_gi_spatial_and_shade_pipeline", "spatial_and_shade", load_embedded_asset!(world, "restir_gi.wgsl"), None, vec![], ), specular_gi_pipeline: create_pipeline( "solari_lighting_specular_gi_pipeline", "specular_gi", load_embedded_asset!(world, "specular_gi.wgsl"), None, vec![], ), #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] resolve_dlss_rr_textures_pipeline: create_pipeline( "solari_lighting_resolve_dlss_rr_textures_pipeline", "resolve_dlss_rr_textures", load_embedded_asset!(world, "resolve_dlss_rr_textures.wgsl"), Some(&bind_group_layout_resolve_dlss_rr_textures), vec![], ), } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_solari/src/realtime/mod.rs
crates/bevy_solari/src/realtime/mod.rs
mod extract; mod node; mod prepare; use crate::SolariPlugins; use bevy_app::{App, Plugin}; use bevy_asset::embedded_asset; use bevy_core_pipeline::{ core_3d::graph::{Core3d, Node3d}, prepass::{ DeferredPrepass, DeferredPrepassDoubleBuffer, DepthPrepass, DepthPrepassDoubleBuffer, MotionVectorPrepass, }, }; use bevy_ecs::{component::Component, reflect::ReflectComponent, schedule::IntoScheduleConfigs}; use bevy_pbr::DefaultOpaqueRendererMethod; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{ render_graph::{RenderGraphExt, ViewNodeRunner}, renderer::RenderDevice, view::Hdr, ExtractSchedule, Render, RenderApp, RenderSystems, }; use bevy_shader::load_shader_library; use extract::extract_solari_lighting; use node::SolariLightingNode; use prepare::prepare_solari_lighting_resources; use tracing::warn; /// Raytraced direct and indirect lighting. /// /// When using this plugin, it's highly recommended to set `shadows_enabled: false` on all lights, as Solari replaces /// traditional shadow mapping. pub struct SolariLightingPlugin; impl Plugin for SolariLightingPlugin { fn build(&self, app: &mut App) { load_shader_library!(app, "gbuffer_utils.wgsl"); load_shader_library!(app, "presample_light_tiles.wgsl"); embedded_asset!(app, "restir_di.wgsl"); embedded_asset!(app, "restir_gi.wgsl"); load_shader_library!(app, "specular_gi.wgsl"); load_shader_library!(app, "world_cache_query.wgsl"); embedded_asset!(app, "world_cache_compact.wgsl"); embedded_asset!(app, "world_cache_update.wgsl"); #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] embedded_asset!(app, "resolve_dlss_rr_textures.wgsl"); app.insert_resource(DefaultOpaqueRendererMethod::deferred()); } fn finish(&self, app: &mut App) { let render_app = app.sub_app_mut(RenderApp); let render_device = render_app.world().resource::<RenderDevice>(); let features = render_device.features(); if !features.contains(SolariPlugins::required_wgpu_features()) { warn!( "SolariLightingPlugin not loaded. GPU lacks support for required features: {:?}.", SolariPlugins::required_wgpu_features().difference(features) ); return; } render_app .add_systems(ExtractSchedule, extract_solari_lighting) .add_systems( Render, prepare_solari_lighting_resources.in_set(RenderSystems::PrepareResources), ) .add_render_graph_node::<ViewNodeRunner<SolariLightingNode>>( Core3d, node::graph::SolariLightingNode, ) .add_render_graph_edges( Core3d, ( Node3d::EndPrepasses, node::graph::SolariLightingNode, Node3d::EndMainPass, ), ); } } /// A component for a 3d camera entity to enable the Solari raytraced lighting system. /// /// Must be used with `CameraMainTextureUsages::default().with(TextureUsages::STORAGE_BINDING)`, and /// `Msaa::Off`. #[derive(Component, Reflect, Clone)] #[reflect(Component, Default, Clone)] #[require( Hdr, DeferredPrepass, DepthPrepass, MotionVectorPrepass, DeferredPrepassDoubleBuffer, DepthPrepassDoubleBuffer )] pub struct SolariLighting { /// Set to true to delete the saved temporal history (past frames). /// /// Useful for preventing ghosting when the history is no longer /// representative of the current frame, such as in sudden camera cuts. /// /// After setting this to true, it will automatically be toggled /// back to false at the end of the frame. pub reset: bool, } impl Default for SolariLighting { fn default() -> Self { Self { reset: true, // No temporal history on the first frame } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_solari/src/realtime/extract.rs
crates/bevy_solari/src/realtime/extract.rs
use super::{prepare::SolariLightingResources, SolariLighting}; use bevy_camera::Camera; use bevy_ecs::system::{Commands, ResMut}; use bevy_pbr::deferred::SkipDeferredLighting; use bevy_render::{sync_world::RenderEntity, MainWorld}; pub fn extract_solari_lighting(mut main_world: ResMut<MainWorld>, mut commands: Commands) { let mut cameras_3d = main_world.query::<(RenderEntity, &Camera, Option<&mut SolariLighting>)>(); for (entity, camera, solari_lighting) in cameras_3d.iter_mut(&mut main_world) { let mut entity_commands = commands .get_entity(entity) .expect("Camera entity wasn't synced."); if let Some(mut solari_lighting) = solari_lighting && camera.is_active { entity_commands.insert((solari_lighting.clone(), SkipDeferredLighting)); solari_lighting.reset = false; } else { entity_commands.remove::<( SolariLighting, SolariLightingResources, SkipDeferredLighting, )>(); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_solari/src/realtime/prepare.rs
crates/bevy_solari/src/realtime/prepare.rs
use super::SolariLighting; #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] use bevy_anti_alias::dlss::{ Dlss, DlssRayReconstructionFeature, ViewDlssRayReconstructionTextures, }; use bevy_camera::MainPassResolutionOverride; #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] use bevy_ecs::query::Has; use bevy_ecs::{ component::Component, entity::Entity, query::With, system::{Commands, Query, Res}, }; use bevy_image::ToExtents; use bevy_math::UVec2; #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] use bevy_render::texture::CachedTexture; use bevy_render::{ camera::ExtractedCamera, render_resource::{ Buffer, BufferDescriptor, BufferUsages, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, TextureView, TextureViewDescriptor, }, renderer::RenderDevice, }; /// Size of the `LightSample` shader struct in bytes. const LIGHT_SAMPLE_STRUCT_SIZE: u64 = 8; /// Size of the `ResolvedLightSamplePacked` shader struct in bytes. const RESOLVED_LIGHT_SAMPLE_STRUCT_SIZE: u64 = 24; /// Size of the GI `Reservoir` shader struct in bytes. const GI_RESERVOIR_STRUCT_SIZE: u64 = 48; pub const LIGHT_TILE_BLOCKS: u64 = 128; pub const LIGHT_TILE_SAMPLES_PER_BLOCK: u64 = 1024; /// Amount of entries in the world cache (must be a power of 2, and >= 2^10) pub const WORLD_CACHE_SIZE: u64 = 2u64.pow(20); /// Internal rendering resources used for Solari lighting. #[derive(Component)] pub struct SolariLightingResources { pub light_tile_samples: Buffer, pub light_tile_resolved_samples: Buffer, pub di_reservoirs_a: TextureView, pub di_reservoirs_b: TextureView, pub gi_reservoirs_a: Buffer, pub gi_reservoirs_b: Buffer, pub world_cache_checksums: Buffer, pub world_cache_life: Buffer, pub world_cache_radiance: Buffer, pub world_cache_geometry_data: Buffer, pub world_cache_luminance_deltas: Buffer, pub world_cache_active_cells_new_radiance: Buffer, pub world_cache_a: Buffer, pub world_cache_b: Buffer, pub world_cache_active_cell_indices: Buffer, pub world_cache_active_cells_count: Buffer, pub world_cache_active_cells_dispatch: Buffer, pub view_size: UVec2, } pub fn prepare_solari_lighting_resources( #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))] query: Query< ( Entity, &ExtractedCamera, Option<&SolariLightingResources>, Option<&MainPassResolutionOverride>, ), With<SolariLighting>, >, #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] query: Query< ( Entity, &ExtractedCamera, Option<&SolariLightingResources>, Option<&MainPassResolutionOverride>, Has<Dlss<DlssRayReconstructionFeature>>, ), With<SolariLighting>, >, render_device: Res<RenderDevice>, mut commands: Commands, ) { for query_item in &query { #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))] let (entity, camera, solari_lighting_resources, resolution_override) = query_item; #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] let (entity, camera, solari_lighting_resources, resolution_override, has_dlss_rr) = query_item; let Some(mut view_size) = camera.physical_viewport_size else { continue; }; if let Some(MainPassResolutionOverride(resolution_override)) = resolution_override { view_size = *resolution_override; } if solari_lighting_resources.map(|r| r.view_size) == Some(view_size) { continue; } let light_tile_samples = render_device.create_buffer(&BufferDescriptor { label: Some("solari_lighting_light_tile_samples"), size: LIGHT_TILE_BLOCKS * LIGHT_TILE_SAMPLES_PER_BLOCK * LIGHT_SAMPLE_STRUCT_SIZE, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let light_tile_resolved_samples = render_device.create_buffer(&BufferDescriptor { label: Some("solari_lighting_light_tile_resolved_samples"), size: LIGHT_TILE_BLOCKS * LIGHT_TILE_SAMPLES_PER_BLOCK * RESOLVED_LIGHT_SAMPLE_STRUCT_SIZE, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let di_reservoirs = |name| { render_device .create_texture(&TextureDescriptor { label: Some(name), size: view_size.to_extents(), mip_level_count: 1, sample_count: 1, dimension: TextureDimension::D2, format: TextureFormat::Rgba32Uint, usage: TextureUsages::STORAGE_BINDING, view_formats: &[], }) .create_view(&TextureViewDescriptor::default()) }; let di_reservoirs_a = di_reservoirs("solari_lighting_di_reservoirs_a"); let di_reservoirs_b = di_reservoirs("solari_lighting_di_reservoirs_b"); let gi_reservoirs = |name| { render_device.create_buffer(&BufferDescriptor { label: Some(name), size: (view_size.x * view_size.y) as u64 * GI_RESERVOIR_STRUCT_SIZE, usage: BufferUsages::STORAGE, mapped_at_creation: false, }) }; let gi_reservoirs_a = gi_reservoirs("solari_lighting_gi_reservoirs_a"); let gi_reservoirs_b = gi_reservoirs("solari_lighting_gi_reservoirs_b"); let world_cache_checksums = render_device.create_buffer(&BufferDescriptor { label: Some("solari_lighting_world_cache_checksums"), size: WORLD_CACHE_SIZE * size_of::<u32>() as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let world_cache_life = render_device.create_buffer(&BufferDescriptor { label: Some("solari_lighting_world_cache_life"), size: WORLD_CACHE_SIZE * size_of::<u32>() as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let world_cache_radiance = render_device.create_buffer(&BufferDescriptor { label: Some("solari_lighting_world_cache_radiance"), size: WORLD_CACHE_SIZE * size_of::<[f32; 4]>() as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let world_cache_geometry_data = render_device.create_buffer(&BufferDescriptor { label: Some("solari_lighting_world_cache_geometry_data"), size: WORLD_CACHE_SIZE * size_of::<[f32; 8]>() as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let world_cache_luminance_deltas = render_device.create_buffer(&BufferDescriptor { label: Some("solari_lighting_world_cache_luminance_deltas"), size: WORLD_CACHE_SIZE * size_of::<f32>() as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let world_cache_active_cells_new_radiance = render_device.create_buffer(&BufferDescriptor { label: Some("solari_lighting_world_cache_active_cells_new_radiance"), size: WORLD_CACHE_SIZE * size_of::<[f32; 4]>() as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let world_cache_a = render_device.create_buffer(&BufferDescriptor { label: Some("solari_lighting_world_cache_a"), size: WORLD_CACHE_SIZE * size_of::<u32>() as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let world_cache_b = render_device.create_buffer(&BufferDescriptor { label: Some("solari_lighting_world_cache_b"), size: 1024 * size_of::<u32>() as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let world_cache_active_cell_indices = render_device.create_buffer(&BufferDescriptor { label: Some("solari_lighting_world_cache_active_cell_indices"), size: WORLD_CACHE_SIZE * size_of::<u32>() as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let world_cache_active_cells_count = render_device.create_buffer(&BufferDescriptor { label: Some("solari_lighting_world_cache_active_cells_count"), size: size_of::<u32>() as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let world_cache_active_cells_dispatch = render_device.create_buffer(&BufferDescriptor { label: Some("solari_lighting_world_cache_active_cells_dispatch"), size: size_of::<[u32; 3]>() as u64, usage: BufferUsages::INDIRECT | BufferUsages::STORAGE, mapped_at_creation: false, }); commands.entity(entity).insert(SolariLightingResources { light_tile_samples, light_tile_resolved_samples, di_reservoirs_a, di_reservoirs_b, gi_reservoirs_a, gi_reservoirs_b, world_cache_checksums, world_cache_life, world_cache_radiance, world_cache_geometry_data, world_cache_luminance_deltas, world_cache_active_cells_new_radiance, world_cache_a, world_cache_b, world_cache_active_cell_indices, world_cache_active_cells_count, world_cache_active_cells_dispatch, view_size, }); #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] if has_dlss_rr { let diffuse_albedo = render_device.create_texture(&TextureDescriptor { label: Some("solari_lighting_diffuse_albedo"), size: view_size.to_extents(), mip_level_count: 1, sample_count: 1, dimension: TextureDimension::D2, format: TextureFormat::Rgba8Unorm, usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING, view_formats: &[], }); let diffuse_albedo_view = diffuse_albedo.create_view(&TextureViewDescriptor::default()); let specular_albedo = render_device.create_texture(&TextureDescriptor { label: Some("solari_lighting_specular_albedo"), size: view_size.to_extents(), mip_level_count: 1, sample_count: 1, dimension: TextureDimension::D2, format: TextureFormat::Rgba8Unorm, usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING, view_formats: &[], }); let specular_albedo_view = specular_albedo.create_view(&TextureViewDescriptor::default()); let normal_roughness = render_device.create_texture(&TextureDescriptor { label: Some("solari_lighting_normal_roughness"), size: view_size.to_extents(), mip_level_count: 1, sample_count: 1, dimension: TextureDimension::D2, format: TextureFormat::Rgba16Float, usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING, view_formats: &[], }); let normal_roughness_view = normal_roughness.create_view(&TextureViewDescriptor::default()); let specular_motion_vectors = render_device.create_texture(&TextureDescriptor { label: Some("solari_lighting_specular_motion_vectors"), size: view_size.to_extents(), mip_level_count: 1, sample_count: 1, dimension: TextureDimension::D2, format: TextureFormat::Rg16Float, usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING, view_formats: &[], }); let specular_motion_vectors_view = specular_motion_vectors.create_view(&TextureViewDescriptor::default()); commands .entity(entity) .insert(ViewDlssRayReconstructionTextures { diffuse_albedo: CachedTexture { texture: diffuse_albedo, default_view: diffuse_albedo_view, }, specular_albedo: CachedTexture { texture: specular_albedo, default_view: specular_albedo_view, }, normal_roughness: CachedTexture { texture: normal_roughness, default_view: normal_roughness_view, }, specular_motion_vectors: CachedTexture { texture: specular_motion_vectors, default_view: specular_motion_vectors_view, }, }); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_picking/src/lib.rs
crates/bevy_picking/src/lib.rs
//! This crate provides 'picking' capabilities for the Bevy game engine, allowing pointers to //! interact with entities using hover, click, and drag events. //! //! ## Overview //! //! In the simplest case, this plugin allows you to click on things in the scene. However, it also //! allows you to express more complex interactions, like detecting when a touch input drags a UI //! element and drops it on a 3d mesh rendered to a different camera. //! //! Pointer events bubble up the entity hierarchy and can be used with observers, allowing you to //! succinctly express rich interaction behaviors by attaching pointer callbacks to entities: //! //! ```rust //! # use bevy_ecs::prelude::*; //! # use bevy_picking::prelude::*; //! # #[derive(Component)] //! # struct MyComponent; //! # let mut world = World::new(); //! world.spawn(MyComponent) //! .observe(|mut event: On<Pointer<Click>>| { //! // Read the underlying pointer event data //! println!("Pointer {:?} was just clicked!", event.pointer_id); //! // Stop the event from bubbling up the entity hierarchy //! event.propagate(false); //! }); //! ``` //! //! At its core, this crate provides a robust abstraction for computing picking state regardless of //! pointing devices, or what you are hit testing against. It is designed to work with any input, //! including mouse, touch, pens, or virtual pointers controlled by gamepads. //! //! ## Expressive Events //! //! Although the events in this module (see [`events`]) can be listened to with normal //! `MessageReader`s, using observers is often more expressive, with less boilerplate. This is because //! observers allow you to attach event handling logic to specific entities, as well as make use of //! event bubbling. //! //! When events are generated, they bubble up the entity hierarchy starting from their target, until //! they reach the root or bubbling is halted with a call to //! [`On::propagate`](bevy_ecs::observer::On::propagate). See [`Observer`] for details. //! //! This allows you to run callbacks when any children of an entity are interacted with, and leads //! to succinct, expressive code: //! //! ``` //! # use bevy_ecs::prelude::*; //! # use bevy_transform::prelude::*; //! # use bevy_picking::prelude::*; //! # #[derive(Message)] //! # struct Greeting; //! fn setup(mut commands: Commands) { //! commands.spawn(Transform::default()) //! // Spawn your entity here, e.g. a `Mesh3d`. //! // When dragged, mutate the `Transform` component on the dragged target entity: //! .observe(|drag: On<Pointer<Drag>>, mut transforms: Query<&mut Transform>| { //! let mut transform = transforms.get_mut(drag.entity).unwrap(); //! transform.rotate_local_y(drag.delta.x / 50.0); //! }) //! .observe(|click: On<Pointer<Click>>, mut commands: Commands| { //! println!("Entity {} goes BOOM!", click.entity); //! commands.entity(click.entity).despawn(); //! }) //! .observe(|over: On<Pointer<Over>>, mut greetings: MessageWriter<Greeting>| { //! greetings.write(Greeting); //! }); //! } //! ``` //! //! ## Modularity //! //! #### Mix and Match Hit Testing Backends //! //! The plugin attempts to handle all the hard parts for you, all you need to do is tell it when a //! pointer is hitting any entities. Multiple backends can be used at the same time! [Use this //! simple API to write your own backend](crate::backend) in about 100 lines of code. //! //! #### Input Agnostic //! //! Picking provides a generic Pointer abstraction, which is useful for reacting to many different //! types of input devices. Pointers can be controlled with anything, whether it's the included //! mouse or touch inputs, or a custom gamepad input system you write yourself to control a virtual //! pointer. //! //! ## Robustness //! //! In addition to these features, this plugin also correctly handles multitouch, multiple windows, //! multiple cameras, viewports, and render layers. Using this as a library allows you to write a //! picking backend that can interoperate with any other picking backend. //! //! # Getting Started //! //! TODO: This section will need to be re-written once more backends are introduced. //! //! #### Next Steps //! //! To learn more, take a look at the examples in the //! [examples](https://github.com/bevyengine/bevy/tree/main/examples/picking). You can read the next //! section to understand how the plugin works. //! //! # The Picking Pipeline //! //! This plugin is designed to be extremely modular. To do so, it works in well-defined stages that //! form a pipeline, where events are used to pass data between each stage. //! //! #### Pointers ([`pointer`](mod@pointer)) //! //! The first stage of the pipeline is to gather inputs and update pointers. This stage is //! ultimately responsible for generating [`PointerInput`](pointer::PointerInput) events. The //! provided crate does this automatically for mouse, touch, and pen inputs. If you wanted to //! implement your own pointer, controlled by some other input, you can do that here. The ordering //! of events within the [`PointerInput`](pointer::PointerInput) stream is meaningful for events //! with the same [`PointerId`](pointer::PointerId), but not between different pointers. //! //! Because pointer positions and presses are driven by these events, you can use them to mock //! inputs for testing. //! //! After inputs are generated, they are then collected to update the current //! [`PointerLocation`](pointer::PointerLocation) for each pointer. //! //! #### Backend ([`backend`]) //! //! A picking backend only has one job: reading [`PointerLocation`](pointer::PointerLocation) //! components, and producing [`PointerHits`](backend::PointerHits). You can find all documentation //! and types needed to implement a backend at [`backend`]. //! //! You will eventually need to choose which picking backend(s) you want to use. This crate does not //! supply any backends, and expects you to select some from the other bevy crates or the //! third-party ecosystem. //! //! It's important to understand that you can mix and match backends! For example, you might have a //! backend for your UI, and one for the 3d scene, with each being specialized for their purpose. //! Bevy provides some backends out of the box, but you can even write your own. It's been made as //! easy as possible intentionally; the `bevy_mod_raycast` backend is 50 lines of code. //! //! #### Hover ([`hover`]) //! //! The next step is to use the data from the backends, combine and sort the results, and determine //! what each cursor is hovering over, producing a [`HoverMap`](`crate::hover::HoverMap`). Note that //! just because a pointer is over an entity, it is not necessarily *hovering* that entity. Although //! multiple backends may be reporting that a pointer is hitting an entity, the hover system needs //! to determine which entities are actually being hovered by this pointer based on the pick depth, //! order of the backend, and the optional [`Pickable`] component of the entity. In other //! words, if one entity is in front of another, usually only the topmost one will be hovered. //! //! #### Events ([`events`]) //! //! In the final step, the high-level pointer events are generated, such as events that trigger when //! a pointer hovers or clicks an entity. These simple events are then used to generate more complex //! events for dragging and dropping. //! //! Because it is completely agnostic to the earlier stages of the pipeline, you can easily extend //! the plugin with arbitrary backends and input methods, yet still use all the high level features. #![deny(missing_docs)] extern crate alloc; pub mod backend; pub mod events; pub mod hover; pub mod input; #[cfg(feature = "mesh_picking")] pub mod mesh_picking; pub mod pointer; pub mod window; use bevy_app::{prelude::*, PluginGroupBuilder}; use bevy_ecs::prelude::*; use bevy_reflect::prelude::*; use hover::{update_is_directly_hovered, update_is_hovered}; /// The picking prelude. /// /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { #[cfg(feature = "mesh_picking")] #[doc(hidden)] pub use crate::mesh_picking::{ ray_cast::{MeshRayCast, MeshRayCastSettings, RayCastBackfaces, RayCastVisibility}, MeshPickingCamera, MeshPickingPlugin, MeshPickingSettings, }; #[doc(hidden)] pub use crate::{ events::*, input::PointerInputPlugin, pointer::PointerButton, DefaultPickingPlugins, InteractionPlugin, Pickable, PickingPlugin, }; } /// An optional component that marks an entity as usable by a backend, and overrides default /// picking behavior for an entity. /// /// This allows you to make an entity non-hoverable, or allow items below it to be hovered. /// /// See the documentation on the fields for more details. #[derive(Component, Debug, Clone, Reflect, PartialEq, Eq)] #[reflect(Component, Default, Debug, PartialEq, Clone)] pub struct Pickable { /// Should this entity block entities below it from being picked? /// /// This is useful if you want picking to continue hitting entities below this one. Normally, /// only the topmost entity under a pointer can be hovered, but this setting allows the pointer /// to hover multiple entities, from nearest to farthest, stopping as soon as it hits an entity /// that blocks lower entities. /// /// Note that the word "lower" here refers to entities that have been reported as hit by any /// picking backend, but are at a lower depth than the current one. This is different from the /// concept of event bubbling, as it works irrespective of the entity hierarchy. /// /// For example, if a pointer is over a UI element, as well as a 3d mesh, backends will report /// hits for both of these entities. Additionally, the hits will be sorted by the camera order, /// so if the UI is drawing on top of the 3d mesh, the UI will be "above" the mesh. When hovering /// is computed, the UI element will be checked first to see if it this field is set to block /// lower entities. If it does (default), the hovering system will stop there, and only the UI /// element will be marked as hovered. However, if this field is set to `false`, both the UI /// element *and* the mesh will be marked as hovered. /// /// Entities without the [`Pickable`] component will block by default. pub should_block_lower: bool, /// If this is set to `false` and `should_block_lower` is set to true, this entity will block /// lower entities from being interacted and at the same time will itself not emit any events. /// /// Note that the word "lower" here refers to entities that have been reported as hit by any /// picking backend, but are at a lower depth than the current one. This is different from the /// concept of event bubbling, as it works irrespective of the entity hierarchy. /// /// For example, if a pointer is over a UI element, and this field is set to `false`, it will /// not be marked as hovered, and consequently will not emit events nor will any picking /// components mark it as hovered. This can be combined with the other field /// [`Self::should_block_lower`], which is orthogonal to this one. /// /// Entities without the [`Pickable`] component are hoverable by default. pub is_hoverable: bool, } impl Pickable { /// This entity will not block entities beneath it, nor will it emit events. /// /// If a backend reports this entity as being hit, the picking plugin will completely ignore it. pub const IGNORE: Self = Self { should_block_lower: false, is_hoverable: false, }; } impl Default for Pickable { fn default() -> Self { Self { should_block_lower: true, is_hoverable: true, } } } /// Groups the stages of the picking process under shared labels. #[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)] pub enum PickingSystems { /// Produces pointer input events. In the [`First`] schedule. Input, /// Runs after input events are generated but before commands are flushed. In the [`First`] /// schedule. PostInput, /// Receives and processes pointer input events. In the [`PreUpdate`] schedule. ProcessInput, /// Reads inputs and produces [`backend::PointerHits`]s. In the [`PreUpdate`] schedule. Backend, /// Reads [`backend::PointerHits`]s, and updates the hovermap, selection, and highlighting states. In /// the [`PreUpdate`] schedule. Hover, /// Runs after all the [`PickingSystems::Hover`] systems are done, before event listeners are triggered. In the /// [`PreUpdate`] schedule. PostHover, /// Runs after all other picking sets. In the [`PreUpdate`] schedule. Last, } /// One plugin that contains the [`PointerInputPlugin`](input::PointerInputPlugin), [`PickingPlugin`] /// and the [`InteractionPlugin`], this is probably the plugin that will be most used. /// /// Note: for any of these plugins to work, they require a picking backend to be active, /// The picking backend is responsible to turn an input, into a [`PointerHits`](`crate::backend::PointerHits`) /// that [`PickingPlugin`] and [`InteractionPlugin`] will refine into [`bevy_ecs::observer::On`]s. #[derive(Default)] pub struct DefaultPickingPlugins; impl PluginGroup for DefaultPickingPlugins { fn build(self) -> PluginGroupBuilder { PluginGroupBuilder::start::<Self>() .add(input::PointerInputPlugin) .add(PickingPlugin) .add(InteractionPlugin) } } #[derive(Copy, Clone, Debug, Resource, Reflect)] #[reflect(Resource, Default, Debug, Clone)] /// Controls the behavior of picking /// /// ## Custom initialization /// ``` /// # use bevy_app::App; /// # use bevy_picking::{PickingSettings, PickingPlugin}; /// App::new() /// .insert_resource(PickingSettings { /// is_enabled: true, /// is_input_enabled: false, /// is_hover_enabled: true, /// is_window_picking_enabled: false, /// }) /// // or DefaultPlugins /// .add_plugins(PickingPlugin); /// ``` pub struct PickingSettings { /// Enables and disables all picking features. pub is_enabled: bool, /// Enables and disables input collection. pub is_input_enabled: bool, /// Enables and disables updating interaction states of entities. pub is_hover_enabled: bool, /// Enables or disables picking for window entities. pub is_window_picking_enabled: bool, } impl PickingSettings { /// Whether or not input collection systems should be running. pub fn input_should_run(state: Res<Self>) -> bool { state.is_input_enabled && state.is_enabled } /// Whether or not systems updating entities' [`PickingInteraction`](hover::PickingInteraction) /// component should be running. pub fn hover_should_run(state: Res<Self>) -> bool { state.is_hover_enabled && state.is_enabled } /// Whether or not window entities should receive pick events. pub fn window_picking_should_run(state: Res<Self>) -> bool { state.is_window_picking_enabled && state.is_enabled } } impl Default for PickingSettings { fn default() -> Self { Self { is_enabled: true, is_input_enabled: true, is_hover_enabled: true, is_window_picking_enabled: true, } } } /// This plugin sets up the core picking infrastructure. It receives input events, and provides the shared /// types used by other picking plugins. /// /// Behavior of picking can be controlled by modifying [`PickingSettings`]. /// /// [`PickingSettings`] will be initialized with default values if it /// is not present at the moment this is added to the app. pub struct PickingPlugin; impl Plugin for PickingPlugin { fn build(&self, app: &mut App) { app.init_resource::<PickingSettings>() .init_resource::<pointer::PointerMap>() .init_resource::<backend::ray::RayMap>() .add_message::<pointer::PointerInput>() .add_message::<backend::PointerHits>() // Rather than try to mark all current and future backends as ambiguous with each other, // we allow them to send their hits in any order. These are later sorted, so submission // order doesn't matter. See `PointerHits` docs for caveats. .allow_ambiguous_resource::<Messages<backend::PointerHits>>() .add_systems( PreUpdate, ( pointer::update_pointer_map, pointer::PointerInput::receive, backend::ray::RayMap::repopulate.after(pointer::PointerInput::receive), ) .in_set(PickingSystems::ProcessInput), ) .add_systems( PreUpdate, window::update_window_hits .run_if(PickingSettings::window_picking_should_run) .in_set(PickingSystems::Backend), ) .configure_sets( First, (PickingSystems::Input, PickingSystems::PostInput) .after(bevy_time::TimeSystems) .after(bevy_ecs::message::MessageUpdateSystems) .chain(), ) .configure_sets( PreUpdate, ( PickingSystems::ProcessInput.run_if(PickingSettings::input_should_run), PickingSystems::Backend, PickingSystems::Hover.run_if(PickingSettings::hover_should_run), PickingSystems::PostHover, PickingSystems::Last, ) .chain(), ); } } /// Generates [`Pointer`](events::Pointer) events and handles event bubbling. #[derive(Default)] pub struct InteractionPlugin; impl Plugin for InteractionPlugin { fn build(&self, app: &mut App) { use events::*; use hover::{generate_hovermap, update_interactions}; app.init_resource::<hover::HoverMap>() .init_resource::<hover::PreviousHoverMap>() .init_resource::<PointerState>() .add_message::<Pointer<Cancel>>() .add_message::<Pointer<Click>>() .add_message::<Pointer<Press>>() .add_message::<Pointer<DragDrop>>() .add_message::<Pointer<DragEnd>>() .add_message::<Pointer<DragEnter>>() .add_message::<Pointer<Drag>>() .add_message::<Pointer<DragLeave>>() .add_message::<Pointer<DragOver>>() .add_message::<Pointer<DragStart>>() .add_message::<Pointer<Move>>() .add_message::<Pointer<Out>>() .add_message::<Pointer<Over>>() .add_message::<Pointer<Release>>() .add_message::<Pointer<Scroll>>() .add_systems( PreUpdate, ( generate_hovermap, update_interactions, (update_is_hovered, update_is_directly_hovered), pointer_events, ) .chain() .in_set(PickingSystems::Hover), ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_picking/src/backend.rs
crates/bevy_picking/src/backend.rs
//! This module provides a simple interface for implementing a picking backend. //! //! Don't be dissuaded by terminology like "backend"; the idea is dead simple. `bevy_picking` //! will tell you where pointers are, all you have to do is send an event if the pointers are //! hitting something. That's it. The rest of this documentation explains the requirements in more //! detail. //! //! Because `bevy_picking` is very loosely coupled with its backends, you can mix and match as //! many backends as you want. For example, you could use the `rapier` backend to raycast against //! physics objects, a picking shader backend to pick non-physics meshes, and the `bevy_ui` backend //! for your UI. The [`PointerHits`] instances produced by these various backends will be combined, //! sorted, and used as a homogeneous input for the picking systems that consume these events. //! //! ## Implementation //! //! - A picking backend only has one job: read [`PointerLocation`](crate::pointer::PointerLocation) //! components and produce [`PointerHits`] events. In plain English, a backend is provided the //! location of pointers, and is asked to provide a list of entities under those pointers. //! //! - The [`PointerHits`] events produced by a backend do **not** need to be sorted or filtered, all //! that is needed is an unordered list of entities and their [`HitData`]. //! //! - Backends do not need to consider the [`Pickable`](crate::Pickable) component, though they may //! use it for optimization purposes. For example, a backend that traverses a spatial hierarchy //! may want to exit early if it intersects an entity that blocks lower entities from being //! picked. //! //! ### Raycasting Backends //! //! Backends that require a ray to cast into the scene should use [`ray::RayMap`]. This //! automatically constructs rays in world space for all cameras and pointers, handling details like //! viewports and DPI for you. use bevy_ecs::prelude::*; use bevy_math::Vec3; use bevy_reflect::Reflect; /// The picking backend prelude. /// /// This includes the most common types in this module, re-exported for your convenience. pub mod prelude { pub use super::{ray::RayMap, HitData, PointerHits}; pub use crate::{ pointer::{PointerId, PointerLocation}, Pickable, PickingSystems, }; } /// A message produced by a picking backend after it has run its hit tests, describing the entities /// under a pointer. /// /// Some backends may only support providing the topmost entity; this is a valid limitation. For /// example, a picking shader might only have data on the topmost rendered output from its buffer. /// /// Note that systems reading these messages in [`PreUpdate`](bevy_app::PreUpdate) will not report ordering /// ambiguities with picking backends. Take care to ensure such systems are explicitly ordered /// against [`PickingSystems::Backend`](crate::PickingSystems::Backend), or better, avoid reading `PointerHits` in `PreUpdate`. #[derive(Message, Debug, Clone, Reflect)] #[reflect(Debug, Clone)] pub struct PointerHits { /// The pointer associated with this hit test. pub pointer: prelude::PointerId, /// An unordered collection of entities and their distance (depth) from the cursor. pub picks: Vec<(Entity, HitData)>, /// Set the order of this group of picks. Normally, this is the /// [`bevy_camera::Camera::order`]. /// /// Used to allow multiple `PointerHits` submitted for the same pointer to be ordered. /// `PointerHits` with a higher `order` will be checked before those with a lower `order`, /// regardless of the depth of each entity pick. /// /// In other words, when pick data is coalesced across all backends, the data is grouped by /// pointer, then sorted by order, and checked sequentially, sorting each `PointerHits` by /// entity depth. Events with a higher `order` are effectively on top of events with a lower /// order. /// /// ### Why is this an `f32`??? /// /// Bevy UI is special in that it can share a camera with other things being rendered. in order /// to properly sort them, we need a way to make `bevy_ui`'s order a tiny bit higher, like adding /// 0.5 to the order. We can't use integers, and we want users to be using camera.order by /// default, so this is the best solution at the moment. pub order: f32, } impl PointerHits { /// Construct [`PointerHits`]. pub fn new(pointer: prelude::PointerId, picks: Vec<(Entity, HitData)>, order: f32) -> Self { Self { pointer, picks, order, } } } /// Holds data from a successful pointer hit test. See [`HitData::depth`] for important details. #[derive(Clone, Debug, PartialEq, Reflect)] #[reflect(Clone, PartialEq)] pub struct HitData { /// The camera entity used to detect this hit. Useful when you need to find the ray that was /// cast for this hit when using a raycasting backend. pub camera: Entity, /// `depth` only needs to be self-consistent with other [`PointerHits`]s using the same /// [`RenderTarget`](bevy_camera::RenderTarget). However, it is recommended to use the /// distance from the pointer to the hit, measured from the near plane of the camera, to the /// point, in world space. pub depth: f32, /// The position reported by the backend, if the data is available. Position data may be in any /// space (e.g. World space, Screen space, Local space), specified by the backend providing it. pub position: Option<Vec3>, /// The normal vector of the hit test, if the data is available from the backend. pub normal: Option<Vec3>, } impl HitData { /// Construct a [`HitData`]. pub fn new(camera: Entity, depth: f32, position: Option<Vec3>, normal: Option<Vec3>) -> Self { Self { camera, depth, position, normal, } } } pub mod ray { //! Types and systems for constructing rays from cameras and pointers. use crate::backend::prelude::{PointerId, PointerLocation}; use bevy_camera::{Camera, RenderTarget}; use bevy_ecs::prelude::*; use bevy_math::Ray3d; use bevy_platform::collections::{hash_map::Iter, HashMap}; use bevy_reflect::Reflect; use bevy_transform::prelude::GlobalTransform; use bevy_window::PrimaryWindow; /// Identifies a ray constructed from some (pointer, camera) combination. A pointer can be over /// multiple cameras, which is why a single pointer may have multiple rays. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Reflect)] #[reflect(Clone, PartialEq, Hash)] pub struct RayId { /// The camera whose projection was used to calculate the ray. pub camera: Entity, /// The pointer whose pixel coordinates were used to calculate the ray. pub pointer: PointerId, } impl RayId { /// Construct a [`RayId`]. pub fn new(camera: Entity, pointer: PointerId) -> Self { Self { camera, pointer } } } /// A map from [`RayId`] to [`Ray3d`]. /// /// This map is cleared and re-populated every frame before any backends run. Ray-based picking /// backends should use this when possible, as it automatically handles viewports, DPI, and /// other details of building rays from pointer locations. /// /// ## Usage /// /// Iterate over each [`Ray3d`] and its [`RayId`] with [`RayMap::iter`]. /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_picking::backend::ray::RayMap; /// # use bevy_picking::backend::PointerHits; /// // My raycasting backend /// pub fn update_hits(ray_map: Res<RayMap>, mut output_messages: MessageWriter<PointerHits>,) { /// for (&ray_id, &ray) in ray_map.iter() { /// // Run a raycast with each ray, returning any `PointerHits` found. /// } /// } /// ``` #[derive(Clone, Debug, Default, Resource)] pub struct RayMap { /// Cartesian product of all pointers and all cameras /// Add your rays here to support picking through indirections, /// e.g. rendered-to-texture cameras pub map: HashMap<RayId, Ray3d>, } impl RayMap { /// Iterates over all world space rays for every picking pointer. pub fn iter(&self) -> Iter<'_, RayId, Ray3d> { self.map.iter() } /// Clears the [`RayMap`] and re-populates it with one ray for each /// combination of pointer entity and camera entity where the pointer /// intersects the camera's viewport. pub fn repopulate( mut ray_map: ResMut<Self>, primary_window_entity: Query<Entity, With<PrimaryWindow>>, cameras: Query<(Entity, &Camera, &RenderTarget, &GlobalTransform)>, pointers: Query<(&PointerId, &PointerLocation)>, ) { ray_map.map.clear(); for (camera_entity, camera, render_target, camera_tfm) in &cameras { if !camera.is_active { continue; } for (&pointer_id, pointer_loc) in &pointers { if let Some(ray) = make_ray( &primary_window_entity, camera, render_target, camera_tfm, pointer_loc, ) { ray_map .map .insert(RayId::new(camera_entity, pointer_id), ray); } } } } } fn make_ray( primary_window_entity: &Query<Entity, With<PrimaryWindow>>, camera: &Camera, render_target: &RenderTarget, camera_tfm: &GlobalTransform, pointer_loc: &PointerLocation, ) -> Option<Ray3d> { let pointer_loc = pointer_loc.location()?; if !pointer_loc.is_in_viewport(camera, render_target, primary_window_entity) { return None; } camera .viewport_to_world(camera_tfm, pointer_loc.position) .ok() } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_picking/src/hover.rs
crates/bevy_picking/src/hover.rs
//! Determines which entities are being hovered by which pointers. //! //! The most important type in this module is the [`HoverMap`], which maps pointers to the entities //! they are hovering over. use alloc::collections::BTreeMap; use core::fmt::Debug; use std::collections::HashSet; use crate::{ backend::{self, HitData}, pointer::{PointerAction, PointerId, PointerInput, PointerInteraction, PointerPress}, Pickable, }; use bevy_derive::{Deref, DerefMut}; use bevy_ecs::{entity::EntityHashSet, prelude::*}; use bevy_math::FloatOrd; use bevy_platform::collections::HashMap; use bevy_reflect::prelude::*; type DepthSortedHits = Vec<(Entity, HitData)>; /// Events returned from backends can be grouped with an order field. This allows picking to work /// with multiple layers of rendered output to the same render target. type PickLayer = FloatOrd; /// Maps [`PickLayer`]s to the map of entities within that pick layer, sorted by depth. type LayerMap = BTreeMap<PickLayer, DepthSortedHits>; /// Maps Pointers to a [`LayerMap`]. Note this is much more complex than the [`HoverMap`] because /// this data structure is used to sort entities by layer then depth for every pointer. type OverMap = HashMap<PointerId, LayerMap>; /// The source of truth for all hover state. This is used to determine what events to send, and what /// state components should be in. /// /// Maps pointers to the entities they are hovering over. /// /// "Hovering" refers to the *hover* state, which is not the same as whether or not a picking /// backend is reporting hits between a pointer and an entity. A pointer is "hovering" an entity /// only if the pointer is hitting the entity (as reported by a picking backend) *and* no entities /// between it and the pointer block interactions. /// /// For example, if a pointer is hitting a UI button and a 3d mesh, but the button is in front of /// the mesh, the UI button will be hovered, but the mesh will not. Unless, the [`Pickable`] /// component is present with [`should_block_lower`](Pickable::should_block_lower) set to `false`. /// /// # Advanced Users /// /// If you want to completely replace the provided picking events or state produced by this plugin, /// you can use this resource to do that. All of the event systems for picking are built *on top of* /// this authoritative hover state, and you can do the same. You can also use the /// [`PreviousHoverMap`] as a robust way of determining changes in hover state from the previous /// update. #[derive(Debug, Deref, DerefMut, Default, Resource)] pub struct HoverMap(pub HashMap<PointerId, HashMap<Entity, HitData>>); /// The previous state of the hover map, used to track changes to hover state. #[derive(Debug, Deref, DerefMut, Default, Resource)] pub struct PreviousHoverMap(pub HashMap<PointerId, HashMap<Entity, HitData>>); /// Coalesces all data from inputs and backends to generate a map of the currently hovered entities. /// This is the final focusing step to determine which entity the pointer is hovering over. pub fn generate_hovermap( // Inputs pickable: Query<&Pickable>, pointers: Query<&PointerId>, mut pointer_hits_reader: MessageReader<backend::PointerHits>, mut pointer_input_reader: MessageReader<PointerInput>, // Local mut over_map: Local<OverMap>, // Output mut hover_map: ResMut<HoverMap>, mut previous_hover_map: ResMut<PreviousHoverMap>, ) { reset_maps( &mut hover_map, &mut previous_hover_map, &mut over_map, &pointers, ); build_over_map( &mut pointer_hits_reader, &mut over_map, &mut pointer_input_reader, ); build_hover_map(&pointers, pickable, &over_map, &mut hover_map); } /// Clear non-empty local maps, reusing allocated memory. fn reset_maps( hover_map: &mut HoverMap, previous_hover_map: &mut PreviousHoverMap, over_map: &mut OverMap, pointers: &Query<&PointerId>, ) { // Swap the previous and current hover maps. This results in the previous values being stored in // `PreviousHoverMap`. Swapping is okay because we clear the `HoverMap` which now holds stale // data. This process is done without any allocations. core::mem::swap(&mut previous_hover_map.0, &mut hover_map.0); for entity_set in hover_map.values_mut() { entity_set.clear(); } for layer_map in over_map.values_mut() { layer_map.clear(); } // Clear pointers from the maps if they have been removed. let active_pointers: Vec<PointerId> = pointers.iter().copied().collect(); hover_map.retain(|pointer, _| active_pointers.contains(pointer)); over_map.retain(|pointer, _| active_pointers.contains(pointer)); } /// Build an ordered map of entities that are under each pointer fn build_over_map( pointer_hit_reader: &mut MessageReader<backend::PointerHits>, pointer_over_map: &mut Local<OverMap>, pointer_input_reader: &mut MessageReader<PointerInput>, ) { let cancelled_pointers: HashSet<PointerId> = pointer_input_reader .read() .filter_map(|p| { if let PointerAction::Cancel = p.action { Some(p.pointer_id) } else { None } }) .collect(); for entities_under_pointer in pointer_hit_reader .read() .filter(|e| !cancelled_pointers.contains(&e.pointer)) { let pointer = entities_under_pointer.pointer; let layer_map = pointer_over_map.entry(pointer).or_default(); for (entity, pick_data) in entities_under_pointer.picks.iter() { let layer = entities_under_pointer.order; let hits = layer_map.entry(FloatOrd(layer)).or_default(); hits.push((*entity, pick_data.clone())); } } for layers in pointer_over_map.values_mut() { for hits in layers.values_mut() { hits.sort_by_key(|(_, hit)| FloatOrd(hit.depth)); } } } /// Build an unsorted set of hovered entities, accounting for depth, layer, and [`Pickable`]. Note /// that unlike the pointer map, this uses [`Pickable`] to determine if lower entities receive hover /// focus. Often, only a single entity per pointer will be hovered. fn build_hover_map( pointers: &Query<&PointerId>, pickable: Query<&Pickable>, over_map: &Local<OverMap>, // Output hover_map: &mut HoverMap, ) { for pointer_id in pointers.iter() { let pointer_entity_set = hover_map.entry(*pointer_id).or_default(); if let Some(layer_map) = over_map.get(pointer_id) { // Note we reverse here to start from the highest layer first. for (entity, pick_data) in layer_map.values().rev().flatten() { if let Ok(pickable) = pickable.get(*entity) { if pickable.is_hoverable { pointer_entity_set.insert(*entity, pick_data.clone()); } if pickable.should_block_lower { break; } } else { pointer_entity_set.insert(*entity, pick_data.clone()); // Emit events by default break; // Entities block by default so we break out of the loop } } } } } /// A component that aggregates picking interaction state of this entity across all pointers. /// /// Unlike bevy's `Interaction` component, this is an aggregate of the state of all pointers /// interacting with this entity. Aggregation is done by taking the interaction with the highest /// precedence. /// /// For example, if we have an entity that is being hovered by one pointer, and pressed by another, /// the entity will be considered pressed. If that entity is instead being hovered by both pointers, /// it will be considered hovered. #[derive(Component, Copy, Clone, Default, Eq, PartialEq, Debug, Reflect)] #[reflect(Component, Default, PartialEq, Debug, Clone)] pub enum PickingInteraction { /// The entity is being pressed down by a pointer. Pressed = 2, /// The entity is being hovered by a pointer. Hovered = 1, /// No pointers are interacting with this entity. #[default] None = 0, } /// Uses [`HoverMap`] changes to update [`PointerInteraction`] and [`PickingInteraction`] components. pub fn update_interactions( // Input hover_map: Res<HoverMap>, previous_hover_map: Res<PreviousHoverMap>, // Outputs mut commands: Commands, mut pointers: Query<(&PointerId, &PointerPress, &mut PointerInteraction)>, mut interact: Query<&mut PickingInteraction>, ) { // Create a map to hold the aggregated interaction for each entity. This is needed because we // need to be able to insert the interaction component on entities if they do not exist. To do // so we need to know the final aggregated interaction state to avoid the scenario where we set // an entity to `Pressed`, then overwrite that with a lower precedent like `Hovered`. let mut new_interaction_state = HashMap::<Entity, PickingInteraction>::default(); for (pointer, pointer_press, mut pointer_interaction) in &mut pointers { if let Some(pointers_hovered_entities) = hover_map.get(pointer) { // Insert a sorted list of hit entities into the pointer's interaction component. let mut sorted_entities: Vec<_> = pointers_hovered_entities.clone().drain().collect(); sorted_entities.sort_by_key(|(_, hit)| FloatOrd(hit.depth)); pointer_interaction.sorted_entities = sorted_entities; for hovered_entity in pointers_hovered_entities.iter().map(|(entity, _)| entity) { merge_interaction_states(pointer_press, hovered_entity, &mut new_interaction_state); } } } // Take the aggregated entity states and update or insert the component if missing. for (&hovered_entity, &new_interaction) in new_interaction_state.iter() { if let Ok(mut interaction) = interact.get_mut(hovered_entity) { interaction.set_if_neq(new_interaction); } else if let Ok(mut entity_commands) = commands.get_entity(hovered_entity) { entity_commands.try_insert(new_interaction); } } // Clear all previous hover data from pointers that are no longer hovering any entities. // We do this last to preserve change detection for picking interactions. for (pointer, _, _) in &mut pointers { let Some(previously_hovered_entities) = previous_hover_map.get(pointer) else { continue; }; for entity in previously_hovered_entities.keys() { if !new_interaction_state.contains_key(entity) && let Ok(mut interaction) = interact.get_mut(*entity) { interaction.set_if_neq(PickingInteraction::None); } } } } /// Merge the interaction state of this entity into the aggregated map. fn merge_interaction_states( pointer_press: &PointerPress, hovered_entity: &Entity, new_interaction_state: &mut HashMap<Entity, PickingInteraction>, ) { let new_interaction = match pointer_press.is_any_pressed() { true => PickingInteraction::Pressed, false => PickingInteraction::Hovered, }; if let Some(old_interaction) = new_interaction_state.get_mut(hovered_entity) { // Only update if the new value has a higher precedence than the old value. if *old_interaction != new_interaction && matches!( (*old_interaction, new_interaction), (PickingInteraction::Hovered, PickingInteraction::Pressed) | (PickingInteraction::None, PickingInteraction::Pressed) | (PickingInteraction::None, PickingInteraction::Hovered) ) { *old_interaction = new_interaction; } } else { new_interaction_state.insert(*hovered_entity, new_interaction); } } /// A component that allows users to use regular Bevy change detection to determine when the pointer /// enters or leaves an entity. Users should insert this component on an entity to indicate interest /// in knowing about hover state changes. /// /// The component's boolean value will be `true` whenever the pointer is currently directly hovering /// over the entity, or any of the entity's descendants (as defined by the [`ChildOf`] /// relationship). This is consistent with the behavior of the CSS `:hover` pseudo-class, which /// applies to the element and all of its descendants. /// /// The contained boolean value is guaranteed to only be mutated when the pointer enters or leaves /// the entity, allowing Bevy change detection to be used efficiently. This is in contrast to the /// [`HoverMap`] resource, which is updated every frame. /// /// Typically, a simple hoverable entity or widget will have this component added to it. More /// complex widgets can have this component added to each hoverable part. /// /// The computational cost of keeping the `Hovered` components up to date is relatively cheap, and /// linear in the number of entities that have the [`Hovered`] component inserted. #[derive(Component, Copy, Clone, Default, Eq, PartialEq, Debug, Reflect)] #[reflect(Component, Default, PartialEq, Debug, Clone)] #[component(immutable)] pub struct Hovered(pub bool); impl Hovered { /// Get whether the entity is currently hovered. pub fn get(&self) -> bool { self.0 } } /// A component that allows users to use regular Bevy change detection to determine when the pointer /// is directly hovering over an entity. Users should insert this component on an entity to indicate /// interest in knowing about hover state changes. /// /// This is similar to [`Hovered`] component, except that it does not include descendants in the /// hover state. #[derive(Component, Copy, Clone, Default, Eq, PartialEq, Debug, Reflect)] #[reflect(Component, Default, PartialEq, Debug, Clone)] #[component(immutable)] pub struct DirectlyHovered(pub bool); impl DirectlyHovered { /// Get whether the entity is currently hovered. pub fn get(&self) -> bool { self.0 } } /// Uses [`HoverMap`] changes to update [`Hovered`] components. pub fn update_is_hovered( hover_map: Option<Res<HoverMap>>, mut hovers: Query<(Entity, &Hovered)>, parent_query: Query<&ChildOf>, mut commands: Commands, ) { // Don't do any work if there's no hover map. let Some(hover_map) = hover_map else { return }; // Don't bother collecting ancestors if there are no hovers. if hovers.is_empty() { return; } // Algorithm: for each entity having a `Hovered` component, we want to know if the current // entry in the hover map is "within" (that is, in the set of descendants of) that entity. Rather // than doing an expensive breadth-first traversal of children, instead start with the hovermap // entry and search upwards. We can make this even cheaper by building a set of ancestors for // the hovermap entry, and then testing each `Hovered` entity against that set. // A set which contains the hovered for the current pointer entity and its ancestors. The // capacity is based on the likely tree depth of the hierarchy, which is typically greater for // UI (because of layout issues) than for 3D scenes. A depth of 32 is a reasonable upper bound // for most use cases. let mut hover_ancestors = EntityHashSet::with_capacity(32); if let Some(map) = hover_map.get(&PointerId::Mouse) { for hovered_entity in map.keys() { hover_ancestors.insert(*hovered_entity); hover_ancestors.extend(parent_query.iter_ancestors(*hovered_entity)); } } // For each hovered entity, it is considered "hovering" if it's in the set of hovered ancestors. for (entity, hoverable) in hovers.iter_mut() { let is_hovering = hover_ancestors.contains(&entity); if hoverable.0 != is_hovering { commands.entity(entity).insert(Hovered(is_hovering)); } } } /// Uses [`HoverMap`] changes to update [`DirectlyHovered`] components. pub fn update_is_directly_hovered( hover_map: Option<Res<HoverMap>>, hovers: Query<(Entity, &DirectlyHovered)>, mut commands: Commands, ) { // Don't do any work if there's no hover map. let Some(hover_map) = hover_map else { return }; // Don't bother collecting ancestors if there are no hovers. if hovers.is_empty() { return; } if let Some(map) = hover_map.get(&PointerId::Mouse) { // It's hovering if it's in the HoverMap. for (entity, hoverable) in hovers.iter() { let is_hovering = map.contains_key(&entity); if hoverable.0 != is_hovering { commands.entity(entity).insert(DirectlyHovered(is_hovering)); } } } else { // No hovered entity, reset all hovers. for (entity, hoverable) in hovers.iter() { if hoverable.0 { commands.entity(entity).insert(DirectlyHovered(false)); } } } } #[cfg(test)] mod tests { use bevy_camera::Camera; use super::*; #[test] fn update_is_hovered_memoized() { let mut world = World::default(); let camera = world.spawn(Camera::default()).id(); // Setup entities let hovered_child = world.spawn_empty().id(); let hovered_entity = world.spawn(Hovered(false)).add_child(hovered_child).id(); // Setup hover map with hovered_entity hovered by mouse let mut hover_map = HoverMap::default(); let mut entity_map = HashMap::new(); entity_map.insert( hovered_child, HitData { depth: 0.0, camera, position: None, normal: None, }, ); hover_map.insert(PointerId::Mouse, entity_map); world.insert_resource(hover_map); // Run the system assert!(world.run_system_cached(update_is_hovered).is_ok()); // Check to insure that the hovered entity has the Hovered component set to true let hover = world.entity(hovered_entity).get_ref::<Hovered>().unwrap(); assert!(hover.get()); assert!(hover.is_changed()); // Now do it again, but don't change the hover map. world.increment_change_tick(); assert!(world.run_system_cached(update_is_hovered).is_ok()); let hover = world.entity(hovered_entity).get_ref::<Hovered>().unwrap(); assert!(hover.get()); // Should not be changed // NOTE: Test doesn't work - thinks it is always changed // assert!(!hover.is_changed()); // Clear the hover map and run again. world.insert_resource(HoverMap::default()); world.increment_change_tick(); assert!(world.run_system_cached(update_is_hovered).is_ok()); let hover = world.entity(hovered_entity).get_ref::<Hovered>().unwrap(); assert!(!hover.get()); assert!(hover.is_changed()); } #[test] fn update_is_hovered_direct_self() { let mut world = World::default(); let camera = world.spawn(Camera::default()).id(); // Setup entities let hovered_entity = world.spawn(DirectlyHovered(false)).id(); // Setup hover map with hovered_entity hovered by mouse let mut hover_map = HoverMap::default(); let mut entity_map = HashMap::new(); entity_map.insert( hovered_entity, HitData { depth: 0.0, camera, position: None, normal: None, }, ); hover_map.insert(PointerId::Mouse, entity_map); world.insert_resource(hover_map); // Run the system assert!(world.run_system_cached(update_is_directly_hovered).is_ok()); // Check to insure that the hovered entity has the DirectlyHovered component set to true let hover = world .entity(hovered_entity) .get_ref::<DirectlyHovered>() .unwrap(); assert!(hover.get()); assert!(hover.is_changed()); // Now do it again, but don't change the hover map. world.increment_change_tick(); assert!(world.run_system_cached(update_is_directly_hovered).is_ok()); let hover = world .entity(hovered_entity) .get_ref::<DirectlyHovered>() .unwrap(); assert!(hover.get()); // Should not be changed // NOTE: Test doesn't work - thinks it is always changed // assert!(!hover.is_changed()); // Clear the hover map and run again. world.insert_resource(HoverMap::default()); world.increment_change_tick(); assert!(world.run_system_cached(update_is_directly_hovered).is_ok()); let hover = world .entity(hovered_entity) .get_ref::<DirectlyHovered>() .unwrap(); assert!(!hover.get()); assert!(hover.is_changed()); } #[test] fn update_is_hovered_direct_child() { let mut world = World::default(); let camera = world.spawn(Camera::default()).id(); // Setup entities let hovered_child = world.spawn_empty().id(); let hovered_entity = world .spawn(DirectlyHovered(false)) .add_child(hovered_child) .id(); // Setup hover map with hovered_entity hovered by mouse let mut hover_map = HoverMap::default(); let mut entity_map = HashMap::new(); entity_map.insert( hovered_child, HitData { depth: 0.0, camera, position: None, normal: None, }, ); hover_map.insert(PointerId::Mouse, entity_map); world.insert_resource(hover_map); // Run the system assert!(world.run_system_cached(update_is_directly_hovered).is_ok()); // Check to insure that the DirectlyHovered component is still false let hover = world .entity(hovered_entity) .get_ref::<DirectlyHovered>() .unwrap(); assert!(!hover.get()); assert!(hover.is_changed()); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_picking/src/window.rs
crates/bevy_picking/src/window.rs
//! This module contains a basic backend that implements picking for window //! entities. //! //! Pointers can exist on windows, images, and gpu texture views. With //! [`update_window_hits`] enabled, when a pointer hovers over a window that //! window will be inserted as a pointer hit, listed behind all other pointer //! hits. This means that when the pointer isn't hovering any other entities, //! the picking events will be routed to the window. //! //! ## Implementation Notes //! //! - This backend does not provide `normal` in `HitData`. use core::f32; use bevy_camera::NormalizedRenderTarget; use bevy_ecs::prelude::*; use crate::{ backend::{HitData, PointerHits}, pointer::{Location, PointerId, PointerLocation}, }; /// Generates pointer hit events for window entities. /// /// A pointer is treated as hitting a window when it is located on that window. The order /// of the hit event is negative infinity, meaning it should appear behind all other entities. /// /// The depth of the hit will be listed as zero. pub fn update_window_hits( pointers: Query<(&PointerId, &PointerLocation)>, mut pointer_hits_writer: MessageWriter<PointerHits>, ) { for (pointer_id, pointer_location) in pointers.iter() { if let Some(Location { target: NormalizedRenderTarget::Window(window_ref), position, .. }) = pointer_location.location { let entity = window_ref.entity(); let hit_data = HitData::new(entity, 0.0, Some(position.extend(0.0)), None); pointer_hits_writer.write(PointerHits::new( *pointer_id, vec![(entity, hit_data)], f32::NEG_INFINITY, )); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_picking/src/events.rs
crates/bevy_picking/src/events.rs
//! This module defines a stateful set of interaction events driven by the `PointerInput` stream //! and the hover state of each Pointer. //! //! # Usage //! //! To receive events from this module, you must use an [`Observer`] or [`MessageReader`] with [`Pointer<E>`] events. //! The simplest example, registering a callback when an entity is hovered over by a pointer, looks like this: //! //! ```rust //! # use bevy_ecs::prelude::*; //! # use bevy_picking::prelude::*; //! # let mut world = World::default(); //! world.spawn_empty() //! .observe(|event: On<Pointer<Over>>| { //! println!("I am being hovered over"); //! }); //! ``` //! //! Observers give us three important properties: //! 1. They allow for attaching event handlers to specific entities, //! 2. they allow events to bubble up the entity hierarchy, //! 3. and they allow events of different types to be called in a specific order. //! //! The order in which interaction events are received is extremely important, and you can read more //! about it on the docs for the dispatcher system: [`pointer_events`]. This system runs in //! [`PreUpdate`](bevy_app::PreUpdate) in [`PickingSystems::Hover`](crate::PickingSystems::Hover). All pointer-event //! observers resolve during the sync point between [`pointer_events`] and //! [`update_interactions`](crate::hover::update_interactions). //! //! # Events Types //! //! The events this module defines fall into a few broad categories: //! + Hovering and movement: [`Over`], [`Move`], and [`Out`]. //! + Clicking and pressing: [`Press`], [`Release`], and [`Click`]. //! + Dragging and dropping: [`DragStart`], [`Drag`], [`DragEnd`], [`DragEnter`], [`DragOver`], [`DragDrop`], [`DragLeave`]. //! //! When received by an observer, these events will always be wrapped by the [`Pointer`] type, which contains //! general metadata about the pointer event. use core::{fmt::Debug, time::Duration}; use bevy_camera::NormalizedRenderTarget; use bevy_ecs::{prelude::*, query::QueryData, system::SystemParam, traversal::Traversal}; use bevy_input::mouse::MouseScrollUnit; use bevy_math::Vec2; use bevy_platform::collections::HashMap; use bevy_platform::time::Instant; use bevy_reflect::prelude::*; use bevy_window::Window; use tracing::debug; use crate::{ backend::{prelude::PointerLocation, HitData}, hover::{HoverMap, PreviousHoverMap}, pointer::{Location, PointerAction, PointerButton, PointerId, PointerInput, PointerMap}, }; /// Stores the common data needed for all pointer events. /// /// The documentation for the [`pointer_events`] explains the events this module exposes and /// the order in which they fire. #[derive(Message, EntityEvent, Clone, PartialEq, Debug, Reflect, Component)] #[entity_event(propagate = PointerTraversal, auto_propagate)] #[reflect(Component, Debug, Clone)] pub struct Pointer<E: Debug + Clone + Reflect> { /// The entity this pointer event happened for. pub entity: Entity, /// The pointer that triggered this event pub pointer_id: PointerId, /// The location of the pointer during this event pub pointer_location: Location, /// Additional event-specific data. [`DragDrop`] for example, has an additional field to describe /// the `Entity` that is being dropped on the target. pub event: E, } /// A traversal query (i.e. it implements [`Traversal`]) intended for use with [`Pointer`] events. /// /// This will always traverse to the parent, if the entity being visited has one. Otherwise, it /// propagates to the pointer's window and stops there. #[derive(QueryData)] pub struct PointerTraversal { child_of: Option<&'static ChildOf>, window: Option<&'static Window>, } impl<E> Traversal<Pointer<E>> for PointerTraversal where E: Debug + Clone + Reflect, { fn traverse(item: Self::Item<'_, '_>, pointer: &Pointer<E>) -> Option<Entity> { let PointerTraversalItem { child_of, window } = item; // Send event to parent, if it has one. if let Some(child_of) = child_of { return Some(child_of.parent()); }; // Otherwise, send it to the window entity (unless this is a window entity). if window.is_none() && let NormalizedRenderTarget::Window(window_ref) = pointer.pointer_location.target { return Some(window_ref.entity()); } None } } impl<E: Debug + Clone + Reflect> core::fmt::Display for Pointer<E> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.write_fmt(format_args!( "{:?}, {:.1?}, {:.1?}", self.pointer_id, self.pointer_location.position, self.event )) } } impl<E: Debug + Clone + Reflect> core::ops::Deref for Pointer<E> { type Target = E; fn deref(&self) -> &Self::Target { &self.event } } impl<E: Debug + Clone + Reflect> Pointer<E> { /// Construct a new `Pointer<E>` event. pub fn new(id: PointerId, location: Location, event: E, entity: Entity) -> Self { Self { pointer_id: id, pointer_location: location, event, entity, } } } /// Fires when a pointer is canceled, and its current interaction state is dropped. #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq)] pub struct Cancel { /// Information about the picking intersection. pub hit: HitData, } /// Fires when a pointer crosses into the bounds of the [target entity](EntityEvent::event_target). #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq)] pub struct Over { /// Information about the picking intersection. pub hit: HitData, } /// Fires when a pointer crosses out of the bounds of the [target entity](EntityEvent::event_target). #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq)] pub struct Out { /// Information about the latest prior picking intersection. pub hit: HitData, } /// Fires when a pointer button is pressed over the [target entity](EntityEvent::event_target). #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq)] pub struct Press { /// Pointer button pressed to trigger this event. pub button: PointerButton, /// Information about the picking intersection. pub hit: HitData, } /// Fires when a pointer button is released over the [target entity](EntityEvent::event_target). #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq)] pub struct Release { /// Pointer button lifted to trigger this event. pub button: PointerButton, /// Information about the picking intersection. pub hit: HitData, } /// Fires when a pointer sends a pointer pressed event followed by a pointer released event, with the same /// [target entity](EntityEvent::event_target) for both events. #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq)] pub struct Click { /// Pointer button pressed and lifted to trigger this event. pub button: PointerButton, /// Information about the picking intersection. pub hit: HitData, /// Duration between the pointer pressed and lifted for this click pub duration: Duration, } /// Fires while a pointer is moving over the [target entity](EntityEvent::event_target). #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq)] pub struct Move { /// Information about the picking intersection. pub hit: HitData, /// The change in position since the last move event. /// /// This is stored in screen pixels, not world coordinates. Screen pixels go from top-left to /// bottom-right, whereas (in 2D) world coordinates go from bottom-left to top-right. Consider /// using methods on [`Camera`](bevy_camera::Camera) to convert from screen-space to /// world-space. pub delta: Vec2, } /// Fires when the [target entity](EntityEvent::event_target) receives a pointer pressed event followed by a pointer move event. #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq)] pub struct DragStart { /// Pointer button pressed and moved to trigger this event. pub button: PointerButton, /// Information about the picking intersection. pub hit: HitData, } /// Fires while the [target entity](EntityEvent::event_target) is being dragged. #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq)] pub struct Drag { /// Pointer button pressed and moved to trigger this event. pub button: PointerButton, /// The total distance vector of a drag, measured from drag start to the current position. /// /// This is stored in screen pixels, not world coordinates. Screen pixels go from top-left to /// bottom-right, whereas (in 2D) world coordinates go from bottom-left to top-right. Consider /// using methods on [`Camera`](bevy_camera::Camera) to convert from screen-space to /// world-space. pub distance: Vec2, /// The change in position since the last drag event. /// /// This is stored in screen pixels, not world coordinates. Screen pixels go from top-left to /// bottom-right, whereas (in 2D) world coordinates go from bottom-left to top-right. Consider /// using methods on [`Camera`](bevy_camera::Camera) to convert from screen-space to /// world-space. pub delta: Vec2, } /// Fires when a pointer is dragging the [target entity](EntityEvent::event_target) and a pointer released event is received. #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq)] pub struct DragEnd { /// Pointer button pressed, moved, and released to trigger this event. pub button: PointerButton, /// The vector of drag movement measured from start to final pointer position. /// /// This is stored in screen pixels, not world coordinates. Screen pixels go from top-left to /// bottom-right, whereas (in 2D) world coordinates go from bottom-left to top-right. Consider /// using methods on [`Camera`](bevy_camera::Camera) to convert from screen-space to /// world-space. pub distance: Vec2, } /// Fires when a pointer dragging the `dragged` entity enters the [target entity](EntityEvent::event_target) #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq)] pub struct DragEnter { /// Pointer button pressed to enter drag. pub button: PointerButton, /// The entity that was being dragged when the pointer entered the [target entity](EntityEvent::event_target). pub dragged: Entity, /// Information about the picking intersection. pub hit: HitData, } /// Fires while the `dragged` entity is being dragged over the [target entity](EntityEvent::event_target). #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq)] pub struct DragOver { /// Pointer button pressed while dragging over. pub button: PointerButton, /// The entity that was being dragged when the pointer was over the [target entity](EntityEvent::event_target). pub dragged: Entity, /// Information about the picking intersection. pub hit: HitData, } /// Fires when a pointer dragging the `dragged` entity leaves the [target entity](EntityEvent::event_target). #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq)] pub struct DragLeave { /// Pointer button pressed while leaving drag. pub button: PointerButton, /// The entity that was being dragged when the pointer left the [target entity](EntityEvent::event_target). pub dragged: Entity, /// Information about the latest prior picking intersection. pub hit: HitData, } /// Fires when a pointer drops the `dropped` entity onto the [target entity](EntityEvent::event_target). #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq)] pub struct DragDrop { /// Pointer button released to drop. pub button: PointerButton, /// The entity that was dropped onto the [target entity](EntityEvent::event_target). pub dropped: Entity, /// Information about the picking intersection. pub hit: HitData, } /// Dragging state. #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq)] pub struct DragEntry { /// The position of the pointer at drag start. /// /// This is stored in screen pixels, not world coordinates. Screen pixels go from top-left to /// bottom-right, whereas (in 2D) world coordinates go from bottom-left to top-right. Consider /// using [`Camera::viewport_to_world`](bevy_camera::Camera::viewport_to_world) or /// [`Camera::viewport_to_world_2d`](bevy_camera::Camera::viewport_to_world_2d) to /// convert from screen-space to world-space. pub start_pos: Vec2, /// The latest position of the pointer during this drag, used to compute deltas. /// /// This is stored in screen pixels, not world coordinates. Screen pixels go from top-left to /// bottom-right, whereas (in 2D) world coordinates go from bottom-left to top-right. Consider /// using [`Camera::viewport_to_world`](bevy_camera::Camera::viewport_to_world) or /// [`Camera::viewport_to_world_2d`](bevy_camera::Camera::viewport_to_world_2d) to /// convert from screen-space to world-space. pub latest_pos: Vec2, } /// Fires while a pointer is scrolling over the [target entity](EntityEvent::event_target). #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(Clone, PartialEq)] pub struct Scroll { /// The mouse scroll unit. pub unit: MouseScrollUnit, /// The horizontal scroll value. pub x: f32, /// The vertical scroll value. pub y: f32, /// Information about the picking intersection. pub hit: HitData, } /// An entry in the cache that drives the `pointer_events` system, storing additional data /// about pointer button presses. #[derive(Debug, Clone, Default)] pub struct PointerButtonState { /// Stores the press location and start time for each button currently being pressed by the pointer. pub pressing: HashMap<Entity, (Location, Instant, HitData)>, /// Stores the starting and current locations for each entity currently being dragged by the pointer. pub dragging: HashMap<Entity, DragEntry>, /// Stores the hit data for each entity currently being dragged over by the pointer. pub dragging_over: HashMap<Entity, HitData>, } impl PointerButtonState { /// Clears all press and drag data tracked for this button on its pointer. pub fn clear(&mut self) { self.pressing.clear(); self.dragging.clear(); self.dragging_over.clear(); } } /// State for all pointers. #[derive(Debug, Clone, Default, Resource)] pub struct PointerState { /// Pressing and dragging state, organized by pointer and button. pub pointer_buttons: HashMap<(PointerId, PointerButton), PointerButtonState>, } impl PointerState { /// Retrieves the current state for a specific pointer and button, if it has been created. pub fn get(&self, pointer_id: PointerId, button: PointerButton) -> Option<&PointerButtonState> { self.pointer_buttons.get(&(pointer_id, button)) } /// Provides write access to the state of a pointer and button, creating it if it does not yet exist. pub fn get_mut( &mut self, pointer_id: PointerId, button: PointerButton, ) -> &mut PointerButtonState { self.pointer_buttons .entry((pointer_id, button)) .or_default() } /// 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)) { state.clear(); } } } } /// A helper system param for accessing the picking event writers. #[derive(SystemParam)] pub struct PickingMessageWriters<'w> { cancel_events: MessageWriter<'w, Pointer<Cancel>>, click_events: MessageWriter<'w, Pointer<Click>>, pressed_events: MessageWriter<'w, Pointer<Press>>, drag_drop_events: MessageWriter<'w, Pointer<DragDrop>>, drag_end_events: MessageWriter<'w, Pointer<DragEnd>>, drag_enter_events: MessageWriter<'w, Pointer<DragEnter>>, drag_events: MessageWriter<'w, Pointer<Drag>>, drag_leave_events: MessageWriter<'w, Pointer<DragLeave>>, drag_over_events: MessageWriter<'w, Pointer<DragOver>>, drag_start_events: MessageWriter<'w, Pointer<DragStart>>, scroll_events: MessageWriter<'w, Pointer<Scroll>>, move_events: MessageWriter<'w, Pointer<Move>>, out_events: MessageWriter<'w, Pointer<Out>>, over_events: MessageWriter<'w, Pointer<Over>>, released_events: MessageWriter<'w, Pointer<Release>>, } /// Dispatches interaction events to the target entities. /// /// Within a single frame, events are dispatched in the following order: /// + [`Out`] → [`DragLeave`]. /// + [`DragEnter`] → [`Over`]. /// + Any number of any of the following: /// + For each movement: [`DragStart`] → [`Drag`] → [`DragOver`] → [`Move`]. /// + For each button press: [`Press`] or [`Click`] → [`Release`] → [`DragDrop`] → [`DragEnd`] → [`DragLeave`]. /// + For each pointer cancellation: [`Cancel`]. /// /// Additionally, across multiple frames, the following are also strictly /// ordered by the interaction state machine: /// + When a pointer moves over the target: /// [`Over`], [`Move`], [`Out`]. /// + When a pointer presses buttons on the target: /// [`Press`], [`Click`], [`Release`]. /// + When a pointer drags the target: /// [`DragStart`], [`Drag`], [`DragEnd`]. /// + When a pointer drags something over the target: /// [`DragEnter`], [`DragOver`], [`DragDrop`], [`DragLeave`]. /// + When a pointer is canceled: /// No other events will follow the [`Cancel`] event for that pointer. /// /// Two events -- [`Over`] and [`Out`] -- are driven only by the [`HoverMap`]. /// The rest rely on additional data from the [`PointerInput`] event stream. To /// receive these events for a custom pointer, you must add [`PointerInput`] /// events. /// /// When the pointer goes from hovering entity A to entity B, entity A will /// receive [`Out`] and then entity B will receive [`Over`]. No entity will ever /// receive both an [`Over`] and an [`Out`] event during the same frame. /// /// When we account for event bubbling, this is no longer true. When the hovering focus shifts /// between children, parent entities may receive redundant [`Out`] → [`Over`] pairs. /// In the context of UI, this is especially problematic. Additional hierarchy-aware /// events will be added in a future release. /// /// Both [`Click`] and [`Release`] 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 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 /// multiple pointer movements and presses each frame, the hover state is /// determined only by the pointer's *final position*. Since the hover state /// ultimately determines which entities receive events, this may mean that an /// entity can receive events from before or after it was actually hovered. pub fn pointer_events( // Input mut input_events: MessageReader<PointerInput>, // ECS State pointers: Query<&PointerLocation>, pointer_map: Res<PointerMap>, hover_map: Res<HoverMap>, previous_hover_map: Res<PreviousHoverMap>, mut pointer_state: ResMut<PointerState>, // Output mut commands: Commands, mut message_writers: PickingMessageWriters, ) { // Setup utilities let now = Instant::now(); let pointer_location = |pointer_id: PointerId| { pointer_map .get_entity(pointer_id) .and_then(|entity| pointers.get(entity).ok()) .and_then(|pointer| pointer.location.clone()) }; // If the entity was hovered by a specific pointer last frame... for (pointer_id, hovered_entity, hit) in previous_hover_map .iter() .flat_map(|(id, hashmap)| hashmap.iter().map(|data| (*id, *data.0, data.1.clone()))) { // ...but is now not being hovered by that same pointer... if !hover_map .get(&pointer_id) .iter() .any(|e| e.contains_key(&hovered_entity)) { let Some(location) = pointer_location(pointer_id) else { debug!( "Unable to get location for pointer {:?} during pointer out", pointer_id ); continue; }; // Always send Out events let out_event = Pointer::new( pointer_id, location.clone(), Out { hit: hit.clone() }, hovered_entity, ); commands.trigger(out_event.clone()); message_writers.out_events.write(out_event); // Possibly send DragLeave events for button in PointerButton::iter() { let state = pointer_state.get_mut(pointer_id, button); state.dragging_over.remove(&hovered_entity); for drag_target in state.dragging.keys() { let drag_leave_event = Pointer::new( pointer_id, location.clone(), DragLeave { button, dragged: *drag_target, hit: hit.clone(), }, hovered_entity, ); commands.trigger(drag_leave_event.clone()); message_writers.drag_leave_events.write(drag_leave_event); } } } } // Iterate all currently hovered entities for each pointer for (pointer_id, hovered_entity, hit) in hover_map .iter() .flat_map(|(id, hashmap)| hashmap.iter().map(|data| (*id, *data.0, data.1.clone()))) { // Continue if the pointer does not have a valid location. let Some(location) = pointer_location(pointer_id) else { debug!( "Unable to get location for pointer {:?} during pointer over", pointer_id ); continue; }; // For each button update its `dragging_over` state and possibly emit DragEnter events. for button in PointerButton::iter() { let state = pointer_state.get_mut(pointer_id, button); // Only update the `dragging_over` state if there is at least one entity being dragged. // Only emit DragEnter events for this `hovered_entity`, if it had no previous `dragging_over` state. if !state.dragging.is_empty() && state .dragging_over .insert(hovered_entity, hit.clone()) .is_none() { for drag_target in state.dragging.keys() { let drag_enter_event = Pointer::new( pointer_id, location.clone(), DragEnter { button, dragged: *drag_target, hit: hit.clone(), }, hovered_entity, ); commands.trigger(drag_enter_event.clone()); message_writers.drag_enter_events.write(drag_enter_event); } } } // Emit an Over event if the `hovered_entity` was not hovered by the same pointer the previous frame. if !previous_hover_map .get(&pointer_id) .iter() .any(|e| e.contains_key(&hovered_entity)) { let over_event = Pointer::new( pointer_id, location.clone(), Over { hit: hit.clone() }, hovered_entity, ); commands.trigger(over_event.clone()); message_writers.over_events.write(over_event); } } // Dispatch input events... for PointerInput { pointer_id, location, action, } in input_events.read().cloned() { match action { PointerAction::Press(button) => { let state = pointer_state.get_mut(pointer_id, button); // If it's a press, emit a Pressed event and mark the hovered entities as pressed for (hovered_entity, hit) in hover_map .get(&pointer_id) .iter() .flat_map(|h| h.iter().map(|(entity, data)| (*entity, data.clone()))) { let pressed_event = Pointer::new( pointer_id, location.clone(), Press { button, hit: hit.clone(), }, hovered_entity, ); commands.trigger(pressed_event.clone()); message_writers.pressed_events.write(pressed_event); // Also insert the press into the state state .pressing .insert(hovered_entity, (location.clone(), now, hit)); } } PointerAction::Release(button) => { let state = pointer_state.get_mut(pointer_id, button); // Emit Click and Release events on all the previously hovered entities. for (hovered_entity, hit) in previous_hover_map .get(&pointer_id) .iter() .flat_map(|h| h.iter().map(|(entity, data)| (*entity, data.clone()))) { // If this pointer previously pressed the hovered entity, emit a Click event if let Some((_, press_instant, _)) = state.pressing.get(&hovered_entity) { let click_event = Pointer::new( pointer_id, location.clone(), Click { button, hit: hit.clone(), duration: now - *press_instant, }, hovered_entity, ); commands.trigger(click_event.clone()); message_writers.click_events.write(click_event); } // Always send the Release event let released_event = Pointer::new( pointer_id, location.clone(), Release { button, hit: hit.clone(), }, hovered_entity, ); commands.trigger(released_event.clone()); message_writers.released_events.write(released_event); } // Then emit the drop events. for (drag_target, drag) in state.dragging.drain() { // Emit DragDrop for (dragged_over, hit) in state.dragging_over.iter() { let drag_drop_event = Pointer::new( pointer_id, location.clone(), DragDrop { button, dropped: drag_target, hit: hit.clone(), }, *dragged_over, ); commands.trigger(drag_drop_event.clone()); message_writers.drag_drop_events.write(drag_drop_event); } // Emit DragEnd let drag_end_event = Pointer::new( pointer_id, location.clone(), DragEnd { button, distance: drag.latest_pos - drag.start_pos, }, drag_target, ); commands.trigger(drag_end_event.clone()); message_writers.drag_end_events.write(drag_end_event); // Emit DragLeave for (dragged_over, hit) in state.dragging_over.iter() { let drag_leave_event = Pointer::new( pointer_id, location.clone(), DragLeave { button, dragged: drag_target, hit: hit.clone(), }, *dragged_over, ); commands.trigger(drag_leave_event.clone()); message_writers.drag_leave_events.write(drag_leave_event); } } // Finally, we can clear the state of everything relating to presses or drags. state.clear(); } // Moved PointerAction::Move { delta } => { if delta == Vec2::ZERO { continue; // If delta is zero, the following events will not be triggered. } // Triggers during movement even if not over an entity for button in PointerButton::iter() { let state = pointer_state.get_mut(pointer_id, button); // Emit DragEntry and DragStart the first time we move while pressing an entity for (press_target, (location, _, hit)) in state.pressing.iter() { if state.dragging.contains_key(press_target) { continue; // This entity is already logged as being dragged } state.dragging.insert( *press_target, DragEntry { start_pos: location.position, latest_pos: location.position, }, ); let drag_start_event = Pointer::new( pointer_id, location.clone(), DragStart { button, hit: hit.clone(), }, *press_target, ); commands.trigger(drag_start_event.clone()); message_writers.drag_start_events.write(drag_start_event); // Insert dragging over state and emit DragEnter for hovered entities. for (hovered_entity, hit) in hover_map .get(&pointer_id) .iter() .flat_map(|h| h.iter().map(|(entity, data)| (*entity, data.to_owned()))) .filter(|(hovered_entity, _)| *hovered_entity != *press_target) { // Inserting the `dragging_over` state here ensures the `DragEnter` event won't be dispatched twice. state.dragging_over.insert(hovered_entity, hit.clone()); let drag_enter_event = Pointer::new( pointer_id, location.clone(), DragEnter { button, dragged: *press_target, hit: hit.clone(), }, hovered_entity, ); commands.trigger(drag_enter_event.clone()); message_writers.drag_enter_events.write(drag_enter_event); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_picking/src/pointer.rs
crates/bevy_picking/src/pointer.rs
//! Types and systems for pointer inputs, such as position and buttons. //! //! The picking system is built around the concept of a 'Pointer', which is an //! abstract representation of a user input with a specific screen location. The cursor //! and touch input is provided under [`input`](`crate::input`), but you can also implement //! your own custom pointers by supplying a unique ID. //! //! The purpose of this module is primarily to provide a common interface that can be //! driven by lower-level input devices and consumed by higher-level interaction systems. use bevy_camera::NormalizedRenderTarget; use bevy_camera::{Camera, RenderTarget}; use bevy_ecs::prelude::*; use bevy_input::mouse::MouseScrollUnit; use bevy_math::Vec2; use bevy_platform::collections::HashMap; use bevy_reflect::prelude::*; use bevy_window::PrimaryWindow; use uuid::Uuid; use core::{fmt::Debug, ops::Deref}; use crate::backend::HitData; /// Identifies a unique pointer entity. `Mouse` and `Touch` pointers are automatically spawned. /// /// This component is needed because pointers can be spawned and despawned, but they need to have a /// stable ID that persists regardless of the Entity they are associated with. #[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, Component, Reflect)] #[require(PointerLocation, PointerPress, PointerInteraction)] #[reflect(Component, Default, Debug, Hash, PartialEq, Clone)] pub enum PointerId { /// The mouse pointer. #[default] Mouse, /// A touch input, usually numbered by window touch events from `winit`. Touch(u64), /// A custom, uniquely identified pointer. Useful for mocking inputs or implementing a software /// controlled cursor. #[reflect(ignore, clone)] Custom(Uuid), } impl PointerId { /// Returns true if the pointer is a touch input. pub fn is_touch(&self) -> bool { matches!(self, PointerId::Touch(_)) } /// Returns true if the pointer is the mouse. pub fn is_mouse(&self) -> bool { matches!(self, PointerId::Mouse) } /// Returns true if the pointer is a custom input. pub fn is_custom(&self) -> bool { matches!(self, PointerId::Custom(_)) } /// Returns the touch id if the pointer is a touch input. pub fn get_touch_id(&self) -> Option<u64> { if let PointerId::Touch(id) = self { Some(*id) } else { None } } } /// Holds a list of entities this pointer is currently interacting with, sorted from nearest to /// farthest. #[derive(Debug, Default, Clone, Component, Reflect)] #[reflect(Component, Default, Debug, Clone)] pub struct PointerInteraction { pub(crate) sorted_entities: Vec<(Entity, HitData)>, } impl PointerInteraction { /// Returns the nearest hit entity and data about that intersection. pub fn get_nearest_hit(&self) -> Option<&(Entity, HitData)> { self.sorted_entities.first() } } impl Deref for PointerInteraction { type Target = Vec<(Entity, HitData)>; fn deref(&self) -> &Self::Target { &self.sorted_entities } } /// A resource that maps each [`PointerId`] to their [`Entity`] for easy lookups. #[derive(Debug, Clone, Default, Resource)] pub struct PointerMap { inner: HashMap<PointerId, Entity>, } impl PointerMap { /// Get the [`Entity`] of the supplied [`PointerId`]. pub fn get_entity(&self, pointer_id: PointerId) -> Option<Entity> { self.inner.get(&pointer_id).copied() } } /// Update the [`PointerMap`] resource with the current frame's data. pub fn update_pointer_map(pointers: Query<(Entity, &PointerId)>, mut map: ResMut<PointerMap>) { map.inner.clear(); for (entity, id) in &pointers { map.inner.insert(*id, entity); } } /// Tracks the state of the pointer's buttons in response to [`PointerInput`] events. #[derive(Debug, Default, Clone, Component, Reflect, PartialEq, Eq)] #[reflect(Component, Default, Debug, PartialEq, Clone)] pub struct PointerPress { primary: bool, secondary: bool, middle: bool, } impl PointerPress { /// Returns true if the primary pointer button is pressed. #[inline] pub fn is_primary_pressed(&self) -> bool { self.primary } /// Returns true if the secondary pointer button is pressed. #[inline] pub fn is_secondary_pressed(&self) -> bool { self.secondary } /// Returns true if the middle (tertiary) pointer button is pressed. #[inline] pub fn is_middle_pressed(&self) -> bool { self.middle } /// Returns true if any pointer button is pressed. #[inline] pub fn is_any_pressed(&self) -> bool { self.primary || self.middle || self.secondary } } /// The stage of the pointer button press event #[derive(Debug, Clone, Copy, PartialEq, Eq, Reflect)] #[reflect(Clone, PartialEq)] pub enum PressDirection { /// The pointer button was just pressed Pressed, /// The pointer button was just released Released, } /// The button that was just pressed or released #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect)] #[reflect(Clone, PartialEq)] pub enum PointerButton { /// The primary pointer button Primary, /// The secondary pointer button Secondary, /// The tertiary pointer button Middle, } impl PointerButton { /// Iterator over all buttons that a pointer can have. pub fn iter() -> impl Iterator<Item = PointerButton> { [Self::Primary, Self::Secondary, Self::Middle].into_iter() } } /// Component that tracks a pointer's current [`Location`]. #[derive(Debug, Default, Clone, Component, Reflect, PartialEq)] #[reflect(Component, Default, Debug, PartialEq, Clone)] pub struct PointerLocation { /// The [`Location`] of the pointer. Note that a location is both the target, and the position /// on the target. #[reflect(ignore, clone)] pub location: Option<Location>, } impl PointerLocation { ///Returns a [`PointerLocation`] associated with the given location pub fn new(location: Location) -> Self { Self { location: Some(location), } } /// Returns `Some(&`[`Location`]`)` if the pointer is active, or `None` if the pointer is /// inactive. pub fn location(&self) -> Option<&Location> { self.location.as_ref() } } /// The location of a pointer, including the current [`NormalizedRenderTarget`], and the x/y /// position of the pointer on this render target. /// /// Note that: /// - a pointer can move freely between render targets /// - a pointer is not associated with a [`Camera`] because multiple cameras can target the same /// render target. It is up to picking backends to associate a Pointer's `Location` with a /// specific `Camera`, if any. #[derive(Debug, Clone, Reflect, PartialEq)] #[reflect(Debug, PartialEq, Clone)] pub struct Location { /// The [`NormalizedRenderTarget`] associated with the pointer, usually a window. pub target: NormalizedRenderTarget, /// The position of the pointer in the `target`. pub position: Vec2, } impl Location { /// Returns `true` if this pointer's [`Location`] is within the [`Camera`]'s viewport. /// /// Note this returns `false` if the location and camera have different render targets. #[inline] pub fn is_in_viewport( &self, camera: &Camera, render_target: &RenderTarget, primary_window: &Query<Entity, With<PrimaryWindow>>, ) -> bool { if render_target .normalize(Some(match primary_window.single() { Ok(w) => w, Err(_) => return false, })) .as_ref() != Some(&self.target) { return false; } camera .logical_viewport_rect() .is_some_and(|rect| rect.contains(self.position)) } } /// Event sent to drive a pointer. #[derive(Debug, Clone, Copy, Reflect)] #[reflect(Clone)] pub enum PointerAction { /// Causes the pointer to press a button. Press(PointerButton), /// Causes the pointer to release a button. Release(PointerButton), /// Move the pointer. Move { /// How much the pointer moved from the previous position. delta: Vec2, }, /// Scroll the pointer Scroll { /// The mouse scroll unit. unit: MouseScrollUnit, /// The horizontal scroll value. x: f32, /// The vertical scroll value. y: f32, }, /// Cancel the pointer. Often used for touch events. Cancel, } /// An input event effecting a pointer. #[derive(Message, Debug, Clone, Reflect)] #[reflect(Clone)] pub struct PointerInput { /// The id of the pointer. pub pointer_id: PointerId, /// The location of the pointer. For [`PointerAction::Move`], this is the location after the movement. pub location: Location, /// The action that the event describes. pub action: PointerAction, } impl PointerInput { /// Creates a new pointer input event. /// /// Note that `location` refers to the position of the pointer *after* the event occurred. pub fn new(pointer_id: PointerId, location: Location, action: PointerAction) -> PointerInput { PointerInput { pointer_id, location, action, } } /// Returns true if the `target_button` of this pointer was just pressed. #[inline] pub fn button_just_pressed(&self, target_button: PointerButton) -> bool { if let PointerAction::Press(button) = self.action { button == target_button } else { false } } /// Returns true if the `target_button` of this pointer was just released. #[inline] pub fn button_just_released(&self, target_button: PointerButton) -> bool { if let PointerAction::Release(button) = self.action { button == target_button } else { false } } /// Updates pointer entities according to the input events. pub fn receive( mut events: MessageReader<PointerInput>, mut pointers: Query<(&PointerId, &mut PointerLocation, &mut PointerPress)>, ) { for event in events.read() { match event.action { PointerAction::Press(button) => { pointers .iter_mut() .for_each(|(pointer_id, _, mut pointer)| { if *pointer_id == event.pointer_id { match button { PointerButton::Primary => pointer.primary = true, PointerButton::Secondary => pointer.secondary = true, PointerButton::Middle => pointer.middle = true, } } }); } PointerAction::Release(button) => { pointers .iter_mut() .for_each(|(pointer_id, _, mut pointer)| { if *pointer_id == event.pointer_id { match button { PointerButton::Primary => pointer.primary = false, PointerButton::Secondary => pointer.secondary = false, PointerButton::Middle => pointer.middle = false, } } }); } PointerAction::Move { .. } => { pointers.iter_mut().for_each(|(id, mut pointer, _)| { if *id == event.pointer_id { pointer.location = Some(event.location.to_owned()); } }); } _ => {} } } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_picking/src/input.rs
crates/bevy_picking/src/input.rs
//! This module provides unsurprising default inputs to `bevy_picking` through [`PointerInput`]. //! The included systems are responsible for sending mouse and touch inputs to their //! respective `Pointer`s. //! //! Because this has it's own plugin, it's easy to omit it, and provide your own inputs as //! needed. Because `Pointer`s aren't coupled to the underlying input hardware, you can easily mock //! inputs, and allow users full accessibility to map whatever inputs they need to pointer input. //! //! If, for example, you wanted to add support for VR input, all you need to do is spawn a pointer //! entity with a custom [`PointerId`], and write a system //! that updates its position. If you want this to work properly with the existing interaction events, //! you need to be sure that you also write a [`PointerInput`] event stream. use bevy_app::prelude::*; use bevy_camera::RenderTarget; use bevy_ecs::prelude::*; use bevy_input::{ mouse::MouseWheel, prelude::*, touch::{TouchInput, TouchPhase}, ButtonState, }; use bevy_math::Vec2; use bevy_platform::collections::{HashMap, HashSet}; use bevy_reflect::prelude::*; use bevy_window::{PrimaryWindow, WindowEvent, WindowRef}; use tracing::debug; use crate::pointer::{ Location, PointerAction, PointerButton, PointerId, PointerInput, PointerLocation, }; use crate::PickingSystems; /// The picking input prelude. /// /// This includes the most common types in this module, re-exported for your convenience. pub mod prelude { pub use crate::input::PointerInputPlugin; } #[derive(Copy, Clone, Resource, Debug, Reflect)] #[reflect(Resource, Default, Clone)] /// Settings for enabling and disabling updating mouse and touch inputs for picking /// /// ## Custom initialization /// ``` /// # use bevy_app::App; /// # use bevy_picking::input::{PointerInputSettings,PointerInputPlugin}; /// App::new() /// .insert_resource(PointerInputSettings { /// is_touch_enabled: false, /// is_mouse_enabled: true, /// }) /// // or DefaultPlugins /// .add_plugins(PointerInputPlugin); /// ``` pub struct PointerInputSettings { /// Should touch inputs be updated? pub is_touch_enabled: bool, /// Should mouse inputs be updated? pub is_mouse_enabled: bool, } impl PointerInputSettings { fn is_mouse_enabled(state: Res<Self>) -> bool { state.is_mouse_enabled } fn is_touch_enabled(state: Res<Self>) -> bool { state.is_touch_enabled } } impl Default for PointerInputSettings { fn default() -> Self { Self { is_touch_enabled: true, is_mouse_enabled: true, } } } /// Adds mouse and touch inputs for picking pointers to your app. This is a default input plugin, /// that you can replace with your own plugin as needed. /// /// Toggling mouse input or touch input can be done at runtime by modifying /// [`PointerInputSettings`] resource. /// /// [`PointerInputSettings`] can be initialized with custom values, but will be /// initialized with default values if it is not present at the moment this is /// added to the app. pub struct PointerInputPlugin; impl Plugin for PointerInputPlugin { fn build(&self, app: &mut App) { app.init_resource::<PointerInputSettings>() .add_systems(Startup, spawn_mouse_pointer) .add_systems( First, ( mouse_pick_events.run_if(PointerInputSettings::is_mouse_enabled), touch_pick_events.run_if(PointerInputSettings::is_touch_enabled), ) .chain() .in_set(PickingSystems::Input), ) .add_systems( Last, deactivate_touch_pointers.run_if(PointerInputSettings::is_touch_enabled), ); } } /// Spawns the default mouse pointer. pub fn spawn_mouse_pointer(mut commands: Commands) { commands.spawn(PointerId::Mouse); } /// Sends mouse pointer events to be processed by the core plugin pub fn mouse_pick_events( // Input mut window_events: MessageReader<WindowEvent>, primary_window: Query<Entity, With<PrimaryWindow>>, // Locals mut cursor_last: Local<Vec2>, // Output mut pointer_inputs: MessageWriter<PointerInput>, ) { for window_event in window_events.read() { match window_event { // Handle cursor movement events WindowEvent::CursorMoved(event) => { let location = Location { target: match RenderTarget::Window(WindowRef::Entity(event.window)) .normalize(primary_window.single().ok()) { Some(target) => target, None => continue, }, position: event.position, }; pointer_inputs.write(PointerInput::new( PointerId::Mouse, location, PointerAction::Move { delta: event.position - *cursor_last, }, )); *cursor_last = event.position; } // Handle mouse button press events WindowEvent::MouseButtonInput(input) => { let location = Location { target: match RenderTarget::Window(WindowRef::Entity(input.window)) .normalize(primary_window.single().ok()) { Some(target) => target, None => continue, }, position: *cursor_last, }; let button = match input.button { MouseButton::Left => PointerButton::Primary, MouseButton::Right => PointerButton::Secondary, MouseButton::Middle => PointerButton::Middle, MouseButton::Other(_) | MouseButton::Back | MouseButton::Forward => continue, }; let action = match input.state { ButtonState::Pressed => PointerAction::Press(button), ButtonState::Released => PointerAction::Release(button), }; pointer_inputs.write(PointerInput::new(PointerId::Mouse, location, action)); } WindowEvent::MouseWheel(event) => { let MouseWheel { unit, x, y, window } = *event; let location = Location { target: match RenderTarget::Window(WindowRef::Entity(window)) .normalize(primary_window.single().ok()) { Some(target) => target, None => continue, }, position: *cursor_last, }; let action = PointerAction::Scroll { x, y, unit }; pointer_inputs.write(PointerInput::new(PointerId::Mouse, location, action)); } _ => {} } } } /// Sends touch pointer events to be consumed by the core plugin pub fn touch_pick_events( // Input mut window_events: MessageReader<WindowEvent>, primary_window: Query<Entity, With<PrimaryWindow>>, // Locals mut touch_cache: Local<HashMap<u64, TouchInput>>, // Output mut commands: Commands, mut pointer_inputs: MessageWriter<PointerInput>, ) { for window_event in window_events.read() { if let WindowEvent::TouchInput(touch) = window_event { let pointer = PointerId::Touch(touch.id); let location = Location { target: match RenderTarget::Window(WindowRef::Entity(touch.window)) .normalize(primary_window.single().ok()) { Some(target) => target, None => continue, }, position: touch.position, }; match touch.phase { TouchPhase::Started => { debug!("Spawning pointer {:?}", pointer); commands.spawn((pointer, PointerLocation::new(location.clone()))); pointer_inputs.write(PointerInput::new( pointer, location, PointerAction::Press(PointerButton::Primary), )); touch_cache.insert(touch.id, *touch); } TouchPhase::Moved => { // Send a move event only if it isn't the same as the last one if let Some(last_touch) = touch_cache.get(&touch.id) { if last_touch == touch { continue; } pointer_inputs.write(PointerInput::new( pointer, location, PointerAction::Move { delta: touch.position - last_touch.position, }, )); } touch_cache.insert(touch.id, *touch); } TouchPhase::Ended => { pointer_inputs.write(PointerInput::new( pointer, location, PointerAction::Release(PointerButton::Primary), )); touch_cache.remove(&touch.id); } TouchPhase::Canceled => { pointer_inputs.write(PointerInput::new( pointer, location, PointerAction::Cancel, )); touch_cache.remove(&touch.id); } } } } } /// Deactivates unused touch pointers. /// /// Because each new touch gets assigned a new ID, we need to remove the pointers associated with /// touches that are no longer active. pub fn deactivate_touch_pointers( mut commands: Commands, mut despawn_list: Local<HashSet<(Entity, PointerId)>>, pointers: Query<(Entity, &PointerId)>, mut touches: MessageReader<TouchInput>, ) { for touch in touches.read() { if let TouchPhase::Ended | TouchPhase::Canceled = touch.phase { for (entity, pointer) in &pointers { if pointer.get_touch_id() == Some(touch.id) { despawn_list.insert((entity, *pointer)); } } } } // A hash set is used to prevent despawning the same entity twice. for (entity, pointer) in despawn_list.drain() { debug!("Despawning pointer {:?}", pointer); commands.entity(entity).despawn(); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_picking/src/mesh_picking/mod.rs
crates/bevy_picking/src/mesh_picking/mod.rs
//! A [mesh ray casting](ray_cast) backend for [`bevy_picking`](crate). //! //! By default, all meshes that have [`bevy_asset::RenderAssetUsages::MAIN_WORLD`] are pickable. //! Picking can be disabled for individual entities by adding [`Pickable::IGNORE`]. //! //! To make mesh picking entirely opt-in, set [`MeshPickingSettings::require_markers`] //! to `true` and add [`MeshPickingCamera`] and [`Pickable`] components to the desired camera and //! target entities. //! //! To manually perform mesh ray casts independent of picking, use the [`MeshRayCast`] system parameter. //! //! ## Implementation Notes //! //! - The `position` reported in `HitData` is in world space. The `normal` is a vector pointing //! away from the face, it is not guaranteed to be normalized for scaled meshes. pub mod ray_cast; use crate::{ backend::{ray::RayMap, HitData, PointerHits}, prelude::*, PickingSystems, }; use bevy_app::prelude::*; use bevy_camera::{visibility::RenderLayers, Camera}; use bevy_ecs::prelude::*; use bevy_reflect::prelude::*; use ray_cast::{MeshRayCast, MeshRayCastSettings, RayCastVisibility}; /// An optional component that marks cameras that should be used in the [`MeshPickingPlugin`]. /// /// Only needed if [`MeshPickingSettings::require_markers`] is set to `true`, and ignored otherwise. #[derive(Debug, Clone, Default, Component, Reflect)] #[reflect(Debug, Default, Component)] pub struct MeshPickingCamera; /// Runtime settings for the [`MeshPickingPlugin`]. #[derive(Resource, Reflect)] #[reflect(Resource, Default)] pub struct MeshPickingSettings { /// When set to `true` ray casting will only consider cameras marked with /// [`MeshPickingCamera`] and entities marked with [`Pickable`]. `false` by default. /// /// This setting is provided to give you fine-grained control over which cameras and entities /// should be used by the mesh picking backend at runtime. pub require_markers: bool, /// Determines how mesh picking should consider [`Visibility`](bevy_camera::visibility::Visibility). /// When set to [`RayCastVisibility::Any`], ray casts can be performed against both visible and hidden entities. /// /// Defaults to [`RayCastVisibility::VisibleInView`], only performing picking against visible entities /// that are in the view of a camera. pub ray_cast_visibility: RayCastVisibility, } impl Default for MeshPickingSettings { fn default() -> Self { Self { require_markers: false, ray_cast_visibility: RayCastVisibility::VisibleInView, } } } /// Adds the mesh picking backend to your app. #[derive(Clone, Default)] pub struct MeshPickingPlugin; impl Plugin for MeshPickingPlugin { fn build(&self, app: &mut App) { app.init_resource::<MeshPickingSettings>() .add_systems(PreUpdate, update_hits.in_set(PickingSystems::Backend)); } } /// Casts rays into the scene using [`MeshPickingSettings`] and sends [`PointerHits`] events. pub fn update_hits( backend_settings: Res<MeshPickingSettings>, ray_map: Res<RayMap>, picking_cameras: Query<(&Camera, Has<MeshPickingCamera>, Option<&RenderLayers>)>, pickables: Query<&Pickable>, marked_targets: Query<&Pickable>, layers: Query<&RenderLayers>, mut ray_cast: MeshRayCast, mut pointer_hits_writer: MessageWriter<PointerHits>, ) { for (&ray_id, &ray) in ray_map.iter() { let Ok((camera, cam_can_pick, cam_layers)) = picking_cameras.get(ray_id.camera) else { continue; }; if backend_settings.require_markers && !cam_can_pick { continue; } let cam_layers = cam_layers.to_owned().unwrap_or_default(); let settings = MeshRayCastSettings { visibility: backend_settings.ray_cast_visibility, filter: &|entity| { let marker_requirement = !backend_settings.require_markers || marked_targets.get(entity).is_ok(); // Other entities missing render layers are on the default layer 0 let entity_layers = layers.get(entity).cloned().unwrap_or_default(); let render_layers_match = cam_layers.intersects(&entity_layers); let is_pickable = pickables.get(entity).ok().is_none_or(|p| p.is_hoverable); marker_requirement && render_layers_match && is_pickable }, early_exit_test: &|entity_hit| { pickables .get(entity_hit) .is_ok_and(|pickable| pickable.should_block_lower) }, }; let picks = ray_cast .cast_ray(ray, &settings) .iter() .map(|(entity, hit)| { let hit_data = HitData::new( ray_id.camera, hit.distance, Some(hit.point), Some(hit.normal), ); (*entity, hit_data) }) .collect::<Vec<_>>(); let order = camera.order as f32; if !picks.is_empty() { pointer_hits_writer.write(PointerHits::new(ray_id.pointer, picks, order)); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_picking/src/mesh_picking/ray_cast/mod.rs
crates/bevy_picking/src/mesh_picking/ray_cast/mod.rs
//! Ray casting for meshes. //! //! See the [`MeshRayCast`] system parameter for more information. mod intersections; use bevy_derive::{Deref, DerefMut}; use bevy_camera::{ primitives::Aabb, visibility::{InheritedVisibility, ViewVisibility}, }; use bevy_math::{bounding::Aabb3d, Ray3d}; use bevy_mesh::{Mesh, Mesh2d, Mesh3d}; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use intersections::*; pub use intersections::{ray_aabb_intersection_3d, ray_mesh_intersection, RayMeshHit}; use bevy_asset::{Assets, Handle}; use bevy_ecs::{prelude::*, system::lifetimeless::Read, system::SystemParam}; use bevy_math::FloatOrd; use bevy_transform::components::GlobalTransform; use tracing::*; /// How a ray cast should handle [`Visibility`](bevy_camera::visibility::Visibility). #[derive(Clone, Copy, Reflect)] #[reflect(Clone)] pub enum RayCastVisibility { /// Completely ignore visibility checks. Hidden items can still be ray cast against. Any, /// Only cast rays against entities that are visible in the hierarchy. See [`Visibility`](bevy_camera::visibility::Visibility). Visible, /// Only cast rays against entities that are visible in the hierarchy and visible to a camera or /// light. See [`Visibility`](bevy_camera::visibility::Visibility). VisibleInView, } /// Settings for a ray cast. #[derive(Clone)] pub struct MeshRayCastSettings<'a> { /// Determines how ray casting should consider [`Visibility`](bevy_camera::visibility::Visibility). pub visibility: RayCastVisibility, /// A predicate that is applied for every entity that ray casts are performed against. /// Only entities that return `true` will be considered. pub filter: &'a dyn Fn(Entity) -> bool, /// A function that is run every time a hit is found. Ray casting will continue to check for hits /// along the ray as long as this returns `false`. pub early_exit_test: &'a dyn Fn(Entity) -> bool, } impl<'a> MeshRayCastSettings<'a> { /// Set the filter to apply to the ray cast. pub fn with_filter(mut self, filter: &'a impl Fn(Entity) -> bool) -> Self { self.filter = filter; self } /// Set the early exit test to apply to the ray cast. pub fn with_early_exit_test(mut self, early_exit_test: &'a impl Fn(Entity) -> bool) -> Self { self.early_exit_test = early_exit_test; self } /// Set the [`RayCastVisibility`] setting to apply to the ray cast. pub fn with_visibility(mut self, visibility: RayCastVisibility) -> Self { self.visibility = visibility; self } /// This ray cast should exit as soon as the nearest hit is found. pub fn always_early_exit(self) -> Self { self.with_early_exit_test(&|_| true) } /// This ray cast should check all entities whose AABB intersects the ray and return all hits. pub fn never_early_exit(self) -> Self { self.with_early_exit_test(&|_| false) } } impl<'a> Default for MeshRayCastSettings<'a> { fn default() -> Self { Self { visibility: RayCastVisibility::VisibleInView, filter: &|_| true, early_exit_test: &|_| true, } } } /// Determines whether backfaces should be culled or included in ray intersection tests. /// /// By default, backfaces are culled. #[derive(Copy, Clone, Default, Reflect)] #[reflect(Default, Clone)] pub enum Backfaces { /// Cull backfaces. #[default] Cull, /// Include backfaces. Include, } /// Disables backface culling for [ray casts](MeshRayCast) on this entity. #[derive(Component, Copy, Clone, Default, Reflect)] #[reflect(Component, Default, Clone)] pub struct RayCastBackfaces; /// A simplified mesh component that can be used for [ray casting](super::MeshRayCast). /// /// Consider using this component for complex meshes that don't need perfectly accurate ray casting. #[derive(Component, Clone, Debug, Deref, DerefMut, Reflect)] #[reflect(Component, Debug, Clone)] pub struct SimplifiedMesh(pub Handle<Mesh>); type MeshFilter = Or<(With<Mesh3d>, With<Mesh2d>, With<SimplifiedMesh>)>; /// Add this ray casting [`SystemParam`] to your system to cast rays into the world with an /// immediate-mode API. Call `cast_ray` to immediately perform a ray cast and get a result. /// /// Under the hood, this is a collection of regular bevy queries, resources, and local parameters /// that are added to your system. /// /// ## Usage /// /// The following system casts a ray into the world with the ray positioned at the origin, pointing in /// the X-direction, and returns a list of intersections: /// /// ``` /// # use bevy_math::prelude::*; /// # use bevy_picking::prelude::*; /// fn ray_cast_system(mut ray_cast: MeshRayCast) { /// let ray = Ray3d::new(Vec3::ZERO, Dir3::X); /// let hits = ray_cast.cast_ray(ray, &MeshRayCastSettings::default()); /// } /// ``` /// /// ## Configuration /// /// You can specify the behavior of the ray cast using [`MeshRayCastSettings`]. This allows you to filter out /// entities, configure early-out behavior, and set whether the [`Visibility`](bevy_camera::visibility::Visibility) /// of an entity should be considered. /// /// ``` /// # use bevy_ecs::prelude::*; /// # use bevy_math::prelude::*; /// # use bevy_picking::prelude::*; /// # #[derive(Component)] /// # struct Foo; /// fn ray_cast_system(mut ray_cast: MeshRayCast, foo_query: Query<(), With<Foo>>) { /// let ray = Ray3d::new(Vec3::ZERO, Dir3::X); /// /// // Only ray cast against entities with the `Foo` component. /// let filter = |entity| foo_query.contains(entity); /// /// // Never early-exit. Note that you can change behavior per-entity. /// let early_exit_test = |_entity| false; /// /// // Ignore the visibility of entities. This allows ray casting hidden entities. /// let visibility = RayCastVisibility::Any; /// /// let settings = MeshRayCastSettings::default() /// .with_filter(&filter) /// .with_early_exit_test(&early_exit_test) /// .with_visibility(visibility); /// /// // Cast the ray with the settings, returning a list of intersections. /// let hits = ray_cast.cast_ray(ray, &settings); /// } /// ``` #[derive(SystemParam)] pub struct MeshRayCast<'w, 's> { #[doc(hidden)] pub meshes: Res<'w, Assets<Mesh>>, #[doc(hidden)] pub hits: Local<'s, Vec<(FloatOrd, (Entity, RayMeshHit))>>, #[doc(hidden)] pub output: Local<'s, Vec<(Entity, RayMeshHit)>>, #[doc(hidden)] pub culled_list: Local<'s, Vec<(FloatOrd, Entity)>>, #[doc(hidden)] pub culling_query: Query< 'w, 's, ( Read<InheritedVisibility>, Read<ViewVisibility>, Read<Aabb>, Read<GlobalTransform>, Entity, ), MeshFilter, >, #[doc(hidden)] pub mesh_query: Query< 'w, 's, ( Option<Read<Mesh2d>>, Option<Read<Mesh3d>>, Option<Read<SimplifiedMesh>>, Has<RayCastBackfaces>, Read<GlobalTransform>, ), MeshFilter, >, } impl<'w, 's> MeshRayCast<'w, 's> { /// Casts the `ray` into the world and returns a sorted list of intersections, nearest first. pub fn cast_ray( &mut self, ray: Ray3d, settings: &MeshRayCastSettings, ) -> &[(Entity, RayMeshHit)] { let ray_cull = info_span!("ray culling"); let ray_cull_guard = ray_cull.enter(); self.hits.clear(); self.culled_list.clear(); self.output.clear(); // Check all entities to see if the ray intersects the AABB. Use this to build a short list // of entities that are in the path of the ray. let (aabb_hits_tx, aabb_hits_rx) = crossbeam_channel::unbounded::<(FloatOrd, Entity)>(); let visibility_setting = settings.visibility; self.culling_query.par_iter().for_each( |(inherited_visibility, view_visibility, aabb, transform, entity)| { let should_ray_cast = match visibility_setting { RayCastVisibility::Any => true, RayCastVisibility::Visible => inherited_visibility.get(), RayCastVisibility::VisibleInView => view_visibility.get(), }; if should_ray_cast && let Some(distance) = ray_aabb_intersection_3d( ray, &Aabb3d::new(aabb.center, aabb.half_extents), &transform.affine(), ) { aabb_hits_tx.send((FloatOrd(distance), entity)).ok(); } }, ); *self.culled_list = aabb_hits_rx.try_iter().collect(); // Sort by the distance along the ray. self.culled_list.sort_by_key(|(aabb_near, _)| *aabb_near); drop(ray_cull_guard); // Perform ray casts against the culled entities. let mut nearest_blocking_hit = FloatOrd(f32::INFINITY); let ray_cast_guard = debug_span!("ray_cast"); self.culled_list .iter() .filter(|(_, entity)| (settings.filter)(*entity)) .for_each(|(aabb_near, entity)| { // Get the mesh components and transform. let Ok((mesh2d, mesh3d, simplified_mesh, has_backfaces, transform)) = self.mesh_query.get(*entity) else { return; }; // Get the underlying mesh handle. One of these will always be `Some` because of the query filters. let Some(mesh_handle) = simplified_mesh .map(|m| &m.0) .or(mesh3d.map(|m| &m.0).or(mesh2d.map(|m| &m.0))) else { return; }; // Is it even possible the mesh could be closer than the current best? if *aabb_near > nearest_blocking_hit { return; } // Does the mesh handle resolve? let Some(mesh) = self.meshes.get(mesh_handle) else { return; }; // Backfaces of 2d meshes are never culled, unlike 3d meshes. let backfaces = match (has_backfaces, mesh2d.is_some()) { (false, false) => Backfaces::Cull, _ => Backfaces::Include, }; // Perform the actual ray cast. let _ray_cast_guard = ray_cast_guard.enter(); let transform = transform.affine(); let intersection = ray_intersection_over_mesh(mesh, &transform, ray, backfaces); if let Some(intersection) = intersection { let distance = FloatOrd(intersection.distance); if (settings.early_exit_test)(*entity) && distance < nearest_blocking_hit { // The reason we don't just return here is because right now we are // going through the AABBs in order, but that doesn't mean that an // AABB that starts further away can't end up with a closer hit than // an AABB that starts closer. We need to keep checking AABBs that // could possibly contain a nearer hit. nearest_blocking_hit = distance.min(nearest_blocking_hit); } self.hits.push((distance, (*entity, intersection))); }; }); self.hits.retain(|(dist, _)| *dist <= nearest_blocking_hit); self.hits.sort_by_key(|(k, _)| *k); let hits = self.hits.iter().map(|(_, (e, i))| (*e, i.to_owned())); self.output.extend(hits); self.output.as_ref() } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_picking/src/mesh_picking/ray_cast/intersections.rs
crates/bevy_picking/src/mesh_picking/ray_cast/intersections.rs
use bevy_math::{bounding::Aabb3d, Affine3A, Dir3, Ray3d, Vec2, Vec3, Vec3A}; use bevy_mesh::{Indices, Mesh, PrimitiveTopology, VertexAttributeValues}; use bevy_reflect::Reflect; use super::Backfaces; /// Hit data for an intersection between a ray and a mesh. #[derive(Debug, Clone, Reflect)] #[reflect(Clone)] pub struct RayMeshHit { /// The point of intersection in world space. pub point: Vec3, /// The normal vector of the triangle at the point of intersection. Not guaranteed to be normalized for scaled meshes. pub normal: Vec3, /// The barycentric coordinates of the intersection. pub barycentric_coords: Vec3, /// The distance from the ray origin to the intersection point. pub distance: f32, /// The vertices of the triangle that was hit. pub triangle: Option<[Vec3; 3]>, /// UV coordinate of the hit, if the mesh has UV attributes. pub uv: Option<Vec2>, /// The index of the triangle that was hit. pub triangle_index: Option<usize>, } /// Hit data for an intersection between a ray and a triangle. #[derive(Default, Debug)] pub struct RayTriangleHit { pub distance: f32, /// Note this uses the convention from the Moller-Trumbore algorithm: /// P = (1 - u - v)A + uB + vC /// This is different from the more common convention of /// P = uA + vB + (1 - u - v)C pub barycentric_coords: (f32, f32), } /// Casts a ray on a mesh, and returns the intersection. pub(super) fn ray_intersection_over_mesh( mesh: &Mesh, transform: &Affine3A, ray: Ray3d, cull: Backfaces, ) -> Option<RayMeshHit> { if mesh.primitive_topology() != PrimitiveTopology::TriangleList { return None; // ray_mesh_intersection assumes vertices are laid out in a triangle list } // Vertex positions are required let positions = mesh.attribute(Mesh::ATTRIBUTE_POSITION)?.as_float3()?; // Normals are optional let normals = mesh .attribute(Mesh::ATTRIBUTE_NORMAL) .and_then(|normal_values| normal_values.as_float3()); let uvs = mesh .attribute(Mesh::ATTRIBUTE_UV_0) .and_then(|uvs| match uvs { VertexAttributeValues::Float32x2(uvs) => Some(uvs.as_slice()), _ => None, }); match mesh.indices() { Some(Indices::U16(indices)) => { ray_mesh_intersection(ray, transform, positions, normals, Some(indices), uvs, cull) } Some(Indices::U32(indices)) => { ray_mesh_intersection(ray, transform, positions, normals, Some(indices), uvs, cull) } None => ray_mesh_intersection::<u32>(ray, transform, positions, normals, None, uvs, cull), } } /// Checks if a ray intersects a mesh, and returns the nearest intersection if one exists. pub fn ray_mesh_intersection<I>( ray: Ray3d, mesh_transform: &Affine3A, positions: &[[f32; 3]], vertex_normals: Option<&[[f32; 3]]>, indices: Option<&[I]>, uvs: Option<&[[f32; 2]]>, backface_culling: Backfaces, ) -> Option<RayMeshHit> where I: TryInto<usize> + Clone + Copy, { let world_to_mesh = mesh_transform.inverse(); let ray = Ray3d::new( world_to_mesh.transform_point3(ray.origin), Dir3::new(world_to_mesh.transform_vector3(*ray.direction)).ok()?, ); let closest_hit = if let Some(indices) = indices { // The index list must be a multiple of three. If not, the mesh is malformed and the raycast // result might be nonsensical. if indices.len() % 3 != 0 { return None; } indices .chunks_exact(3) .enumerate() .fold( (f32::MAX, None), |(closest_distance, closest_hit), (tri_idx, triangle)| { let [Ok(a), Ok(b), Ok(c)] = [ triangle[0].try_into(), triangle[1].try_into(), triangle[2].try_into(), ] else { return (closest_distance, closest_hit); }; let tri_vertices = match [positions.get(a), positions.get(b), positions.get(c)] { [Some(a), Some(b), Some(c)] => { [Vec3::from(*a), Vec3::from(*b), Vec3::from(*c)] } _ => return (closest_distance, closest_hit), }; match ray_triangle_intersection(&ray, &tri_vertices, backface_culling) { Some(hit) if hit.distance >= 0. && hit.distance < closest_distance => { (hit.distance, Some((tri_idx, hit))) } _ => (closest_distance, closest_hit), } }, ) .1 } else { positions .chunks_exact(3) .enumerate() .fold( (f32::MAX, None), |(closest_distance, closest_hit), (tri_idx, triangle)| { let tri_vertices = [ Vec3::from(triangle[0]), Vec3::from(triangle[1]), Vec3::from(triangle[2]), ]; match ray_triangle_intersection(&ray, &tri_vertices, backface_culling) { Some(hit) if hit.distance >= 0. && hit.distance < closest_distance => { (hit.distance, Some((tri_idx, hit))) } _ => (closest_distance, closest_hit), } }, ) .1 }; closest_hit.and_then(|(tri_idx, hit)| { let [a, b, c] = match indices { Some(indices) => { let [i, j, k] = [tri_idx * 3, tri_idx * 3 + 1, tri_idx * 3 + 2]; [ indices.get(i).copied()?.try_into().ok()?, indices.get(j).copied()?.try_into().ok()?, indices.get(k).copied()?.try_into().ok()?, ] } None => [tri_idx * 3, tri_idx * 3 + 1, tri_idx * 3 + 2], }; let tri_vertices = match [positions.get(a), positions.get(b), positions.get(c)] { [Some(a), Some(b), Some(c)] => [Vec3::from(*a), Vec3::from(*b), Vec3::from(*c)], _ => return None, }; let tri_normals = vertex_normals.and_then(|normals| { let [Some(a), Some(b), Some(c)] = [normals.get(a), normals.get(b), normals.get(c)] else { return None; }; Some([Vec3::from(*a), Vec3::from(*b), Vec3::from(*c)]) }); let point = ray.get_point(hit.distance); // Note that we need to convert from the Möller-Trumbore convention to the more common // P = uA + vB + (1 - u - v)C convention. let u = hit.barycentric_coords.0; let v = hit.barycentric_coords.1; let w = 1.0 - u - v; let barycentric = Vec3::new(w, u, v); let normal = if let Some(normals) = tri_normals { normals[1] * u + normals[2] * v + normals[0] * w } else { (tri_vertices[1] - tri_vertices[0]) .cross(tri_vertices[2] - tri_vertices[0]) .normalize() }; let uv = uvs.and_then(|uvs| { let tri_uvs = if let Some(indices) = indices { let i = tri_idx * 3; [ uvs[indices[i].try_into().ok()?], uvs[indices[i + 1].try_into().ok()?], uvs[indices[i + 2].try_into().ok()?], ] } else { let i = tri_idx * 3; [uvs[i], uvs[i + 1], uvs[i + 2]] }; Some( barycentric.x * Vec2::from(tri_uvs[0]) + barycentric.y * Vec2::from(tri_uvs[1]) + barycentric.z * Vec2::from(tri_uvs[2]), ) }); Some(RayMeshHit { point: mesh_transform.transform_point3(point), normal: mesh_transform.transform_vector3(normal), uv, barycentric_coords: barycentric, distance: mesh_transform .transform_vector3(ray.direction * hit.distance) .length(), triangle: Some(tri_vertices.map(|v| mesh_transform.transform_point3(v))), triangle_index: Some(tri_idx), }) }) } /// Takes a ray and triangle and computes the intersection. #[inline] fn ray_triangle_intersection( ray: &Ray3d, triangle: &[Vec3; 3], backface_culling: Backfaces, ) -> Option<RayTriangleHit> { // Source: https://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/moller-trumbore-ray-triangle-intersection let vector_v0_to_v1: Vec3 = triangle[1] - triangle[0]; let vector_v0_to_v2: Vec3 = triangle[2] - triangle[0]; let p_vec: Vec3 = ray.direction.cross(vector_v0_to_v2); let determinant: f32 = vector_v0_to_v1.dot(p_vec); match backface_culling { Backfaces::Cull => { // if the determinant is negative the triangle is back facing // if the determinant is close to 0, the ray misses the triangle // This test checks both cases if determinant < f32::EPSILON { return None; } } Backfaces::Include => { // ray and triangle are parallel if det is close to 0 if determinant.abs() < f32::EPSILON { return None; } } } let determinant_inverse = 1.0 / determinant; let t_vec = ray.origin - triangle[0]; let u = t_vec.dot(p_vec) * determinant_inverse; if !(0.0..=1.0).contains(&u) { return None; } let q_vec = t_vec.cross(vector_v0_to_v1); let v = (*ray.direction).dot(q_vec) * determinant_inverse; if v < 0.0 || u + v > 1.0 { return None; } // The distance between ray origin and intersection is t. let t: f32 = vector_v0_to_v2.dot(q_vec) * determinant_inverse; Some(RayTriangleHit { distance: t, barycentric_coords: (u, v), }) } // TODO: It'd be nice to reuse `RayCast3d::aabb_intersection_at`, but it assumes a normalized ray. // In our case, the ray is transformed to model space, which could involve scaling. /// Checks if the ray intersects with the AABB of a mesh, returning the distance to the point of intersection. /// The distance is zero if the ray starts inside the AABB. pub fn ray_aabb_intersection_3d( ray: Ray3d, aabb: &Aabb3d, model_to_world: &Affine3A, ) -> Option<f32> { // Transform the ray to model space let world_to_model = model_to_world.inverse(); let ray_direction: Vec3A = world_to_model.transform_vector3a((*ray.direction).into()); let ray_direction_recip = ray_direction.recip(); let ray_origin: Vec3A = world_to_model.transform_point3a(ray.origin.into()); // Check if the ray intersects the mesh's AABB. It's useful to work in model space // because we can do an AABB intersection test, instead of an OBB intersection test. // NOTE: This is largely copied from `RayCast3d::aabb_intersection_at`. let positive = ray_direction.signum().cmpgt(Vec3A::ZERO); let min = Vec3A::select(positive, aabb.min, aabb.max); let max = Vec3A::select(positive, aabb.max, aabb.min); // 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; // 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(); if tmin <= tmax { Some(tmin) } else { None } } #[cfg(test)] mod tests { use bevy_math::Vec3; use bevy_transform::components::GlobalTransform; use super::*; // Triangle vertices to be used in a left-hand coordinate system const V0: [f32; 3] = [1.0, -1.0, 2.0]; const V1: [f32; 3] = [1.0, 2.0, -1.0]; const V2: [f32; 3] = [1.0, -1.0, -1.0]; #[test] fn ray_cast_triangle_mt() { let triangle = [V0.into(), V1.into(), V2.into()]; let ray = Ray3d::new(Vec3::ZERO, Dir3::X); let result = ray_triangle_intersection(&ray, &triangle, Backfaces::Include); assert!(result.unwrap().distance - 1.0 <= f32::EPSILON); } #[test] fn ray_cast_triangle_mt_culling() { let triangle = [V2.into(), V1.into(), V0.into()]; let ray = Ray3d::new(Vec3::ZERO, Dir3::X); let result = ray_triangle_intersection(&ray, &triangle, Backfaces::Cull); assert!(result.is_none()); } #[test] fn ray_mesh_intersection_simple() { let ray = Ray3d::new(Vec3::ZERO, Dir3::X); let mesh_transform = GlobalTransform::IDENTITY.affine(); let positions = &[V0, V1, V2]; let vertex_normals = None; let indices: Option<&[u16]> = None; let backface_culling = Backfaces::Cull; let result = ray_mesh_intersection( ray, &mesh_transform, positions, vertex_normals, indices, None, backface_culling, ); assert!(result.is_some()); } #[test] fn ray_mesh_intersection_indices() { let ray = Ray3d::new(Vec3::ZERO, Dir3::X); let mesh_transform = GlobalTransform::IDENTITY.affine(); let positions = &[V0, V1, V2]; let vertex_normals = None; let indices: Option<&[u16]> = Some(&[0, 1, 2]); let backface_culling = Backfaces::Cull; let result = ray_mesh_intersection( ray, &mesh_transform, positions, vertex_normals, indices, None, backface_culling, ); assert!(result.is_some()); } #[test] fn ray_mesh_intersection_indices_vertex_normals() { let ray = Ray3d::new(Vec3::ZERO, Dir3::X); let mesh_transform = GlobalTransform::IDENTITY.affine(); let positions = &[V0, V1, V2]; let vertex_normals: Option<&[[f32; 3]]> = Some(&[[-1., 0., 0.], [-1., 0., 0.], [-1., 0., 0.]]); let indices: Option<&[u16]> = Some(&[0, 1, 2]); let backface_culling = Backfaces::Cull; let result = ray_mesh_intersection( ray, &mesh_transform, positions, vertex_normals, indices, None, backface_culling, ); assert!(result.is_some()); } #[test] fn ray_mesh_intersection_vertex_normals() { let ray = Ray3d::new(Vec3::ZERO, Dir3::X); let mesh_transform = GlobalTransform::IDENTITY.affine(); let positions = &[V0, V1, V2]; let vertex_normals: Option<&[[f32; 3]]> = Some(&[[-1., 0., 0.], [-1., 0., 0.], [-1., 0., 0.]]); let indices: Option<&[u16]> = None; let backface_culling = Backfaces::Cull; let result = ray_mesh_intersection( ray, &mesh_transform, positions, vertex_normals, indices, None, backface_culling, ); assert!(result.is_some()); } #[test] fn ray_mesh_intersection_missing_vertex_normals() { let ray = Ray3d::new(Vec3::ZERO, Dir3::X); let mesh_transform = GlobalTransform::IDENTITY.affine(); let positions = &[V0, V1, V2]; let vertex_normals: Option<&[[f32; 3]]> = Some(&[]); let indices: Option<&[u16]> = None; let backface_culling = Backfaces::Cull; let result = ray_mesh_intersection( ray, &mesh_transform, positions, vertex_normals, indices, None, backface_culling, ); assert!(result.is_some()); } #[test] fn ray_mesh_intersection_indices_missing_vertex_normals() { let ray = Ray3d::new(Vec3::ZERO, Dir3::X); let mesh_transform = GlobalTransform::IDENTITY.affine(); let positions = &[V0, V1, V2]; let vertex_normals: Option<&[[f32; 3]]> = Some(&[]); let indices: Option<&[u16]> = Some(&[0, 1, 2]); let backface_culling = Backfaces::Cull; let result = ray_mesh_intersection( ray, &mesh_transform, positions, vertex_normals, indices, None, backface_culling, ); assert!(result.is_some()); } #[test] fn ray_mesh_intersection_not_enough_indices() { let ray = Ray3d::new(Vec3::ZERO, Dir3::X); let mesh_transform = GlobalTransform::IDENTITY.affine(); let positions = &[V0, V1, V2]; let vertex_normals = None; let indices: Option<&[u16]> = Some(&[0]); let backface_culling = Backfaces::Cull; let result = ray_mesh_intersection( ray, &mesh_transform, positions, vertex_normals, indices, None, backface_culling, ); assert!(result.is_none()); } #[test] fn ray_mesh_intersection_bad_indices() { let ray = Ray3d::new(Vec3::ZERO, Dir3::X); let mesh_transform = GlobalTransform::IDENTITY.affine(); let positions = &[V0, V1, V2]; let vertex_normals = None; let indices: Option<&[u16]> = Some(&[0, 1, 3]); let backface_culling = Backfaces::Cull; let result = ray_mesh_intersection( ray, &mesh_transform, positions, vertex_normals, indices, None, backface_culling, ); assert!(result.is_none()); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_tasks/src/slice.rs
crates/bevy_tasks/src/slice.rs
use super::TaskPool; use alloc::vec::Vec; /// Provides functions for mapping read-only slices across a provided [`TaskPool`]. pub trait ParallelSlice<T: Sync>: AsRef<[T]> { /// Splits the slice in chunks of size `chunks_size` or less and maps the chunks /// in parallel across the provided `task_pool`. One task is spawned in the task pool /// for every chunk. /// /// The iteration function takes the index of the chunk in the original slice as the /// first argument, and the chunk as the second argument. /// /// Returns a `Vec` of the mapped results in the same order as the input. /// /// # Example /// /// ``` /// # use bevy_tasks::prelude::*; /// # use bevy_tasks::TaskPool; /// let task_pool = TaskPool::new(); /// let counts = (0..10000).collect::<Vec<u32>>(); /// let incremented = counts.par_chunk_map(&task_pool, 100, |_index, chunk| { /// let mut results = Vec::new(); /// for count in chunk { /// results.push(*count + 2); /// } /// results /// }); /// # let flattened: Vec<_> = incremented.into_iter().flatten().collect(); /// # assert_eq!(flattened, (2..10002).collect::<Vec<u32>>()); /// ``` /// /// # See Also /// /// - [`ParallelSliceMut::par_chunk_map_mut`] for mapping mutable slices. /// - [`ParallelSlice::par_splat_map`] for mapping when a specific chunk size is unknown. fn par_chunk_map<F, R>(&self, task_pool: &TaskPool, chunk_size: usize, f: F) -> Vec<R> where F: Fn(usize, &[T]) -> R + Send + Sync, R: Send + 'static, { let slice = self.as_ref(); let f = &f; task_pool.scope(|scope| { for (index, chunk) in slice.chunks(chunk_size).enumerate() { scope.spawn(async move { f(index, chunk) }); } }) } /// Splits the slice into a maximum of `max_tasks` chunks, and maps the chunks in parallel /// across the provided `task_pool`. One task is spawned in the task pool for every chunk. /// /// If `max_tasks` is `None`, this function will attempt to use one chunk per thread in /// `task_pool`. /// /// The iteration function takes the index of the chunk in the original slice as the /// first argument, and the chunk as the second argument. /// /// Returns a `Vec` of the mapped results in the same order as the input. /// /// # Example /// /// ``` /// # use bevy_tasks::prelude::*; /// # use bevy_tasks::TaskPool; /// let task_pool = TaskPool::new(); /// let counts = (0..10000).collect::<Vec<u32>>(); /// let incremented = counts.par_splat_map(&task_pool, None, |_index, chunk| { /// let mut results = Vec::new(); /// for count in chunk { /// results.push(*count + 2); /// } /// results /// }); /// # let flattened: Vec<_> = incremented.into_iter().flatten().collect(); /// # assert_eq!(flattened, (2..10002).collect::<Vec<u32>>()); /// ``` /// /// # See Also /// /// [`ParallelSliceMut::par_splat_map_mut`] for mapping mutable slices. /// [`ParallelSlice::par_chunk_map`] for mapping when a specific chunk size is desirable. fn par_splat_map<F, R>(&self, task_pool: &TaskPool, max_tasks: Option<usize>, f: F) -> Vec<R> where F: Fn(usize, &[T]) -> R + Send + Sync, R: Send + 'static, { let slice = self.as_ref(); let chunk_size = core::cmp::max( 1, core::cmp::max( slice.len() / task_pool.thread_num(), slice.len() / max_tasks.unwrap_or(usize::MAX), ), ); slice.par_chunk_map(task_pool, chunk_size, f) } } impl<S, T: Sync> ParallelSlice<T> for S where S: AsRef<[T]> {} /// Provides functions for mapping mutable slices across a provided [`TaskPool`]. pub trait ParallelSliceMut<T: Send>: AsMut<[T]> { /// Splits the slice in chunks of size `chunks_size` or less and maps the chunks /// in parallel across the provided `task_pool`. One task is spawned in the task pool /// for every chunk. /// /// The iteration function takes the index of the chunk in the original slice as the /// first argument, and the chunk as the second argument. /// /// Returns a `Vec` of the mapped results in the same order as the input. /// /// # Example /// /// ``` /// # use bevy_tasks::prelude::*; /// # use bevy_tasks::TaskPool; /// let task_pool = TaskPool::new(); /// let mut counts = (0..10000).collect::<Vec<u32>>(); /// let incremented = counts.par_chunk_map_mut(&task_pool, 100, |_index, chunk| { /// let mut results = Vec::new(); /// for count in chunk { /// *count += 5; /// results.push(*count - 2); /// } /// results /// }); /// /// assert_eq!(counts, (5..10005).collect::<Vec<u32>>()); /// # let flattened: Vec<_> = incremented.into_iter().flatten().collect(); /// # assert_eq!(flattened, (3..10003).collect::<Vec<u32>>()); /// ``` /// /// # See Also /// /// [`ParallelSlice::par_chunk_map`] for mapping immutable slices. /// [`ParallelSliceMut::par_splat_map_mut`] for mapping when a specific chunk size is unknown. fn par_chunk_map_mut<F, R>(&mut self, task_pool: &TaskPool, chunk_size: usize, f: F) -> Vec<R> where F: Fn(usize, &mut [T]) -> R + Send + Sync, R: Send + 'static, { let slice = self.as_mut(); let f = &f; task_pool.scope(|scope| { for (index, chunk) in slice.chunks_mut(chunk_size).enumerate() { scope.spawn(async move { f(index, chunk) }); } }) } /// Splits the slice into a maximum of `max_tasks` chunks, and maps the chunks in parallel /// across the provided `task_pool`. One task is spawned in the task pool for every chunk. /// /// If `max_tasks` is `None`, this function will attempt to use one chunk per thread in /// `task_pool`. /// /// The iteration function takes the index of the chunk in the original slice as the /// first argument, and the chunk as the second argument. /// /// Returns a `Vec` of the mapped results in the same order as the input. /// /// # Example /// /// ``` /// # use bevy_tasks::prelude::*; /// # use bevy_tasks::TaskPool; /// let task_pool = TaskPool::new(); /// let mut counts = (0..10000).collect::<Vec<u32>>(); /// let incremented = counts.par_splat_map_mut(&task_pool, None, |_index, chunk| { /// let mut results = Vec::new(); /// for count in chunk { /// *count += 5; /// results.push(*count - 2); /// } /// results /// }); /// /// assert_eq!(counts, (5..10005).collect::<Vec<u32>>()); /// # let flattened: Vec<_> = incremented.into_iter().flatten().collect::<Vec<u32>>(); /// # assert_eq!(flattened, (3..10003).collect::<Vec<u32>>()); /// ``` /// /// # See Also /// /// [`ParallelSlice::par_splat_map`] for mapping immutable slices. /// [`ParallelSliceMut::par_chunk_map_mut`] for mapping when a specific chunk size is desirable. fn par_splat_map_mut<F, R>( &mut self, task_pool: &TaskPool, max_tasks: Option<usize>, f: F, ) -> Vec<R> where F: Fn(usize, &mut [T]) -> R + Send + Sync, R: Send + 'static, { let mut slice = self.as_mut(); let chunk_size = core::cmp::max( 1, core::cmp::max( slice.len() / task_pool.thread_num(), slice.len() / max_tasks.unwrap_or(usize::MAX), ), ); slice.par_chunk_map_mut(task_pool, chunk_size, f) } } impl<S, T: Send> ParallelSliceMut<T> for S where S: AsMut<[T]> {} #[cfg(test)] mod tests { use crate::*; use alloc::vec; #[test] fn test_par_chunks_map() { let v = vec![42; 1000]; let task_pool = TaskPool::new(); let outputs = v.par_splat_map(&task_pool, None, |_, numbers| -> i32 { numbers.iter().sum() }); let mut sum = 0; for output in outputs { sum += output; } assert_eq!(sum, 1000 * 42); } #[test] fn test_par_chunks_map_mut() { let mut v = vec![42; 1000]; let task_pool = TaskPool::new(); let outputs = v.par_splat_map_mut(&task_pool, None, |_, numbers| -> i32 { for number in numbers.iter_mut() { *number *= 2; } numbers.iter().sum() }); let mut sum = 0; for output in outputs { sum += output; } assert_eq!(sum, 1000 * 42 * 2); assert_eq!(v[0], 84); } #[test] fn test_par_chunks_map_index() { let v = vec![1; 1000]; let task_pool = TaskPool::new(); let outputs = v.par_chunk_map(&task_pool, 100, |index, numbers| -> i32 { numbers.iter().sum::<i32>() * index as i32 }); assert_eq!(outputs.iter().sum::<i32>(), 100 * (9 * 10) / 2); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_tasks/src/lib.rs
crates/bevy_tasks/src/lib.rs
#![doc = include_str!("../README.md")] #![cfg_attr(docsrs, feature(doc_cfg))] #![doc( html_logo_url = "https://bevy.org/assets/icon.png", html_favicon_url = "https://bevy.org/assets/icon.png" )] #![no_std] /// Configuration information for this crate. pub mod cfg { pub(crate) use bevy_platform::cfg::*; pub use bevy_platform::cfg::{alloc, std, web}; define_alias! { #[cfg(feature = "async_executor")] => { /// Indicates `async_executor` is used as the future execution backend. async_executor } #[cfg(all(not(target_arch = "wasm32"), feature = "multi_threaded"))] => { /// Indicates multithreading support. multi_threaded } #[cfg(target_arch = "wasm32")] => { /// Indicates the current target requires additional `Send` bounds. conditional_send } #[cfg(feature = "async-io")] => { /// Indicates `async-io` will be used for the implementation of `block_on`. async_io } #[cfg(feature = "futures-lite")] => { /// Indicates `futures-lite` will be used for the implementation of `block_on`. futures_lite } } } cfg::std! { extern crate std; } extern crate alloc; cfg::conditional_send! { if { /// Use [`ConditionalSend`] to mark an optional Send trait bound. Useful as on certain platforms (eg. Wasm), /// futures aren't Send. pub trait ConditionalSend {} impl<T> ConditionalSend for T {} } else { /// Use [`ConditionalSend`] to mark an optional Send trait bound. Useful as on certain platforms (eg. Wasm), /// futures aren't Send. pub trait ConditionalSend: Send {} impl<T: Send> ConditionalSend for T {} } } /// Use [`ConditionalSendFuture`] for a future with an optional Send trait bound, as on certain platforms (eg. Wasm), /// futures aren't Send. pub trait ConditionalSendFuture: Future + ConditionalSend {} impl<T: Future + ConditionalSend> ConditionalSendFuture for T {} use alloc::boxed::Box; /// An owned and dynamically typed Future used when you can't statically type your result or need to add some indirection. pub type BoxedFuture<'a, T> = core::pin::Pin<Box<dyn ConditionalSendFuture<Output = T> + 'a>>; // Modules mod executor; pub mod futures; mod iter; mod slice; mod task; mod usages; cfg::async_executor! { if {} else { mod edge_executor; } } // Exports pub use iter::ParallelIterator; pub use slice::{ParallelSlice, ParallelSliceMut}; pub use task::Task; pub use usages::{AsyncComputeTaskPool, ComputeTaskPool, IoTaskPool}; pub use futures_lite; pub use futures_lite::future::poll_once; cfg::web! { if {} else { pub use usages::tick_global_task_pools_on_main_thread; } } cfg::multi_threaded! { if { mod task_pool; mod thread_executor; pub use task_pool::{Scope, TaskPool, TaskPoolBuilder}; pub use thread_executor::{ThreadExecutor, ThreadExecutorTicker}; } else { mod single_threaded_task_pool; pub use single_threaded_task_pool::{Scope, TaskPool, TaskPoolBuilder, ThreadExecutor}; } } cfg::switch! { cfg::async_io => { pub use async_io::block_on; } cfg::futures_lite => { pub use futures_lite::future::block_on; } _ => { /// Blocks on the supplied `future`. /// This implementation will busy-wait until it is completed. /// Consider enabling the `async-io` or `futures-lite` features. pub fn block_on<T>(future: impl Future<Output = T>) -> T { use core::task::{Poll, Context}; // Pin the future on the stack. let mut future = core::pin::pin!(future); // We don't care about the waker as we're just going to poll as fast as possible. let cx = &mut Context::from_waker(core::task::Waker::noop()); // Keep polling until the future is ready. loop { match future.as_mut().poll(cx) { Poll::Ready(output) => return output, Poll::Pending => core::hint::spin_loop(), } } } } } /// The tasks prelude. /// /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { #[doc(hidden)] pub use crate::{ block_on, iter::ParallelIterator, slice::{ParallelSlice, ParallelSliceMut}, usages::{AsyncComputeTaskPool, ComputeTaskPool, IoTaskPool}, }; } /// Gets the logical CPU core count available to the current process. /// /// This is identical to `std::thread::available_parallelism`, except /// it will return a default value of 1 if it internally errors out. /// /// This will always return at least 1. pub fn available_parallelism() -> usize { cfg::switch! {{ cfg::std => { std::thread::available_parallelism() .map(core::num::NonZero::<usize>::get) .unwrap_or(1) } _ => { 1 } }} }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_tasks/src/futures.rs
crates/bevy_tasks/src/futures.rs
//! Utilities for working with [`Future`]s. use core::{ future::Future, pin::pin, task::{Context, Poll, Waker}, }; /// Consumes a future, polls it once, and immediately returns the output /// or returns `None` if it wasn't ready yet. /// /// This will cancel the future if it's not ready. pub fn now_or_never<F: Future>(future: F) -> Option<F::Output> { let mut cx = Context::from_waker(Waker::noop()); match pin!(future).poll(&mut cx) { Poll::Ready(x) => Some(x), _ => None, } } /// Polls a future once, and returns the output if ready /// or returns `None` if it wasn't ready yet. pub fn check_ready<F: Future + Unpin>(future: &mut F) -> Option<F::Output> { now_or_never(future) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_tasks/src/single_threaded_task_pool.rs
crates/bevy_tasks/src/single_threaded_task_pool.rs
use alloc::{string::String, vec::Vec}; use bevy_platform::sync::Arc; use core::{cell::{RefCell, Cell}, future::Future, marker::PhantomData, mem}; use crate::executor::LocalExecutor; use crate::{block_on, Task}; crate::cfg::std! { if { use std::thread_local; use crate::executor::LocalExecutor as Executor; thread_local! { static LOCAL_EXECUTOR: Executor<'static> = const { Executor::new() }; } } else { // Because we do not have thread-locals without std, we cannot use LocalExecutor here. use crate::executor::Executor; static LOCAL_EXECUTOR: Executor<'static> = const { Executor::new() }; } } /// Used to create a [`TaskPool`]. #[derive(Debug, Default, Clone)] pub struct TaskPoolBuilder {} /// This is a dummy struct for wasm support to provide the same api as with the multithreaded /// task pool. In the case of the multithreaded task pool this struct is used to spawn /// tasks on a specific thread. But the wasm task pool just calls /// `wasm_bindgen_futures::spawn_local` for spawning which just runs tasks on the main thread /// and so the [`ThreadExecutor`] does nothing. #[derive(Default)] pub struct ThreadExecutor<'a>(PhantomData<&'a ()>); impl<'a> ThreadExecutor<'a> { /// Creates a new `ThreadExecutor` pub fn new() -> Self { Self::default() } } impl TaskPoolBuilder { /// Creates a new `TaskPoolBuilder` instance pub fn new() -> Self { Self::default() } /// No op on the single threaded task pool pub fn num_threads(self, _num_threads: usize) -> Self { self } /// No op on the single threaded task pool pub fn stack_size(self, _stack_size: usize) -> Self { self } /// No op on the single threaded task pool pub fn thread_name(self, _thread_name: String) -> Self { self } /// No op on the single threaded task pool pub fn on_thread_spawn(self, _f: impl Fn() + Send + Sync + 'static) -> Self { self } /// No op on the single threaded task pool pub fn on_thread_destroy(self, _f: impl Fn() + Send + Sync + 'static) -> Self { self } /// Creates a new [`TaskPool`] pub fn build(self) -> TaskPool { TaskPool::new_internal() } } /// A thread pool for executing tasks. Tasks are futures that are being automatically driven by /// the pool on threads owned by the pool. In this case - main thread only. #[derive(Debug, Default, Clone)] pub struct TaskPool {} impl TaskPool { /// Just create a new `ThreadExecutor` for wasm pub fn get_thread_executor() -> Arc<ThreadExecutor<'static>> { Arc::new(ThreadExecutor::new()) } /// Create a `TaskPool` with the default configuration. pub fn new() -> Self { TaskPoolBuilder::new().build() } fn new_internal() -> Self { Self {} } /// Return the number of threads owned by the task pool pub fn thread_num(&self) -> usize { 1 } /// Allows spawning non-`'static` futures on the thread pool. The function takes a callback, /// passing a scope object into it. The scope object provided to the callback can be used /// to spawn tasks. This function will await the completion of all tasks before returning. /// /// This is similar to `rayon::scope` and `crossbeam::scope` pub fn scope<'env, F, T>(&self, f: F) -> Vec<T> where F: for<'scope> FnOnce(&'scope mut Scope<'scope, 'env, T>), T: Send + 'static, { self.scope_with_executor(false, None, f) } /// Allows spawning non-`'static` futures on the thread pool. The function takes a callback, /// passing a scope object into it. The scope object provided to the callback can be used /// to spawn tasks. This function will await the completion of all tasks before returning. /// /// This is similar to `rayon::scope` and `crossbeam::scope` #[expect(unsafe_code, reason = "Required to transmute lifetimes.")] pub fn scope_with_executor<'env, F, T>( &self, _tick_task_pool_executor: bool, _thread_executor: Option<&ThreadExecutor>, f: F, ) -> Vec<T> where F: for<'scope> FnOnce(&'scope mut Scope<'scope, 'env, T>), T: Send + 'static, { // SAFETY: This safety comment applies to all references transmuted to 'env. // Any futures spawned with these references need to return before this function completes. // This is guaranteed because we drive all the futures spawned onto the Scope // to completion in this function. However, rust has no way of knowing this so we // transmute the lifetimes to 'env here to appease the compiler as it is unable to validate safety. // Any usages of the references passed into `Scope` must be accessed through // the transmuted reference for the rest of this function. let executor = LocalExecutor::new(); // SAFETY: As above, all futures must complete in this function so we can change the lifetime let executor_ref: &'env LocalExecutor<'env> = unsafe { mem::transmute(&executor) }; let results: RefCell<Vec<Option<T>>> = RefCell::new(Vec::new()); // SAFETY: As above, all futures must complete in this function so we can change the lifetime let results_ref: &'env RefCell<Vec<Option<T>>> = unsafe { mem::transmute(&results) }; let pending_tasks: Cell<usize> = Cell::new(0); // SAFETY: As above, all futures must complete in this function so we can change the lifetime let pending_tasks: &'env Cell<usize> = unsafe { mem::transmute(&pending_tasks) }; let mut scope = Scope { executor_ref, pending_tasks, results_ref, scope: PhantomData, env: PhantomData, }; // SAFETY: As above, all futures must complete in this function so we can change the lifetime let scope_ref: &'env mut Scope<'_, 'env, T> = unsafe { mem::transmute(&mut scope) }; f(scope_ref); // Wait until the scope is complete block_on(executor.run(async { while pending_tasks.get() != 0 { futures_lite::future::yield_now().await; } })); results .take() .into_iter() .map(|result| result.unwrap()) .collect() } /// Spawns a static future onto the thread pool. The returned Task is a future, which can be polled /// to retrieve the output of the original future. Dropping the task will attempt to cancel it. /// It can also be "detached", allowing it to continue running without having to be polled by the /// end-user. /// /// If the provided future is non-`Send`, [`TaskPool::spawn_local`] should be used instead. pub fn spawn<T>( &self, future: impl Future<Output = T> + 'static + MaybeSend + MaybeSync, ) -> Task<T> where T: 'static + MaybeSend + MaybeSync, { crate::cfg::switch! {{ crate::cfg::web => { Task::wrap_future(future) } crate::cfg::std => { LOCAL_EXECUTOR.with(|executor| { let task = executor.spawn(future); // Loop until all tasks are done while executor.try_tick() {} Task::new(task) }) } _ => { let task = LOCAL_EXECUTOR.spawn(future); // Loop until all tasks are done while LOCAL_EXECUTOR.try_tick() {} Task::new(task) } }} } /// Spawns a static future on the JS event loop. This is exactly the same as [`TaskPool::spawn`]. pub fn spawn_local<T>( &self, future: impl Future<Output = T> + 'static + MaybeSend + MaybeSync, ) -> Task<T> where T: 'static + MaybeSend + MaybeSync, { self.spawn(future) } /// Runs a function with the local executor. Typically used to tick /// the local executor on the main thread as it needs to share time with /// other things. /// /// ``` /// use bevy_tasks::TaskPool; /// /// TaskPool::new().with_local_executor(|local_executor| { /// local_executor.try_tick(); /// }); /// ``` pub fn with_local_executor<F, R>(&self, f: F) -> R where F: FnOnce(&Executor) -> R, { crate::cfg::switch! {{ crate::cfg::std => { LOCAL_EXECUTOR.with(f) } _ => { f(&LOCAL_EXECUTOR) } }} } } /// A `TaskPool` scope for running one or more non-`'static` futures. /// /// For more information, see [`TaskPool::scope`]. #[derive(Debug)] pub struct Scope<'scope, 'env: 'scope, T> { executor_ref: &'scope LocalExecutor<'scope>, // The number of pending tasks spawned on the scope pending_tasks: &'scope Cell<usize>, // Vector to gather results of all futures spawned during scope run results_ref: &'env RefCell<Vec<Option<T>>>, // make `Scope` invariant over 'scope and 'env scope: PhantomData<&'scope mut &'scope ()>, env: PhantomData<&'env mut &'env ()>, } impl<'scope, 'env, T: Send + 'env> Scope<'scope, 'env, T> { /// Spawns a scoped future onto the executor. The scope *must* outlive /// the provided future. The results of the future will be returned as a part of /// [`TaskPool::scope`]'s return value. /// /// On the single threaded task pool, it just calls [`Scope::spawn_on_scope`]. /// /// For more information, see [`TaskPool::scope`]. pub fn spawn<Fut: Future<Output = T> + 'scope + MaybeSend>(&self, f: Fut) { self.spawn_on_scope(f); } /// Spawns a scoped future onto the executor. The scope *must* outlive /// the provided future. The results of the future will be returned as a part of /// [`TaskPool::scope`]'s return value. /// /// On the single threaded task pool, it just calls [`Scope::spawn_on_scope`]. /// /// For more information, see [`TaskPool::scope`]. pub fn spawn_on_external<Fut: Future<Output = T> + 'scope + MaybeSend>(&self, f: Fut) { self.spawn_on_scope(f); } /// Spawns a scoped future that runs on the thread the scope called from. The /// scope *must* outlive the provided future. The results of the future will be /// returned as a part of [`TaskPool::scope`]'s return value. /// /// For more information, see [`TaskPool::scope`]. pub fn spawn_on_scope<Fut: Future<Output = T> + 'scope + MaybeSend>(&self, f: Fut) { // increment the number of pending tasks let pending_tasks = self.pending_tasks; pending_tasks.update(|i| i + 1); // add a spot to keep the result, and record the index let results_ref = self.results_ref; let mut results = results_ref.borrow_mut(); let task_number = results.len(); results.push(None); drop(results); // create the job closure let f = async move { let result = f.await; // store the result in the allocated slot let mut results = results_ref.borrow_mut(); results[task_number] = Some(result); drop(results); // decrement the pending tasks count pending_tasks.update(|i| i - 1); }; // spawn the job itself self.executor_ref.spawn(f).detach(); } } crate::cfg::std! { if { pub trait MaybeSend {} impl<T> MaybeSend for T {} pub trait MaybeSync {} impl<T> MaybeSync for T {} } else { pub trait MaybeSend: Send {} impl<T: Send> MaybeSend for T {} pub trait MaybeSync: Sync {} impl<T: Sync> MaybeSync for T {} } } #[cfg(test)] mod test { use std::{time, thread}; use super::*; /// This test creates a scope with a single task that goes to sleep for a /// nontrivial amount of time. At one point, the scope would (incorrectly) /// return early under these conditions, causing a crash. /// /// The correct behavior is for the scope to block until the receiver is /// woken by the external thread. #[test] fn scoped_spawn() { let (sender, receiver) = async_channel::unbounded(); let task_pool = TaskPool {}; let thread = thread::spawn(move || { let duration = time::Duration::from_millis(50); thread::sleep(duration); let _ = sender.send(0); }); task_pool.scope(|scope| { scope.spawn(async { receiver.recv().await }); }); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_tasks/src/thread_executor.rs
crates/bevy_tasks/src/thread_executor.rs
use core::marker::PhantomData; use std::thread::{self, ThreadId}; use crate::executor::Executor; use async_task::Task; use futures_lite::Future; /// An executor that can only be ticked on the thread it was instantiated on. But /// can spawn `Send` tasks from other threads. /// /// # Example /// ``` /// # use std::sync::{Arc, atomic::{AtomicI32, Ordering}}; /// use bevy_tasks::ThreadExecutor; /// /// let thread_executor = ThreadExecutor::new(); /// let count = Arc::new(AtomicI32::new(0)); /// /// // create some owned values that can be moved into another thread /// let count_clone = count.clone(); /// /// std::thread::scope(|scope| { /// scope.spawn(|| { /// // we cannot get the ticker from another thread /// let not_thread_ticker = thread_executor.ticker(); /// assert!(not_thread_ticker.is_none()); /// /// // but we can spawn tasks from another thread /// thread_executor.spawn(async move { /// count_clone.fetch_add(1, Ordering::Relaxed); /// }).detach(); /// }); /// }); /// /// // the tasks do not make progress unless the executor is manually ticked /// assert_eq!(count.load(Ordering::Relaxed), 0); /// /// // tick the ticker until task finishes /// let thread_ticker = thread_executor.ticker().unwrap(); /// thread_ticker.try_tick(); /// assert_eq!(count.load(Ordering::Relaxed), 1); /// ``` #[derive(Debug)] pub struct ThreadExecutor<'task> { executor: Executor<'task>, thread_id: ThreadId, } impl<'task> Default for ThreadExecutor<'task> { fn default() -> Self { Self { executor: Executor::new(), thread_id: thread::current().id(), } } } impl<'task> ThreadExecutor<'task> { /// create a new [`ThreadExecutor`] pub fn new() -> Self { Self::default() } /// Spawn a task on the thread executor pub fn spawn<T: Send + 'task>( &self, future: impl Future<Output = T> + Send + 'task, ) -> Task<T> { self.executor.spawn(future) } /// Gets the [`ThreadExecutorTicker`] for this executor. /// Use this to tick the executor. /// It only returns the ticker if it's on the thread the executor was created on /// and returns `None` otherwise. pub fn ticker<'ticker>(&'ticker self) -> Option<ThreadExecutorTicker<'task, 'ticker>> { if thread::current().id() == self.thread_id { return Some(ThreadExecutorTicker { executor: self, _marker: PhantomData, }); } None } /// Returns true if `self` and `other`'s executor is same pub fn is_same(&self, other: &Self) -> bool { core::ptr::eq(self, other) } } /// Used to tick the [`ThreadExecutor`]. The executor does not /// make progress unless it is manually ticked on the thread it was /// created on. #[derive(Debug)] pub struct ThreadExecutorTicker<'task, 'ticker> { executor: &'ticker ThreadExecutor<'task>, // make type not send or sync _marker: PhantomData<*const ()>, } impl<'task, 'ticker> ThreadExecutorTicker<'task, 'ticker> { /// Tick the thread executor. pub async fn tick(&self) { self.executor.executor.tick().await; } /// Synchronously try to tick a task on the executor. /// Returns false if does not find a task to tick. pub fn try_tick(&self) -> bool { self.executor.executor.try_tick() } } #[cfg(test)] mod tests { use super::*; use alloc::sync::Arc; #[test] fn test_ticker() { let executor = Arc::new(ThreadExecutor::new()); let ticker = executor.ticker(); assert!(ticker.is_some()); thread::scope(|s| { s.spawn(|| { let ticker = executor.ticker(); assert!(ticker.is_none()); }); }); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_tasks/src/executor.rs
crates/bevy_tasks/src/executor.rs
//! Provides a fundamental executor primitive appropriate for the target platform //! and feature set selected. //! By default, the `async_executor` feature will be enabled, which will rely on //! [`async-executor`] for the underlying implementation. This requires `std`, //! so is not suitable for `no_std` contexts. Instead, you must use `edge_executor`, //! which relies on the alternate [`edge-executor`] backend. //! //! [`async-executor`]: https://crates.io/crates/async-executor //! [`edge-executor`]: https://crates.io/crates/edge-executor use core::{ fmt, panic::{RefUnwindSafe, UnwindSafe}, }; use derive_more::{Deref, DerefMut}; crate::cfg::async_executor! { if { type ExecutorInner<'a> = async_executor::Executor<'a>; type LocalExecutorInner<'a> = async_executor::LocalExecutor<'a>; } else { type ExecutorInner<'a> = crate::edge_executor::Executor<'a, 64>; type LocalExecutorInner<'a> = crate::edge_executor::LocalExecutor<'a, 64>; } } crate::cfg::multi_threaded! { pub use async_task::FallibleTask; } /// Wrapper around a multi-threading-aware async executor. /// Spawning will generally require tasks to be `Send` and `Sync` to allow multiple /// threads to send/receive/advance tasks. /// /// If you require an executor _without_ the `Send` and `Sync` requirements, consider /// using [`LocalExecutor`] instead. #[derive(Deref, DerefMut, Default)] pub struct Executor<'a>(ExecutorInner<'a>); /// Wrapper around a single-threaded async executor. /// Spawning wont generally require tasks to be `Send` and `Sync`, at the cost of /// this executor itself not being `Send` or `Sync`. This makes it unsuitable for /// global statics. /// /// If need to store an executor in a global static, or send across threads, /// consider using [`Executor`] instead. #[derive(Deref, DerefMut, Default)] pub struct LocalExecutor<'a>(LocalExecutorInner<'a>); impl Executor<'_> { /// Construct a new [`Executor`] #[expect(clippy::allow_attributes, reason = "This lint may not always trigger.")] #[allow(dead_code, reason = "not all feature flags require this function")] pub const fn new() -> Self { Self(ExecutorInner::new()) } } impl LocalExecutor<'_> { /// Construct a new [`LocalExecutor`] #[expect(clippy::allow_attributes, reason = "This lint may not always trigger.")] #[allow(dead_code, reason = "not all feature flags require this function")] pub const fn new() -> Self { Self(LocalExecutorInner::new()) } } impl UnwindSafe for Executor<'_> {} impl RefUnwindSafe for Executor<'_> {} impl UnwindSafe for LocalExecutor<'_> {} impl RefUnwindSafe for LocalExecutor<'_> {} impl fmt::Debug for Executor<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Executor").finish() } } impl fmt::Debug for LocalExecutor<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("LocalExecutor").finish() } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_tasks/src/task_pool.rs
crates/bevy_tasks/src/task_pool.rs
use alloc::{boxed::Box, format, string::String, vec::Vec}; use core::{future::Future, marker::PhantomData, mem, panic::AssertUnwindSafe}; use std::{ thread::{self, JoinHandle}, thread_local, }; use crate::executor::FallibleTask; use bevy_platform::sync::Arc; use concurrent_queue::ConcurrentQueue; use futures_lite::FutureExt; use crate::{ block_on, thread_executor::{ThreadExecutor, ThreadExecutorTicker}, Task, }; struct CallOnDrop(Option<Arc<dyn Fn() + Send + Sync + 'static>>); impl Drop for CallOnDrop { fn drop(&mut self) { if let Some(call) = self.0.as_ref() { call(); } } } /// Used to create a [`TaskPool`] #[derive(Default)] #[must_use] pub struct TaskPoolBuilder { /// If set, we'll set up the thread pool to use at most `num_threads` threads. /// Otherwise use the logical core count of the system num_threads: Option<usize>, /// If set, we'll use the given stack size rather than the system default stack_size: Option<usize>, /// Allows customizing the name of the threads - helpful for debugging. If set, threads will /// be named `<thread_name> (<thread_index>)`, i.e. `"MyThreadPool (2)"`. thread_name: Option<String>, on_thread_spawn: Option<Arc<dyn Fn() + Send + Sync + 'static>>, on_thread_destroy: Option<Arc<dyn Fn() + Send + Sync + 'static>>, } impl TaskPoolBuilder { /// Creates a new [`TaskPoolBuilder`] instance pub fn new() -> Self { Self::default() } /// Override the number of threads created for the pool. If unset, we default to the number /// of logical cores of the system pub fn num_threads(mut self, num_threads: usize) -> Self { self.num_threads = Some(num_threads); self } /// Override the stack size of the threads created for the pool pub fn stack_size(mut self, stack_size: usize) -> Self { self.stack_size = Some(stack_size); self } /// Override the name of the threads created for the pool. If set, threads will /// be named `<thread_name> (<thread_index>)`, i.e. `MyThreadPool (2)` pub fn thread_name(mut self, thread_name: String) -> Self { self.thread_name = Some(thread_name); self } /// Sets a callback that is invoked once for every created thread as it starts. /// /// This is called on the thread itself and has access to all thread-local storage. /// This will block running async tasks on the thread until the callback completes. pub fn on_thread_spawn(mut self, f: impl Fn() + Send + Sync + 'static) -> Self { let arc = Arc::new(f); #[cfg(not(target_has_atomic = "ptr"))] #[expect( unsafe_code, reason = "unsized coercion is an unstable feature for non-std types" )] // SAFETY: // - Coercion from `impl Fn` to `dyn Fn` is valid // - `Arc::from_raw` receives a valid pointer from a previous call to `Arc::into_raw` let arc = unsafe { Arc::from_raw(Arc::into_raw(arc) as *const (dyn Fn() + Send + Sync + 'static)) }; self.on_thread_spawn = Some(arc); self } /// Sets a callback that is invoked once for every created thread as it terminates. /// /// This is called on the thread itself and has access to all thread-local storage. /// This will block thread termination until the callback completes. pub fn on_thread_destroy(mut self, f: impl Fn() + Send + Sync + 'static) -> Self { let arc = Arc::new(f); #[cfg(not(target_has_atomic = "ptr"))] #[expect( unsafe_code, reason = "unsized coercion is an unstable feature for non-std types" )] // SAFETY: // - Coercion from `impl Fn` to `dyn Fn` is valid // - `Arc::from_raw` receives a valid pointer from a previous call to `Arc::into_raw` let arc = unsafe { Arc::from_raw(Arc::into_raw(arc) as *const (dyn Fn() + Send + Sync + 'static)) }; self.on_thread_destroy = Some(arc); self } /// Creates a new [`TaskPool`] based on the current options. pub fn build(self) -> TaskPool { TaskPool::new_internal(self) } } /// A thread pool for executing tasks. /// /// While futures usually need to be polled to be executed, Bevy tasks are being /// automatically driven by the pool on threads owned by the pool. The [`Task`] /// future only needs to be polled in order to receive the result. (For that /// purpose, it is often stored in a component or resource, see the /// `async_compute` example.) /// /// If the result is not required, one may also use [`Task::detach`] and the pool /// will still execute a task, even if it is dropped. #[derive(Debug)] pub struct TaskPool { /// The executor for the pool. executor: Arc<crate::executor::Executor<'static>>, // The inner state of the pool. threads: Vec<JoinHandle<()>>, shutdown_tx: async_channel::Sender<()>, } impl TaskPool { thread_local! { static LOCAL_EXECUTOR: crate::executor::LocalExecutor<'static> = const { crate::executor::LocalExecutor::new() }; static THREAD_EXECUTOR: Arc<ThreadExecutor<'static>> = Arc::new(ThreadExecutor::new()); } /// Each thread should only create one `ThreadExecutor`, otherwise, there are good chances they will deadlock pub fn get_thread_executor() -> Arc<ThreadExecutor<'static>> { Self::THREAD_EXECUTOR.with(Clone::clone) } /// Create a `TaskPool` with the default configuration. pub fn new() -> Self { TaskPoolBuilder::new().build() } fn new_internal(builder: TaskPoolBuilder) -> Self { let (shutdown_tx, shutdown_rx) = async_channel::unbounded::<()>(); let executor = Arc::new(crate::executor::Executor::new()); let num_threads = builder .num_threads .unwrap_or_else(crate::available_parallelism); let threads = (0..num_threads) .map(|i| { let ex = Arc::clone(&executor); let shutdown_rx = shutdown_rx.clone(); let thread_name = if let Some(thread_name) = builder.thread_name.as_deref() { format!("{thread_name} ({i})") } else { format!("TaskPool ({i})") }; let mut thread_builder = thread::Builder::new().name(thread_name); if let Some(stack_size) = builder.stack_size { thread_builder = thread_builder.stack_size(stack_size); } let on_thread_spawn = builder.on_thread_spawn.clone(); let on_thread_destroy = builder.on_thread_destroy.clone(); thread_builder .spawn(move || { TaskPool::LOCAL_EXECUTOR.with(|local_executor| { if let Some(on_thread_spawn) = on_thread_spawn { on_thread_spawn(); drop(on_thread_spawn); } let _destructor = CallOnDrop(on_thread_destroy); loop { let res = std::panic::catch_unwind(|| { let tick_forever = async move { loop { local_executor.tick().await; } }; block_on(ex.run(tick_forever.or(shutdown_rx.recv()))) }); if let Ok(value) = res { // Use unwrap_err because we expect a Closed error value.unwrap_err(); break; } } }); }) .expect("Failed to spawn thread.") }) .collect(); Self { executor, threads, shutdown_tx, } } /// Return the number of threads owned by the task pool pub fn thread_num(&self) -> usize { self.threads.len() } /// Allows spawning non-`'static` futures on the thread pool. The function takes a callback, /// passing a scope object into it. The scope object provided to the callback can be used /// to spawn tasks. This function will await the completion of all tasks before returning. /// /// This is similar to [`thread::scope`] and `rayon::scope`. /// /// # Example /// /// ``` /// use bevy_tasks::TaskPool; /// /// let pool = TaskPool::new(); /// let mut x = 0; /// let results = pool.scope(|s| { /// s.spawn(async { /// // you can borrow the spawner inside a task and spawn tasks from within the task /// s.spawn(async { /// // borrow x and mutate it. /// x = 2; /// // return a value from the task /// 1 /// }); /// // return some other value from the first task /// 0 /// }); /// }); /// /// // The ordering of results is non-deterministic if you spawn from within tasks as above. /// // If you're doing this, you'll have to write your code to not depend on the ordering. /// assert!(results.contains(&0)); /// assert!(results.contains(&1)); /// /// // The ordering is deterministic if you only spawn directly from the closure function. /// let results = pool.scope(|s| { /// s.spawn(async { 0 }); /// s.spawn(async { 1 }); /// }); /// assert_eq!(&results[..], &[0, 1]); /// /// // You can access x after scope runs, since it was only temporarily borrowed in the scope. /// assert_eq!(x, 2); /// ``` /// /// # Lifetimes /// /// The [`Scope`] object takes two lifetimes: `'scope` and `'env`. /// /// The `'scope` lifetime represents the lifetime of the scope. That is the time during /// which the provided closure and tasks that are spawned into the scope are run. /// /// The `'env` lifetime represents the lifetime of whatever is borrowed by the scope. /// Thus this lifetime must outlive `'scope`. /// /// ```compile_fail /// use bevy_tasks::TaskPool; /// fn scope_escapes_closure() { /// let pool = TaskPool::new(); /// let foo = Box::new(42); /// pool.scope(|scope| { /// std::thread::spawn(move || { /// // UB. This could spawn on the scope after `.scope` returns and the internal Scope is dropped. /// scope.spawn(async move { /// assert_eq!(*foo, 42); /// }); /// }); /// }); /// } /// ``` /// /// ```compile_fail /// use bevy_tasks::TaskPool; /// fn cannot_borrow_from_closure() { /// let pool = TaskPool::new(); /// pool.scope(|scope| { /// let x = 1; /// let y = &x; /// scope.spawn(async move { /// assert_eq!(*y, 1); /// }); /// }); /// } pub fn scope<'env, F, T>(&self, f: F) -> Vec<T> where F: for<'scope> FnOnce(&'scope Scope<'scope, 'env, T>), T: Send + 'static, { Self::THREAD_EXECUTOR.with(|scope_executor| { self.scope_with_executor_inner(true, scope_executor, scope_executor, f) }) } /// This allows passing an external executor to spawn tasks on. When you pass an external executor /// [`Scope::spawn_on_scope`] spawns is then run on the thread that [`ThreadExecutor`] is being ticked on. /// If [`None`] is passed the scope will use a [`ThreadExecutor`] that is ticked on the current thread. /// /// When `tick_task_pool_executor` is set to `true`, the multithreaded task stealing executor is ticked on the scope /// thread. Disabling this can be useful when finishing the scope is latency sensitive. Pulling tasks from /// global executor can run tasks unrelated to the scope and delay when the scope returns. /// /// See [`Self::scope`] for more details in general about how scopes work. pub fn scope_with_executor<'env, F, T>( &self, tick_task_pool_executor: bool, external_executor: Option<&ThreadExecutor>, f: F, ) -> Vec<T> where F: for<'scope> FnOnce(&'scope Scope<'scope, 'env, T>), T: Send + 'static, { Self::THREAD_EXECUTOR.with(|scope_executor| { // If an `external_executor` is passed, use that. Otherwise, get the executor stored // in the `THREAD_EXECUTOR` thread local. if let Some(external_executor) = external_executor { self.scope_with_executor_inner( tick_task_pool_executor, external_executor, scope_executor, f, ) } else { self.scope_with_executor_inner( tick_task_pool_executor, scope_executor, scope_executor, f, ) } }) } #[expect(unsafe_code, reason = "Required to transmute lifetimes.")] fn scope_with_executor_inner<'env, F, T>( &self, tick_task_pool_executor: bool, external_executor: &ThreadExecutor, scope_executor: &ThreadExecutor, f: F, ) -> Vec<T> where F: for<'scope> FnOnce(&'scope Scope<'scope, 'env, T>), T: Send + 'static, { // SAFETY: This safety comment applies to all references transmuted to 'env. // Any futures spawned with these references need to return before this function completes. // This is guaranteed because we drive all the futures spawned onto the Scope // to completion in this function. However, rust has no way of knowing this so we // transmute the lifetimes to 'env here to appease the compiler as it is unable to validate safety. // Any usages of the references passed into `Scope` must be accessed through // the transmuted reference for the rest of this function. let executor: &crate::executor::Executor = &self.executor; // SAFETY: As above, all futures must complete in this function so we can change the lifetime let executor: &'env crate::executor::Executor = unsafe { mem::transmute(executor) }; // SAFETY: As above, all futures must complete in this function so we can change the lifetime let external_executor: &'env ThreadExecutor<'env> = unsafe { mem::transmute(external_executor) }; // SAFETY: As above, all futures must complete in this function so we can change the lifetime let scope_executor: &'env ThreadExecutor<'env> = unsafe { mem::transmute(scope_executor) }; let spawned: ConcurrentQueue<FallibleTask<Result<T, Box<dyn core::any::Any + Send>>>> = ConcurrentQueue::unbounded(); // shadow the variable so that the owned value cannot be used for the rest of the function // SAFETY: As above, all futures must complete in this function so we can change the lifetime let spawned: &'env ConcurrentQueue< FallibleTask<Result<T, Box<dyn core::any::Any + Send>>>, > = unsafe { mem::transmute(&spawned) }; let scope = Scope { executor, external_executor, scope_executor, spawned, scope: PhantomData, env: PhantomData, }; // shadow the variable so that the owned value cannot be used for the rest of the function // SAFETY: As above, all futures must complete in this function so we can change the lifetime let scope: &'env Scope<'_, 'env, T> = unsafe { mem::transmute(&scope) }; f(scope); if spawned.is_empty() { Vec::new() } else { block_on(async move { let get_results = async { let mut results = Vec::with_capacity(spawned.len()); while let Ok(task) = spawned.pop() { if let Some(res) = task.await { match res { Ok(res) => results.push(res), Err(payload) => std::panic::resume_unwind(payload), } } else { panic!("Failed to catch panic!"); } } results }; let tick_task_pool_executor = tick_task_pool_executor || self.threads.is_empty(); // we get this from a thread local so we should always be on the scope executors thread. // note: it is possible `scope_executor` and `external_executor` is the same executor, // in that case, we should only tick one of them, otherwise, it may cause deadlock. let scope_ticker = scope_executor.ticker().unwrap(); let external_ticker = if !external_executor.is_same(scope_executor) { external_executor.ticker() } else { None }; match (external_ticker, tick_task_pool_executor) { (Some(external_ticker), true) => { Self::execute_global_external_scope( executor, external_ticker, scope_ticker, get_results, ) .await } (Some(external_ticker), false) => { Self::execute_external_scope(external_ticker, scope_ticker, get_results) .await } // either external_executor is none or it is same as scope_executor (None, true) => { Self::execute_global_scope(executor, scope_ticker, get_results).await } (None, false) => Self::execute_scope(scope_ticker, get_results).await, } }) } } #[inline] async fn execute_global_external_scope<'scope, 'ticker, T>( executor: &'scope crate::executor::Executor<'scope>, external_ticker: ThreadExecutorTicker<'scope, 'ticker>, scope_ticker: ThreadExecutorTicker<'scope, 'ticker>, get_results: impl Future<Output = Vec<T>>, ) -> Vec<T> { // we restart the executors if a task errors. if a scoped // task errors it will panic the scope on the call to get_results let execute_forever = async move { loop { let tick_forever = async { loop { external_ticker.tick().or(scope_ticker.tick()).await; } }; // we don't care if it errors. If a scoped task errors it will propagate // to get_results let _result = AssertUnwindSafe(executor.run(tick_forever)) .catch_unwind() .await .is_ok(); } }; get_results.or(execute_forever).await } #[inline] async fn execute_external_scope<'scope, 'ticker, T>( external_ticker: ThreadExecutorTicker<'scope, 'ticker>, scope_ticker: ThreadExecutorTicker<'scope, 'ticker>, get_results: impl Future<Output = Vec<T>>, ) -> Vec<T> { let execute_forever = async { loop { let tick_forever = async { loop { external_ticker.tick().or(scope_ticker.tick()).await; } }; let _result = AssertUnwindSafe(tick_forever).catch_unwind().await.is_ok(); } }; get_results.or(execute_forever).await } #[inline] async fn execute_global_scope<'scope, 'ticker, T>( executor: &'scope crate::executor::Executor<'scope>, scope_ticker: ThreadExecutorTicker<'scope, 'ticker>, get_results: impl Future<Output = Vec<T>>, ) -> Vec<T> { let execute_forever = async { loop { let tick_forever = async { loop { scope_ticker.tick().await; } }; let _result = AssertUnwindSafe(executor.run(tick_forever)) .catch_unwind() .await .is_ok(); } }; get_results.or(execute_forever).await } #[inline] async fn execute_scope<'scope, 'ticker, T>( scope_ticker: ThreadExecutorTicker<'scope, 'ticker>, get_results: impl Future<Output = Vec<T>>, ) -> Vec<T> { let execute_forever = async { loop { let tick_forever = async { loop { scope_ticker.tick().await; } }; let _result = AssertUnwindSafe(tick_forever).catch_unwind().await.is_ok(); } }; get_results.or(execute_forever).await } /// Spawns a static future onto the thread pool. The returned [`Task`] is a /// future that can be polled for the result. It can also be canceled and /// "detached", allowing the task to continue running even if dropped. In /// any case, the pool will execute the task even without polling by the /// end-user. /// /// If the provided future is non-`Send`, [`TaskPool::spawn_local`] should /// be used instead. pub fn spawn<T>(&self, future: impl Future<Output = T> + Send + 'static) -> Task<T> where T: Send + 'static, { Task::new(self.executor.spawn(future)) } /// Spawns a static future on the thread-local async executor for the /// current thread. The task will run entirely on the thread the task was /// spawned on. /// /// The returned [`Task`] is a future that can be polled for the /// result. It can also be canceled and "detached", allowing the task to /// continue running even if dropped. In any case, the pool will execute the /// task even without polling by the end-user. /// /// Users should generally prefer to use [`TaskPool::spawn`] instead, /// unless the provided future is not `Send`. pub fn spawn_local<T>(&self, future: impl Future<Output = T> + 'static) -> Task<T> where T: 'static, { Task::new(TaskPool::LOCAL_EXECUTOR.with(|executor| executor.spawn(future))) } /// Runs a function with the local executor. Typically used to tick /// the local executor on the main thread as it needs to share time with /// other things. /// /// ``` /// use bevy_tasks::TaskPool; /// /// TaskPool::new().with_local_executor(|local_executor| { /// local_executor.try_tick(); /// }); /// ``` pub fn with_local_executor<F, R>(&self, f: F) -> R where F: FnOnce(&crate::executor::LocalExecutor) -> R, { Self::LOCAL_EXECUTOR.with(f) } } impl Default for TaskPool { fn default() -> Self { Self::new() } } impl Drop for TaskPool { fn drop(&mut self) { self.shutdown_tx.close(); let panicking = thread::panicking(); for join_handle in self.threads.drain(..) { let res = join_handle.join(); if !panicking { res.expect("Task thread panicked while executing."); } } } } /// A [`TaskPool`] scope for running one or more non-`'static` futures. /// /// For more information, see [`TaskPool::scope`]. #[derive(Debug)] pub struct Scope<'scope, 'env: 'scope, T> { executor: &'scope crate::executor::Executor<'scope>, external_executor: &'scope ThreadExecutor<'scope>, scope_executor: &'scope ThreadExecutor<'scope>, spawned: &'scope ConcurrentQueue<FallibleTask<Result<T, Box<dyn core::any::Any + Send>>>>, // make `Scope` invariant over 'scope and 'env scope: PhantomData<&'scope mut &'scope ()>, env: PhantomData<&'env mut &'env ()>, } impl<'scope, 'env, T: Send + 'scope> Scope<'scope, 'env, T> { /// Spawns a scoped future onto the thread pool. The scope *must* outlive /// the provided future. The results of the future will be returned as a part of /// [`TaskPool::scope`]'s return value. /// /// For futures that should run on the thread `scope` is called on [`Scope::spawn_on_scope`] should be used /// instead. /// /// For more information, see [`TaskPool::scope`]. pub fn spawn<Fut: Future<Output = T> + 'scope + Send>(&self, f: Fut) { let task = self .executor .spawn(AssertUnwindSafe(f).catch_unwind()) .fallible(); // ConcurrentQueue only errors when closed or full, but we never // close and use an unbounded queue, so it is safe to unwrap self.spawned.push(task).unwrap(); } /// Spawns a scoped future onto the thread the scope is run on. The scope *must* outlive /// the provided future. The results of the future will be returned as a part of /// [`TaskPool::scope`]'s return value. Users should generally prefer to use /// [`Scope::spawn`] instead, unless the provided future needs to run on the scope's thread. /// /// For more information, see [`TaskPool::scope`]. pub fn spawn_on_scope<Fut: Future<Output = T> + 'scope + Send>(&self, f: Fut) { let task = self .scope_executor .spawn(AssertUnwindSafe(f).catch_unwind()) .fallible(); // ConcurrentQueue only errors when closed or full, but we never // close and use an unbounded queue, so it is safe to unwrap self.spawned.push(task).unwrap(); } /// Spawns a scoped future onto the thread of the external thread executor. /// This is typically the main thread. The scope *must* outlive /// the provided future. The results of the future will be returned as a part of /// [`TaskPool::scope`]'s return value. Users should generally prefer to use /// [`Scope::spawn`] instead, unless the provided future needs to run on the external thread. /// /// For more information, see [`TaskPool::scope`]. pub fn spawn_on_external<Fut: Future<Output = T> + 'scope + Send>(&self, f: Fut) { let task = self .external_executor .spawn(AssertUnwindSafe(f).catch_unwind()) .fallible(); // ConcurrentQueue only errors when closed or full, but we never // close and use an unbounded queue, so it is safe to unwrap self.spawned.push(task).unwrap(); } } impl<'scope, 'env, T> Drop for Scope<'scope, 'env, T> where T: 'scope, { fn drop(&mut self) { block_on(async { while let Ok(task) = self.spawned.pop() { task.cancel().await; } }); } } #[cfg(test)] mod tests { use super::*; use core::sync::atomic::{AtomicBool, AtomicI32, Ordering}; use std::sync::Barrier; #[test] fn test_spawn() { let pool = TaskPool::new(); let foo = Box::new(42); let foo = &*foo; let count = Arc::new(AtomicI32::new(0)); let outputs = pool.scope(|scope| { for _ in 0..100 { let count_clone = count.clone(); scope.spawn(async move { if *foo != 42 { panic!("not 42!?!?") } else { count_clone.fetch_add(1, Ordering::Relaxed); *foo } }); } }); for output in &outputs { assert_eq!(*output, 42); } assert_eq!(outputs.len(), 100); assert_eq!(count.load(Ordering::Relaxed), 100); } #[test] fn test_thread_callbacks() { let counter = Arc::new(AtomicI32::new(0)); let start_counter = counter.clone(); { let barrier = Arc::new(Barrier::new(11)); let last_barrier = barrier.clone(); // Build and immediately drop to terminate let _pool = TaskPoolBuilder::new() .num_threads(10) .on_thread_spawn(move || { start_counter.fetch_add(1, Ordering::Relaxed); barrier.clone().wait(); }) .build(); last_barrier.wait(); assert_eq!(10, counter.load(Ordering::Relaxed)); } assert_eq!(10, counter.load(Ordering::Relaxed)); let end_counter = counter.clone(); { let _pool = TaskPoolBuilder::new() .num_threads(20) .on_thread_destroy(move || { end_counter.fetch_sub(1, Ordering::Relaxed); }) .build(); assert_eq!(10, counter.load(Ordering::Relaxed)); } assert_eq!(-10, counter.load(Ordering::Relaxed)); let start_counter = counter.clone(); let end_counter = counter.clone(); { let barrier = Arc::new(Barrier::new(6)); let last_barrier = barrier.clone(); let _pool = TaskPoolBuilder::new() .num_threads(5) .on_thread_spawn(move || { start_counter.fetch_add(1, Ordering::Relaxed); barrier.wait(); }) .on_thread_destroy(move || { end_counter.fetch_sub(1, Ordering::Relaxed); }) .build(); last_barrier.wait(); assert_eq!(-5, counter.load(Ordering::Relaxed)); } assert_eq!(-10, counter.load(Ordering::Relaxed)); } #[test] fn test_mixed_spawn_on_scope_and_spawn() { let pool = TaskPool::new(); let foo = Box::new(42); let foo = &*foo; let local_count = Arc::new(AtomicI32::new(0)); let non_local_count = Arc::new(AtomicI32::new(0)); let outputs = pool.scope(|scope| { for i in 0..100 { if i % 2 == 0 { let count_clone = non_local_count.clone(); scope.spawn(async move { if *foo != 42 { panic!("not 42!?!?") } else { count_clone.fetch_add(1, Ordering::Relaxed); *foo } }); } else { let count_clone = local_count.clone(); scope.spawn_on_scope(async move { if *foo != 42 { panic!("not 42!?!?") } else { count_clone.fetch_add(1, Ordering::Relaxed); *foo } }); } } }); for output in &outputs { assert_eq!(*output, 42); } assert_eq!(outputs.len(), 100); assert_eq!(local_count.load(Ordering::Relaxed), 50); assert_eq!(non_local_count.load(Ordering::Relaxed), 50); } #[test] fn test_thread_locality() { let pool = Arc::new(TaskPool::new()); let count = Arc::new(AtomicI32::new(0)); let barrier = Arc::new(Barrier::new(101)); let thread_check_failed = Arc::new(AtomicBool::new(false)); for _ in 0..100 { let inner_barrier = barrier.clone(); let count_clone = count.clone(); let inner_pool = pool.clone(); let inner_thread_check_failed = thread_check_failed.clone(); thread::spawn(move || { inner_pool.scope(|scope| { let inner_count_clone = count_clone.clone(); scope.spawn(async move { inner_count_clone.fetch_add(1, Ordering::Release); }); let spawner = thread::current().id();
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_tasks/src/task.rs
crates/bevy_tasks/src/task.rs
use alloc::fmt; use core::{ future::Future, pin::Pin, task::{Context, Poll}, }; use crate::cfg; /// Wraps `async_executor::Task`, a spawned future. /// /// Tasks are also futures themselves and yield the output of the spawned future. /// /// When a task is dropped, it gets canceled and won't be polled again. To cancel a task a bit /// more gracefully and wait until it stops running, use the [`Task::cancel()`] method. /// /// Tasks that panic get immediately canceled. Awaiting a canceled task also causes a panic. #[must_use = "Tasks are canceled when dropped, use `.detach()` to run them in the background."] pub struct Task<T>( cfg::web! { if { async_channel::Receiver<Result<T, Panic>> } else { async_task::Task<T> } }, ); // Custom constructors for web and non-web platforms cfg::web! { if { impl<T: 'static> Task<T> { /// Creates a new task by passing the given future to the web /// runtime as a promise. pub(crate) fn wrap_future(future: impl Future<Output = T> + 'static) -> Self { use bevy_platform::exports::wasm_bindgen_futures::spawn_local; let (sender, receiver) = async_channel::bounded(1); spawn_local(async move { // Catch any panics that occur when polling the future so they can // be propagated back to the task handle. let value = CatchUnwind(AssertUnwindSafe(future)).await; let _ = sender.send(value).await; }); Self(receiver) } } } else { impl<T> Task<T> { /// Creates a new task from a given `async_executor::Task` pub(crate) fn new(task: async_task::Task<T>) -> Self { Self(task) } } } } impl<T> Task<T> { /// Detaches the task to let it keep running in the background. /// /// # Platform-Specific Behavior /// /// When building for the web, this method has no effect. pub fn detach(self) { cfg::web! { if { // Tasks are already treated as detached on the web. } else { self.0.detach(); } } } /// Cancels the task and waits for it to stop running. /// /// Returns the task's output if it was completed just before it got canceled, or [`None`] if /// it didn't complete. /// /// While it's possible to simply drop the [`Task`] to cancel it, this is a cleaner way of /// canceling because it also waits for the task to stop running. /// /// # Platform-Specific Behavior /// /// Canceling tasks is unsupported on the web, and this is the same as awaiting the task. pub async fn cancel(self) -> Option<T> { cfg::web! { if { // Await the task and handle any panics. match self.0.recv().await { Ok(Ok(value)) => Some(value), Err(_) => None, Ok(Err(panic)) => { // drop this to prevent the panic payload from resuming the panic on drop. // this also leaks the box but I'm not sure how to avoid that core::mem::forget(panic); None } } } else { // Wait for the task to become canceled self.0.cancel().await } } } /// Returns `true` if the current task is finished. /// /// Unlike poll, it doesn't resolve the final value, it just checks if the task has finished. /// Note that in a multithreaded environment, this task can be finished immediately after calling this function. pub fn is_finished(&self) -> bool { cfg::web! { if { // We treat the task as unfinished until the result is sent over the channel. !self.0.is_empty() } else { // Defer to the `async_task` implementation. self.0.is_finished() } } } } impl<T> Future for Task<T> { type Output = T; cfg::web! { if { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { // `recv()` returns a future, so we just poll that and hand the result. let recv = core::pin::pin!(self.0.recv()); match recv.poll(cx) { Poll::Ready(Ok(Ok(value))) => Poll::Ready(value), // NOTE: Propagating the panic here sorta has parity with the async_executor behavior. // For those tasks, polling them after a panic returns a `None` which gets `unwrap`ed, so // using `resume_unwind` here is essentially keeping the same behavior while adding more information. Poll::Ready(Ok(Err(_panic))) => crate::cfg::switch! {{ crate::cfg::std => { std::panic::resume_unwind(_panic) } _ => { unreachable!("catching a panic is only possible with std") } }}, Poll::Ready(Err(_)) => panic!("Polled a task after it finished running"), Poll::Pending => Poll::Pending, } } } else { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { // `async_task` has `Task` implement `Future`, so we just poll it. Pin::new(&mut self.0).poll(cx) } } } } // All variants of Task<T> are expected to implement Unpin impl<T> Unpin for Task<T> {} // Derive doesn't work for macro types, so we have to implement this manually. impl<T> fmt::Debug for Task<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } // Utilities for catching unwinds on the web. cfg::web! { use alloc::boxed::Box; use core::{ panic::{AssertUnwindSafe, UnwindSafe}, any::Any, }; type Panic = Box<dyn Any + Send + 'static>; #[pin_project::pin_project] struct CatchUnwind<F: UnwindSafe>(#[pin] F); impl<F: Future + UnwindSafe> Future for CatchUnwind<F> { type Output = Result<F::Output, Panic>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let f = AssertUnwindSafe(|| self.project().0.poll(cx)); let result = cfg::std! { if { std::panic::catch_unwind(f)? } else { f() } }; result.map(Ok) } } } #[cfg(test)] mod tests { use crate::Task; #[test] fn task_is_sync() { fn is_sync<T: Sync>() {} is_sync::<Task<()>>(); } #[test] fn task_is_send() { fn is_send<T: Send>() {} is_send::<Task<()>>(); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_tasks/src/edge_executor.rs
crates/bevy_tasks/src/edge_executor.rs
//! Alternative to `async_executor` based on [`edge_executor`] by Ivan Markov. //! //! It has been vendored along with its tests to update several outdated dependencies. //! //! [`async_executor`]: https://github.com/smol-rs/async-executor //! [`edge_executor`]: https://github.com/ivmarkov/edge-executor #![expect(unsafe_code, reason = "original implementation relies on unsafe")] #![expect( dead_code, reason = "keeping methods from original implementation for transparency" )] // TODO: Create a more tailored replacement, possibly integrating [Fotre](https://github.com/NthTensor/Forte) use alloc::rc::Rc; use core::{ future::{poll_fn, Future}, marker::PhantomData, task::{Context, Poll}, }; use async_task::{Runnable, Task}; use atomic_waker::AtomicWaker; use bevy_platform::sync::{Arc, LazyLock}; use futures_lite::FutureExt; /// An async executor. /// /// # Examples /// /// A multi-threaded executor: /// /// ```ignore /// use async_channel::unbounded; /// use easy_parallel::Parallel; /// /// use edge_executor::{Executor, block_on}; /// /// let ex: Executor = Default::default(); /// let (signal, shutdown) = unbounded::<()>(); /// /// Parallel::new() /// // Run four executor threads. /// .each(0..4, |_| block_on(ex.run(shutdown.recv()))) /// // Run the main future on the current thread. /// .finish(|| block_on(async { /// println!("Hello world!"); /// drop(signal); /// })); /// ``` pub struct Executor<'a, const C: usize = 64> { state: LazyLock<Arc<State<C>>>, _invariant: PhantomData<core::cell::UnsafeCell<&'a ()>>, } impl<'a, const C: usize> Executor<'a, C> { /// Creates a new executor. /// /// # Examples /// /// ```ignore /// use edge_executor::Executor; /// /// let ex: Executor = Default::default(); /// ``` pub const fn new() -> Self { Self { state: LazyLock::new(|| Arc::new(State::new())), _invariant: PhantomData, } } /// Spawns a task onto the executor. /// /// # Examples /// /// ```ignore /// use edge_executor::Executor; /// /// let ex: Executor = Default::default(); /// /// let task = ex.spawn(async { /// println!("Hello world"); /// }); /// ``` /// /// Note that if the executor's queue size is equal to the number of currently /// spawned and running tasks, spawning this additional task might cause the executor to panic /// later, when the task is scheduled for polling. pub fn spawn<F>(&self, fut: F) -> Task<F::Output> where F: Future + Send + 'a, F::Output: Send + 'a, { // SAFETY: Original implementation missing safety documentation unsafe { self.spawn_unchecked(fut) } } /// Attempts to run a task if at least one is scheduled. /// /// Running a scheduled task means simply polling its future once. /// /// # Examples /// /// ```ignore /// use edge_executor::Executor; /// /// let ex: Executor = Default::default(); /// assert!(!ex.try_tick()); // no tasks to run /// /// let task = ex.spawn(async { /// println!("Hello world"); /// }); /// assert!(ex.try_tick()); // a task was found /// ``` pub fn try_tick(&self) -> bool { if let Some(runnable) = self.try_runnable() { runnable.run(); true } else { false } } /// Runs a single task asynchronously. /// /// Running a task means simply polling its future once. /// /// If no tasks are scheduled when this method is called, it will wait until one is scheduled. /// /// # Examples /// /// ```ignore /// use edge_executor::{Executor, block_on}; /// /// let ex: Executor = Default::default(); /// /// let task = ex.spawn(async { /// println!("Hello world"); /// }); /// block_on(ex.tick()); // runs the task /// ``` pub async fn tick(&self) { self.runnable().await.run(); } /// Runs the executor asynchronously until the given future completes. /// /// # Examples /// /// ```ignore /// use edge_executor::{Executor, block_on}; /// /// let ex: Executor = Default::default(); /// /// let task = ex.spawn(async { 1 + 2 }); /// let res = block_on(ex.run(async { task.await * 2 })); /// /// assert_eq!(res, 6); /// ``` pub async fn run<F>(&self, fut: F) -> F::Output where F: Future + Send + 'a, { // SAFETY: Original implementation missing safety documentation unsafe { self.run_unchecked(fut).await } } /// Waits for the next runnable task to run. async fn runnable(&self) -> Runnable { poll_fn(|ctx| self.poll_runnable(ctx)).await } /// Polls the first task scheduled for execution by the executor. fn poll_runnable(&self, ctx: &Context<'_>) -> Poll<Runnable> { self.state().waker.register(ctx.waker()); if let Some(runnable) = self.try_runnable() { Poll::Ready(runnable) } else { Poll::Pending } } /// Pops the first task scheduled for execution by the executor. /// /// Returns /// - `None` - if no task was scheduled for execution /// - `Some(Runnable)` - the first task scheduled for execution. Calling `Runnable::run` will /// execute the task. In other words, it will poll its future. fn try_runnable(&self) -> Option<Runnable> { let runnable; #[cfg(all( target_has_atomic = "8", target_has_atomic = "16", target_has_atomic = "32", target_has_atomic = "64", target_has_atomic = "ptr" ))] { runnable = self.state().queue.pop(); } #[cfg(not(all( target_has_atomic = "8", target_has_atomic = "16", target_has_atomic = "32", target_has_atomic = "64", target_has_atomic = "ptr" )))] { runnable = self.state().queue.dequeue(); } runnable } /// # Safety /// /// Original implementation missing safety documentation unsafe fn spawn_unchecked<F>(&self, fut: F) -> Task<F::Output> where F: Future, { let schedule = { let state = self.state().clone(); move |runnable| { #[cfg(all( target_has_atomic = "8", target_has_atomic = "16", target_has_atomic = "32", target_has_atomic = "64", target_has_atomic = "ptr" ))] { state.queue.push(runnable).unwrap(); } #[cfg(not(all( target_has_atomic = "8", target_has_atomic = "16", target_has_atomic = "32", target_has_atomic = "64", target_has_atomic = "ptr" )))] { state.queue.enqueue(runnable).unwrap(); } if let Some(waker) = state.waker.take() { waker.wake(); } } }; // SAFETY: Original implementation missing safety documentation let (runnable, task) = unsafe { async_task::spawn_unchecked(fut, schedule) }; runnable.schedule(); task } /// # Safety /// /// Original implementation missing safety documentation async unsafe fn run_unchecked<F>(&self, fut: F) -> F::Output where F: Future, { let run_forever = async { loop { self.tick().await; } }; run_forever.or(fut).await } /// Returns a reference to the inner state. fn state(&self) -> &Arc<State<C>> { &self.state } } impl<'a, const C: usize> Default for Executor<'a, C> { fn default() -> Self { Self::new() } } // SAFETY: Original implementation missing safety documentation unsafe impl<'a, const C: usize> Send for Executor<'a, C> {} // SAFETY: Original implementation missing safety documentation unsafe impl<'a, const C: usize> Sync for Executor<'a, C> {} /// A thread-local executor. /// /// The executor can only be run on the thread that created it. /// /// # Examples /// /// ```ignore /// use edge_executor::{LocalExecutor, block_on}; /// /// let local_ex: LocalExecutor = Default::default(); /// /// block_on(local_ex.run(async { /// println!("Hello world!"); /// })); /// ``` pub struct LocalExecutor<'a, const C: usize = 64> { executor: Executor<'a, C>, _not_send: PhantomData<core::cell::UnsafeCell<&'a Rc<()>>>, } impl<'a, const C: usize> LocalExecutor<'a, C> { /// Creates a single-threaded executor. /// /// # Examples /// /// ```ignore /// use edge_executor::LocalExecutor; /// /// let local_ex: LocalExecutor = Default::default(); /// ``` pub const fn new() -> Self { Self { executor: Executor::<C>::new(), _not_send: PhantomData, } } /// Spawns a task onto the executor. /// /// # Examples /// /// ```ignore /// use edge_executor::LocalExecutor; /// /// let local_ex: LocalExecutor = Default::default(); /// /// let task = local_ex.spawn(async { /// println!("Hello world"); /// }); /// ``` /// /// Note that if the executor's queue size is equal to the number of currently /// spawned and running tasks, spawning this additional task might cause the executor to panic /// later, when the task is scheduled for polling. pub fn spawn<F>(&self, fut: F) -> Task<F::Output> where F: Future + 'a, F::Output: 'a, { // SAFETY: Original implementation missing safety documentation unsafe { self.executor.spawn_unchecked(fut) } } /// Attempts to run a task if at least one is scheduled. /// /// Running a scheduled task means simply polling its future once. /// /// # Examples /// /// ```ignore /// use edge_executor::LocalExecutor; /// /// let local_ex: LocalExecutor = Default::default(); /// assert!(!local_ex.try_tick()); // no tasks to run /// /// let task = local_ex.spawn(async { /// println!("Hello world"); /// }); /// assert!(local_ex.try_tick()); // a task was found /// ``` pub fn try_tick(&self) -> bool { self.executor.try_tick() } /// Runs a single task asynchronously. /// /// Running a task means simply polling its future once. /// /// If no tasks are scheduled when this method is called, it will wait until one is scheduled. /// /// # Examples /// /// ```ignore /// use edge_executor::{LocalExecutor, block_on}; /// /// let local_ex: LocalExecutor = Default::default(); /// /// let task = local_ex.spawn(async { /// println!("Hello world"); /// }); /// block_on(local_ex.tick()); // runs the task /// ``` pub async fn tick(&self) { self.executor.tick().await; } /// Runs the executor asynchronously until the given future completes. /// /// # Examples /// /// ```ignore /// use edge_executor::{LocalExecutor, block_on}; /// /// let local_ex: LocalExecutor = Default::default(); /// /// let task = local_ex.spawn(async { 1 + 2 }); /// let res = block_on(local_ex.run(async { task.await * 2 })); /// /// assert_eq!(res, 6); /// ``` pub async fn run<F>(&self, fut: F) -> F::Output where F: Future, { // SAFETY: Original implementation missing safety documentation unsafe { self.executor.run_unchecked(fut) }.await } } impl<'a, const C: usize> Default for LocalExecutor<'a, C> { fn default() -> Self { Self::new() } } struct State<const C: usize> { #[cfg(all( target_has_atomic = "8", target_has_atomic = "16", target_has_atomic = "32", target_has_atomic = "64", target_has_atomic = "ptr" ))] queue: crossbeam_queue::ArrayQueue<Runnable>, #[cfg(not(all( target_has_atomic = "8", target_has_atomic = "16", target_has_atomic = "32", target_has_atomic = "64", target_has_atomic = "ptr" )))] queue: heapless::mpmc::Queue<Runnable, C>, waker: AtomicWaker, } impl<const C: usize> State<C> { fn new() -> Self { Self { #[cfg(all( target_has_atomic = "8", target_has_atomic = "16", target_has_atomic = "32", target_has_atomic = "64", target_has_atomic = "ptr" ))] queue: crossbeam_queue::ArrayQueue::new(C), #[cfg(not(all( target_has_atomic = "8", target_has_atomic = "16", target_has_atomic = "32", target_has_atomic = "64", target_has_atomic = "ptr" )))] #[allow(deprecated)] queue: heapless::mpmc::Queue::new(), waker: AtomicWaker::new(), } } } #[cfg(test)] mod different_executor_tests { use core::cell::Cell; use bevy_tasks::{ block_on, futures_lite::{pending, poll_once}, }; use futures_lite::pin; use super::LocalExecutor; #[test] fn shared_queue_slot() { block_on(async { let was_polled = Cell::new(false); let future = async { was_polled.set(true); pending::<()>().await; }; let ex1: LocalExecutor = Default::default(); let ex2: LocalExecutor = Default::default(); // Start the futures for running forever. let (run1, run2) = (ex1.run(pending::<()>()), ex2.run(pending::<()>())); pin!(run1); pin!(run2); assert!(poll_once(run1.as_mut()).await.is_none()); assert!(poll_once(run2.as_mut()).await.is_none()); // Spawn the future on executor one and then poll executor two. ex1.spawn(future).detach(); assert!(poll_once(run2).await.is_none()); assert!(!was_polled.get()); // Poll the first one. assert!(poll_once(run1).await.is_none()); assert!(was_polled.get()); }); } } #[cfg(test)] mod drop_tests { use alloc::string::String; use core::mem; use core::sync::atomic::{AtomicUsize, Ordering}; use core::task::{Poll, Waker}; use std::sync::Mutex; use bevy_platform::sync::LazyLock; use futures_lite::future; use super::{Executor, Task}; #[test] fn leaked_executor_leaks_everything() { static DROP: AtomicUsize = AtomicUsize::new(0); static WAKER: LazyLock<Mutex<Option<Waker>>> = LazyLock::new(Default::default); let ex: Executor = Default::default(); let task = ex.spawn(async { let _guard = CallOnDrop(|| { DROP.fetch_add(1, Ordering::SeqCst); }); future::poll_fn(|cx| { *WAKER.lock().unwrap() = Some(cx.waker().clone()); Poll::Pending::<()> }) .await; }); future::block_on(ex.tick()); assert!(WAKER.lock().unwrap().is_some()); assert_eq!(DROP.load(Ordering::SeqCst), 0); mem::forget(ex); assert_eq!(DROP.load(Ordering::SeqCst), 0); assert!(future::block_on(future::poll_once(task)).is_none()); assert_eq!(DROP.load(Ordering::SeqCst), 0); } #[test] fn await_task_after_dropping_executor() { let s: String = "hello".into(); let ex: Executor = Default::default(); let task: Task<&str> = ex.spawn(async { &*s }); assert!(ex.try_tick()); drop(ex); assert_eq!(future::block_on(task), "hello"); drop(s); } #[test] fn drop_executor_and_then_drop_finished_task() { static DROP: AtomicUsize = AtomicUsize::new(0); let ex: Executor = Default::default(); let task = ex.spawn(async { CallOnDrop(|| { DROP.fetch_add(1, Ordering::SeqCst); }) }); assert!(ex.try_tick()); assert_eq!(DROP.load(Ordering::SeqCst), 0); drop(ex); assert_eq!(DROP.load(Ordering::SeqCst), 0); drop(task); assert_eq!(DROP.load(Ordering::SeqCst), 1); } #[test] fn drop_finished_task_and_then_drop_executor() { static DROP: AtomicUsize = AtomicUsize::new(0); let ex: Executor = Default::default(); let task = ex.spawn(async { CallOnDrop(|| { DROP.fetch_add(1, Ordering::SeqCst); }) }); assert!(ex.try_tick()); assert_eq!(DROP.load(Ordering::SeqCst), 0); drop(task); assert_eq!(DROP.load(Ordering::SeqCst), 1); drop(ex); assert_eq!(DROP.load(Ordering::SeqCst), 1); } struct CallOnDrop<F: Fn()>(F); impl<F: Fn()> Drop for CallOnDrop<F> { fn drop(&mut self) { (self.0)(); } } } #[cfg(test)] mod local_queue { use alloc::boxed::Box; use futures_lite::{future, pin}; use super::Executor; #[test] fn two_queues() { future::block_on(async { // Create an executor with two runners. let ex: Executor = Default::default(); let (run1, run2) = ( ex.run(future::pending::<()>()), ex.run(future::pending::<()>()), ); let mut run1 = Box::pin(run1); pin!(run2); // Poll them both. assert!(future::poll_once(run1.as_mut()).await.is_none()); assert!(future::poll_once(run2.as_mut()).await.is_none()); // Drop the first one, which should leave the local queue in the `None` state. drop(run1); assert!(future::poll_once(run2.as_mut()).await.is_none()); }); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_tasks/src/usages.rs
crates/bevy_tasks/src/usages.rs
use super::TaskPool; use bevy_platform::sync::OnceLock; use core::ops::Deref; macro_rules! taskpool { ($(#[$attr:meta])* ($static:ident, $type:ident)) => { static $static: OnceLock<$type> = OnceLock::new(); $(#[$attr])* #[derive(Debug)] pub struct $type(TaskPool); impl $type { #[doc = concat!(" Gets the global [`", stringify!($type), "`] instance, or initializes it with `f`.")] pub fn get_or_init(f: impl FnOnce() -> TaskPool) -> &'static Self { $static.get_or_init(|| Self(f())) } #[doc = concat!(" Attempts to get the global [`", stringify!($type), "`] instance, \ or returns `None` if it is not initialized.")] pub fn try_get() -> Option<&'static Self> { $static.get() } #[doc = concat!(" Gets the global [`", stringify!($type), "`] instance.")] #[doc = ""] #[doc = " # Panics"] #[doc = " Panics if the global instance has not been initialized yet."] pub fn get() -> &'static Self { $static.get().expect( concat!( "The ", stringify!($type), " has not been initialized yet. Please call ", stringify!($type), "::get_or_init beforehand." ) ) } } impl Deref for $type { type Target = TaskPool; fn deref(&self) -> &Self::Target { &self.0 } } }; } taskpool! { /// A newtype for a task pool for CPU-intensive work that must be completed to /// deliver the next frame /// /// See [`TaskPool`] documentation for details on Bevy tasks. /// [`AsyncComputeTaskPool`] should be preferred if the work does not have to be /// completed before the next frame. (COMPUTE_TASK_POOL, ComputeTaskPool) } taskpool! { /// A newtype for a task pool for CPU-intensive work that may span across multiple frames /// /// See [`TaskPool`] documentation for details on Bevy tasks. /// Use [`ComputeTaskPool`] if the work must be complete before advancing to the next frame. (ASYNC_COMPUTE_TASK_POOL, AsyncComputeTaskPool) } taskpool! { /// A newtype for a task pool for IO-intensive work (i.e. tasks that spend very little time in a /// "woken" state) /// /// See [`TaskPool`] documentation for details on Bevy tasks. (IO_TASK_POOL, IoTaskPool) } crate::cfg::web! { if {} else { /// A function used by `bevy_app` to tick the global tasks pools on the main thread. /// This will run a maximum of 100 local tasks per executor per call to this function. /// /// # Warning /// /// This function *must* be called on the main thread, or the task pools will not be updated appropriately. pub fn tick_global_task_pools_on_main_thread() { COMPUTE_TASK_POOL .get() .unwrap() .with_local_executor(|compute_local_executor| { ASYNC_COMPUTE_TASK_POOL .get() .unwrap() .with_local_executor(|async_local_executor| { IO_TASK_POOL .get() .unwrap() .with_local_executor(|io_local_executor| { for _ in 0..100 { compute_local_executor.try_tick(); async_local_executor.try_tick(); io_local_executor.try_tick(); } }); }); }); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_tasks/src/iter/adapters.rs
crates/bevy_tasks/src/iter/adapters.rs
use crate::iter::ParallelIterator; /// Chains two [`ParallelIterator`]s `T` and `U`, first returning /// batches from `T`, and then from `U`. #[derive(Debug)] pub struct Chain<T, U> { pub(crate) left: T, pub(crate) right: U, pub(crate) left_in_progress: bool, } impl<B, T, U> ParallelIterator<B> for Chain<T, U> where B: Iterator + Send, T: ParallelIterator<B>, U: ParallelIterator<B>, { fn next_batch(&mut self) -> Option<B> { if self.left_in_progress { match self.left.next_batch() { b @ Some(_) => return b, None => self.left_in_progress = false, } } self.right.next_batch() } } /// Maps a [`ParallelIterator`] `P` using the provided function `F`. #[derive(Debug)] pub struct Map<P, F> { pub(crate) iter: P, pub(crate) f: F, } impl<B, U, T, F> ParallelIterator<core::iter::Map<B, F>> for Map<U, F> where B: Iterator + Send, U: ParallelIterator<B>, F: FnMut(B::Item) -> T + Send + Clone, { fn next_batch(&mut self) -> Option<core::iter::Map<B, F>> { self.iter.next_batch().map(|b| b.map(self.f.clone())) } } /// Filters a [`ParallelIterator`] `P` using the provided predicate `F`. #[derive(Debug)] pub struct Filter<P, F> { pub(crate) iter: P, pub(crate) predicate: F, } impl<B, P, F> ParallelIterator<core::iter::Filter<B, F>> for Filter<P, F> where B: Iterator + Send, P: ParallelIterator<B>, F: FnMut(&B::Item) -> bool + Send + Clone, { fn next_batch(&mut self) -> Option<core::iter::Filter<B, F>> { self.iter .next_batch() .map(|b| b.filter(self.predicate.clone())) } } /// Filter-maps a [`ParallelIterator`] `P` using the provided function `F`. #[derive(Debug)] pub struct FilterMap<P, F> { pub(crate) iter: P, pub(crate) f: F, } impl<B, P, R, F> ParallelIterator<core::iter::FilterMap<B, F>> for FilterMap<P, F> where B: Iterator + Send, P: ParallelIterator<B>, F: FnMut(B::Item) -> Option<R> + Send + Clone, { fn next_batch(&mut self) -> Option<core::iter::FilterMap<B, F>> { self.iter.next_batch().map(|b| b.filter_map(self.f.clone())) } } /// Flat-maps a [`ParallelIterator`] `P` using the provided function `F`. #[derive(Debug)] pub struct FlatMap<P, F> { pub(crate) iter: P, pub(crate) f: F, } impl<B, P, U, F> ParallelIterator<core::iter::FlatMap<B, U, F>> for FlatMap<P, F> where B: Iterator + Send, P: ParallelIterator<B>, F: FnMut(B::Item) -> U + Send + Clone, U: IntoIterator, U::IntoIter: Send, { // This extends each batch using the flat map. The other option is // to turn each IntoIter into its own batch. fn next_batch(&mut self) -> Option<core::iter::FlatMap<B, U, F>> { self.iter.next_batch().map(|b| b.flat_map(self.f.clone())) } } /// Flattens a [`ParallelIterator`] `P`. #[derive(Debug)] pub struct Flatten<P> { pub(crate) iter: P, } impl<B, P> ParallelIterator<core::iter::Flatten<B>> for Flatten<P> where B: Iterator + Send, P: ParallelIterator<B>, B::Item: IntoIterator, <B::Item as IntoIterator>::IntoIter: Send, { // This extends each batch using the flatten. The other option is to // turn each IntoIter into its own batch. fn next_batch(&mut self) -> Option<core::iter::Flatten<B>> { self.iter.next_batch().map(Iterator::flatten) } } /// Fuses a [`ParallelIterator`] `P`, ensuring once it returns [`None`] once, it always /// returns [`None`]. #[derive(Debug)] pub struct Fuse<P> { pub(crate) iter: Option<P>, } impl<B, P> ParallelIterator<B> for Fuse<P> where B: Iterator + Send, P: ParallelIterator<B>, { fn next_batch(&mut self) -> Option<B> { match &mut self.iter { Some(iter) => iter.next_batch().or_else(|| { self.iter = None; None }), None => None, } } } /// Inspects a [`ParallelIterator`] `P` using the provided function `F`. #[derive(Debug)] pub struct Inspect<P, F> { pub(crate) iter: P, pub(crate) f: F, } impl<B, P, F> ParallelIterator<core::iter::Inspect<B, F>> for Inspect<P, F> where B: Iterator + Send, P: ParallelIterator<B>, F: FnMut(&B::Item) + Send + Clone, { fn next_batch(&mut self) -> Option<core::iter::Inspect<B, F>> { self.iter.next_batch().map(|b| b.inspect(self.f.clone())) } } /// Copies a [`ParallelIterator`] `P`'s returned values. #[derive(Debug)] pub struct Copied<P> { pub(crate) iter: P, } impl<'a, B, P, T> ParallelIterator<core::iter::Copied<B>> for Copied<P> where B: Iterator<Item = &'a T> + Send, P: ParallelIterator<B>, T: 'a + Copy, { fn next_batch(&mut self) -> Option<core::iter::Copied<B>> { self.iter.next_batch().map(Iterator::copied) } } /// Clones a [`ParallelIterator`] `P`'s returned values. #[derive(Debug)] pub struct Cloned<P> { pub(crate) iter: P, } impl<'a, B, P, T> ParallelIterator<core::iter::Cloned<B>> for Cloned<P> where B: Iterator<Item = &'a T> + Send, P: ParallelIterator<B>, T: 'a + Copy, { fn next_batch(&mut self) -> Option<core::iter::Cloned<B>> { self.iter.next_batch().map(Iterator::cloned) } } /// Cycles a [`ParallelIterator`] `P` indefinitely. #[derive(Debug)] pub struct Cycle<P> { pub(crate) iter: P, pub(crate) curr: Option<P>, } impl<B, P> ParallelIterator<B> for Cycle<P> where B: Iterator + Send, P: ParallelIterator<B> + Clone, { fn next_batch(&mut self) -> Option<B> { self.curr .as_mut() .and_then(ParallelIterator::next_batch) .or_else(|| { self.curr = Some(self.iter.clone()); self.next_batch() }) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_tasks/src/iter/mod.rs
crates/bevy_tasks/src/iter/mod.rs
use crate::TaskPool; use alloc::vec::Vec; mod adapters; pub use adapters::*; /// [`ParallelIterator`] closely emulates the `std::iter::Iterator` /// interface. However, it uses `bevy_task` to compute batches in parallel. /// /// Note that the overhead of [`ParallelIterator`] is high relative to some /// workloads. In particular, if the batch size is too small or task being /// run in parallel is inexpensive, *a [`ParallelIterator`] could take longer /// than a normal [`Iterator`]*. Therefore, you should profile your code before /// using [`ParallelIterator`]. pub trait ParallelIterator<BatchIter> where BatchIter: Iterator + Send, Self: Sized + Send, { /// Returns the next batch of items for processing. /// /// Each batch is an iterator with items of the same type as the /// [`ParallelIterator`]. Returns `None` when there are no batches left. fn next_batch(&mut self) -> Option<BatchIter>; /// Returns the bounds on the remaining number of items in the /// parallel iterator. /// /// See [`Iterator::size_hint()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.size_hint) fn size_hint(&self) -> (usize, Option<usize>) { (0, None) } /// Consumes the parallel iterator and returns the number of items. /// /// See [`Iterator::count()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.count) fn count(mut self, pool: &TaskPool) -> usize { pool.scope(|s| { while let Some(batch) = self.next_batch() { s.spawn(async move { batch.count() }); } }) .iter() .sum() } /// Consumes the parallel iterator and returns the last item. /// /// See [`Iterator::last()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.last) fn last(mut self, _pool: &TaskPool) -> Option<BatchIter::Item> { let mut last_item = None; while let Some(batch) = self.next_batch() { last_item = batch.last(); } last_item } /// Consumes the parallel iterator and returns the nth item. /// /// See [`Iterator::nth()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.nth) // TODO: Optimize with size_hint on each batch fn nth(mut self, _pool: &TaskPool, n: usize) -> Option<BatchIter::Item> { let mut i = 0; while let Some(batch) = self.next_batch() { for item in batch { if i == n { return Some(item); } i += 1; } } None } /// Takes two parallel iterators and returns a parallel iterators over /// both in sequence. /// /// See [`Iterator::chain()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.chain) // TODO: Use IntoParallelIterator for U fn chain<U>(self, other: U) -> Chain<Self, U> where U: ParallelIterator<BatchIter>, { Chain { left: self, right: other, left_in_progress: true, } } /// Takes a closure and creates a parallel iterator which calls that /// closure on each item. /// /// See [`Iterator::map()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map) fn map<T, F>(self, f: F) -> Map<Self, F> where F: FnMut(BatchIter::Item) -> T + Send + Clone, { Map { iter: self, f } } /// Calls a closure on each item of a parallel iterator. /// /// See [`Iterator::for_each()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.for_each) fn for_each<F>(mut self, pool: &TaskPool, f: F) where F: FnMut(BatchIter::Item) + Send + Clone + Sync, { pool.scope(|s| { while let Some(batch) = self.next_batch() { let newf = f.clone(); s.spawn(async move { batch.for_each(newf); }); } }); } /// Creates a parallel iterator which uses a closure to determine /// if an element should be yielded. /// /// See [`Iterator::filter()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.filter) fn filter<F>(self, predicate: F) -> Filter<Self, F> where F: FnMut(&BatchIter::Item) -> bool, { Filter { iter: self, predicate, } } /// Creates a parallel iterator that both filters and maps. /// /// See [`Iterator::filter_map()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.filter_map) fn filter_map<R, F>(self, f: F) -> FilterMap<Self, F> where F: FnMut(BatchIter::Item) -> Option<R>, { FilterMap { iter: self, f } } /// Creates a parallel iterator that works like map, but flattens /// nested structure. /// /// See [`Iterator::flat_map()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.flat_map) fn flat_map<U, F>(self, f: F) -> FlatMap<Self, F> where F: FnMut(BatchIter::Item) -> U, U: IntoIterator, { FlatMap { iter: self, f } } /// Creates a parallel iterator that flattens nested structure. /// /// See [`Iterator::flatten()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.flatten) fn flatten(self) -> Flatten<Self> where BatchIter::Item: IntoIterator, { Flatten { iter: self } } /// Creates a parallel iterator which ends after the first None. /// /// See [`Iterator::fuse()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.fuse) fn fuse(self) -> Fuse<Self> { Fuse { iter: Some(self) } } /// Does something with each item of a parallel iterator, passing /// the value on. /// /// See [`Iterator::inspect()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.inspect) fn inspect<F>(self, f: F) -> Inspect<Self, F> where F: FnMut(&BatchIter::Item), { Inspect { iter: self, f } } /// Borrows a parallel iterator, rather than consuming it. /// /// See [`Iterator::by_ref()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.by_ref) fn by_ref(&mut self) -> &mut Self { self } /// Transforms a parallel iterator into a collection. /// /// See [`Iterator::collect()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect) // TODO: Investigate optimizations for less copying fn collect<C>(mut self, pool: &TaskPool) -> C where C: FromIterator<BatchIter::Item>, BatchIter::Item: Send + 'static, { pool.scope(|s| { while let Some(batch) = self.next_batch() { s.spawn(async move { batch.collect::<Vec<_>>() }); } }) .into_iter() .flatten() .collect() } /// Consumes a parallel iterator, creating two collections from it. /// /// See [`Iterator::partition()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.partition) // TODO: Investigate optimizations for less copying fn partition<C, F>(mut self, pool: &TaskPool, f: F) -> (C, C) where C: Default + Extend<BatchIter::Item> + Send, F: FnMut(&BatchIter::Item) -> bool + Send + Sync + Clone, BatchIter::Item: Send + 'static, { 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::<Vec<_>, F>(newf) }); } }) .into_iter() .for_each(|(c, d)| { a.extend(c); b.extend(d); }); (a, b) } /// Repeatedly applies a function to items of each batch of a parallel /// iterator, producing a Vec of final values. /// /// *Note that this folds each batch independently and returns a Vec of /// results (in batch order).* /// /// See [`Iterator::fold()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.fold) fn fold<C, F, D>(mut self, pool: &TaskPool, init: C, f: F) -> Vec<C> where F: FnMut(C, BatchIter::Item) -> C + Send + Sync + Clone, C: Clone + Send + Sync + 'static, { 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) }); } }) } /// Tests if every element of the parallel iterator matches a predicate. /// /// *Note that all is **not** short circuiting.* /// /// See [`Iterator::all()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.all) fn all<F>(mut self, pool: &TaskPool, f: F) -> bool where F: FnMut(BatchIter::Item) -> bool + Send + Sync + Clone, { pool.scope(|s| { while let Some(mut batch) = self.next_batch() { let newf = f.clone(); s.spawn(async move { batch.all(newf) }); } }) .into_iter() .all(core::convert::identity) } /// Tests if any element of the parallel iterator matches a predicate. /// /// *Note that any is **not** short circuiting.* /// /// See [`Iterator::any()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.any) fn any<F>(mut self, pool: &TaskPool, f: F) -> bool where F: FnMut(BatchIter::Item) -> bool + Send + Sync + Clone, { pool.scope(|s| { while let Some(mut batch) = self.next_batch() { let newf = f.clone(); s.spawn(async move { batch.any(newf) }); } }) .into_iter() .any(core::convert::identity) } /// Searches for an element in a parallel iterator, returning its index. /// /// *Note that position consumes the whole iterator.* /// /// See [`Iterator::position()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.position) // TODO: Investigate optimizations for less copying fn position<F>(mut self, pool: &TaskPool, f: F) -> Option<usize> where F: FnMut(BatchIter::Item) -> bool + Send + Sync + Clone, { let poses = pool.scope(|s| { while let Some(batch) = self.next_batch() { let mut newf = f.clone(); s.spawn(async move { let mut len = 0; let mut pos = None; for item in batch { if pos.is_none() && newf(item) { pos = Some(len); } len += 1; } (len, pos) }); } }); let mut start = 0; for (len, pos) in poses { if let Some(pos) = pos { return Some(start + pos); } start += len; } None } /// Returns the maximum item of a parallel iterator. /// /// See [`Iterator::max()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.max) fn max(mut self, pool: &TaskPool) -> Option<BatchIter::Item> where BatchIter::Item: Ord + Send + 'static, { pool.scope(|s| { while let Some(batch) = self.next_batch() { s.spawn(async move { batch.max() }); } }) .into_iter() .flatten() .max() } /// Returns the minimum item of a parallel iterator. /// /// See [`Iterator::min()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.min) fn min(mut self, pool: &TaskPool) -> Option<BatchIter::Item> where BatchIter::Item: Ord + Send + 'static, { pool.scope(|s| { while let Some(batch) = self.next_batch() { s.spawn(async move { batch.min() }); } }) .into_iter() .flatten() .min() } /// Returns the item that gives the maximum value from the specified function. /// /// See [`Iterator::max_by_key()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.max_by_key) fn max_by_key<R, F>(mut self, pool: &TaskPool, f: F) -> Option<BatchIter::Item> where R: Ord, F: FnMut(&BatchIter::Item) -> R + Send + Sync + Clone, BatchIter::Item: Send + 'static, { pool.scope(|s| { while let Some(batch) = self.next_batch() { let newf = f.clone(); s.spawn(async move { batch.max_by_key(newf) }); } }) .into_iter() .flatten() .max_by_key(f) } /// Returns the item that gives the maximum value with respect to the specified comparison /// function. /// /// See [`Iterator::max_by()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.max_by) fn max_by<F>(mut self, pool: &TaskPool, f: F) -> Option<BatchIter::Item> where F: FnMut(&BatchIter::Item, &BatchIter::Item) -> core::cmp::Ordering + Send + Sync + Clone, BatchIter::Item: Send + 'static, { pool.scope(|s| { while let Some(batch) = self.next_batch() { let newf = f.clone(); s.spawn(async move { batch.max_by(newf) }); } }) .into_iter() .flatten() .max_by(f) } /// Returns the item that gives the minimum value from the specified function. /// /// See [`Iterator::min_by_key()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.min_by_key) fn min_by_key<R, F>(mut self, pool: &TaskPool, f: F) -> Option<BatchIter::Item> where R: Ord, F: FnMut(&BatchIter::Item) -> R + Send + Sync + Clone, BatchIter::Item: Send + 'static, { pool.scope(|s| { while let Some(batch) = self.next_batch() { let newf = f.clone(); s.spawn(async move { batch.min_by_key(newf) }); } }) .into_iter() .flatten() .min_by_key(f) } /// Returns the item that gives the minimum value with respect to the specified comparison /// function. /// /// See [`Iterator::min_by()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.min_by) fn min_by<F>(mut self, pool: &TaskPool, f: F) -> Option<BatchIter::Item> where F: FnMut(&BatchIter::Item, &BatchIter::Item) -> core::cmp::Ordering + Send + Sync + Clone, BatchIter::Item: Send + 'static, { pool.scope(|s| { while let Some(batch) = self.next_batch() { let newf = f.clone(); s.spawn(async move { batch.min_by(newf) }); } }) .into_iter() .flatten() .min_by(f) } /// Creates a parallel iterator which copies all of its items. /// /// See [`Iterator::copied()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.copied) fn copied<'a, T>(self) -> Copied<Self> where Self: ParallelIterator<BatchIter>, T: 'a + Copy, { Copied { iter: self } } /// Creates a parallel iterator which clones all of its items. /// /// See [`Iterator::cloned()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.cloned) fn cloned<'a, T>(self) -> Cloned<Self> where Self: ParallelIterator<BatchIter>, T: 'a + Copy, { Cloned { iter: self } } /// Repeats a parallel iterator endlessly. /// /// See [`Iterator::cycle()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.cycle) fn cycle(self) -> Cycle<Self> where Self: Clone, { Cycle { iter: self, curr: None, } } /// Sums the items of a parallel iterator. /// /// See [`Iterator::sum()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.sum) fn sum<S, R>(mut self, pool: &TaskPool) -> R where S: core::iter::Sum<BatchIter::Item> + Send + 'static, R: core::iter::Sum<S>, { pool.scope(|s| { while let Some(batch) = self.next_batch() { s.spawn(async move { batch.sum() }); } }) .into_iter() .sum() } /// Multiplies all the items of a parallel iterator. /// /// See [`Iterator::product()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.product) fn product<S, R>(mut self, pool: &TaskPool) -> R where S: core::iter::Product<BatchIter::Item> + Send + 'static, R: core::iter::Product<S>, { pool.scope(|s| { while let Some(batch) = self.next_batch() { s.spawn(async move { batch.product() }); } }) .into_iter() .product() } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_tasks/examples/idle_behavior.rs
crates/bevy_tasks/examples/idle_behavior.rs
//! This sample demonstrates a thread pool with one thread per logical core and only one task //! spinning. Other than the one thread, the system should remain idle, demonstrating good behavior //! for small workloads. #![expect(clippy::print_stdout, reason = "Allowed in examples.")] use bevy_platform::time::Instant; use bevy_tasks::TaskPoolBuilder; use core::time::Duration; fn main() { let pool = TaskPoolBuilder::new() .thread_name("Idle Behavior ThreadPool".to_string()) .build(); pool.scope(|s| { for i in 0..1 { s.spawn(async move { println!("Blocking for 10 seconds"); let now = Instant::now(); while Instant::now() - now < Duration::from_millis(10000) { // spin, simulating work being done } println!( "Thread {:?} index {} finished", std::thread::current().id(), i ); }); } }); println!("all tasks finished"); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_tasks/examples/busy_behavior.rs
crates/bevy_tasks/examples/busy_behavior.rs
//! This sample demonstrates creating a thread pool with 4 tasks and spawning 40 tasks that spin //! for 100ms. It's expected to take about a second to run (assuming the machine has >= 4 logical //! cores) #![expect(clippy::print_stdout, reason = "Allowed in examples.")] use bevy_platform::time::Instant; use bevy_tasks::TaskPoolBuilder; use core::time::Duration; fn main() { let pool = TaskPoolBuilder::new() .thread_name("Busy Behavior ThreadPool".to_string()) .num_threads(4) .build(); let t0 = Instant::now(); pool.scope(|s| { for i in 0..40 { s.spawn(async move { let now = Instant::now(); while Instant::now() - now < Duration::from_millis(100) { // spin, simulating work being done } println!( "Thread {:?} index {} finished", std::thread::current().id(), i ); }); } }); let t1 = Instant::now(); println!("all tasks finished in {} secs", (t1 - t0).as_secs_f32()); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui_widgets/src/button.rs
crates/bevy_ui_widgets/src/button.rs
use accesskit::Role; use bevy_a11y::AccessibilityNode; use bevy_app::{App, Plugin}; use bevy_ecs::query::Has; use bevy_ecs::{ component::Component, entity::Entity, observer::On, query::With, system::{Commands, Query}, }; use bevy_input::keyboard::{KeyCode, KeyboardInput}; use bevy_input::ButtonState; use bevy_input_focus::FocusedInput; use bevy_picking::events::{Cancel, Click, DragEnd, Pointer, Press, Release}; use bevy_ui::{InteractionDisabled, Pressed}; use crate::Activate; /// Headless button widget. This widget maintains a "pressed" state, which is used to /// indicate whether the button is currently being pressed by the user. It emits an [`Activate`] /// event when the button is un-pressed. #[derive(Component, Default, Debug)] #[require(AccessibilityNode(accesskit::Node::new(Role::Button)))] pub struct Button; fn button_on_key_event( mut event: On<FocusedInput<KeyboardInput>>, q_state: Query<Has<InteractionDisabled>, With<Button>>, mut commands: Commands, ) { if let Ok(disabled) = q_state.get(event.focused_entity) && !disabled { let input_event = &event.input; if !input_event.repeat && input_event.state == ButtonState::Pressed && (input_event.key_code == KeyCode::Enter || input_event.key_code == KeyCode::Space) { event.propagate(false); commands.trigger(Activate { entity: event.focused_entity, }); } } } fn button_on_pointer_click( mut click: On<Pointer<Click>>, mut q_state: Query<(Has<Pressed>, Has<InteractionDisabled>), With<Button>>, mut commands: Commands, ) { if let Ok((pressed, disabled)) = q_state.get_mut(click.entity) { click.propagate(false); if pressed && !disabled { commands.trigger(Activate { entity: click.entity, }); } } } fn button_on_pointer_down( mut press: On<Pointer<Press>>, mut q_state: Query<(Entity, Has<InteractionDisabled>, Has<Pressed>), With<Button>>, mut commands: Commands, ) { if let Ok((button, disabled, pressed)) = q_state.get_mut(press.entity) { press.propagate(false); if !disabled && !pressed { commands.entity(button).insert(Pressed); } } } fn button_on_pointer_up( mut release: On<Pointer<Release>>, mut q_state: Query<(Entity, Has<InteractionDisabled>, Has<Pressed>), With<Button>>, mut commands: Commands, ) { if let Ok((button, disabled, pressed)) = q_state.get_mut(release.entity) { release.propagate(false); if !disabled && pressed { commands.entity(button).remove::<Pressed>(); } } } fn button_on_pointer_drag_end( mut drag_end: On<Pointer<DragEnd>>, mut q_state: Query<(Entity, Has<InteractionDisabled>, Has<Pressed>), With<Button>>, mut commands: Commands, ) { if let Ok((button, disabled, pressed)) = q_state.get_mut(drag_end.entity) { drag_end.propagate(false); if !disabled && pressed { commands.entity(button).remove::<Pressed>(); } } } fn button_on_pointer_cancel( mut cancel: On<Pointer<Cancel>>, mut q_state: Query<(Entity, Has<InteractionDisabled>, Has<Pressed>), With<Button>>, mut commands: Commands, ) { if let Ok((button, disabled, pressed)) = q_state.get_mut(cancel.entity) { cancel.propagate(false); if !disabled && pressed { commands.entity(button).remove::<Pressed>(); } } } /// Plugin that adds the observers for the [`Button`] widget. pub struct ButtonPlugin; impl Plugin for ButtonPlugin { fn build(&self, app: &mut App) { app.add_observer(button_on_key_event) .add_observer(button_on_pointer_down) .add_observer(button_on_pointer_up) .add_observer(button_on_pointer_click) .add_observer(button_on_pointer_drag_end) .add_observer(button_on_pointer_cancel); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui_widgets/src/observe.rs
crates/bevy_ui_widgets/src/observe.rs
// TODO: This probably doesn't belong in bevy_ui_widgets, but I am not sure where it should go. // It is certainly a useful thing to have. #![expect(unsafe_code, reason = "Unsafe code is used to improve performance.")] use core::{marker::PhantomData, mem}; use bevy_ecs::{ bundle::{Bundle, DynamicBundle}, event::EntityEvent, system::IntoObserverSystem, }; /// Helper struct that adds an observer when inserted as a [`Bundle`]. pub struct AddObserver<E: EntityEvent, B: Bundle, M, I: IntoObserverSystem<E, B, M>> { observer: I, marker: PhantomData<(E, B, M)>, } // SAFETY: Empty method bodies. unsafe impl< E: EntityEvent, B: Bundle, M: Send + Sync + 'static, I: IntoObserverSystem<E, B, M> + Send + Sync, > Bundle for AddObserver<E, B, M, I> { #[inline] fn component_ids( _components: &mut bevy_ecs::component::ComponentsRegistrator, ) -> impl Iterator<Item = bevy_ecs::component::ComponentId> + use<E, B, M, I> { // SAFETY: Empty iterator core::iter::empty() } #[inline] fn get_component_ids( _components: &bevy_ecs::component::Components, ) -> impl Iterator<Item = Option<bevy_ecs::component::ComponentId>> { // SAFETY: Empty iterator core::iter::empty() } } impl<E: EntityEvent, B: Bundle, M, I: IntoObserverSystem<E, B, M>> DynamicBundle for AddObserver<E, B, M, I> { type Effect = Self; #[inline] unsafe fn get_components( ptr: bevy_ecs::ptr::MovingPtr<'_, Self>, _func: &mut impl FnMut(bevy_ecs::component::StorageType, bevy_ecs::ptr::OwningPtr<'_>), ) { // SAFETY: We must not drop the pointer here, or it will be uninitialized in `apply_effect` // below. mem::forget(ptr); } #[inline] unsafe fn apply_effect( ptr: bevy_ecs::ptr::MovingPtr<'_, mem::MaybeUninit<Self>>, entity: &mut bevy_ecs::world::EntityWorldMut, ) { // SAFETY: The pointer was not dropped in `get_components`, so the allocation is still // initialized. let add_observer = unsafe { ptr.assume_init() }; let add_observer = add_observer.read(); entity.observe(add_observer.observer); } } /// Adds an observer as a bundle effect. pub fn observe<E: EntityEvent, B: Bundle, M, I: IntoObserverSystem<E, B, M>>( observer: I, ) -> AddObserver<E, B, M, I> { AddObserver { observer, marker: PhantomData, } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui_widgets/src/lib.rs
crates/bevy_ui_widgets/src/lib.rs
//! This crate provides a set of standard widgets for Bevy UI, such as buttons, checkboxes, and sliders. //! These widgets have no inherent styling, it's the responsibility of the user to add styling //! appropriate for their game or application. //! //! ## Warning: Experimental //! //! This crate is currently experimental and under active development. //! The API is likely to change substantially: be prepared to migrate your code. //! //! We are actively seeking feedback on the design and implementation of this crate, so please //! file issues or create PRs if you have any comments or suggestions. //! //! ## State Management //! //! Most of the widgets use external state management: this means that the widgets do not //! automatically update their own internal state, but instead rely on the app to update the widget //! state (as well as any other related game state) in response to a change event emitted by the //! widget. The primary motivation for this is to avoid two-way data binding in scenarios where the //! user interface is showing a live view of dynamic data coming from deeper within the game engine. mod button; mod checkbox; mod menu; mod observe; pub mod popover; mod radio; mod scrollbar; mod slider; pub use button::*; pub use checkbox::*; pub use menu::*; pub use observe::*; pub use radio::*; pub use scrollbar::*; pub use slider::*; use bevy_app::{PluginGroup, PluginGroupBuilder}; use bevy_ecs::{entity::Entity, event::EntityEvent}; use crate::popover::PopoverPlugin; /// A plugin group that registers the observers for all of the widgets in this crate. If you don't want to /// use all of the widgets, you can import the individual widget plugins instead. pub struct UiWidgetsPlugins; impl PluginGroup for UiWidgetsPlugins { fn build(self) -> PluginGroupBuilder { PluginGroupBuilder::start::<Self>() .add(PopoverPlugin) .add(ButtonPlugin) .add(CheckboxPlugin) .add(MenuPlugin) .add(RadioGroupPlugin) .add(ScrollbarPlugin) .add(SliderPlugin) } } /// Notification sent by a button or menu item. #[derive(Copy, Clone, Debug, PartialEq, EntityEvent)] pub struct Activate { /// The activated entity. pub entity: Entity, } /// Notification sent by a widget that edits a scalar value. #[derive(Copy, Clone, Debug, PartialEq, EntityEvent)] pub struct ValueChange<T> { /// The id of the widget that produced this value. #[event_target] pub source: Entity, /// The new value. pub value: T, }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui_widgets/src/slider.rs
crates/bevy_ui_widgets/src/slider.rs
use core::ops::RangeInclusive; use accesskit::{Orientation, Role}; use bevy_a11y::AccessibilityNode; use bevy_app::{App, Plugin}; use bevy_ecs::event::EntityEvent; use bevy_ecs::hierarchy::Children; use bevy_ecs::lifecycle::Insert; use bevy_ecs::query::Has; use bevy_ecs::system::Res; use bevy_ecs::world::DeferredWorld; use bevy_ecs::{ component::Component, observer::On, query::With, reflect::ReflectComponent, system::{Commands, Query}, }; use bevy_input::keyboard::{KeyCode, KeyboardInput}; use bevy_input::ButtonState; use bevy_input_focus::FocusedInput; use bevy_log::warn_once; use bevy_math::ops; use bevy_picking::events::{Drag, DragEnd, DragStart, Pointer, Press}; use bevy_reflect::{prelude::ReflectDefault, Reflect}; use bevy_ui::{ ComputedNode, ComputedUiRenderTargetInfo, InteractionDisabled, UiGlobalTransform, UiScale, }; use crate::ValueChange; use bevy_ecs::entity::Entity; /// Defines how the slider should behave when you click on the track (not the thumb). #[derive(Debug, Default, PartialEq, Clone, Copy, Reflect)] #[reflect(Clone, PartialEq, Default)] pub enum TrackClick { /// Clicking on the track lets you drag to edit the value, just like clicking on the thumb. #[default] Drag, /// Clicking on the track increments or decrements the slider by [`SliderStep`]. Step, /// Clicking on the track snaps the value to the clicked position. Snap, } /// A headless slider widget, which can be used to build custom sliders. Sliders have a value /// (represented by the [`SliderValue`] component) and a range (represented by [`SliderRange`]). An /// optional step size can be specified via [`SliderStep`], and you can control the rounding /// during dragging with [`SliderPrecision`]. /// /// You can also control the slider remotely by triggering a [`SetSliderValue`] event on it. This /// can be useful in a console environment for controlling the value gamepad inputs. /// /// The presence of the `on_change` property controls whether the slider uses internal or external /// state management. If the `on_change` property is `None`, then the slider updates its own state /// automatically. Otherwise, the `on_change` property contains the id of a one-shot system which is /// passed the new slider value. In this case, the slider value is not modified, it is the /// responsibility of the callback to trigger whatever data-binding mechanism is used to update the /// slider's value. /// /// Typically a slider will contain entities representing the "track" and "thumb" elements. The core /// slider makes no assumptions about the hierarchical structure of these elements, but expects that /// the thumb will be marked with a [`SliderThumb`] component. /// /// The core slider does not modify the visible position of the thumb: that is the responsibility of /// the stylist. This can be done either in percent or pixel units as desired. To prevent overhang /// at the ends of the slider, the positioning should take into account the thumb width, by reducing /// the amount of travel. So for example, in a slider 100px wide, with a thumb that is 10px, the /// amount of travel is 90px. The core slider's calculations for clicking and dragging assume this /// is the case, and will reduce the travel by the measured size of the thumb entity, which allows /// the movement of the thumb to be perfectly synchronized with the movement of the mouse. /// /// In cases where overhang is desired for artistic reasons, the thumb may have additional /// decorative child elements, absolutely positioned, which don't affect the size measurement. #[derive(Component, Debug, Default)] #[require( AccessibilityNode(accesskit::Node::new(Role::Slider)), CoreSliderDragState, SliderValue, SliderRange, SliderStep )] pub struct Slider { /// Set the track-clicking behavior for this slider. pub track_click: TrackClick, // TODO: Think about whether we want a "vertical" option. } /// Marker component that identifies which descendant element is the slider thumb. #[derive(Component, Debug, Default)] pub struct SliderThumb; /// A component which stores the current value of the slider. #[derive(Component, Debug, Default, PartialEq, Clone, Copy)] #[component(immutable)] pub struct SliderValue(pub f32); /// A component which represents the allowed range of the slider value. Defaults to 0.0..=1.0. #[derive(Component, Debug, PartialEq, Clone, Copy)] #[component(immutable)] pub struct SliderRange { /// The beginning of the allowed range for the slider value. start: f32, /// The end of the allowed range for the slider value. end: f32, } impl SliderRange { /// Creates a new slider range with the given start and end values. pub fn new(start: f32, end: f32) -> Self { if end < start { warn_once!( "Expected SliderRange::start ({}) <= SliderRange::end ({})", start, end ); } Self { start, end } } /// Creates a new slider range from a Rust range. pub fn from_range(range: RangeInclusive<f32>) -> Self { let (start, end) = range.into_inner(); Self { start, end } } /// Returns the minimum allowed value for this slider. pub fn start(&self) -> f32 { self.start } /// Return a new instance of a `SliderRange` with a new start position. pub fn with_start(&self, start: f32) -> Self { Self::new(start, self.end) } /// Returns the maximum allowed value for this slider. pub fn end(&self) -> f32 { self.end } /// Return a new instance of a `SliderRange` with a new end position. pub fn with_end(&self, end: f32) -> Self { Self::new(self.start, end) } /// Returns the full span of the range (max - min). pub fn span(&self) -> f32 { self.end - self.start } /// Returns the center value of the range. pub fn center(&self) -> f32 { (self.start + self.end) / 2.0 } /// Constrain a value between the minimum and maximum allowed values for this slider. pub fn clamp(&self, value: f32) -> f32 { value.clamp(self.start, self.end) } /// Compute the position of the thumb on the slider, as a value between 0 and 1, taking /// into account the proportion of the value between the minimum and maximum limits. pub fn thumb_position(&self, value: f32) -> f32 { if self.end > self.start { (value - self.start) / (self.end - self.start) } else { 0.5 } } } impl Default for SliderRange { fn default() -> Self { Self { start: 0.0, end: 1.0, } } } /// Defines the amount by which to increment or decrement the slider value when using keyboard /// shortcuts. Defaults to 1.0. #[derive(Component, Debug, PartialEq, Clone)] #[component(immutable)] #[derive(Reflect)] #[reflect(Component)] pub struct SliderStep(pub f32); impl Default for SliderStep { fn default() -> Self { Self(1.0) } } /// A component which controls the rounding of the slider value during dragging. /// /// Stepping is not affected, although presumably the step size will be an integer multiple of the /// rounding factor. This also doesn't prevent the slider value from being set to non-rounded values /// by other means, such as manually entering digits via a numeric input field. /// /// The value in this component represents the number of decimal places of desired precision, so a /// value of 2 would round to the nearest 1/100th. A value of -3 would round to the nearest /// thousand. #[derive(Component, Debug, Default, Clone, Copy, Reflect)] #[reflect(Component, Default)] pub struct SliderPrecision(pub i32); impl SliderPrecision { fn round(&self, value: f32) -> f32 { let factor = ops::powf(10.0_f32, self.0 as f32); (value * factor).round() / factor } } /// Component used to manage the state of a slider during dragging. #[derive(Component, Default, Reflect)] #[reflect(Component)] pub struct CoreSliderDragState { /// Whether the slider is currently being dragged. pub dragging: bool, /// The value of the slider when dragging started. offset: f32, } pub(crate) fn slider_on_pointer_down( mut press: On<Pointer<Press>>, q_slider: Query<( &Slider, &SliderValue, &SliderRange, &SliderStep, Option<&SliderPrecision>, &ComputedNode, &ComputedUiRenderTargetInfo, &UiGlobalTransform, Has<InteractionDisabled>, )>, q_thumb: Query<&ComputedNode, With<SliderThumb>>, q_children: Query<&Children>, mut commands: Commands, ui_scale: Res<UiScale>, ) { if q_thumb.contains(press.entity) { // Thumb click, stop propagation to prevent track click. press.propagate(false); } else if let Ok(( slider, value, range, step, precision, node, node_target, transform, disabled, )) = q_slider.get(press.entity) { // Track click press.propagate(false); if disabled { return; } // Detect orientation: vertical if height > width let is_vertical = node.size().y > node.size().x; // Find thumb size by searching descendants for the first entity with SliderThumb let thumb_size = q_children .iter_descendants(press.entity) .find_map(|child_id| { q_thumb.get(child_id).ok().map(|thumb| { if is_vertical { thumb.size().y } else { thumb.size().x } }) }) .unwrap_or(0.0); // Detect track click. let local_pos = transform.try_inverse().unwrap().transform_point2( press.pointer_location.position * node_target.scale_factor() / ui_scale.0, ); let track_size = if is_vertical { node.size().y - thumb_size } else { node.size().x - thumb_size }; // Avoid division by zero let click_val = if track_size > 0. { if is_vertical { // For vertical sliders: bottom-to-top (0 at bottom, max at top) // local_pos.y ranges from -height/2 (top) to +height/2 (bottom) let y_from_bottom = (node.size().y / 2.0) - local_pos.y; let adjusted_y = y_from_bottom - thumb_size / 2.0; adjusted_y * range.span() / track_size + range.start() } else { // For horizontal sliders: convert from center-origin to left-origin let x_from_left = local_pos.x + node.size().x / 2.0; let adjusted_x = x_from_left - thumb_size / 2.0; adjusted_x * range.span() / track_size + range.start() } } else { range.center() }; // Compute new value from click position let new_value = range.clamp(match slider.track_click { TrackClick::Drag => { return; } TrackClick::Step => { if click_val < value.0 { value.0 - step.0 } else { value.0 + step.0 } } TrackClick::Snap => precision .map(|prec| prec.round(click_val)) .unwrap_or(click_val), }); commands.trigger(ValueChange { source: press.entity, value: new_value, }); } } pub(crate) fn slider_on_drag_start( mut drag_start: On<Pointer<DragStart>>, mut q_slider: Query< ( &SliderValue, &mut CoreSliderDragState, Has<InteractionDisabled>, ), With<Slider>, >, ) { if let Ok((value, mut drag, disabled)) = q_slider.get_mut(drag_start.entity) { drag_start.propagate(false); if !disabled { drag.dragging = true; drag.offset = value.0; } } } pub(crate) fn slider_on_drag( mut event: On<Pointer<Drag>>, mut q_slider: Query< ( &ComputedNode, &SliderRange, Option<&SliderPrecision>, &UiGlobalTransform, &mut CoreSliderDragState, Has<InteractionDisabled>, ), With<Slider>, >, q_thumb: Query<&ComputedNode, With<SliderThumb>>, q_children: Query<&Children>, mut commands: Commands, ui_scale: Res<UiScale>, ) { if let Ok((node, range, precision, transform, drag, disabled)) = q_slider.get_mut(event.entity) { event.propagate(false); if drag.dragging && !disabled { // Detect orientation: vertical if height > width let is_vertical = node.size().y > node.size().x; let mut distance = event.distance / ui_scale.0; distance.y *= -1.; let distance = transform.transform_vector2(distance); // Find thumb size by searching descendants for the first entity with SliderThumb let thumb_size = q_children .iter_descendants(event.entity) .find_map(|child_id| { q_thumb.get(child_id).ok().map(|thumb| { if is_vertical { thumb.size().y } else { thumb.size().x } }) }) .unwrap_or(0.0); let slider_size = if is_vertical { ((node.size().y - thumb_size) * node.inverse_scale_factor).max(1.0) } else { ((node.size().x - thumb_size) * node.inverse_scale_factor).max(1.0) }; let drag_distance = if is_vertical { distance.y } else { distance.x }; let span = range.span(); let new_value = if span > 0. { drag.offset + (drag_distance * span) / slider_size } else { range.start() + span * 0.5 }; let rounded_value = range.clamp( precision .map(|prec| prec.round(new_value)) .unwrap_or(new_value), ); commands.trigger(ValueChange { source: event.entity, value: rounded_value, }); } } } pub(crate) fn slider_on_drag_end( mut drag_end: On<Pointer<DragEnd>>, mut q_slider: Query<(&Slider, &mut CoreSliderDragState)>, ) { if let Ok((_slider, mut drag)) = q_slider.get_mut(drag_end.entity) { drag_end.propagate(false); if drag.dragging { drag.dragging = false; } } } fn slider_on_key_input( mut focused_input: On<FocusedInput<KeyboardInput>>, q_slider: Query< ( &SliderValue, &SliderRange, &SliderStep, Has<InteractionDisabled>, ), With<Slider>, >, mut commands: Commands, ) { if let Ok((value, range, step, disabled)) = q_slider.get(focused_input.focused_entity) { let input_event = &focused_input.input; if !disabled && input_event.state == ButtonState::Pressed { let new_value = match input_event.key_code { KeyCode::ArrowLeft => range.clamp(value.0 - step.0), KeyCode::ArrowRight => range.clamp(value.0 + step.0), KeyCode::Home => range.start(), KeyCode::End => range.end(), _ => { return; } }; focused_input.propagate(false); commands.trigger(ValueChange { source: focused_input.focused_entity, value: new_value, }); } } } pub(crate) fn slider_on_insert(insert: On<Insert, Slider>, mut world: DeferredWorld) { let mut entity = world.entity_mut(insert.entity); if let Some(mut accessibility) = entity.get_mut::<AccessibilityNode>() { accessibility.set_orientation(Orientation::Horizontal); } } pub(crate) fn slider_on_insert_value(insert: On<Insert, SliderValue>, mut world: DeferredWorld) { let mut entity = world.entity_mut(insert.entity); let value = entity.get::<SliderValue>().unwrap().0; if let Some(mut accessibility) = entity.get_mut::<AccessibilityNode>() { accessibility.set_numeric_value(value.into()); } } pub(crate) fn slider_on_insert_range(insert: On<Insert, SliderRange>, mut world: DeferredWorld) { let mut entity = world.entity_mut(insert.entity); let range = *entity.get::<SliderRange>().unwrap(); if let Some(mut accessibility) = entity.get_mut::<AccessibilityNode>() { accessibility.set_min_numeric_value(range.start().into()); accessibility.set_max_numeric_value(range.end().into()); } } pub(crate) fn slider_on_insert_step(insert: On<Insert, SliderStep>, mut world: DeferredWorld) { let mut entity = world.entity_mut(insert.entity); let step = entity.get::<SliderStep>().unwrap().0; if let Some(mut accessibility) = entity.get_mut::<AccessibilityNode>() { accessibility.set_numeric_value_step(step.into()); } } /// An [`EntityEvent`] that can be triggered on a slider to modify its value (using the `on_change` callback). /// This can be used to control the slider via gamepad buttons or other inputs. The value will be /// clamped when the event is processed. /// /// # Example: /// /// ``` /// # use bevy_ecs::system::Commands; /// # use bevy_ui_widgets::{Slider, SliderRange, SliderValue, SetSliderValue, SliderValueChange}; /// fn setup(mut commands: Commands) { /// // Create a slider /// let entity = commands.spawn(( /// Slider::default(), /// SliderValue(0.5), /// SliderRange::new(0.0, 1.0), /// )).id(); /// /// // Set to an absolute value /// commands.trigger(SetSliderValue { /// entity, /// change: SliderValueChange::Absolute(0.75), /// }); /// /// // Adjust relatively /// commands.trigger(SetSliderValue { /// entity, /// change: SliderValueChange::Relative(-0.25), /// }); /// } /// ``` #[derive(EntityEvent, Clone)] pub struct SetSliderValue { /// The slider entity to change. pub entity: Entity, /// The change to apply to the slider entity. pub change: SliderValueChange, } /// The type of slider value change to apply in [`SetSliderValue`]. #[derive(Clone)] pub enum SliderValueChange { /// Set the slider value to a specific value. Absolute(f32), /// Add a delta to the slider value. Relative(f32), /// Add a delta to the slider value, multiplied by the step size. RelativeStep(f32), } fn slider_on_set_value( set_slider_value: On<SetSliderValue>, q_slider: Query<(&SliderValue, &SliderRange, Option<&SliderStep>), With<Slider>>, mut commands: Commands, ) { if let Ok((value, range, step)) = q_slider.get(set_slider_value.entity) { let new_value = match set_slider_value.change { SliderValueChange::Absolute(new_value) => range.clamp(new_value), SliderValueChange::Relative(delta) => range.clamp(value.0 + delta), SliderValueChange::RelativeStep(delta) => { range.clamp(value.0 + delta * step.map(|s| s.0).unwrap_or_default()) } }; commands.trigger(ValueChange { source: set_slider_value.entity, value: new_value, }); } } /// Observer function which updates the slider value in response to a [`ValueChange`] event. /// This can be used to make the slider automatically update its own state when dragged, /// as opposed to managing the slider state externally. pub fn slider_self_update(value_change: On<ValueChange<f32>>, mut commands: Commands) { commands .entity(value_change.source) .insert(SliderValue(value_change.value)); } /// Plugin that adds the observers for the [`Slider`] widget. pub struct SliderPlugin; impl Plugin for SliderPlugin { fn build(&self, app: &mut App) { app.add_observer(slider_on_pointer_down) .add_observer(slider_on_drag_start) .add_observer(slider_on_drag_end) .add_observer(slider_on_drag) .add_observer(slider_on_key_input) .add_observer(slider_on_insert) .add_observer(slider_on_insert_value) .add_observer(slider_on_insert_range) .add_observer(slider_on_insert_step) .add_observer(slider_on_set_value); } } #[cfg(test)] mod tests { use super::*; #[test] fn test_slider_precision_rounding() { // Test positive precision values (decimal places) let precision_2dp = SliderPrecision(2); assert_eq!(precision_2dp.round(1.234567), 1.23); assert_eq!(precision_2dp.round(1.235), 1.24); // Test zero precision (rounds to integers) let precision_0dp = SliderPrecision(0); assert_eq!(precision_0dp.round(1.4), 1.0); // Test negative precision (rounds to tens, hundreds, etc.) let precision_neg1 = SliderPrecision(-1); assert_eq!(precision_neg1.round(14.0), 10.0); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui_widgets/src/menu.rs
crates/bevy_ui_widgets/src/menu.rs
//! Standard widget components for popup menus. use accesskit::Role; use bevy_a11y::AccessibilityNode; use bevy_app::{App, Plugin, Update}; use bevy_ecs::{ component::Component, entity::Entity, event::EntityEvent, hierarchy::ChildOf, observer::On, query::{Has, With, Without}, schedule::IntoScheduleConfigs, system::{Commands, Query, Res, ResMut}, }; use bevy_input::{ keyboard::{KeyCode, KeyboardInput}, ButtonState, }; use bevy_input_focus::{ tab_navigation::{NavAction, TabGroup, TabNavigation}, FocusedInput, InputFocus, }; use bevy_log::warn; use bevy_picking::events::{Cancel, Click, DragEnd, Pointer, Press, Release}; use bevy_ui::{InteractionDisabled, Pressed}; use crate::Activate; /// Action type for [`MenuEvent`]. #[derive(Clone, Copy, Debug)] pub enum MenuAction { /// Indicates we want to open the menu, if it is not already open. Open, /// Open the menu if it's closed, close it if it's open. Generally sent from a menu button. Toggle, /// Close the menu and despawn it. Despawning may not happen immediately if there is a closing /// transition animation. Close, /// Close the entire menu stack. CloseAll, /// Set focus to the menu button or other owner of the popup stack. This happens when /// the escape key is pressed. FocusRoot, } /// Event used to control the state of the open menu. This bubbles upwards from the menu items /// and the menu container, through the portal relation, and to the menu owner entity. /// /// Focus navigation: the menu may be part of a composite of multiple menus such as a menu bar. /// This means that depending on direction, focus movement may move to the next menu item, or /// the next menu. This also means that different events will often be handled at different /// levels of the hierarchy - some being handled by the popup, and some by the popup's owner. #[derive(EntityEvent, Clone, Debug)] #[entity_event(propagate, auto_propagate)] pub struct MenuEvent { /// The [`MenuItem`] or [`MenuPopup`] that triggered this event. #[event_target] pub source: Entity, /// The desired action in response to this event. pub action: MenuAction, } /// Specifies the layout direction of the menu, for keyboard navigation #[derive(Default, Debug, Clone, PartialEq)] pub enum MenuLayout { /// A vertical stack. Up and down arrows to move between items. #[default] Column, /// A horizontal row. Left and right arrows to move between items. Row, /// A 2D grid. Arrow keys are not mapped, you'll need to write your own observer. Grid, } /// Component that defines a popup menu container. /// /// Menus are automatically dismissed when the user clicks outside the menu bounds. Unlike a modal /// dialog, where the click event is intercepted, we don't want to actually prevent the click event /// from triggering its normal action. The easiest way to detect this kind of click is to look for /// keyboard focus loss. When a menu is opened, one of its children will gain focus, and the menu /// remains open so long as at least one descendant is focused. Arrow keys can be used to navigate /// between menu items. /// /// This means that popup menu *must* contain at least one focusable entity. It also means that two /// menus cannot be displayed at the same time unless one is an ancestor of the other. /// /// Some care needs to be taken in implementing a menu button: we normally want menu buttons to /// toggle the open state of the menu; but clicking on the button will cause focus loss which means /// that the menu will always be closed by the time the click event is processed. #[derive(Component, Debug, Default, Clone)] #[require( AccessibilityNode(accesskit::Node::new(Role::MenuListPopup)), TabGroup::modal() )] #[require(MenuAcquireFocus)] pub struct MenuPopup { /// The layout orientation of the menu pub layout: MenuLayout, } /// Component that defines a menu item. #[derive(Component, Debug, Clone)] #[require(AccessibilityNode(accesskit::Node::new(Role::MenuItem)))] pub struct MenuItem; /// Marker component that indicates that we need to set focus to the first menu item. #[derive(Component, Debug, Default)] struct MenuAcquireFocus; /// Component that indicates that the menu lost focus and is in the process of closing. #[derive(Component, Debug, Default)] struct MenuLostFocus; fn menu_acquire_focus( q_menus: Query<Entity, (With<MenuPopup>, With<MenuAcquireFocus>)>, mut focus: ResMut<InputFocus>, tab_navigation: TabNavigation, mut commands: Commands, ) { for menu in q_menus.iter() { // When a menu is spawned, attempt to find the first focusable menu item, and set focus // to it. match tab_navigation.initialize(menu, NavAction::First) { Ok(next) => { commands.entity(menu).remove::<MenuAcquireFocus>(); focus.0 = Some(next); } Err(e) => { warn!( "No focusable menu items for popup menu: {}, error: {:?}", menu, e ); } } } } fn menu_on_lose_focus( q_menus: Query< Entity, ( With<MenuPopup>, Without<MenuAcquireFocus>, Without<MenuLostFocus>, ), >, q_parent: Query<&ChildOf>, focus: Res<InputFocus>, mut commands: Commands, ) { // Close any menu which doesn't contain the focus entity. for menu in q_menus.iter() { // TODO: Change this logic when we support submenus. Don't want to send multiple close // events. Perhaps what we can do is add `MenuLostFocus` to the whole stack. let contains_focus = match focus.0 { Some(focus_ent) => { focus_ent == menu || q_parent.iter_ancestors(focus_ent).any(|ent| ent == menu) } None => false, }; if !contains_focus { commands.entity(menu).insert(MenuLostFocus); commands.trigger(MenuEvent { source: menu, action: MenuAction::CloseAll, }); } } } fn menu_on_key_event( mut ev: On<FocusedInput<KeyboardInput>>, q_item: Query<Has<InteractionDisabled>, With<MenuItem>>, q_menu: Query<&MenuPopup>, tab_navigation: TabNavigation, mut focus: ResMut<InputFocus>, mut commands: Commands, ) { if let Ok(disabled) = q_item.get(ev.focused_entity) { if !disabled { let event = &ev.event().input; let entity = ev.event().focused_entity; if !event.repeat && event.state == ButtonState::Pressed { match event.key_code { // Activate the item and close the popup KeyCode::Enter | KeyCode::Space => { ev.propagate(false); // Trigger the action for this menu item. commands.trigger(Activate { entity }); // Set the focus to the menu button. commands.trigger(MenuEvent { source: entity, action: MenuAction::FocusRoot, }); // Close the stack commands.trigger(MenuEvent { source: entity, action: MenuAction::CloseAll, }); } _ => (), } } } } else if let Ok(menu) = q_menu.get(ev.focused_entity) { let event = &ev.event().input; if !event.repeat && event.state == ButtonState::Pressed { match event.key_code { // Close the popup KeyCode::Escape => { ev.propagate(false); // Set the focus to the menu button. commands.trigger(MenuEvent { source: ev.focused_entity, action: MenuAction::FocusRoot, }); // Close the stack commands.trigger(MenuEvent { source: ev.focused_entity, action: MenuAction::CloseAll, }); } // Focus the adjacent item in the up direction KeyCode::ArrowUp => { if menu.layout == MenuLayout::Column { ev.propagate(false); focus.0 = tab_navigation.navigate(&focus, NavAction::Previous).ok(); } } // Focus the adjacent item in the down direction KeyCode::ArrowDown => { if menu.layout == MenuLayout::Column { ev.propagate(false); focus.0 = tab_navigation.navigate(&focus, NavAction::Next).ok(); } } // Focus the adjacent item in the left direction KeyCode::ArrowLeft => { if menu.layout == MenuLayout::Row { ev.propagate(false); focus.0 = tab_navigation.navigate(&focus, NavAction::Previous).ok(); } } // Focus the adjacent item in the right direction KeyCode::ArrowRight => { if menu.layout == MenuLayout::Row { ev.propagate(false); focus.0 = tab_navigation.navigate(&focus, NavAction::Next).ok(); } } // Focus the first item KeyCode::Home => { ev.propagate(false); focus.0 = tab_navigation.navigate(&focus, NavAction::First).ok(); } // Focus the last item KeyCode::End => { ev.propagate(false); focus.0 = tab_navigation.navigate(&focus, NavAction::Last).ok(); } _ => (), } } } } fn menu_item_on_pointer_click( mut ev: On<Pointer<Click>>, mut q_state: Query<(Has<Pressed>, Has<InteractionDisabled>), With<MenuItem>>, mut commands: Commands, ) { if let Ok((pressed, disabled)) = q_state.get_mut(ev.entity) { ev.propagate(false); if pressed && !disabled { // Trigger the menu action. commands.trigger(Activate { entity: ev.entity }); // Set the focus to the menu button. commands.trigger(MenuEvent { source: ev.entity, action: MenuAction::FocusRoot, }); // Close the stack commands.trigger(MenuEvent { source: ev.entity, action: MenuAction::CloseAll, }); } } } fn menu_item_on_pointer_down( mut ev: On<Pointer<Press>>, mut q_state: Query<(Entity, Has<InteractionDisabled>, Has<Pressed>), With<MenuItem>>, mut commands: Commands, ) { if let Ok((item, disabled, pressed)) = q_state.get_mut(ev.entity) { ev.propagate(false); if !disabled && !pressed { commands.entity(item).insert(Pressed); } } } fn menu_item_on_pointer_up( mut ev: On<Pointer<Release>>, mut q_state: Query<(Entity, Has<InteractionDisabled>, Has<Pressed>), With<MenuItem>>, mut commands: Commands, ) { if let Ok((item, disabled, pressed)) = q_state.get_mut(ev.entity) { ev.propagate(false); if !disabled && pressed { commands.entity(item).remove::<Pressed>(); } } } fn menu_item_on_pointer_drag_end( mut ev: On<Pointer<DragEnd>>, mut q_state: Query<(Entity, Has<InteractionDisabled>, Has<Pressed>), With<MenuItem>>, mut commands: Commands, ) { if let Ok((item, disabled, pressed)) = q_state.get_mut(ev.entity) { ev.propagate(false); if !disabled && pressed { commands.entity(item).remove::<Pressed>(); } } } fn menu_item_on_pointer_cancel( mut ev: On<Pointer<Cancel>>, mut q_state: Query<(Entity, Has<InteractionDisabled>, Has<Pressed>), With<MenuItem>>, mut commands: Commands, ) { if let Ok((item, disabled, pressed)) = q_state.get_mut(ev.entity) { ev.propagate(false); if !disabled && pressed { commands.entity(item).remove::<Pressed>(); } } } fn menu_on_menu_event( mut ev: On<MenuEvent>, q_popup: Query<(), With<MenuPopup>>, mut commands: Commands, ) { if q_popup.contains(ev.source) && let MenuAction::Close = ev.event().action { ev.propagate(false); commands.entity(ev.source).despawn(); } } /// Headless menu button widget. This is similar to a button, except for a few differences: /// * It emits a menu toggle event when pressed or activated. /// * It uses `Pointer<Press>` rather than click, so as to process the pointer event before /// stealing focus from the menu. #[derive(Component, Default, Debug)] #[require(AccessibilityNode(accesskit::Node::new(Role::Button)))] pub struct MenuButton; fn menubutton_on_key_event( mut event: On<FocusedInput<KeyboardInput>>, q_state: Query<Has<InteractionDisabled>, With<MenuButton>>, mut commands: Commands, ) { if let Ok(disabled) = q_state.get(event.focused_entity) && !disabled { let input_event = &event.input; if !input_event.repeat && input_event.state == ButtonState::Pressed && (input_event.key_code == KeyCode::Enter || input_event.key_code == KeyCode::Space) { event.propagate(false); commands.trigger(MenuEvent { action: MenuAction::Toggle, source: event.focused_entity, }); } } } fn menubutton_on_pointer_press( mut press: On<Pointer<Press>>, mut q_state: Query<(Entity, Has<InteractionDisabled>, Has<Pressed>), With<MenuButton>>, mut commands: Commands, ) { if let Ok((button, disabled, pressed)) = q_state.get_mut(press.entity) { press.propagate(false); if !disabled && !pressed { commands.trigger(MenuEvent { action: MenuAction::Toggle, source: button, }); } } } /// Plugin that adds the observers for the [`MenuItem`] component. pub struct MenuPlugin; impl Plugin for MenuPlugin { fn build(&self, app: &mut App) { app.add_systems(Update, (menu_acquire_focus, menu_on_lose_focus).chain()) .add_observer(menu_on_key_event) .add_observer(menu_on_menu_event) .add_observer(menu_item_on_pointer_down) .add_observer(menu_item_on_pointer_up) .add_observer(menu_item_on_pointer_click) .add_observer(menu_item_on_pointer_drag_end) .add_observer(menu_item_on_pointer_cancel) .add_observer(menubutton_on_key_event) .add_observer(menubutton_on_pointer_press); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui_widgets/src/popover.rs
crates/bevy_ui_widgets/src/popover.rs
//! Framework for positioning of popups, tooltips, and other popover UI elements. use bevy_app::{App, Plugin, PostUpdate}; use bevy_camera::visibility::Visibility; use bevy_ecs::{ change_detection::DetectChangesMut, component::Component, hierarchy::ChildOf, query::Without, schedule::IntoScheduleConfigs, system::Query, }; use bevy_math::{Rect, Vec2}; use bevy_ui::{ ComputedNode, ComputedUiRenderTargetInfo, Node, PositionType, UiGlobalTransform, UiSystems, Val, }; /// Which side of the parent element the popover element should be placed. #[derive(Debug, Default, Clone, Copy, PartialEq)] pub enum PopoverSide { /// The popover element should be placed above the parent. Top, /// The popover element should be placed below the parent. #[default] Bottom, /// The popover element should be placed to the left of the parent. Left, /// The popover element should be placed to the right of the parent. Right, } impl PopoverSide { /// Returns the side that is the mirror image of this side. pub fn mirror(&self) -> Self { match self { PopoverSide::Top => PopoverSide::Bottom, PopoverSide::Bottom => PopoverSide::Top, PopoverSide::Left => PopoverSide::Right, PopoverSide::Right => PopoverSide::Left, } } } /// How the popover element should be aligned to the parent element. The alignment will be along an /// axis that is perpendicular to the direction of the popover side. So for example, if the popup is /// positioned below the parent, then the [`PopoverAlign`] variant controls the horizontal alignment /// of the popup. #[derive(Debug, Default, Clone, Copy, PartialEq)] pub enum PopoverAlign { /// The starting edge of the popover element should be aligned to the starting edge of the /// parent. #[default] Start, /// The center of the popover element should be aligned to the center of the parent. Center, /// The ending edge of the popover element should be aligned to the ending edge of the parent. End, } /// Indicates a possible position of a popover element relative to it's parent. You can /// specify multiple possible positions; the positioning code will check to see if there is /// sufficient space to display the popup without being clipped by the window edge. If any position /// has sufficient room, it will pick the first one; if there are none, then it will pick the least /// bad one. #[derive(Debug, Default, Clone, Copy, PartialEq)] pub struct PopoverPlacement { /// The side of the parent entity where the popover element should be placed. pub side: PopoverSide, /// How the popover element should be aligned to the parent entity. pub align: PopoverAlign, /// The size of the gap between the parent and the popover element, in logical pixels. This will /// offset the popover along the direction of `side`. pub gap: f32, } /// Component which is inserted into a popover element to make it dynamically position relative to /// an parent element. #[derive(Component, PartialEq, Default)] pub struct Popover { /// List of potential positions for the popover element relative to the parent. pub positions: Vec<PopoverPlacement>, /// Indicates how close to the window edge the popup is allowed to go. pub window_margin: f32, } impl Clone for Popover { fn clone(&self) -> Self { Self { positions: self.positions.clone(), window_margin: self.window_margin, } } } fn position_popover( mut q_popover: Query<( &mut Node, &mut Visibility, &ComputedNode, &ComputedUiRenderTargetInfo, &Popover, &ChildOf, )>, q_parent: Query<(&ComputedNode, &UiGlobalTransform), Without<Popover>>, ) { for (mut node, mut visibility, computed_node, computed_target, popover, parent) in q_popover.iter_mut() { // A rectangle which represents the area of the window. let window_rect = Rect { min: Vec2::ZERO, max: computed_target.logical_size(), } .inflate(-popover.window_margin); // Compute the parent rectangle. let Ok((parent_node, parent_transform)) = q_parent.get(parent.parent()) else { continue; }; // Computed node size includes the border, but since absolute positioning doesn't include // border we need to remove it from the calculations. let parent_size = parent_node.size() - parent_node.border.min_inset - parent_node.border.max_inset; let parent_rect = scale_rect( Rect::from_center_size(parent_transform.translation, parent_size), parent_node.inverse_scale_factor, ); let mut best_occluded = f32::MAX; let mut best_rect = Rect::default(); // Loop through all the potential positions and find a good one. for position in &popover.positions { let popover_size = computed_node.size() * computed_node.inverse_scale_factor; let mut rect = Rect::default(); let target_width = popover_size.x; let target_height = popover_size.y; // Position along main axis. match position.side { PopoverSide::Top => { rect.max.y = parent_rect.min.y - position.gap; rect.min.y = rect.max.y - popover_size.y; } PopoverSide::Bottom => { rect.min.y = parent_rect.max.y + position.gap; rect.max.y = rect.min.y + popover_size.y; } PopoverSide::Left => { rect.max.x = parent_rect.min.x - position.gap; rect.min.x = rect.max.x - popover_size.x; } PopoverSide::Right => { rect.min.x = parent_rect.max.x + position.gap; rect.max.x = rect.min.x + popover_size.x; } } // Position along secondary axis. match position.align { PopoverAlign::Start => match position.side { PopoverSide::Top | PopoverSide::Bottom => { rect.min.x = parent_rect.min.x; rect.max.x = rect.min.x + target_width; } PopoverSide::Left | PopoverSide::Right => { rect.min.y = parent_rect.min.y; rect.max.y = rect.min.y + target_height; } }, PopoverAlign::End => match position.side { PopoverSide::Top | PopoverSide::Bottom => { rect.max.x = parent_rect.max.x; rect.min.x = rect.max.x - target_width; } PopoverSide::Left | PopoverSide::Right => { rect.max.y = parent_rect.max.y; rect.min.y = rect.max.y - target_height; } }, PopoverAlign::Center => match position.side { PopoverSide::Top | PopoverSide::Bottom => { rect.min.x = parent_rect.min.x + (parent_rect.width() - target_width) * 0.5; rect.max.x = rect.min.x + target_width; } PopoverSide::Left | PopoverSide::Right => { rect.min.y = parent_rect.min.y + (parent_rect.height() - target_height) * 0.5; rect.max.y = rect.min.y + target_height; } }, } // Clip to window and see how much of the popover element is occluded. We can calculate // how much was clipped by intersecting the rectangle against the window bounds, and // then subtracting the area from the area of the unclipped rectangle. let clipped_rect = rect.intersect(window_rect); let occlusion = rect.area() - clipped_rect.area(); // Find the position that has the least occlusion. if occlusion < best_occluded { best_occluded = occlusion; best_rect = rect; } } // Update node properties, but only if they are different from before (to avoid setting // change detection bit). if best_occluded < f32::MAX { let left = Val::Px(best_rect.min.x - parent_rect.min.x); let top = Val::Px(best_rect.min.y - parent_rect.min.y); visibility.set_if_neq(Visibility::Visible); if node.left != left { node.left = left; } if node.top != top { node.top = top; } if node.bottom != Val::DEFAULT { node.bottom = Val::DEFAULT; } if node.right != Val::DEFAULT { node.right = Val::DEFAULT; } if node.position_type != PositionType::Absolute { node.position_type = PositionType::Absolute; } } } } /// Plugin that adds systems for the [`Popover`] component. pub struct PopoverPlugin; impl Plugin for PopoverPlugin { fn build(&self, app: &mut App) { app.add_systems(PostUpdate, position_popover.in_set(UiSystems::Prepare)); } } #[inline] fn scale_rect(rect: Rect, factor: f32) -> Rect { Rect { min: rect.min * factor, max: rect.max * factor, } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui_widgets/src/radio.rs
crates/bevy_ui_widgets/src/radio.rs
use accesskit::Role; use bevy_a11y::AccessibilityNode; use bevy_app::{App, Plugin}; use bevy_ecs::{ component::Component, entity::Entity, hierarchy::{ChildOf, Children}, observer::On, query::{Has, With}, reflect::ReflectComponent, system::{Commands, Query}, }; use bevy_input::keyboard::{KeyCode, KeyboardInput}; use bevy_input::ButtonState; use bevy_input_focus::FocusedInput; use bevy_picking::events::{Click, Pointer}; use bevy_reflect::Reflect; use bevy_ui::{Checkable, Checked, InteractionDisabled}; use crate::ValueChange; /// Headless widget implementation for a "radio button group". This component is used to group /// multiple [`RadioButton`] components together, allowing them to behave as a single unit. It /// implements the tab navigation logic and keyboard shortcuts for radio buttons. /// /// The [`RadioGroup`] component does not have any state itself, and makes no assumptions about /// what, if any, value is associated with each radio button, or what Rust type that value might be. /// Instead, the output of the group is a [`ValueChange`] event whose payload is the entity id of /// the selected button. This event is emitted whenever a radio button is clicked, or when using /// the arrow keys while the radio group is focused. The app can then derive the selected value from /// this using app-specific means, such as accessing a component on the individual buttons. /// /// The [`RadioGroup`] doesn't actually set the [`Checked`] states directly, that is presumed to /// happen by the app or via some external data-binding scheme. Typically, each button would be /// associated with a particular constant value, and would be checked whenever that value is equal /// to the group's value. This also means that as long as each button's associated value is unique /// within the group, it should never be the case that more than one button is selected at a time. #[derive(Component, Debug)] #[require(AccessibilityNode(accesskit::Node::new(Role::RadioGroup)))] pub struct RadioGroup; /// Headless widget implementation for radio buttons. They can be used independently, /// but enclosing them in a [`RadioGroup`] widget allows them to behave as a single, /// mutually exclusive unit. /// /// According to the WAI-ARIA best practices document, radio buttons should not be focusable, /// but rather the enclosing group should be focusable. /// See <https://www.w3.org/WAI/ARIA/apg/patterns/radio>/ /// /// The widget emits a [`ValueChange<bool>`] event with the value `true` whenever it becomes checked, /// either through a mouse click or when a [`RadioGroup`] checks the widget. /// If the [`RadioButton`] is focusable, it can also be checked using the `Enter` or `Space` keys, /// in which case the event will likewise be emitted. #[derive(Component, Debug)] #[require(AccessibilityNode(accesskit::Node::new(Role::RadioButton)), Checkable)] #[derive(Reflect)] #[reflect(Component)] pub struct RadioButton; fn radio_group_on_key_input( mut ev: On<FocusedInput<KeyboardInput>>, q_group: Query<(), With<RadioGroup>>, q_radio: Query<(Has<Checked>, Has<InteractionDisabled>), With<RadioButton>>, q_children: Query<&Children>, mut commands: Commands, ) { if q_group.contains(ev.focused_entity) { let event = &ev.event().input; if event.state == ButtonState::Pressed && !event.repeat && matches!( event.key_code, KeyCode::ArrowUp | KeyCode::ArrowDown | KeyCode::ArrowLeft | KeyCode::ArrowRight | KeyCode::Home | KeyCode::End ) { let key_code = event.key_code; ev.propagate(false); // Find all radio descendants that are not disabled let radio_buttons = q_children .iter_descendants(ev.focused_entity) .filter_map(|child_id| match q_radio.get(child_id) { Ok((checked, false)) => Some((child_id, checked)), Ok((_, true)) | Err(_) => None, }) .collect::<Vec<_>>(); if radio_buttons.is_empty() { return; // No enabled radio buttons in the group } let current_index = radio_buttons .iter() .position(|(_, checked)| *checked) .unwrap_or(usize::MAX); // Default to invalid index if none are checked let next_index = match key_code { KeyCode::ArrowUp | KeyCode::ArrowLeft => { // Navigate to the previous radio button in the group if current_index == 0 || current_index >= radio_buttons.len() { // If we're at the first one, wrap around to the last radio_buttons.len() - 1 } else { // Move to the previous one current_index - 1 } } KeyCode::ArrowDown | KeyCode::ArrowRight => { // Navigate to the next radio button in the group if current_index >= radio_buttons.len() - 1 { // If we're at the last one, wrap around to the first 0 } else { // Move to the next one current_index + 1 } } KeyCode::Home => { // Navigate to the first radio button in the group 0 } KeyCode::End => { // Navigate to the last radio button in the group radio_buttons.len() - 1 } _ => { return; } }; if current_index == next_index { // If the next index is the same as the current, do nothing return; } let (next_id, _) = radio_buttons[next_index]; // Trigger the value change event on the radio button commands.trigger(ValueChange::<bool> { source: next_id, value: true, }); // Trigger the on_change event for the newly checked radio button on radio group commands.trigger(ValueChange::<Entity> { source: ev.focused_entity, value: next_id, }); } } } // Provides functionality for standalone focusable [`RadioButton`] to react // on `Space` or `Enter` key press. fn radio_button_on_key_input( mut ev: On<FocusedInput<KeyboardInput>>, q_radio_button: Query<(Has<InteractionDisabled>, Has<Checked>), With<RadioButton>>, q_group: Query<(), With<RadioGroup>>, q_parents: Query<&ChildOf>, mut commands: Commands, ) { let Ok((disabled, checked)) = q_radio_button.get(ev.focused_entity) else { // Not a radio button return; }; let event = &ev.event().input; if event.state == ButtonState::Pressed && !event.repeat && (event.key_code == KeyCode::Enter || event.key_code == KeyCode::Space) { ev.propagate(false); // Radio button is disabled or already checked if disabled || checked { return; } trigger_radio_button_and_radio_group_value_change( ev.focused_entity, &q_group, &q_parents, &mut commands, ); } } fn radio_button_on_click( mut ev: On<Pointer<Click>>, q_group: Query<(), With<RadioGroup>>, q_radio: Query<(Has<InteractionDisabled>, Has<Checked>), With<RadioButton>>, q_parents: Query<&ChildOf>, mut commands: Commands, ) { let Ok((disabled, checked)) = q_radio.get(ev.entity) else { // Not a radio button return; }; ev.propagate(false); // Radio button is disabled or already checked if disabled || checked { return; } trigger_radio_button_and_radio_group_value_change( ev.entity, &q_group, &q_parents, &mut commands, ); } fn trigger_radio_button_and_radio_group_value_change( radio_button: Entity, q_group: &Query<(), With<RadioGroup>>, q_parents: &Query<&ChildOf>, commands: &mut Commands, ) { commands.trigger(ValueChange::<bool> { source: radio_button, value: true, }); // Find if radio button is inside radio group let radio_group = q_parents .iter_ancestors(radio_button) .find(|ancestor| q_group.contains(*ancestor)); // If is inside radio group if let Some(radio_group) = radio_group { // Trigger event for radio group commands.trigger(ValueChange::<Entity> { source: radio_group, value: radio_button, }); } } /// Plugin that adds the observers for [`RadioButton`] and [`RadioGroup`] widget. pub struct RadioGroupPlugin; impl Plugin for RadioGroupPlugin { fn build(&self, app: &mut App) { app.add_observer(radio_group_on_key_input) .add_observer(radio_button_on_click) .add_observer(radio_button_on_key_input); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui_widgets/src/checkbox.rs
crates/bevy_ui_widgets/src/checkbox.rs
use accesskit::Role; use bevy_a11y::AccessibilityNode; use bevy_app::{App, Plugin}; use bevy_ecs::event::EntityEvent; use bevy_ecs::query::{Has, With, Without}; use bevy_ecs::system::ResMut; use bevy_ecs::{ component::Component, observer::On, system::{Commands, Query}, }; use bevy_input::keyboard::{KeyCode, KeyboardInput}; use bevy_input::ButtonState; use bevy_input_focus::{FocusedInput, InputFocus, InputFocusVisible}; use bevy_picking::events::{Click, Pointer}; use bevy_ui::{Checkable, Checked, InteractionDisabled}; use crate::ValueChange; use bevy_ecs::entity::Entity; /// Headless widget implementation for checkboxes. The [`Checked`] component represents the current /// state of the checkbox. The widget will emit a [`ValueChange<bool>`] event when clicked, or when /// the `Enter` or `Space` key is pressed while the checkbox is focused. /// /// Add the [`checkbox_self_update`] observer watching the entity with this component to automatically add and remove the [`Checked`] component. /// /// # Toggle switches /// /// The [`Checkbox`] component can be used to implement other kinds of toggle widgets. If you /// are going to do a toggle switch, you should override the [`AccessibilityNode`] component with /// the `Switch` role instead of the `Checkbox` role. #[derive(Component, Debug, Default)] #[require(AccessibilityNode(accesskit::Node::new(Role::CheckBox)), Checkable)] pub struct Checkbox; fn checkbox_on_key_input( mut ev: On<FocusedInput<KeyboardInput>>, q_checkbox: Query<Has<Checked>, (With<Checkbox>, Without<InteractionDisabled>)>, mut commands: Commands, ) { if let Ok(is_checked) = q_checkbox.get(ev.focused_entity) { let event = &ev.event().input; if event.state == ButtonState::Pressed && !event.repeat && (event.key_code == KeyCode::Enter || event.key_code == KeyCode::Space) { ev.propagate(false); commands.trigger(ValueChange { source: ev.focused_entity, value: !is_checked, }); } } } fn checkbox_on_pointer_click( mut click: On<Pointer<Click>>, q_checkbox: Query<(Has<Checked>, Has<InteractionDisabled>), With<Checkbox>>, focus: Option<ResMut<InputFocus>>, focus_visible: Option<ResMut<InputFocusVisible>>, mut commands: Commands, ) { if let Ok((is_checked, disabled)) = q_checkbox.get(click.entity) { // Clicking on a button makes it the focused input, // and hides the focus ring if it was visible. if let Some(mut focus) = focus { focus.0 = Some(click.entity); } if let Some(mut focus_visible) = focus_visible { focus_visible.0 = false; } click.propagate(false); if !disabled { commands.trigger(ValueChange { source: click.entity, value: !is_checked, }); } } } /// Event which can be triggered on a checkbox to set the checked state. This can be used to control /// the checkbox via gamepad buttons or other inputs. /// /// # Example: /// /// ``` /// use bevy_ecs::system::Commands; /// use bevy_ui_widgets::{Checkbox, SetChecked}; /// /// fn setup(mut commands: Commands) { /// // Create a checkbox /// let entity = commands.spawn(( /// Checkbox::default(), /// )).id(); /// /// // Set to checked /// commands.trigger(SetChecked { entity, checked: true}); /// } /// ``` #[derive(EntityEvent)] pub struct SetChecked { /// The [`Checkbox`] entity to set the "checked" state on. pub entity: Entity, /// Sets the `checked` state to `true` or `false`. pub checked: bool, } /// Event which can be triggered on a checkbox to toggle the checked state. This can be used to /// control the checkbox via gamepad buttons or other inputs. /// /// # Example: /// /// ``` /// use bevy_ecs::system::Commands; /// use bevy_ui_widgets::{Checkbox, ToggleChecked}; /// /// fn setup(mut commands: Commands) { /// // Create a checkbox /// let entity = commands.spawn(( /// Checkbox::default(), /// )).id(); /// /// // Set to checked /// commands.trigger(ToggleChecked { entity }); /// } /// ``` #[derive(EntityEvent)] pub struct ToggleChecked { /// The [`Entity`] of the toggled [`Checkbox`] pub entity: Entity, } fn checkbox_on_set_checked( set_checked: On<SetChecked>, q_checkbox: Query<(Has<Checked>, Has<InteractionDisabled>), With<Checkbox>>, mut commands: Commands, ) { if let Ok((is_checked, disabled)) = q_checkbox.get(set_checked.entity) { if disabled { return; } let will_be_checked = set_checked.checked; if will_be_checked != is_checked { commands.trigger(ValueChange { source: set_checked.entity, value: will_be_checked, }); } } } fn checkbox_on_toggle_checked( toggle_checked: On<ToggleChecked>, q_checkbox: Query<(Has<Checked>, Has<InteractionDisabled>), With<Checkbox>>, mut commands: Commands, ) { if let Ok((is_checked, disabled)) = q_checkbox.get(toggle_checked.entity) { if disabled { return; } commands.trigger(ValueChange { source: toggle_checked.entity, value: !is_checked, }); } } /// Plugin that adds the observers for the [`Checkbox`] widget. pub struct CheckboxPlugin; impl Plugin for CheckboxPlugin { fn build(&self, app: &mut App) { app.add_observer(checkbox_on_key_input) .add_observer(checkbox_on_pointer_click) .add_observer(checkbox_on_set_checked) .add_observer(checkbox_on_toggle_checked); } } /// Observer function which updates the checkbox value in response to a [`ValueChange`] event. /// This can be used to make the checkbox automatically update its own state when clicked, /// as opposed to managing the checkbox state externally. pub fn checkbox_self_update(value_change: On<ValueChange<bool>>, mut commands: Commands) { if value_change.value { commands.entity(value_change.source).insert(Checked); } else { commands.entity(value_change.source).remove::<Checked>(); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui_widgets/src/scrollbar.rs
crates/bevy_ui_widgets/src/scrollbar.rs
use bevy_app::{App, Plugin, PostUpdate}; use bevy_ecs::{ component::Component, entity::Entity, hierarchy::{ChildOf, Children}, observer::On, query::{With, Without}, reflect::ReflectComponent, system::{Query, Res}, }; use bevy_math::Vec2; use bevy_picking::events::{Cancel, Drag, DragEnd, DragStart, Pointer, Press}; use bevy_reflect::{prelude::ReflectDefault, Reflect}; use bevy_ui::{ ComputedNode, ComputedUiRenderTargetInfo, Node, ScrollPosition, UiGlobalTransform, UiScale, Val, }; /// Used to select the orientation of a scrollbar, slider, or other oriented control. // TODO: Move this to a more central place. #[derive(Debug, Default, Clone, Copy, PartialEq, Reflect)] #[reflect(PartialEq, Clone, Default)] pub enum ControlOrientation { /// Horizontal orientation (stretching from left to right) Horizontal, /// Vertical orientation (stretching from top to bottom) #[default] Vertical, } /// A headless scrollbar widget, which can be used to build custom scrollbars. /// /// Scrollbars operate differently than the other UI widgets in a number of respects. /// /// Unlike sliders, scrollbars don't have an [`AccessibilityNode`](bevy_a11y::AccessibilityNode) /// component, nor can they have keyboard focus. This is because scrollbars are usually used in /// conjunction with a scrollable container, which is itself accessible and focusable. This also /// means that scrollbars don't accept keyboard events, which is also the responsibility of the /// scrollable container. /// /// Scrollbars don't emit notification events; instead they modify the scroll position of the target /// entity directly. /// /// A scrollbar can have any number of child entities, but one entity must be the scrollbar thumb, /// which is marked with the [`CoreScrollbarThumb`] component. Other children are ignored. The core /// scrollbar will directly update the position and size of this entity; the application is free to /// set any other style properties as desired. /// /// The application is free to position the scrollbars relative to the scrolling container however /// it wants: it can overlay them on top of the scrolling content, or use a grid layout to displace /// the content to make room for the scrollbars. #[derive(Component, Debug, Reflect)] #[reflect(Component)] pub struct Scrollbar { /// Entity being scrolled. pub target: Entity, /// Whether the scrollbar is vertical or horizontal. pub orientation: ControlOrientation, /// Minimum length of the scrollbar thumb, in pixel units, in the direction parallel to the main /// scrollbar axis. The scrollbar will resize the thumb entity based on the proportion of /// visible size to content size, but no smaller than this. This prevents the thumb from /// disappearing in cases where the ratio of content size to visible size is large. pub min_thumb_length: f32, } /// Marker component to indicate that the entity is a scrollbar thumb (the moving, draggable part of /// the scrollbar). This should be a child of the scrollbar entity. #[derive(Component, Debug)] #[require(CoreScrollbarDragState)] #[derive(Reflect)] #[reflect(Component)] pub struct CoreScrollbarThumb; impl Scrollbar { /// Construct a new scrollbar. /// /// # Arguments /// /// * `target` - The scrollable entity that this scrollbar will control. /// * `orientation` - The orientation of the scrollbar (horizontal or vertical). /// * `min_thumb_length` - The minimum size of the scrollbar's thumb, in pixels. pub fn new(target: Entity, orientation: ControlOrientation, min_thumb_length: f32) -> Self { Self { target, orientation, min_thumb_length, } } } /// Component used to manage the state of a scrollbar during dragging. This component is /// inserted on the thumb entity. #[derive(Component, Default, Reflect)] #[reflect(Component, Default)] pub struct CoreScrollbarDragState { /// Whether the scrollbar is currently being dragged. pub dragging: bool, /// The value of the scrollbar when dragging started. drag_origin: f32, } fn scrollbar_on_pointer_down( mut ev: On<Pointer<Press>>, q_thumb: Query<&ChildOf, With<CoreScrollbarThumb>>, mut q_scrollbar: Query<( &Scrollbar, &ComputedNode, &ComputedUiRenderTargetInfo, &UiGlobalTransform, )>, mut q_scroll_pos: Query<(&mut ScrollPosition, &ComputedNode), Without<Scrollbar>>, ui_scale: Res<UiScale>, ) { if q_thumb.contains(ev.entity) { // If they click on the thumb, do nothing. This will be handled by the drag event. ev.propagate(false); } else if let Ok((scrollbar, node, node_target, transform)) = q_scrollbar.get_mut(ev.entity) { // If they click on the scrollbar track, page up or down. ev.propagate(false); // Convert to widget-local coordinates. let local_pos = transform.try_inverse().unwrap().transform_point2( ev.event().pointer_location.position * node_target.scale_factor() / ui_scale.0, ) + node.size() * 0.5; // Bail if we don't find the target entity. let Ok((mut scroll_pos, scroll_content)) = q_scroll_pos.get_mut(scrollbar.target) else { return; }; // Convert the click coordinates into a scroll position. If it's greater than the // current scroll position, scroll forward by one step (visible size) otherwise scroll // back. let visible_size = (scroll_content.size() - scroll_content.scrollbar_size) * scroll_content.inverse_scale_factor; let content_size = scroll_content.content_size() * scroll_content.inverse_scale_factor; let max_range = (content_size - visible_size).max(Vec2::ZERO); fn adjust_scroll_pos(scroll_pos: &mut f32, click_pos: f32, step: f32, range: f32) { *scroll_pos = (*scroll_pos + if click_pos > *scroll_pos { step } else { -step }).clamp(0., range); } match scrollbar.orientation { ControlOrientation::Horizontal => { if node.size().x > 0. { let click_pos = local_pos.x * content_size.x / node.size().x; adjust_scroll_pos(&mut scroll_pos.x, click_pos, visible_size.x, max_range.x); } } ControlOrientation::Vertical => { if node.size().y > 0. { let click_pos = local_pos.y * content_size.y / node.size().y; adjust_scroll_pos(&mut scroll_pos.y, click_pos, visible_size.y, max_range.y); } } } } } fn scrollbar_on_drag_start( mut ev: On<Pointer<DragStart>>, mut q_thumb: Query<(&ChildOf, &mut CoreScrollbarDragState), With<CoreScrollbarThumb>>, q_scrollbar: Query<&Scrollbar>, q_scroll_area: Query<&ScrollPosition>, ) { if let Ok((ChildOf(thumb_parent), mut drag)) = q_thumb.get_mut(ev.entity) { ev.propagate(false); if let Ok(scrollbar) = q_scrollbar.get(*thumb_parent) && let Ok(scroll_area) = q_scroll_area.get(scrollbar.target) { drag.dragging = true; drag.drag_origin = match scrollbar.orientation { ControlOrientation::Horizontal => scroll_area.x, ControlOrientation::Vertical => scroll_area.y, }; } } } fn scrollbar_on_drag( mut ev: On<Pointer<Drag>>, mut q_thumb: Query<(&ChildOf, &mut CoreScrollbarDragState), With<CoreScrollbarThumb>>, mut q_scrollbar: Query<(&ComputedNode, &Scrollbar)>, mut q_scroll_pos: Query<(&mut ScrollPosition, &ComputedNode), Without<Scrollbar>>, ui_scale: Res<UiScale>, ) { if let Ok((ChildOf(thumb_parent), drag)) = q_thumb.get_mut(ev.entity) && let Ok((node, scrollbar)) = q_scrollbar.get_mut(*thumb_parent) { ev.propagate(false); let Ok((mut scroll_pos, scroll_content)) = q_scroll_pos.get_mut(scrollbar.target) else { return; }; if drag.dragging { let distance = ev.event().distance / ui_scale.0; let visible_size = (scroll_content.size() - scroll_content.scrollbar_size) * scroll_content.inverse_scale_factor; let content_size = scroll_content.content_size() * scroll_content.inverse_scale_factor; let scrollbar_size = (node.size() * node.inverse_scale_factor).max(Vec2::ONE); match scrollbar.orientation { ControlOrientation::Horizontal => { let range = (content_size.x - visible_size.x).max(0.); scroll_pos.x = (drag.drag_origin + (distance.x * content_size.x) / scrollbar_size.x) .clamp(0., range); } ControlOrientation::Vertical => { let range = (content_size.y - visible_size.y).max(0.); scroll_pos.y = (drag.drag_origin + (distance.y * content_size.y) / scrollbar_size.y) .clamp(0., range); } }; } } } fn scrollbar_on_drag_end( mut ev: On<Pointer<DragEnd>>, mut q_thumb: Query<&mut CoreScrollbarDragState, With<CoreScrollbarThumb>>, ) { if let Ok(mut drag) = q_thumb.get_mut(ev.entity) { ev.propagate(false); if drag.dragging { drag.dragging = false; } } } fn scrollbar_on_drag_cancel( mut ev: On<Pointer<Cancel>>, mut q_thumb: Query<&mut CoreScrollbarDragState, With<CoreScrollbarThumb>>, ) { if let Ok(mut drag) = q_thumb.get_mut(ev.entity) { ev.propagate(false); if drag.dragging { drag.dragging = false; } } } fn update_scrollbar_thumb( q_scroll_area: Query<(&ScrollPosition, &ComputedNode)>, q_scrollbar: Query<(&Scrollbar, &ComputedNode, &Children)>, mut q_thumb: Query<&mut Node, With<CoreScrollbarThumb>>, ) { for (scrollbar, scrollbar_node, children) in q_scrollbar.iter() { let Ok(scroll_area) = q_scroll_area.get(scrollbar.target) else { continue; }; // Size of the visible scrolling area. let visible_size = (scroll_area.1.size() - scroll_area.1.scrollbar_size) * scroll_area.1.inverse_scale_factor; // Size of the scrolling content. let content_size = scroll_area.1.content_size() * scroll_area.1.inverse_scale_factor; // Length of the scrollbar track. let track_length = scrollbar_node.size() * scrollbar_node.inverse_scale_factor; fn size_and_pos( content_size: f32, visible_size: f32, track_length: f32, min_size: f32, mut offset: f32, ) -> (f32, f32) { let thumb_size = if content_size > visible_size { (track_length * visible_size / content_size) .max(min_size) .min(track_length) } else { track_length }; if content_size > visible_size { let max_offset = content_size - visible_size; // Clamp offset to prevent thumb from going out of bounds during inertial scroll offset = offset.clamp(0.0, max_offset); } else { offset = 0.0; } let thumb_pos = if content_size > visible_size { offset * (track_length - thumb_size) / (content_size - visible_size) } else { 0. }; (thumb_size, thumb_pos) } for child in children { if let Ok(mut thumb) = q_thumb.get_mut(*child) { match scrollbar.orientation { ControlOrientation::Horizontal => { let (thumb_size, thumb_pos) = size_and_pos( content_size.x, visible_size.x, track_length.x, scrollbar.min_thumb_length, scroll_area.0.x, ); thumb.top = Val::Px(0.); thumb.bottom = Val::Px(0.); thumb.left = Val::Px(thumb_pos); thumb.width = Val::Px(thumb_size); } ControlOrientation::Vertical => { let (thumb_size, thumb_pos) = size_and_pos( content_size.y, visible_size.y, track_length.y, scrollbar.min_thumb_length, scroll_area.0.y, ); thumb.left = Val::Px(0.); thumb.right = Val::Px(0.); thumb.top = Val::Px(thumb_pos); thumb.height = Val::Px(thumb_size); } }; } } } } /// Plugin that adds the observers for the [`Scrollbar`] widget. pub struct ScrollbarPlugin; impl Plugin for ScrollbarPlugin { fn build(&self, app: &mut App) { app.add_observer(scrollbar_on_pointer_down) .add_observer(scrollbar_on_drag_start) .add_observer(scrollbar_on_drag_end) .add_observer(scrollbar_on_drag_cancel) .add_observer(scrollbar_on_drag) .add_systems(PostUpdate, update_scrollbar_thumb); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_internal/src/prelude.rs
crates/bevy_internal/src/prelude.rs
#[doc(hidden)] pub use crate::{ app::prelude::*, ecs::prelude::*, input::prelude::*, math::prelude::*, platform::prelude::*, reflect::prelude::*, time::prelude::*, transform::prelude::*, utils::prelude::*, DefaultPlugins, MinimalPlugins, }; #[doc(hidden)] #[cfg(feature = "bevy_log")] pub use crate::log::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_window")] pub use crate::window::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_image")] pub use crate::image::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_mesh")] pub use crate::mesh::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_light")] pub use crate::light::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_camera")] pub use crate::camera::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_shader")] pub use crate::shader::prelude::*; pub use bevy_derive::{bevy_main, Deref, DerefMut}; #[doc(hidden)] #[cfg(feature = "bevy_asset")] pub use crate::asset::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_audio")] pub use crate::audio::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_animation")] pub use crate::animation::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_color")] pub use crate::color::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_pbr")] pub use crate::pbr::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_render")] pub use crate::render::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_scene")] pub use crate::scene::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_sprite")] pub use crate::sprite::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_sprite_render")] pub use crate::sprite_render::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_text")] pub use crate::text::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_ui")] pub use crate::ui::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_ui_render")] pub use crate::ui_render::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_gizmos")] pub use crate::gizmos::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_gilrs")] pub use crate::gilrs::*; #[doc(hidden)] #[cfg(feature = "bevy_state")] pub use crate::state::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_gltf")] pub use crate::gltf::prelude::*; #[doc(hidden)] #[cfg(feature = "bevy_picking")] pub use crate::picking::prelude::*;
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_internal/src/lib.rs
crates/bevy_internal/src/lib.rs
#![cfg_attr(docsrs, feature(doc_cfg))] #![forbid(unsafe_code)] #![doc( html_logo_url = "https://bevy.org/assets/icon.png", html_favicon_url = "https://bevy.org/assets/icon.png" )] #![no_std] //! This module is separated into its own crate to enable simple dynamic linking for Bevy, and should not be used directly /// `use bevy::prelude::*;` to import common components, bundles, and plugins. pub mod prelude; mod default_plugins; pub use default_plugins::*; #[cfg(feature = "bevy_window")] pub use bevy_a11y as a11y; #[cfg(target_os = "android")] pub use bevy_android as android; #[cfg(feature = "bevy_animation")] pub use bevy_animation as animation; #[cfg(feature = "bevy_anti_alias")] pub use bevy_anti_alias as anti_alias; pub use bevy_app as app; #[cfg(feature = "bevy_asset")] pub use bevy_asset as asset; #[cfg(feature = "bevy_audio")] pub use bevy_audio as audio; #[cfg(feature = "bevy_camera")] pub use bevy_camera as camera; #[cfg(feature = "bevy_camera_controller")] pub use bevy_camera_controller as camera_controller; #[cfg(feature = "bevy_color")] pub use bevy_color as color; #[cfg(feature = "bevy_core_pipeline")] pub use bevy_core_pipeline as core_pipeline; #[cfg(feature = "bevy_dev_tools")] pub use bevy_dev_tools as dev_tools; pub use bevy_diagnostic as diagnostic; pub use bevy_ecs as ecs; #[cfg(feature = "bevy_feathers")] pub use bevy_feathers as feathers; #[cfg(feature = "bevy_gilrs")] pub use bevy_gilrs as gilrs; #[cfg(feature = "bevy_gizmos")] pub use bevy_gizmos as gizmos; #[cfg(feature = "bevy_gizmos_render")] pub use bevy_gizmos_render as gizmos_render; #[cfg(feature = "bevy_gltf")] pub use bevy_gltf as gltf; #[cfg(feature = "bevy_image")] pub use bevy_image as image; pub use bevy_input as input; #[cfg(feature = "bevy_input_focus")] pub use bevy_input_focus as input_focus; #[cfg(feature = "bevy_light")] pub use bevy_light as light; #[cfg(feature = "bevy_log")] pub use bevy_log as log; pub use bevy_math as math; #[cfg(feature = "bevy_mesh")] pub use bevy_mesh as mesh; #[cfg(feature = "bevy_pbr")] pub use bevy_pbr as pbr; #[cfg(feature = "bevy_picking")] pub use bevy_picking as picking; pub use bevy_platform as platform; #[cfg(feature = "bevy_post_process")] pub use bevy_post_process as post_process; pub use bevy_ptr as ptr; pub use bevy_reflect as reflect; #[cfg(feature = "bevy_remote")] pub use bevy_remote as remote; #[cfg(feature = "bevy_render")] pub use bevy_render as render; #[cfg(feature = "bevy_scene")] pub use bevy_scene as scene; #[cfg(feature = "bevy_shader")] pub use bevy_shader as shader; #[cfg(feature = "bevy_solari")] pub use bevy_solari as solari; #[cfg(feature = "bevy_sprite")] pub use bevy_sprite as sprite; #[cfg(feature = "bevy_sprite_render")] pub use bevy_sprite_render as sprite_render; #[cfg(feature = "bevy_state")] pub use bevy_state as state; pub use bevy_tasks as tasks; #[cfg(feature = "bevy_text")] pub use bevy_text as text; pub use bevy_time as time; pub use bevy_transform as transform; #[cfg(feature = "bevy_ui")] pub use bevy_ui as ui; #[cfg(feature = "bevy_ui_render")] pub use bevy_ui_render as ui_render; #[cfg(feature = "bevy_ui_widgets")] pub use bevy_ui_widgets as ui_widgets; pub use bevy_utils as utils; #[cfg(feature = "bevy_window")] pub use bevy_window as window; #[cfg(feature = "bevy_winit")] pub use bevy_winit as winit;
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_internal/src/default_plugins.rs
crates/bevy_internal/src/default_plugins.rs
use bevy_app::{plugin_group, Plugin}; plugin_group! { /// This plugin group will add all the default plugins for a *Bevy* application: pub struct DefaultPlugins { bevy_app:::PanicHandlerPlugin, #[cfg(feature = "bevy_log")] bevy_log:::LogPlugin, bevy_app:::TaskPoolPlugin, bevy_diagnostic:::FrameCountPlugin, bevy_time:::TimePlugin, bevy_transform:::TransformPlugin, bevy_diagnostic:::DiagnosticsPlugin, bevy_input:::InputPlugin, #[custom(cfg(not(feature = "bevy_window")))] bevy_app:::ScheduleRunnerPlugin, #[cfg(feature = "bevy_window")] bevy_window:::WindowPlugin, #[cfg(feature = "bevy_window")] bevy_a11y:::AccessibilityPlugin, #[cfg(feature = "std")] #[custom(cfg(any(all(unix, not(target_os = "horizon")), windows)))] bevy_app:::TerminalCtrlCHandlerPlugin, // NOTE: Load this before AssetPlugin to properly register http asset sources. #[cfg(feature = "bevy_asset")] #[custom(cfg(any(feature = "http", feature = "https")))] bevy_asset::io::web:::WebAssetPlugin, #[cfg(feature = "bevy_asset")] bevy_asset:::AssetPlugin, #[cfg(feature = "bevy_scene")] bevy_scene:::ScenePlugin, // NOTE: WinitPlugin needs to be after AssetPlugin because of custom cursors. #[cfg(feature = "bevy_winit")] bevy_winit:::WinitPlugin, #[custom(cfg(all(feature = "dlss", not(feature = "force_disable_dlss"))))] bevy_anti_alias::dlss:::DlssInitPlugin, #[cfg(feature = "bevy_render")] bevy_render:::RenderPlugin, // NOTE: Load this after renderer initialization so that it knows about the supported // compressed texture formats. #[cfg(feature = "bevy_image")] bevy_image:::ImagePlugin, #[cfg(feature = "bevy_mesh")] bevy_mesh:::MeshPlugin, #[cfg(feature = "bevy_camera")] bevy_camera:::CameraPlugin, #[cfg(feature = "bevy_light")] bevy_light:::LightPlugin, #[cfg(feature = "bevy_render")] #[custom(cfg(all(not(target_arch = "wasm32"), feature = "multi_threaded")))] bevy_render::pipelined_rendering:::PipelinedRenderingPlugin, #[cfg(feature = "bevy_core_pipeline")] bevy_core_pipeline:::CorePipelinePlugin, #[cfg(feature = "bevy_post_process")] bevy_post_process:::PostProcessPlugin, #[cfg(feature = "bevy_anti_alias")] bevy_anti_alias:::AntiAliasPlugin, #[cfg(feature = "bevy_sprite")] bevy_sprite:::SpritePlugin, #[cfg(feature = "bevy_sprite_render")] bevy_sprite_render:::SpriteRenderPlugin, #[cfg(feature = "bevy_text")] bevy_text:::TextPlugin, #[cfg(feature = "bevy_ui")] bevy_ui:::UiPlugin, #[cfg(feature = "bevy_ui_render")] bevy_ui_render:::UiRenderPlugin, #[cfg(feature = "bevy_pbr")] bevy_pbr:::PbrPlugin, // NOTE: Load this after renderer initialization so that it knows about the supported // compressed texture formats. #[cfg(feature = "bevy_gltf")] bevy_gltf:::GltfPlugin, #[cfg(feature = "bevy_audio")] bevy_audio:::AudioPlugin, #[cfg(feature = "bevy_gilrs")] bevy_gilrs:::GilrsPlugin, #[cfg(feature = "bevy_animation")] bevy_animation:::AnimationPlugin, #[cfg(feature = "bevy_gizmos")] bevy_gizmos:::GizmoPlugin, #[cfg(feature = "bevy_gizmos_render")] bevy_gizmos_render:::GizmoRenderPlugin, #[cfg(feature = "bevy_state")] bevy_state::app:::StatesPlugin, #[cfg(feature = "bevy_ci_testing")] bevy_dev_tools::ci_testing:::CiTestingPlugin, #[cfg(feature = "hotpatching")] bevy_app::hotpatch:::HotPatchPlugin, #[plugin_group] #[cfg(feature = "bevy_picking")] bevy_picking:::DefaultPickingPlugins, #[doc(hidden)] :IgnoreAmbiguitiesPlugin, } /// [`DefaultPlugins`] obeys *Cargo* *feature* flags. Users may exert control over this plugin group /// by disabling `default-features` in their `Cargo.toml` and enabling only those features /// that they wish to use. /// /// [`DefaultPlugins`] contains all the plugins typically required to build /// a *Bevy* application which includes a *window* and presentation components. /// For the absolute minimum number of plugins needed to run a Bevy application, see [`MinimalPlugins`]. } #[derive(Default)] struct IgnoreAmbiguitiesPlugin; impl Plugin for IgnoreAmbiguitiesPlugin { #[expect( clippy::allow_attributes, reason = "`unused_variables` is not always linted" )] #[allow( unused_variables, reason = "The `app` parameter is used only if a combination of crates that contain ambiguities with each other are enabled." )] fn build(&self, app: &mut bevy_app::App) { // bevy_ui owns the Transform and cannot be animated #[cfg(all(feature = "bevy_animation", feature = "bevy_ui"))] if app.is_plugin_added::<bevy_animation::AnimationPlugin>() && app.is_plugin_added::<bevy_ui::UiPlugin>() { app.ignore_ambiguity( bevy_app::PostUpdate, bevy_animation::advance_animations, bevy_ui::ui_layout_system, ); app.ignore_ambiguity( bevy_app::PostUpdate, bevy_animation::animate_targets, bevy_ui::ui_layout_system, ); } } } plugin_group! { /// This plugin group will add the minimal plugins for a *Bevy* application: pub struct MinimalPlugins { bevy_app:::TaskPoolPlugin, bevy_diagnostic:::FrameCountPlugin, bevy_time:::TimePlugin, bevy_app:::ScheduleRunnerPlugin, #[cfg(feature = "bevy_ci_testing")] bevy_dev_tools::ci_testing:::CiTestingPlugin, } /// This plugin group represents the absolute minimum, bare-bones, bevy application. /// Use this if you want to have absolute control over the plugins used. /// /// It includes a [schedule runner (`ScheduleRunnerPlugin`)](crate::app::ScheduleRunnerPlugin) /// to provide functionality that would otherwise be driven by a windowed application's /// *event loop* or *message loop*. /// /// By default, this loop will run as fast as possible, which can result in high CPU usage. /// You can add a delay using [`run_loop`](crate::app::ScheduleRunnerPlugin::run_loop), /// or remove the loop using [`run_once`](crate::app::ScheduleRunnerPlugin::run_once). /// # Example: /// ```rust, no_run /// # use std::time::Duration; /// # use bevy_app::{App, PluginGroup, ScheduleRunnerPlugin}; /// # use bevy_internal::MinimalPlugins; /// App::new().add_plugins(MinimalPlugins.set(ScheduleRunnerPlugin::run_loop( /// // Run 60 times per second. /// Duration::from_secs_f64(1.0 / 60.0), /// ))).run(); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/lib.rs
crates/bevy_post_process/src/lib.rs
#![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")] #![forbid(unsafe_code)] #![cfg_attr(docsrs, feature(doc_cfg))] #![doc( html_logo_url = "https://bevy.org/assets/icon.png", html_favicon_url = "https://bevy.org/assets/icon.png" )] pub mod auto_exposure; pub mod bloom; pub mod dof; pub mod effect_stack; pub mod motion_blur; pub mod msaa_writeback; use crate::{ bloom::BloomPlugin, dof::DepthOfFieldPlugin, effect_stack::EffectStackPlugin, motion_blur::MotionBlurPlugin, msaa_writeback::MsaaWritebackPlugin, }; use bevy_app::{App, Plugin}; use bevy_shader::load_shader_library; /// Adds bloom, motion blur, depth of field, and chromatic aberration support. #[derive(Default)] pub struct PostProcessPlugin; impl Plugin for PostProcessPlugin { fn build(&self, app: &mut App) { load_shader_library!(app, "gaussian_blur.wgsl"); app.add_plugins(( MsaaWritebackPlugin, BloomPlugin, MotionBlurPlugin, DepthOfFieldPlugin, EffectStackPlugin, )); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/msaa_writeback.rs
crates/bevy_post_process/src/msaa_writeback.rs
use bevy_app::{App, Plugin}; use bevy_camera::MsaaWriteback; use bevy_color::LinearRgba; use bevy_core_pipeline::{ blit::{BlitPipeline, BlitPipelineKey}, core_2d::graph::{Core2d, Node2d}, core_3d::graph::{Core3d, Node3d}, }; use bevy_ecs::{prelude::*, query::QueryItem}; use bevy_render::{ camera::ExtractedCamera, diagnostic::RecordDiagnostics, render_graph::{NodeRunError, RenderGraphContext, RenderGraphExt, ViewNode, ViewNodeRunner}, render_resource::*, renderer::RenderContext, view::{Msaa, ViewTarget}, Render, RenderApp, RenderSystems, }; /// This enables "msaa writeback" support for the `core_2d` and `core_3d` pipelines, which can be enabled on cameras /// using [`bevy_camera::Camera::msaa_writeback`]. See the docs on that field for more information. #[derive(Default)] pub struct MsaaWritebackPlugin; impl Plugin for MsaaWritebackPlugin { fn build(&self, app: &mut App) { let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return; }; render_app.add_systems( Render, prepare_msaa_writeback_pipelines.in_set(RenderSystems::Prepare), ); { render_app .add_render_graph_node::<ViewNodeRunner<MsaaWritebackNode>>( Core2d, Node2d::MsaaWriteback, ) .add_render_graph_edge(Core2d, Node2d::MsaaWriteback, Node2d::StartMainPass); } { render_app .add_render_graph_node::<ViewNodeRunner<MsaaWritebackNode>>( Core3d, Node3d::MsaaWriteback, ) .add_render_graph_edge(Core3d, Node3d::MsaaWriteback, Node3d::StartMainPass); } } } #[derive(Default)] pub struct MsaaWritebackNode; impl ViewNode for MsaaWritebackNode { type ViewQuery = ( &'static ViewTarget, &'static MsaaWritebackBlitPipeline, &'static Msaa, ); fn run<'w>( &self, _graph: &mut RenderGraphContext, render_context: &mut RenderContext<'w>, (target, blit_pipeline_id, msaa): QueryItem<'w, '_, Self::ViewQuery>, world: &'w World, ) -> Result<(), NodeRunError> { if *msaa == Msaa::Off { return Ok(()); } let blit_pipeline = world.resource::<BlitPipeline>(); let pipeline_cache = world.resource::<PipelineCache>(); let Some(pipeline) = pipeline_cache.get_render_pipeline(blit_pipeline_id.0) else { return Ok(()); }; let diagnostics = render_context.diagnostic_recorder(); // The current "main texture" needs to be bound as an input resource, and we need the "other" // unused target to be the "resolve target" for the MSAA write. Therefore this is the same // as a post process write! let post_process = target.post_process_write(); let pass_descriptor = RenderPassDescriptor { label: Some("msaa_writeback"), // The target's "resolve target" is the "destination" in post_process. // We will indirectly write the results to the "destination" using // the MSAA resolve step. color_attachments: &[Some(RenderPassColorAttachment { // If MSAA is enabled, then the sampled texture will always exist view: target.sampled_main_texture_view().unwrap(), depth_slice: None, resolve_target: Some(post_process.destination), ops: Operations { load: LoadOp::Clear(LinearRgba::BLACK.into()), store: StoreOp::Store, }, })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, }; let bind_group = blit_pipeline.create_bind_group( render_context.render_device(), post_process.source, pipeline_cache, ); let mut render_pass = render_context .command_encoder() .begin_render_pass(&pass_descriptor); let pass_span = diagnostics.pass_span(&mut render_pass, "msaa_writeback"); render_pass.set_pipeline(pipeline); render_pass.set_bind_group(0, &bind_group, &[]); render_pass.draw(0..3, 0..1); pass_span.end(&mut render_pass); Ok(()) } } #[derive(Component)] pub struct MsaaWritebackBlitPipeline(CachedRenderPipelineId); fn prepare_msaa_writeback_pipelines( mut commands: Commands, pipeline_cache: Res<PipelineCache>, mut pipelines: ResMut<SpecializedRenderPipelines<BlitPipeline>>, blit_pipeline: Res<BlitPipeline>, view_targets: Query<(Entity, &ViewTarget, &ExtractedCamera, &Msaa)>, ) { for (entity, view_target, camera, msaa) in view_targets.iter() { // Determine if we should do MSAA writeback based on the camera's setting let should_writeback = match camera.msaa_writeback { MsaaWriteback::Off => false, MsaaWriteback::Auto => camera.sorted_camera_index_for_target > 0, MsaaWriteback::Always => true, }; if msaa.samples() > 1 && should_writeback { let key = BlitPipelineKey { texture_format: view_target.main_texture_format(), samples: msaa.samples(), blend_state: None, }; let pipeline = pipelines.specialize(&pipeline_cache, &blit_pipeline, key); commands .entity(entity) .insert(MsaaWritebackBlitPipeline(pipeline)); } else { // This isn't strictly necessary now, but if we move to retained render entity state I don't // want this to silently break commands .entity(entity) .remove::<MsaaWritebackBlitPipeline>(); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/motion_blur/node.rs
crates/bevy_post_process/src/motion_blur/node.rs
use bevy_ecs::{query::QueryItem, world::World}; use bevy_render::{ diagnostic::RecordDiagnostics, extract_component::ComponentUniforms, globals::GlobalsBuffer, render_graph::{NodeRunError, RenderGraphContext, ViewNode}, render_resource::{ BindGroupEntries, Operations, PipelineCache, RenderPassColorAttachment, RenderPassDescriptor, }, renderer::RenderContext, view::{Msaa, ViewTarget}, }; use bevy_core_pipeline::prepass::ViewPrepassTextures; use super::{ pipeline::{MotionBlurPipeline, MotionBlurPipelineId}, MotionBlurUniform, }; #[derive(Default)] pub struct MotionBlurNode; impl ViewNode for MotionBlurNode { type ViewQuery = ( &'static ViewTarget, &'static MotionBlurPipelineId, &'static ViewPrepassTextures, &'static MotionBlurUniform, &'static Msaa, ); fn run( &self, _graph: &mut RenderGraphContext, render_context: &mut RenderContext, (view_target, pipeline_id, prepass_textures, motion_blur, msaa): QueryItem<Self::ViewQuery>, world: &World, ) -> Result<(), NodeRunError> { if motion_blur.samples == 0 || motion_blur.shutter_angle <= 0.0 { return Ok(()); // We can skip running motion blur in these cases. } let motion_blur_pipeline = world.resource::<MotionBlurPipeline>(); let pipeline_cache = world.resource::<PipelineCache>(); let settings_uniforms = world.resource::<ComponentUniforms<MotionBlurUniform>>(); let Some(pipeline) = pipeline_cache.get_render_pipeline(pipeline_id.0) else { return Ok(()); }; let Some(settings_binding) = settings_uniforms.uniforms().binding() else { return Ok(()); }; let (Some(prepass_motion_vectors_texture), Some(prepass_depth_texture)) = (&prepass_textures.motion_vectors, &prepass_textures.depth) else { return Ok(()); }; let Some(globals_uniforms) = world.resource::<GlobalsBuffer>().buffer.binding() else { return Ok(()); }; let diagnostics = render_context.diagnostic_recorder(); let post_process = view_target.post_process_write(); let layout = if msaa.samples() == 1 { &motion_blur_pipeline.layout } else { &motion_blur_pipeline.layout_msaa }; let bind_group = render_context.render_device().create_bind_group( Some("motion_blur_bind_group"), &pipeline_cache.get_bind_group_layout(layout), &BindGroupEntries::sequential(( post_process.source, &prepass_motion_vectors_texture.texture.default_view, &prepass_depth_texture.texture.default_view, &motion_blur_pipeline.sampler, settings_binding.clone(), globals_uniforms.clone(), )), ); let mut render_pass = render_context.begin_tracked_render_pass(RenderPassDescriptor { label: Some("motion_blur"), color_attachments: &[Some(RenderPassColorAttachment { view: post_process.destination, depth_slice: None, resolve_target: None, ops: Operations::default(), })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, }); let pass_span = diagnostics.pass_span(&mut render_pass, "motion_blur"); render_pass.set_render_pipeline(pipeline); render_pass.set_bind_group(0, &bind_group, &[]); render_pass.draw(0..3, 0..1); pass_span.end(&mut render_pass); Ok(()) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/motion_blur/mod.rs
crates/bevy_post_process/src/motion_blur/mod.rs
//! Per-object, per-pixel motion blur. //! //! Add the [`MotionBlur`] component to a camera to enable motion blur. use bevy_app::{App, Plugin}; use bevy_asset::embedded_asset; use bevy_camera::Camera; use bevy_core_pipeline::{ core_3d::graph::{Core3d, Node3d}, prepass::{DepthPrepass, MotionVectorPrepass}, }; use bevy_ecs::{ component::Component, query::{QueryItem, With}, reflect::ReflectComponent, schedule::IntoScheduleConfigs, }; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{ extract_component::{ExtractComponent, ExtractComponentPlugin, UniformComponentPlugin}, render_graph::{RenderGraphExt, ViewNodeRunner}, render_resource::{ShaderType, SpecializedRenderPipelines}, Render, RenderApp, RenderStartup, RenderSystems, }; pub mod node; pub mod pipeline; /// A component that enables and configures motion blur when added to a camera. /// /// Motion blur is an effect that simulates how moving objects blur as they change position during /// the exposure of film, a sensor, or an eyeball. /// /// Because rendering simulates discrete steps in time, we use per-pixel motion vectors to estimate /// the path of objects between frames. This kind of implementation has some artifacts: /// - Fast moving objects in front of a stationary object or when in front of empty space, will not /// have their edges blurred. /// - Transparent objects do not write to depth or motion vectors, so they cannot be blurred. /// /// Other approaches, such as *A Reconstruction Filter for Plausible Motion Blur* produce more /// correct results, but are more expensive and complex, and have other kinds of artifacts. This /// implementation is relatively inexpensive and effective. /// /// # Usage /// /// Add the [`MotionBlur`] component to a camera to enable and configure motion blur for that /// camera. /// /// ``` /// # use bevy_post_process::motion_blur::MotionBlur; /// # use bevy_camera::Camera3d; /// # use bevy_ecs::prelude::*; /// # fn test(mut commands: Commands) { /// commands.spawn(( /// Camera3d::default(), /// MotionBlur::default(), /// )); /// # } /// ```` #[derive(Reflect, Component, Clone)] #[reflect(Component, Default, Clone)] #[require(DepthPrepass, MotionVectorPrepass)] pub struct MotionBlur { /// The strength of motion blur from `0.0` to `1.0`. /// /// The shutter angle describes the fraction of a frame that a camera's shutter is open and /// exposing the film/sensor. For 24fps cinematic film, a shutter angle of 0.5 (180 degrees) is /// common. This means that the shutter was open for half of the frame, or 1/48th of a second. /// The lower the shutter angle, the less exposure time and thus less blur. /// /// A value greater than one is non-physical and results in an object's blur stretching further /// than it traveled in that frame. This might be a desirable effect for artistic reasons, but /// consider allowing users to opt out of this. /// /// This value is intentionally tied to framerate to avoid the aforementioned non-physical /// over-blurring. If you want to emulate a cinematic look, your options are: /// - Framelimit your app to 24fps, and set the shutter angle to 0.5 (180 deg). Note that /// depending on artistic intent or the action of a scene, it is common to set the shutter /// angle between 0.125 (45 deg) and 0.5 (180 deg). This is the most faithful way to /// reproduce the look of film. /// - Set the shutter angle greater than one. For example, to emulate the blur strength of /// film while rendering at 60fps, you would set the shutter angle to `60/24 * 0.5 = 1.25`. /// Note that this will result in artifacts where the motion of objects will stretch further /// than they moved between frames; users may find this distracting. pub shutter_angle: f32, /// The quality of motion blur, corresponding to the number of per-pixel samples taken in each /// direction during blur. /// /// Setting this to `1` results in each pixel being sampled once in the leading direction, once /// in the trailing direction, and once in the middle, for a total of 3 samples (`1 * 2 + 1`). /// Setting this to `3` will result in `3 * 2 + 1 = 7` samples. Setting this to `0` is /// equivalent to disabling motion blur. pub samples: u32, } impl Default for MotionBlur { fn default() -> Self { Self { shutter_angle: 0.5, samples: 1, } } } impl ExtractComponent for MotionBlur { type QueryData = &'static Self; type QueryFilter = With<Camera>; type Out = MotionBlurUniform; fn extract_component(item: QueryItem<Self::QueryData>) -> Option<Self::Out> { Some(MotionBlurUniform { shutter_angle: item.shutter_angle, samples: item.samples, #[cfg(all(feature = "webgl", target_arch = "wasm32", not(feature = "webgpu")))] _webgl2_padding: Default::default(), }) } } #[doc(hidden)] #[derive(Component, ShaderType, Clone)] pub struct MotionBlurUniform { shutter_angle: f32, samples: u32, #[cfg(all(feature = "webgl", target_arch = "wasm32", not(feature = "webgpu")))] // WebGL2 structs must be 16 byte aligned. _webgl2_padding: bevy_math::Vec2, } /// Adds support for per-object motion blur to the app. See [`MotionBlur`] for details. #[derive(Default)] pub struct MotionBlurPlugin; impl Plugin for MotionBlurPlugin { fn build(&self, app: &mut App) { embedded_asset!(app, "motion_blur.wgsl"); app.add_plugins(( ExtractComponentPlugin::<MotionBlur>::default(), UniformComponentPlugin::<MotionBlurUniform>::default(), )); let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return; }; render_app .init_resource::<SpecializedRenderPipelines<pipeline::MotionBlurPipeline>>() .add_systems(RenderStartup, pipeline::init_motion_blur_pipeline) .add_systems( Render, pipeline::prepare_motion_blur_pipelines.in_set(RenderSystems::Prepare), ); render_app .add_render_graph_node::<ViewNodeRunner<node::MotionBlurNode>>( Core3d, Node3d::MotionBlur, ) .add_render_graph_edges( Core3d, ( Node3d::StartMainPassPostProcessing, Node3d::MotionBlur, Node3d::Bloom, // we want blurred areas to bloom and tonemap properly. ), ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/motion_blur/pipeline.rs
crates/bevy_post_process/src/motion_blur/pipeline.rs
use bevy_asset::{load_embedded_asset, AssetServer, Handle}; use bevy_core_pipeline::FullscreenShader; use bevy_ecs::{ component::Component, entity::Entity, query::With, resource::Resource, system::{Commands, Query, Res, ResMut}, }; use bevy_image::BevyDefault as _; use bevy_render::{ globals::GlobalsUniform, render_resource::{ binding_types::{ sampler, texture_2d, texture_2d_multisampled, texture_depth_2d, texture_depth_2d_multisampled, uniform_buffer_sized, }, BindGroupLayoutDescriptor, BindGroupLayoutEntries, CachedRenderPipelineId, ColorTargetState, ColorWrites, FragmentState, PipelineCache, RenderPipelineDescriptor, Sampler, SamplerBindingType, SamplerDescriptor, ShaderStages, ShaderType, SpecializedRenderPipeline, SpecializedRenderPipelines, TextureFormat, TextureSampleType, }, renderer::RenderDevice, view::{ExtractedView, Msaa, ViewTarget}, }; use bevy_shader::{Shader, ShaderDefVal}; use bevy_utils::default; use super::MotionBlurUniform; #[derive(Resource)] pub struct MotionBlurPipeline { pub(crate) sampler: Sampler, pub(crate) layout: BindGroupLayoutDescriptor, pub(crate) layout_msaa: BindGroupLayoutDescriptor, pub(crate) fullscreen_shader: FullscreenShader, pub(crate) fragment_shader: Handle<Shader>, } impl MotionBlurPipeline { pub(crate) fn new( render_device: &RenderDevice, fullscreen_shader: FullscreenShader, fragment_shader: Handle<Shader>, ) -> Self { let mb_layout = &BindGroupLayoutEntries::sequential( ShaderStages::FRAGMENT, ( // View target (read) texture_2d(TextureSampleType::Float { filterable: true }), // Motion Vectors texture_2d(TextureSampleType::Float { filterable: true }), // Depth texture_depth_2d(), // Linear Sampler sampler(SamplerBindingType::Filtering), // Motion blur settings uniform input uniform_buffer_sized(false, Some(MotionBlurUniform::min_size())), // Globals uniform input uniform_buffer_sized(false, Some(GlobalsUniform::min_size())), ), ); let mb_layout_msaa = &BindGroupLayoutEntries::sequential( ShaderStages::FRAGMENT, ( // View target (read) texture_2d(TextureSampleType::Float { filterable: true }), // Motion Vectors texture_2d_multisampled(TextureSampleType::Float { filterable: false }), // Depth texture_depth_2d_multisampled(), // Linear Sampler sampler(SamplerBindingType::Filtering), // Motion blur settings uniform input uniform_buffer_sized(false, Some(MotionBlurUniform::min_size())), // Globals uniform input uniform_buffer_sized(false, Some(GlobalsUniform::min_size())), ), ); let sampler = render_device.create_sampler(&SamplerDescriptor::default()); let layout = BindGroupLayoutDescriptor::new("motion_blur_layout", mb_layout); let layout_msaa = BindGroupLayoutDescriptor::new("motion_blur_layout_msaa", mb_layout_msaa); Self { sampler, layout, layout_msaa, fullscreen_shader, fragment_shader, } } } pub fn init_motion_blur_pipeline( mut commands: Commands, render_device: Res<RenderDevice>, fullscreen_shader: Res<FullscreenShader>, asset_server: Res<AssetServer>, ) { let fullscreen_shader = fullscreen_shader.clone(); let fragment_shader = load_embedded_asset!(asset_server.as_ref(), "motion_blur.wgsl"); commands.insert_resource(MotionBlurPipeline::new( &render_device, fullscreen_shader, fragment_shader, )); } #[derive(PartialEq, Eq, Hash, Clone, Copy)] pub struct MotionBlurPipelineKey { hdr: bool, samples: u32, } impl SpecializedRenderPipeline for MotionBlurPipeline { type Key = MotionBlurPipelineKey; fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor { let layout = match key.samples { 1 => vec![self.layout.clone()], _ => vec![self.layout_msaa.clone()], }; let mut shader_defs = vec![]; if key.samples > 1 { shader_defs.push(ShaderDefVal::from("MULTISAMPLED")); } #[cfg(all(feature = "webgl", target_arch = "wasm32", not(feature = "webgpu")))] { shader_defs.push("NO_DEPTH_TEXTURE_SUPPORT".into()); shader_defs.push("SIXTEEN_BYTE_ALIGNMENT".into()); } RenderPipelineDescriptor { label: Some("motion_blur_pipeline".into()), layout, vertex: self.fullscreen_shader.to_vertex_state(), fragment: Some(FragmentState { shader: self.fragment_shader.clone(), shader_defs, targets: vec![Some(ColorTargetState { format: if key.hdr { ViewTarget::TEXTURE_FORMAT_HDR } else { TextureFormat::bevy_default() }, blend: None, write_mask: ColorWrites::ALL, })], ..default() }), ..default() } } } #[derive(Component)] pub struct MotionBlurPipelineId(pub CachedRenderPipelineId); pub(crate) fn prepare_motion_blur_pipelines( mut commands: Commands, pipeline_cache: Res<PipelineCache>, mut pipelines: ResMut<SpecializedRenderPipelines<MotionBlurPipeline>>, pipeline: Res<MotionBlurPipeline>, views: Query<(Entity, &ExtractedView, &Msaa), With<MotionBlurUniform>>, ) { for (entity, view, msaa) in &views { let pipeline_id = pipelines.specialize( &pipeline_cache, &pipeline, MotionBlurPipelineKey { hdr: view.hdr, samples: msaa.samples(), }, ); commands .entity(entity) .insert(MotionBlurPipelineId(pipeline_id)); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/bloom/settings.rs
crates/bevy_post_process/src/bloom/settings.rs
use super::downsampling_pipeline::BloomUniforms; use bevy_camera::Camera; use bevy_ecs::{ prelude::Component, query::{QueryItem, With}, reflect::ReflectComponent, }; use bevy_math::{AspectRatio, URect, UVec4, Vec2, Vec4}; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{extract_component::ExtractComponent, view::Hdr}; /// Applies a bloom effect to an HDR-enabled 2d or 3d camera. /// /// Bloom emulates an effect found in real cameras and the human eye, /// causing halos to appear around very bright parts of the scene. /// /// See also <https://en.wikipedia.org/wiki/Bloom_(shader_effect)>. /// /// # Usage Notes /// /// **Bloom is currently not compatible with WebGL2.** /// /// Often used in conjunction with `bevy_pbr::StandardMaterial::emissive` for 3d meshes. /// /// Bloom is best used alongside a tonemapping function that desaturates bright colors, /// such as [`bevy_core_pipeline::tonemapping::Tonemapping::TonyMcMapface`]. /// /// Bevy's implementation uses a parametric curve to blend between a set of /// blurred (lower frequency) images generated from the camera's view. /// See <https://starlederer.github.io/bloom/> for a visualization of the parametric curve /// used in Bevy as well as a visualization of the curve's respective scattering profile. #[derive(Component, Reflect, Clone)] #[reflect(Component, Default, Clone)] #[require(Hdr)] pub struct Bloom { /// Controls the baseline of how much the image is scattered (default: 0.15). /// /// This parameter should be used only to control the strength of the bloom /// for the scene as a whole. Increasing it too much will make the scene appear /// blurry and over-exposed. /// /// To make a mesh glow brighter, rather than increase the bloom intensity, /// you should increase the mesh's `emissive` value. /// /// # In energy-conserving mode /// The value represents how likely the light is to scatter. /// /// The value should be between 0.0 and 1.0 where: /// * 0.0 means no bloom /// * 1.0 means the light is scattered as much as possible /// /// # In additive mode /// The value represents how much scattered light is added to /// the image to create the glow effect. /// /// In this configuration: /// * 0.0 means no bloom /// * Greater than 0.0 means a proportionate amount of scattered light is added pub intensity: f32, /// Low frequency contribution boost. /// Controls how much more likely the light /// is to scatter completely sideways (low frequency image). /// /// Comparable to a low shelf boost on an equalizer. /// /// # In energy-conserving mode /// The value should be between 0.0 and 1.0 where: /// * 0.0 means low frequency light uses base intensity for blend factor calculation /// * 1.0 means low frequency light contributes at full power /// /// # In additive mode /// The value represents how much scattered light is added to /// the image to create the glow effect. /// /// In this configuration: /// * 0.0 means no bloom /// * Greater than 0.0 means a proportionate amount of scattered light is added pub low_frequency_boost: f32, /// Low frequency contribution boost curve. /// Controls the curvature of the blend factor function /// making frequencies next to the lowest ones contribute more. /// /// Somewhat comparable to the Q factor of an equalizer node. /// /// Valid range: /// * 0.0 - base intensity and boosted intensity are linearly interpolated /// * 1.0 - all frequencies below maximum are at boosted intensity level pub low_frequency_boost_curvature: f32, /// Tightens how much the light scatters (default: 1.0). /// /// Valid range: /// * 0.0 - maximum scattering angle is 0 degrees (no scattering) /// * 1.0 - maximum scattering angle is 90 degrees pub high_pass_frequency: f32, /// Controls the threshold filter used for extracting the brightest regions from the input image /// before blurring them and compositing back onto the original image. /// /// Changing these settings creates a physically inaccurate image and makes it easy to make /// the final result look worse. However, they can be useful when emulating the 1990s-2000s game look. /// See [`BloomPrefilter`] for more information. pub prefilter: BloomPrefilter, /// Controls whether bloom textures /// are blended between or added to each other. Useful /// if image brightening is desired and a must-change /// if `prefilter` is used. /// /// # Recommendation /// Set to [`BloomCompositeMode::Additive`] if `prefilter` is /// configured in a non-energy-conserving way, /// otherwise set to [`BloomCompositeMode::EnergyConserving`]. pub composite_mode: BloomCompositeMode, /// Maximum size of each dimension for the largest mipchain texture used in downscaling/upscaling. /// Only tweak if you are seeing visual artifacts. pub max_mip_dimension: u32, /// Amount to stretch the bloom on each axis. Artistic control, can be used to emulate /// anamorphic blur by using a large x-value. For large values, you may need to increase /// [`Bloom::max_mip_dimension`] to reduce sampling artifacts. pub scale: Vec2, } impl Bloom { const DEFAULT_MAX_MIP_DIMENSION: u32 = 512; /// The default bloom preset. /// /// This uses the [`EnergyConserving`](BloomCompositeMode::EnergyConserving) composite mode. pub const NATURAL: Self = Self { intensity: 0.15, low_frequency_boost: 0.7, low_frequency_boost_curvature: 0.95, high_pass_frequency: 1.0, prefilter: BloomPrefilter { threshold: 0.0, threshold_softness: 0.0, }, composite_mode: BloomCompositeMode::EnergyConserving, max_mip_dimension: Self::DEFAULT_MAX_MIP_DIMENSION, scale: Vec2::ONE, }; /// Emulates the look of stylized anamorphic bloom, stretched horizontally. pub const ANAMORPHIC: Self = Self { // The larger scale necessitates a larger resolution to reduce artifacts: max_mip_dimension: Self::DEFAULT_MAX_MIP_DIMENSION * 2, scale: Vec2::new(4.0, 1.0), ..Self::NATURAL }; /// A preset that's similar to how older games did bloom. pub const OLD_SCHOOL: Self = Self { intensity: 0.05, low_frequency_boost: 0.7, low_frequency_boost_curvature: 0.95, high_pass_frequency: 1.0, prefilter: BloomPrefilter { threshold: 0.6, threshold_softness: 0.2, }, composite_mode: BloomCompositeMode::Additive, max_mip_dimension: Self::DEFAULT_MAX_MIP_DIMENSION, scale: Vec2::ONE, }; /// A preset that applies a very strong bloom, and blurs the whole screen. pub const SCREEN_BLUR: Self = Self { intensity: 1.0, low_frequency_boost: 0.0, low_frequency_boost_curvature: 0.0, high_pass_frequency: 1.0 / 3.0, prefilter: BloomPrefilter { threshold: 0.0, threshold_softness: 0.0, }, composite_mode: BloomCompositeMode::EnergyConserving, max_mip_dimension: Self::DEFAULT_MAX_MIP_DIMENSION, scale: Vec2::ONE, }; } impl Default for Bloom { fn default() -> Self { Self::NATURAL } } /// Applies a threshold filter to the input image to extract the brightest /// regions before blurring them and compositing back onto the original image. /// These settings are useful when emulating the 1990s-2000s game look. /// /// # Considerations /// * Changing these settings creates a physically inaccurate image /// * Changing these settings makes it easy to make the final result look worse /// * Non-default prefilter settings should be used in conjunction with [`BloomCompositeMode::Additive`] #[derive(Default, Clone, Reflect)] #[reflect(Clone, Default)] pub struct BloomPrefilter { /// Baseline of the quadratic threshold curve (default: 0.0). /// /// RGB values under the threshold curve will not contribute to the effect. pub threshold: f32, /// Controls how much to blend between the thresholded and non-thresholded colors (default: 0.0). /// /// 0.0 = Abrupt threshold, no blending /// 1.0 = Fully soft threshold /// /// Values outside of the range [0.0, 1.0] will be clamped. pub threshold_softness: f32, } #[derive(Debug, Clone, Reflect, PartialEq, Eq, Hash, Copy)] #[reflect(Clone, Hash, PartialEq)] pub enum BloomCompositeMode { EnergyConserving, Additive, } impl ExtractComponent for Bloom { type QueryData = (&'static Self, &'static Camera); type QueryFilter = With<Hdr>; type Out = (Self, BloomUniforms); fn extract_component((bloom, camera): QueryItem<'_, '_, Self::QueryData>) -> Option<Self::Out> { match ( camera.physical_viewport_rect(), camera.physical_viewport_size(), camera.physical_target_size(), camera.is_active, ) { (Some(URect { min: origin, .. }), Some(size), Some(target_size), true) if size.x != 0 && size.y != 0 => { let threshold = bloom.prefilter.threshold; let threshold_softness = bloom.prefilter.threshold_softness; let knee = threshold * threshold_softness.clamp(0.0, 1.0); let uniform = BloomUniforms { threshold_precomputations: Vec4::new( threshold, threshold - knee, 2.0 * knee, 0.25 / (knee + 0.00001), ), viewport: UVec4::new(origin.x, origin.y, size.x, size.y).as_vec4() / UVec4::new(target_size.x, target_size.y, target_size.x, target_size.y) .as_vec4(), aspect: AspectRatio::try_from_pixels(size.x, size.y) .expect("Valid screen size values for Bloom settings") .ratio(), scale: bloom.scale, }; Some((bloom.clone(), uniform)) } _ => None, } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/bloom/downsampling_pipeline.rs
crates/bevy_post_process/src/bloom/downsampling_pipeline.rs
use bevy_core_pipeline::FullscreenShader; use super::{Bloom, BLOOM_TEXTURE_FORMAT}; use bevy_asset::{load_embedded_asset, AssetServer, Handle}; use bevy_ecs::{ prelude::{Component, Entity}, resource::Resource, system::{Commands, Query, Res, ResMut}, }; use bevy_math::{Vec2, Vec4}; use bevy_render::{ render_resource::{ binding_types::{sampler, texture_2d, uniform_buffer}, *, }, renderer::RenderDevice, }; use bevy_shader::Shader; use bevy_utils::default; #[derive(Component)] pub struct BloomDownsamplingPipelineIds { pub main: CachedRenderPipelineId, pub first: CachedRenderPipelineId, } #[derive(Resource)] pub struct BloomDownsamplingPipeline { /// Layout with a texture, a sampler, and uniforms pub bind_group_layout: BindGroupLayoutDescriptor, pub sampler: Sampler, /// The asset handle for the fullscreen vertex shader. pub fullscreen_shader: FullscreenShader, /// The fragment shader asset handle. pub fragment_shader: Handle<Shader>, } #[derive(PartialEq, Eq, Hash, Clone)] pub struct BloomDownsamplingPipelineKeys { prefilter: bool, first_downsample: bool, uniform_scale: bool, } /// The uniform struct extracted from [`Bloom`] attached to a Camera. /// Will be available for use in the Bloom shader. #[derive(Component, ShaderType, Clone)] pub struct BloomUniforms { // Precomputed values used when thresholding, see https://catlikecoding.com/unity/tutorials/advanced-rendering/bloom/#3.4 pub threshold_precomputations: Vec4, pub viewport: Vec4, pub scale: Vec2, pub aspect: f32, } pub fn init_bloom_downsampling_pipeline( mut commands: Commands, render_device: Res<RenderDevice>, fullscreen_shader: Res<FullscreenShader>, asset_server: Res<AssetServer>, ) { // Bind group layout let bind_group_layout = BindGroupLayoutDescriptor::new( "bloom_downsampling_bind_group_layout_with_settings", &BindGroupLayoutEntries::sequential( ShaderStages::FRAGMENT, ( // Input texture binding texture_2d(TextureSampleType::Float { filterable: true }), // Sampler binding sampler(SamplerBindingType::Filtering), // Downsampling settings binding uniform_buffer::<BloomUniforms>(true), ), ), ); // Sampler let sampler = render_device.create_sampler(&SamplerDescriptor { min_filter: FilterMode::Linear, mag_filter: FilterMode::Linear, address_mode_u: AddressMode::ClampToEdge, address_mode_v: AddressMode::ClampToEdge, ..Default::default() }); commands.insert_resource(BloomDownsamplingPipeline { bind_group_layout, sampler, fullscreen_shader: fullscreen_shader.clone(), fragment_shader: load_embedded_asset!(asset_server.as_ref(), "bloom.wgsl"), }); } impl SpecializedRenderPipeline for BloomDownsamplingPipeline { type Key = BloomDownsamplingPipelineKeys; fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor { let layout = vec![self.bind_group_layout.clone()]; let entry_point = if key.first_downsample { "downsample_first".into() } else { "downsample".into() }; let mut shader_defs = vec![]; if key.first_downsample { shader_defs.push("FIRST_DOWNSAMPLE".into()); } if key.prefilter { shader_defs.push("USE_THRESHOLD".into()); } if key.uniform_scale { shader_defs.push("UNIFORM_SCALE".into()); } RenderPipelineDescriptor { label: Some( if key.first_downsample { "bloom_downsampling_pipeline_first" } else { "bloom_downsampling_pipeline" } .into(), ), layout, vertex: self.fullscreen_shader.to_vertex_state(), fragment: Some(FragmentState { shader: self.fragment_shader.clone(), shader_defs, entry_point: Some(entry_point), targets: vec![Some(ColorTargetState { format: BLOOM_TEXTURE_FORMAT, blend: None, write_mask: ColorWrites::ALL, })], }), ..default() } } } pub fn prepare_downsampling_pipeline( mut commands: Commands, pipeline_cache: Res<PipelineCache>, mut pipelines: ResMut<SpecializedRenderPipelines<BloomDownsamplingPipeline>>, pipeline: Res<BloomDownsamplingPipeline>, views: Query<(Entity, &Bloom)>, ) { for (entity, bloom) in &views { let prefilter = bloom.prefilter.threshold > 0.0; let pipeline_id = pipelines.specialize( &pipeline_cache, &pipeline, BloomDownsamplingPipelineKeys { prefilter, first_downsample: false, uniform_scale: bloom.scale == Vec2::ONE, }, ); let pipeline_first_id = pipelines.specialize( &pipeline_cache, &pipeline, BloomDownsamplingPipelineKeys { prefilter, first_downsample: true, uniform_scale: bloom.scale == Vec2::ONE, }, ); commands .entity(entity) .insert(BloomDownsamplingPipelineIds { first: pipeline_first_id, main: pipeline_id, }); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/bloom/upsampling_pipeline.rs
crates/bevy_post_process/src/bloom/upsampling_pipeline.rs
use bevy_core_pipeline::FullscreenShader; use super::{ downsampling_pipeline::BloomUniforms, Bloom, BloomCompositeMode, BLOOM_TEXTURE_FORMAT, }; use bevy_asset::{load_embedded_asset, AssetServer, Handle}; use bevy_ecs::{ prelude::{Component, Entity}, resource::Resource, system::{Commands, Query, Res, ResMut}, }; use bevy_render::{ render_resource::{ binding_types::{sampler, texture_2d, uniform_buffer}, *, }, view::ViewTarget, }; use bevy_shader::Shader; use bevy_utils::default; #[derive(Component)] pub struct UpsamplingPipelineIds { pub id_main: CachedRenderPipelineId, pub id_final: CachedRenderPipelineId, } #[derive(Resource)] pub struct BloomUpsamplingPipeline { pub bind_group_layout: BindGroupLayoutDescriptor, /// The asset handle for the fullscreen vertex shader. pub fullscreen_shader: FullscreenShader, /// The fragment shader asset handle. pub fragment_shader: Handle<Shader>, } #[derive(PartialEq, Eq, Hash, Clone)] pub struct BloomUpsamplingPipelineKeys { composite_mode: BloomCompositeMode, final_pipeline: bool, } pub fn init_bloom_upscaling_pipeline( mut commands: Commands, fullscreen_shader: Res<FullscreenShader>, asset_server: Res<AssetServer>, ) { let bind_group_layout = BindGroupLayoutDescriptor::new( "bloom_upsampling_bind_group_layout", &BindGroupLayoutEntries::sequential( ShaderStages::FRAGMENT, ( // Input texture texture_2d(TextureSampleType::Float { filterable: true }), // Sampler sampler(SamplerBindingType::Filtering), // BloomUniforms uniform_buffer::<BloomUniforms>(true), ), ), ); commands.insert_resource(BloomUpsamplingPipeline { bind_group_layout, fullscreen_shader: fullscreen_shader.clone(), fragment_shader: load_embedded_asset!(asset_server.as_ref(), "bloom.wgsl"), }); } impl SpecializedRenderPipeline for BloomUpsamplingPipeline { type Key = BloomUpsamplingPipelineKeys; fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor { let texture_format = if key.final_pipeline { ViewTarget::TEXTURE_FORMAT_HDR } else { BLOOM_TEXTURE_FORMAT }; let color_blend = match key.composite_mode { BloomCompositeMode::EnergyConserving => { // At the time of developing this we decided to blend our // blur pyramid levels using native WGPU render pass blend // constants. They are set in the bloom node's run function. // This seemed like a good approach at the time which allowed // us to perform complex calculations for blend levels on the CPU, // however, we missed the fact that this prevented us from using // textures to customize bloom appearance on individual parts // of the screen and create effects such as lens dirt or // screen blur behind certain UI elements. // // 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) // 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. BlendComponent { src_factor: BlendFactor::Constant, dst_factor: BlendFactor::OneMinusConstant, operation: BlendOperation::Add, } } BloomCompositeMode::Additive => BlendComponent { src_factor: BlendFactor::Constant, dst_factor: BlendFactor::One, operation: BlendOperation::Add, }, }; RenderPipelineDescriptor { label: Some("bloom_upsampling_pipeline".into()), layout: vec![self.bind_group_layout.clone()], vertex: self.fullscreen_shader.to_vertex_state(), fragment: Some(FragmentState { shader: self.fragment_shader.clone(), entry_point: Some("upsample".into()), targets: vec![Some(ColorTargetState { format: texture_format, blend: Some(BlendState { color: color_blend, alpha: BlendComponent { src_factor: BlendFactor::Zero, dst_factor: BlendFactor::One, operation: BlendOperation::Add, }, }), write_mask: ColorWrites::ALL, })], ..default() }), ..default() } } } pub fn prepare_upsampling_pipeline( mut commands: Commands, pipeline_cache: Res<PipelineCache>, mut pipelines: ResMut<SpecializedRenderPipelines<BloomUpsamplingPipeline>>, pipeline: Res<BloomUpsamplingPipeline>, views: Query<(Entity, &Bloom)>, ) { for (entity, bloom) in &views { let pipeline_id = pipelines.specialize( &pipeline_cache, &pipeline, BloomUpsamplingPipelineKeys { composite_mode: bloom.composite_mode, final_pipeline: false, }, ); let pipeline_final_id = pipelines.specialize( &pipeline_cache, &pipeline, BloomUpsamplingPipelineKeys { composite_mode: bloom.composite_mode, final_pipeline: true, }, ); commands.entity(entity).insert(UpsamplingPipelineIds { id_main: pipeline_id, id_final: pipeline_final_id, }); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/bloom/mod.rs
crates/bevy_post_process/src/bloom/mod.rs
mod downsampling_pipeline; mod settings; mod upsampling_pipeline; use bevy_image::ToExtents; pub use settings::{Bloom, BloomCompositeMode, BloomPrefilter}; use crate::bloom::{ downsampling_pipeline::init_bloom_downsampling_pipeline, upsampling_pipeline::init_bloom_upscaling_pipeline, }; use bevy_app::{App, Plugin}; use bevy_asset::embedded_asset; use bevy_color::{Gray, LinearRgba}; use bevy_core_pipeline::{ core_2d::graph::{Core2d, Node2d}, core_3d::graph::{Core3d, Node3d}, }; use bevy_ecs::{prelude::*, query::QueryItem}; use bevy_math::{ops, UVec2}; use bevy_render::{ camera::ExtractedCamera, diagnostic::RecordDiagnostics, extract_component::{ ComponentUniforms, DynamicUniformIndex, ExtractComponentPlugin, UniformComponentPlugin, }, render_graph::{NodeRunError, RenderGraphContext, RenderGraphExt, ViewNode, ViewNodeRunner}, render_resource::*, renderer::{RenderContext, RenderDevice}, texture::{CachedTexture, TextureCache}, view::ViewTarget, Render, RenderApp, RenderStartup, RenderSystems, }; use downsampling_pipeline::{ prepare_downsampling_pipeline, BloomDownsamplingPipeline, BloomDownsamplingPipelineIds, BloomUniforms, }; #[cfg(feature = "trace")] use tracing::info_span; use upsampling_pipeline::{ prepare_upsampling_pipeline, BloomUpsamplingPipeline, UpsamplingPipelineIds, }; const BLOOM_TEXTURE_FORMAT: TextureFormat = TextureFormat::Rg11b10Ufloat; #[derive(Default)] pub struct BloomPlugin; impl Plugin for BloomPlugin { fn build(&self, app: &mut App) { embedded_asset!(app, "bloom.wgsl"); app.add_plugins(( ExtractComponentPlugin::<Bloom>::default(), UniformComponentPlugin::<BloomUniforms>::default(), )); let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return; }; render_app .init_resource::<SpecializedRenderPipelines<BloomDownsamplingPipeline>>() .init_resource::<SpecializedRenderPipelines<BloomUpsamplingPipeline>>() .add_systems( RenderStartup, ( init_bloom_downsampling_pipeline, init_bloom_upscaling_pipeline, ), ) .add_systems( Render, ( prepare_downsampling_pipeline.in_set(RenderSystems::Prepare), prepare_upsampling_pipeline.in_set(RenderSystems::Prepare), prepare_bloom_textures.in_set(RenderSystems::PrepareResources), prepare_bloom_bind_groups.in_set(RenderSystems::PrepareBindGroups), ), ) // Add bloom to the 3d render graph .add_render_graph_node::<ViewNodeRunner<BloomNode>>(Core3d, Node3d::Bloom) .add_render_graph_edges( Core3d, ( Node3d::StartMainPassPostProcessing, Node3d::Bloom, Node3d::Tonemapping, ), ) // Add bloom to the 2d render graph .add_render_graph_node::<ViewNodeRunner<BloomNode>>(Core2d, Node2d::Bloom) .add_render_graph_edges( Core2d, ( Node2d::StartMainPassPostProcessing, Node2d::Bloom, Node2d::Tonemapping, ), ); } } #[derive(Default)] struct BloomNode; impl ViewNode for BloomNode { type ViewQuery = ( &'static ExtractedCamera, &'static ViewTarget, &'static BloomTexture, &'static BloomBindGroups, &'static DynamicUniformIndex<BloomUniforms>, &'static Bloom, &'static UpsamplingPipelineIds, &'static BloomDownsamplingPipelineIds, ); // Atypically for a post-processing effect, we do not need to // use a secondary texture normally provided by view_target.post_process_write(), // instead we write into our own bloom texture and then directly back onto main. fn run<'w>( &self, _graph: &mut RenderGraphContext, render_context: &mut RenderContext<'w>, ( camera, view_target, bloom_texture, bind_groups, uniform_index, bloom_settings, upsampling_pipeline_ids, downsampling_pipeline_ids, ): QueryItem<'w, '_, Self::ViewQuery>, world: &'w World, ) -> Result<(), NodeRunError> { if bloom_settings.intensity == 0.0 { return Ok(()); } let downsampling_pipeline_res = world.resource::<BloomDownsamplingPipeline>(); let pipeline_cache = world.resource::<PipelineCache>(); let uniforms = world.resource::<ComponentUniforms<BloomUniforms>>(); let ( Some(uniforms), Some(downsampling_first_pipeline), Some(downsampling_pipeline), Some(upsampling_pipeline), Some(upsampling_final_pipeline), ) = ( uniforms.binding(), pipeline_cache.get_render_pipeline(downsampling_pipeline_ids.first), pipeline_cache.get_render_pipeline(downsampling_pipeline_ids.main), pipeline_cache.get_render_pipeline(upsampling_pipeline_ids.id_main), pipeline_cache.get_render_pipeline(upsampling_pipeline_ids.id_final), ) else { return Ok(()); }; let view_texture = view_target.main_texture_view(); let view_texture_unsampled = view_target.get_unsampled_color_attachment(); let diagnostics = render_context.diagnostic_recorder(); render_context.add_command_buffer_generation_task(move |render_device| { #[cfg(feature = "trace")] let _bloom_span = info_span!("bloom").entered(); let mut command_encoder = render_device.create_command_encoder(&CommandEncoderDescriptor { label: Some("bloom_command_encoder"), }); command_encoder.push_debug_group("bloom"); let time_span = diagnostics.time_span(&mut command_encoder, "bloom"); // First downsample pass { let downsampling_first_bind_group = render_device.create_bind_group( "bloom_downsampling_first_bind_group", &pipeline_cache .get_bind_group_layout(&downsampling_pipeline_res.bind_group_layout), &BindGroupEntries::sequential(( // Read from main texture directly view_texture, &bind_groups.sampler, uniforms.clone(), )), ); let view = &bloom_texture.view(0); let mut downsampling_first_pass = command_encoder.begin_render_pass(&RenderPassDescriptor { label: Some("bloom_downsampling_first_pass"), color_attachments: &[Some(RenderPassColorAttachment { view, depth_slice: None, resolve_target: None, ops: Operations::default(), })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, }); downsampling_first_pass.set_pipeline(downsampling_first_pipeline); downsampling_first_pass.set_bind_group( 0, &downsampling_first_bind_group, &[uniform_index.index()], ); downsampling_first_pass.draw(0..3, 0..1); } // Other downsample passes for mip in 1..bloom_texture.mip_count { let view = &bloom_texture.view(mip); let mut downsampling_pass = command_encoder.begin_render_pass(&RenderPassDescriptor { label: Some("bloom_downsampling_pass"), color_attachments: &[Some(RenderPassColorAttachment { view, depth_slice: None, resolve_target: None, ops: Operations::default(), })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, }); downsampling_pass.set_pipeline(downsampling_pipeline); downsampling_pass.set_bind_group( 0, &bind_groups.downsampling_bind_groups[mip as usize - 1], &[uniform_index.index()], ); downsampling_pass.draw(0..3, 0..1); } // Upsample passes except the final one for mip in (1..bloom_texture.mip_count).rev() { let view = &bloom_texture.view(mip - 1); let mut upsampling_pass = command_encoder.begin_render_pass(&RenderPassDescriptor { label: Some("bloom_upsampling_pass"), color_attachments: &[Some(RenderPassColorAttachment { view, depth_slice: None, resolve_target: None, ops: Operations { load: LoadOp::Load, store: StoreOp::Store, }, })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, }); upsampling_pass.set_pipeline(upsampling_pipeline); upsampling_pass.set_bind_group( 0, &bind_groups.upsampling_bind_groups [(bloom_texture.mip_count - mip - 1) as usize], &[uniform_index.index()], ); let blend = compute_blend_factor( bloom_settings, mip as f32, (bloom_texture.mip_count - 1) as f32, ); upsampling_pass.set_blend_constant(LinearRgba::gray(blend).into()); upsampling_pass.draw(0..3, 0..1); } // Final upsample pass // This is very similar to the above upsampling passes with the only difference // being the pipeline (which itself is barely different) and the color attachment { let mut upsampling_final_pass = command_encoder.begin_render_pass(&RenderPassDescriptor { label: Some("bloom_upsampling_final_pass"), color_attachments: &[Some(view_texture_unsampled)], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, }); upsampling_final_pass.set_pipeline(upsampling_final_pipeline); upsampling_final_pass.set_bind_group( 0, &bind_groups.upsampling_bind_groups[(bloom_texture.mip_count - 1) as usize], &[uniform_index.index()], ); if let Some(viewport) = camera.viewport.as_ref() { upsampling_final_pass.set_viewport( viewport.physical_position.x as f32, viewport.physical_position.y as f32, viewport.physical_size.x as f32, viewport.physical_size.y as f32, viewport.depth.start, viewport.depth.end, ); } let blend = compute_blend_factor(bloom_settings, 0.0, (bloom_texture.mip_count - 1) as f32); upsampling_final_pass.set_blend_constant(LinearRgba::gray(blend).into()); upsampling_final_pass.draw(0..3, 0..1); } time_span.end(&mut command_encoder); command_encoder.pop_debug_group(); command_encoder.finish() }); Ok(()) } } #[derive(Component)] struct BloomTexture { // First mip is half the screen resolution, successive mips are half the previous #[cfg(any( not(feature = "webgl"), not(target_arch = "wasm32"), feature = "webgpu" ))] texture: CachedTexture, // WebGL does not support binding specific mip levels for sampling, fallback to separate textures instead #[cfg(all(feature = "webgl", target_arch = "wasm32", not(feature = "webgpu")))] texture: Vec<CachedTexture>, mip_count: u32, } impl BloomTexture { #[cfg(any( not(feature = "webgl"), not(target_arch = "wasm32"), feature = "webgpu" ))] fn view(&self, base_mip_level: u32) -> TextureView { self.texture.texture.create_view(&TextureViewDescriptor { base_mip_level, mip_level_count: Some(1u32), ..Default::default() }) } #[cfg(all(feature = "webgl", target_arch = "wasm32", not(feature = "webgpu")))] fn view(&self, base_mip_level: u32) -> TextureView { self.texture[base_mip_level as usize] .texture .create_view(&TextureViewDescriptor { base_mip_level: 0, mip_level_count: Some(1u32), ..Default::default() }) } } fn prepare_bloom_textures( mut commands: Commands, mut texture_cache: ResMut<TextureCache>, render_device: Res<RenderDevice>, views: Query<(Entity, &ExtractedCamera, &Bloom)>, ) { for (entity, camera, bloom) in &views { if let Some(viewport) = camera.physical_viewport_size { // How many times we can halve the resolution minus one so we don't go unnecessarily low let mip_count = bloom.max_mip_dimension.ilog2().max(2) - 1; let mip_height_ratio = if viewport.y != 0 { bloom.max_mip_dimension as f32 / viewport.y as f32 } else { 0. }; let texture_descriptor = TextureDescriptor { label: Some("bloom_texture"), size: (viewport.as_vec2() * mip_height_ratio) .round() .as_uvec2() .max(UVec2::ONE) .to_extents(), mip_level_count: mip_count, sample_count: 1, dimension: TextureDimension::D2, format: BLOOM_TEXTURE_FORMAT, usage: TextureUsages::RENDER_ATTACHMENT | TextureUsages::TEXTURE_BINDING, view_formats: &[], }; #[cfg(any( not(feature = "webgl"), not(target_arch = "wasm32"), feature = "webgpu" ))] let texture = texture_cache.get(&render_device, texture_descriptor); #[cfg(all(feature = "webgl", target_arch = "wasm32", not(feature = "webgpu")))] let texture: Vec<CachedTexture> = (0..mip_count) .map(|mip| { texture_cache.get( &render_device, TextureDescriptor { size: Extent3d { width: (texture_descriptor.size.width >> mip).max(1), height: (texture_descriptor.size.height >> mip).max(1), depth_or_array_layers: 1, }, mip_level_count: 1, ..texture_descriptor.clone() }, ) }) .collect(); commands .entity(entity) .insert(BloomTexture { texture, mip_count }); } } } #[derive(Component)] struct BloomBindGroups { cache_key: (TextureId, BufferId), downsampling_bind_groups: Box<[BindGroup]>, upsampling_bind_groups: Box<[BindGroup]>, sampler: Sampler, } fn prepare_bloom_bind_groups( mut commands: Commands, render_device: Res<RenderDevice>, downsampling_pipeline: Res<BloomDownsamplingPipeline>, upsampling_pipeline: Res<BloomUpsamplingPipeline>, views: Query<(Entity, &BloomTexture, Option<&BloomBindGroups>)>, uniforms: Res<ComponentUniforms<BloomUniforms>>, pipeline_cache: Res<PipelineCache>, ) { let sampler = &downsampling_pipeline.sampler; for (entity, bloom_texture, bloom_bind_groups) in &views { if let Some(b) = bloom_bind_groups && b.cache_key == ( bloom_texture.texture.texture.id(), uniforms.buffer().unwrap().id(), ) { continue; } let bind_group_count = bloom_texture.mip_count as usize - 1; let mut downsampling_bind_groups = Vec::with_capacity(bind_group_count); for mip in 1..bloom_texture.mip_count { downsampling_bind_groups.push(render_device.create_bind_group( "bloom_downsampling_bind_group", &pipeline_cache.get_bind_group_layout(&downsampling_pipeline.bind_group_layout), &BindGroupEntries::sequential(( &bloom_texture.view(mip - 1), sampler, uniforms.binding().unwrap(), )), )); } let mut upsampling_bind_groups = Vec::with_capacity(bind_group_count); for mip in (0..bloom_texture.mip_count).rev() { upsampling_bind_groups.push(render_device.create_bind_group( "bloom_upsampling_bind_group", &pipeline_cache.get_bind_group_layout(&upsampling_pipeline.bind_group_layout), &BindGroupEntries::sequential(( &bloom_texture.view(mip), sampler, uniforms.binding().unwrap(), )), )); } commands.entity(entity).insert(BloomBindGroups { cache_key: ( bloom_texture.texture.texture.id(), uniforms.buffer().unwrap().id(), ), downsampling_bind_groups: downsampling_bind_groups.into_boxed_slice(), upsampling_bind_groups: upsampling_bind_groups.into_boxed_slice(), sampler: sampler.clone(), }); } } /// Calculates blend intensities of blur pyramid levels /// during the upsampling + compositing stage. /// /// The function assumes all pyramid levels are upsampled and /// blended into higher frequency ones using this function to /// calculate blend levels every time. The final (highest frequency) /// pyramid level in not blended into anything therefore this function /// is not applied to it. As a result, the *mip* parameter of 0 indicates /// the second-highest frequency pyramid level (in our case that is the /// 0th mip of the bloom texture with the original image being the /// actual highest frequency level). /// /// Parameters: /// * `mip` - the index of the lower frequency pyramid level (0 - `max_mip`, where 0 indicates highest frequency mip but not the highest frequency image). /// * `max_mip` - the index of the lowest frequency pyramid level. /// /// This function can be visually previewed for all values of *mip* (normalized) with tweakable /// [`Bloom`] parameters on [Desmos graphing calculator](https://www.desmos.com/calculator/ncc8xbhzzl). fn compute_blend_factor(bloom: &Bloom, mip: f32, max_mip: f32) -> f32 { let mut lf_boost = (1.0 - ops::powf( 1.0 - (mip / max_mip), 1.0 / (1.0 - bloom.low_frequency_boost_curvature), )) * bloom.low_frequency_boost; let high_pass_lq = 1.0 - (((mip / max_mip) - bloom.high_pass_frequency) / bloom.high_pass_frequency) .clamp(0.0, 1.0); lf_boost *= match bloom.composite_mode { BloomCompositeMode::EnergyConserving => 1.0 - bloom.intensity, BloomCompositeMode::Additive => 1.0, }; (bloom.intensity + lf_boost) * high_pass_lq }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/auto_exposure/buffers.rs
crates/bevy_post_process/src/auto_exposure/buffers.rs
use bevy_ecs::prelude::*; use bevy_platform::collections::{hash_map::Entry, HashMap}; use bevy_render::{ render_resource::{StorageBuffer, UniformBuffer}, renderer::{RenderDevice, RenderQueue}, sync_world::RenderEntity, Extract, }; use super::{pipeline::AutoExposureUniform, AutoExposure}; #[derive(Resource, Default)] pub(super) struct AutoExposureBuffers { pub(super) buffers: HashMap<Entity, AutoExposureBuffer>, } pub(super) struct AutoExposureBuffer { pub(super) state: StorageBuffer<f32>, pub(super) settings: UniformBuffer<AutoExposureUniform>, } #[derive(Resource)] pub(super) struct ExtractedStateBuffers { changed: Vec<(Entity, AutoExposure)>, removed: Vec<Entity>, } pub(super) fn extract_buffers( mut commands: Commands, changed: Extract<Query<(RenderEntity, &AutoExposure), Changed<AutoExposure>>>, mut removed: Extract<RemovedComponents<AutoExposure>>, ) { commands.insert_resource(ExtractedStateBuffers { changed: changed .iter() .map(|(entity, settings)| (entity, settings.clone())) .collect(), removed: removed.read().collect(), }); } pub(super) fn prepare_buffers( device: Res<RenderDevice>, queue: Res<RenderQueue>, mut extracted: ResMut<ExtractedStateBuffers>, mut buffers: ResMut<AutoExposureBuffers>, ) { for (entity, settings) in extracted.changed.drain(..) { let (min_log_lum, max_log_lum) = settings.range.into_inner(); let (low_percent, high_percent) = settings.filter.into_inner(); let initial_state = 0.0f32.clamp(min_log_lum, max_log_lum); let settings = AutoExposureUniform { min_log_lum, inv_log_lum_range: 1.0 / (max_log_lum - min_log_lum), log_lum_range: max_log_lum - min_log_lum, low_percent, high_percent, speed_up: settings.speed_brighten, speed_down: settings.speed_darken, exponential_transition_distance: settings.exponential_transition_distance, }; match buffers.buffers.entry(entity) { Entry::Occupied(mut entry) => { // Update the settings buffer, but skip updating the state buffer. // The state buffer is skipped so that the animation stays continuous. let value = entry.get_mut(); value.settings.set(settings); value.settings.write_buffer(&device, &queue); } Entry::Vacant(entry) => { let value = entry.insert(AutoExposureBuffer { state: StorageBuffer::from(initial_state), settings: UniformBuffer::from(settings), }); value.state.write_buffer(&device, &queue); value.settings.write_buffer(&device, &queue); } } } for entity in extracted.removed.drain(..) { buffers.buffers.remove(&entity); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/auto_exposure/settings.rs
crates/bevy_post_process/src/auto_exposure/settings.rs
use core::ops::RangeInclusive; use super::compensation_curve::AutoExposureCompensationCurve; use bevy_asset::Handle; use bevy_ecs::{prelude::Component, reflect::ReflectComponent}; use bevy_image::Image; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{extract_component::ExtractComponent, view::Hdr}; use bevy_utils::default; /// Component that enables auto exposure for an HDR-enabled 2d or 3d camera. /// /// Auto exposure adjusts the exposure of the camera automatically to /// simulate the human eye's ability to adapt to different lighting conditions. /// /// Bevy's implementation builds a 64 bin histogram of the scene's luminance, /// and then adjusts the exposure so that the average brightness of the final /// render will be middle gray. Because it's using a histogram, some details can /// be selectively ignored or emphasized. Outliers like shadows and specular /// highlights can be ignored, and certain areas can be given more (or less) /// weight based on a mask. /// /// # Usage Notes /// /// **Auto Exposure requires compute shaders and is not compatible with WebGL2.** #[derive(Component, Clone, Reflect, ExtractComponent)] #[reflect(Component, Default, Clone)] #[require(Hdr)] pub struct AutoExposure { /// The range of exposure values for the histogram. /// /// Pixel values below this range will be ignored, and pixel values above this range will be /// clamped in the sense that they will count towards the highest bin in the histogram. /// The default value is `-8.0..=8.0`. pub range: RangeInclusive<f32>, /// 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`. pub filter: RangeInclusive<f32>, /// The speed at which the exposure adapts from dark to bright scenes, in F-stops per second. pub speed_brighten: f32, /// The speed at which the exposure adapts from bright to dark scenes, in F-stops per second. pub speed_darken: f32, /// The distance in F-stops from the target exposure from where to transition from animating /// in linear fashion to animating exponentially. This helps against jittering when the /// target exposure keeps on changing slightly from frame to frame, while still maintaining /// a relatively slow animation for big changes in scene brightness. /// /// ```text /// ev /// ➔●┐ /// | ⬈ ├ exponential section /// │ ⬈ ┘ /// │ ⬈ ┐ /// │ ⬈ ├ linear section /// │⬈ ┘ /// ●───────────────────────── time /// ``` /// /// The default value is 1.5. pub exponential_transition_distance: f32, /// The mask to apply when metering. The mask will cover the entire screen, where: /// * `(0.0, 0.0)` is the top-left corner, /// * `(1.0, 1.0)` is the bottom-right corner. /// /// Only the red channel of the texture is used. /// The sample at the current screen position will be used to weight the contribution /// of each pixel to the histogram: /// * 0.0 means the pixel will not contribute to the histogram, /// * 1.0 means the pixel will contribute fully to the histogram. /// /// The default value is a white image, so all pixels contribute equally. /// /// # Usage Notes /// /// The mask is quantized to 16 discrete levels because of limitations in the compute shader /// implementation. pub metering_mask: Handle<Image>, /// Exposure compensation curve to apply after metering. /// The default value is a flat line at 0.0. /// For more information, see [`AutoExposureCompensationCurve`]. pub compensation_curve: Handle<AutoExposureCompensationCurve>, } impl Default for AutoExposure { fn default() -> Self { Self { range: -8.0..=8.0, filter: 0.10..=0.90, speed_brighten: 3.0, speed_darken: 1.0, exponential_transition_distance: 1.5, metering_mask: default(), compensation_curve: default(), } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/auto_exposure/node.rs
crates/bevy_post_process/src/auto_exposure/node.rs
use super::{ buffers::AutoExposureBuffers, compensation_curve::GpuAutoExposureCompensationCurve, pipeline::{AutoExposurePipeline, ViewAutoExposurePipeline}, AutoExposureResources, }; use bevy_ecs::{ query::QueryState, system::lifetimeless::Read, world::{FromWorld, World}, }; use bevy_render::{ diagnostic::RecordDiagnostics, globals::GlobalsBuffer, render_asset::RenderAssets, render_graph::*, render_resource::*, renderer::RenderContext, texture::{FallbackImage, GpuImage}, view::{ExtractedView, ViewTarget, ViewUniform, ViewUniformOffset, ViewUniforms}, }; #[derive(RenderLabel, Debug, Clone, Hash, PartialEq, Eq)] pub struct AutoExposure; pub struct AutoExposureNode { query: QueryState<( Read<ViewUniformOffset>, Read<ViewTarget>, Read<ViewAutoExposurePipeline>, Read<ExtractedView>, )>, } impl FromWorld for AutoExposureNode { fn from_world(world: &mut World) -> Self { Self { query: QueryState::new(world), } } } impl Node for AutoExposureNode { fn update(&mut self, world: &mut World) { self.query.update_archetypes(world); } fn run( &self, graph: &mut RenderGraphContext, render_context: &mut RenderContext, world: &World, ) -> Result<(), NodeRunError> { let view_entity = graph.view_entity(); let pipeline_cache = world.resource::<PipelineCache>(); let pipeline = world.resource::<AutoExposurePipeline>(); let resources = world.resource::<AutoExposureResources>(); let view_uniforms_resource = world.resource::<ViewUniforms>(); let view_uniforms = &view_uniforms_resource.uniforms; let view_uniforms_buffer = view_uniforms.buffer().unwrap(); let globals_buffer = world.resource::<GlobalsBuffer>(); let auto_exposure_buffers = world.resource::<AutoExposureBuffers>(); let ( Ok((view_uniform_offset, view_target, auto_exposure, view)), Some(auto_exposure_buffers), ) = ( self.query.get_manual(world, view_entity), auto_exposure_buffers.buffers.get(&view_entity), ) else { return Ok(()); }; let (Some(histogram_pipeline), Some(average_pipeline)) = ( pipeline_cache.get_compute_pipeline(auto_exposure.histogram_pipeline), pipeline_cache.get_compute_pipeline(auto_exposure.mean_luminance_pipeline), ) else { return Ok(()); }; let source = view_target.main_texture_view(); let fallback = world.resource::<FallbackImage>(); let mask = world .resource::<RenderAssets<GpuImage>>() .get(&auto_exposure.metering_mask); let mask = mask .map(|i| &i.texture_view) .unwrap_or(&fallback.d2.texture_view); let Some(compensation_curve) = world .resource::<RenderAssets<GpuAutoExposureCompensationCurve>>() .get(&auto_exposure.compensation_curve) else { return Ok(()); }; let diagnostics = render_context.diagnostic_recorder(); let compute_bind_group = render_context.render_device().create_bind_group( None, &pipeline_cache.get_bind_group_layout(&pipeline.histogram_layout), &BindGroupEntries::sequential(( &globals_buffer.buffer, &auto_exposure_buffers.settings, source, mask, &compensation_curve.texture_view, &compensation_curve.extents, resources.histogram.as_entire_buffer_binding(), &auto_exposure_buffers.state, BufferBinding { buffer: view_uniforms_buffer, size: Some(ViewUniform::min_size()), offset: 0, }, )), ); let mut compute_pass = render_context .command_encoder() .begin_compute_pass(&ComputePassDescriptor { label: Some("auto_exposure"), timestamp_writes: None, }); let pass_span = diagnostics.pass_span(&mut compute_pass, "auto_exposure"); compute_pass.set_bind_group(0, &compute_bind_group, &[view_uniform_offset.offset]); compute_pass.set_pipeline(histogram_pipeline); compute_pass.dispatch_workgroups( view.viewport.z.div_ceil(16), view.viewport.w.div_ceil(16), 1, ); compute_pass.set_pipeline(average_pipeline); compute_pass.dispatch_workgroups(1, 1, 1); pass_span.end(&mut compute_pass); Ok(()) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/auto_exposure/compensation_curve.rs
crates/bevy_post_process/src/auto_exposure/compensation_curve.rs
use bevy_asset::{prelude::*, RenderAssetUsages}; use bevy_ecs::system::{lifetimeless::SRes, SystemParamItem}; use bevy_math::{cubic_splines::CubicGenerator, FloatExt, Vec2}; use bevy_reflect::prelude::*; use bevy_render::{ render_asset::RenderAsset, render_resource::{ Extent3d, ShaderType, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, TextureView, UniformBuffer, }, renderer::{RenderDevice, RenderQueue}, }; use thiserror::Error; const LUT_SIZE: usize = 256; /// An auto exposure compensation curve. /// This curve is used to map the average log luminance of a scene to an /// exposure compensation value, to allow for fine control over the final exposure. #[derive(Asset, Reflect, Debug, Clone)] #[reflect(Default, Clone)] pub struct AutoExposureCompensationCurve { /// The minimum log luminance value in the curve. (the x-axis) min_log_lum: f32, /// The maximum log luminance value in the curve. (the x-axis) max_log_lum: f32, /// The minimum exposure compensation value in the curve. (the y-axis) min_compensation: f32, /// The maximum exposure compensation value in the curve. (the y-axis) max_compensation: f32, /// The lookup table for the curve. Uploaded to the GPU as a 1D texture. /// Each value in the LUT is a `u8` representing a normalized exposure compensation value: /// * `0` maps to `min_compensation` /// * `255` maps to `max_compensation` /// /// The position in the LUT corresponds to the normalized log luminance value. /// * `0` maps to `min_log_lum` /// * `LUT_SIZE - 1` maps to `max_log_lum` lut: [u8; LUT_SIZE], } /// Various errors that can occur when constructing an [`AutoExposureCompensationCurve`]. #[derive(Error, Debug)] pub enum AutoExposureCompensationCurveError { /// The curve couldn't be built in the first place. #[error("curve could not be constructed from the given data")] InvalidCurve, /// A discontinuity was found in the curve. #[error("discontinuity found between curve segments")] DiscontinuityFound, /// The curve is not monotonically increasing on the x-axis. #[error("curve is not monotonically increasing on the x-axis")] NotMonotonic, } impl Default for AutoExposureCompensationCurve { fn default() -> Self { Self { min_log_lum: 0.0, max_log_lum: 0.0, min_compensation: 0.0, max_compensation: 0.0, lut: [0; LUT_SIZE], } } } impl AutoExposureCompensationCurve { const SAMPLES_PER_SEGMENT: usize = 64; /// Build an [`AutoExposureCompensationCurve`] from a [`CubicGenerator<Vec2>`], where: /// - x represents the average log luminance of the scene in EV-100; /// - y represents the exposure compensation value in F-stops. /// /// # Errors /// /// If the curve is not monotonically increasing on the x-axis, /// returns [`AutoExposureCompensationCurveError::NotMonotonic`]. /// /// If a discontinuity is found between curve segments, /// returns [`AutoExposureCompensationCurveError::DiscontinuityFound`]. /// /// # Example /// /// ``` /// # use bevy_asset::prelude::*; /// # use bevy_math::vec2; /// # use bevy_math::cubic_splines::*; /// # use bevy_post_process::auto_exposure::AutoExposureCompensationCurve; /// # let mut compensation_curves = Assets::<AutoExposureCompensationCurve>::default(); /// let curve: Handle<AutoExposureCompensationCurve> = compensation_curves.add( /// AutoExposureCompensationCurve::from_curve(LinearSpline::new([ /// vec2(-4.0, -2.0), /// vec2(0.0, 0.0), /// vec2(2.0, 0.0), /// vec2(4.0, 2.0), /// ])) /// .unwrap() /// ); /// ``` pub fn from_curve<T>(curve: T) -> Result<Self, AutoExposureCompensationCurveError> where T: CubicGenerator<Vec2>, { let Ok(curve) = curve.to_curve() else { return Err(AutoExposureCompensationCurveError::InvalidCurve); }; let min_log_lum = curve.position(0.0).x; let max_log_lum = curve.position(curve.segments().len() as f32).x; let log_lum_range = max_log_lum - min_log_lum; let mut lut = [0.0; LUT_SIZE]; let mut previous = curve.position(0.0); let mut min_compensation = previous.y; let mut max_compensation = previous.y; for segment in curve { if segment.position(0.0) != previous { return Err(AutoExposureCompensationCurveError::DiscontinuityFound); } for i in 1..Self::SAMPLES_PER_SEGMENT { let current = segment.position(i as f32 / (Self::SAMPLES_PER_SEGMENT - 1) as f32); if current.x < previous.x { return Err(AutoExposureCompensationCurveError::NotMonotonic); } // Find the range of LUT entries that this line segment covers. let (lut_begin, lut_end) = ( ((previous.x - min_log_lum) / log_lum_range) * (LUT_SIZE - 1) as f32, ((current.x - min_log_lum) / log_lum_range) * (LUT_SIZE - 1) as f32, ); let lut_inv_range = 1.0 / (lut_end - lut_begin); // Iterate over all LUT entries whose pixel centers fall within the current segment. #[expect( clippy::needless_range_loop, reason = "This for-loop also uses `i` to calculate a value `t`." )] for i in lut_begin.ceil() as usize..=lut_end.floor() as usize { let t = (i as f32 - lut_begin) * lut_inv_range; lut[i] = previous.y.lerp(current.y, t); min_compensation = min_compensation.min(lut[i]); max_compensation = max_compensation.max(lut[i]); } previous = current; } } let compensation_range = max_compensation - min_compensation; Ok(Self { min_log_lum, max_log_lum, min_compensation, max_compensation, lut: if compensation_range > 0.0 { let scale = 255.0 / compensation_range; lut.map(|f: f32| ((f - min_compensation) * scale) as u8) } else { [0; LUT_SIZE] }, }) } } /// The GPU-representation of an [`AutoExposureCompensationCurve`]. /// Consists of a [`TextureView`] with the curve's data, /// and a [`UniformBuffer`] with the curve's extents. pub struct GpuAutoExposureCompensationCurve { pub(super) texture_view: TextureView, pub(super) extents: UniformBuffer<AutoExposureCompensationCurveUniform>, } #[derive(ShaderType, Clone, Copy)] pub(super) struct AutoExposureCompensationCurveUniform { min_log_lum: f32, inv_log_lum_range: f32, min_compensation: f32, compensation_range: f32, } impl RenderAsset for GpuAutoExposureCompensationCurve { type SourceAsset = AutoExposureCompensationCurve; type Param = (SRes<RenderDevice>, SRes<RenderQueue>); fn asset_usage(_: &Self::SourceAsset) -> RenderAssetUsages { RenderAssetUsages::RENDER_WORLD } fn prepare_asset( source: Self::SourceAsset, _: AssetId<Self::SourceAsset>, (render_device, render_queue): &mut SystemParamItem<Self::Param>, _: Option<&Self>, ) -> Result<Self, bevy_render::render_asset::PrepareAssetError<Self::SourceAsset>> { let texture = render_device.create_texture_with_data( render_queue, &TextureDescriptor { label: None, size: Extent3d { width: LUT_SIZE as u32, height: 1, depth_or_array_layers: 1, }, mip_level_count: 1, sample_count: 1, dimension: TextureDimension::D1, format: TextureFormat::R8Unorm, usage: TextureUsages::COPY_DST | TextureUsages::TEXTURE_BINDING, view_formats: &[TextureFormat::R8Unorm], }, Default::default(), &source.lut, ); let texture_view = texture.create_view(&Default::default()); let mut extents = UniformBuffer::from(AutoExposureCompensationCurveUniform { min_log_lum: source.min_log_lum, inv_log_lum_range: 1.0 / (source.max_log_lum - source.min_log_lum), min_compensation: source.min_compensation, compensation_range: source.max_compensation - source.min_compensation, }); extents.write_buffer(render_device, render_queue); Ok(GpuAutoExposureCompensationCurve { texture_view, extents, }) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/auto_exposure/mod.rs
crates/bevy_post_process/src/auto_exposure/mod.rs
use bevy_app::prelude::*; use bevy_asset::{embedded_asset, AssetApp, Assets, Handle}; use bevy_ecs::prelude::*; use bevy_render::{ extract_component::ExtractComponentPlugin, render_asset::RenderAssetPlugin, render_graph::RenderGraphExt, render_resource::{ Buffer, BufferDescriptor, BufferUsages, PipelineCache, SpecializedComputePipelines, }, renderer::RenderDevice, ExtractSchedule, Render, RenderApp, RenderStartup, RenderSystems, }; mod buffers; mod compensation_curve; mod node; mod pipeline; mod settings; use buffers::{extract_buffers, prepare_buffers, AutoExposureBuffers}; pub use compensation_curve::{AutoExposureCompensationCurve, AutoExposureCompensationCurveError}; use node::AutoExposureNode; use pipeline::{AutoExposurePass, AutoExposurePipeline, ViewAutoExposurePipeline}; pub use settings::AutoExposure; use crate::auto_exposure::{ compensation_curve::GpuAutoExposureCompensationCurve, pipeline::init_auto_exposure_pipeline, }; use bevy_core_pipeline::core_3d::graph::{Core3d, Node3d}; /// Plugin for the auto exposure feature. /// /// See [`AutoExposure`] for more details. pub struct AutoExposurePlugin; #[derive(Resource)] struct AutoExposureResources { histogram: Buffer, } impl Plugin for AutoExposurePlugin { fn build(&self, app: &mut App) { embedded_asset!(app, "auto_exposure.wgsl"); app.add_plugins(RenderAssetPlugin::<GpuAutoExposureCompensationCurve>::default()) .init_asset::<AutoExposureCompensationCurve>() .register_asset_reflect::<AutoExposureCompensationCurve>(); app.world_mut() .resource_mut::<Assets<AutoExposureCompensationCurve>>() .insert(&Handle::default(), AutoExposureCompensationCurve::default()) .unwrap(); app.add_plugins(ExtractComponentPlugin::<AutoExposure>::default()); let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return; }; render_app .init_resource::<SpecializedComputePipelines<AutoExposurePipeline>>() .init_resource::<AutoExposureBuffers>() .add_systems( RenderStartup, (init_auto_exposure_pipeline, init_auto_exposure_resources), ) .add_systems(ExtractSchedule, extract_buffers) .add_systems( Render, ( prepare_buffers.in_set(RenderSystems::Prepare), queue_view_auto_exposure_pipelines.in_set(RenderSystems::Queue), ), ) .add_render_graph_node::<AutoExposureNode>(Core3d, node::AutoExposure) .add_render_graph_edges( Core3d, ( Node3d::StartMainPassPostProcessing, node::AutoExposure, Node3d::Tonemapping, ), ); } } pub fn init_auto_exposure_resources(mut commands: Commands, render_device: Res<RenderDevice>) { commands.insert_resource(AutoExposureResources { histogram: render_device.create_buffer(&BufferDescriptor { label: Some("histogram buffer"), size: pipeline::HISTOGRAM_BIN_COUNT * 4, usage: BufferUsages::STORAGE, mapped_at_creation: false, }), }); } fn queue_view_auto_exposure_pipelines( mut commands: Commands, pipeline_cache: Res<PipelineCache>, mut compute_pipelines: ResMut<SpecializedComputePipelines<AutoExposurePipeline>>, pipeline: Res<AutoExposurePipeline>, view_targets: Query<(Entity, &AutoExposure)>, ) { for (entity, auto_exposure) in view_targets.iter() { let histogram_pipeline = compute_pipelines.specialize(&pipeline_cache, &pipeline, AutoExposurePass::Histogram); let average_pipeline = compute_pipelines.specialize(&pipeline_cache, &pipeline, AutoExposurePass::Average); commands.entity(entity).insert(ViewAutoExposurePipeline { histogram_pipeline, mean_luminance_pipeline: average_pipeline, compensation_curve: auto_exposure.compensation_curve.clone(), metering_mask: auto_exposure.metering_mask.clone(), }); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/auto_exposure/pipeline.rs
crates/bevy_post_process/src/auto_exposure/pipeline.rs
use super::compensation_curve::{ AutoExposureCompensationCurve, AutoExposureCompensationCurveUniform, }; use bevy_asset::{load_embedded_asset, prelude::*}; use bevy_ecs::prelude::*; use bevy_image::Image; use bevy_render::{ globals::GlobalsUniform, render_resource::{binding_types::*, *}, view::ViewUniform, }; use bevy_shader::Shader; use bevy_utils::default; use core::num::NonZero; #[derive(Resource)] pub struct AutoExposurePipeline { pub histogram_layout: BindGroupLayoutDescriptor, pub histogram_shader: Handle<Shader>, } #[derive(Component)] pub struct ViewAutoExposurePipeline { pub histogram_pipeline: CachedComputePipelineId, pub mean_luminance_pipeline: CachedComputePipelineId, pub compensation_curve: Handle<AutoExposureCompensationCurve>, pub metering_mask: Handle<Image>, } #[derive(ShaderType, Clone, Copy)] pub struct AutoExposureUniform { pub(super) min_log_lum: f32, pub(super) inv_log_lum_range: f32, pub(super) log_lum_range: f32, pub(super) low_percent: f32, pub(super) high_percent: f32, pub(super) speed_up: f32, pub(super) speed_down: f32, pub(super) exponential_transition_distance: f32, } #[derive(PartialEq, Eq, Hash, Clone)] pub enum AutoExposurePass { Histogram, Average, } pub const HISTOGRAM_BIN_COUNT: u64 = 64; pub fn init_auto_exposure_pipeline(mut commands: Commands, asset_server: Res<AssetServer>) { commands.insert_resource(AutoExposurePipeline { histogram_layout: BindGroupLayoutDescriptor::new( "compute histogram bind group", &BindGroupLayoutEntries::sequential( ShaderStages::COMPUTE, ( uniform_buffer::<GlobalsUniform>(false), uniform_buffer::<AutoExposureUniform>(false), texture_2d(TextureSampleType::Float { filterable: false }), texture_2d(TextureSampleType::Float { filterable: false }), texture_1d(TextureSampleType::Float { filterable: false }), uniform_buffer::<AutoExposureCompensationCurveUniform>(false), storage_buffer_sized(false, NonZero::<u64>::new(HISTOGRAM_BIN_COUNT * 4)), storage_buffer_sized(false, NonZero::<u64>::new(4)), storage_buffer::<ViewUniform>(true), ), ), ), histogram_shader: load_embedded_asset!(asset_server.as_ref(), "auto_exposure.wgsl"), }); } impl SpecializedComputePipeline for AutoExposurePipeline { type Key = AutoExposurePass; fn specialize(&self, pass: AutoExposurePass) -> ComputePipelineDescriptor { ComputePipelineDescriptor { label: Some("luminance compute pipeline".into()), layout: vec![self.histogram_layout.clone()], shader: self.histogram_shader.clone(), shader_defs: vec![], entry_point: Some(match pass { AutoExposurePass::Histogram => "compute_histogram".into(), AutoExposurePass::Average => "compute_average".into(), }), ..default() } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/effect_stack/mod.rs
crates/bevy_post_process/src/effect_stack/mod.rs
//! Miscellaneous built-in postprocessing effects. //! //! Currently, this consists only of chromatic aberration. use bevy_app::{App, Plugin}; use bevy_asset::{ embedded_asset, load_embedded_asset, AssetServer, Assets, Handle, RenderAssetUsages, }; use bevy_camera::Camera; use bevy_derive::{Deref, DerefMut}; use bevy_ecs::{ component::Component, entity::Entity, query::{QueryItem, With}, reflect::ReflectComponent, resource::Resource, schedule::IntoScheduleConfigs as _, system::{lifetimeless::Read, Commands, Query, Res, ResMut}, world::World, }; use bevy_image::{BevyDefault, Image}; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{ diagnostic::RecordDiagnostics, extract_component::{ExtractComponent, ExtractComponentPlugin}, render_asset::RenderAssets, render_graph::{ NodeRunError, RenderGraphContext, RenderGraphExt as _, ViewNode, ViewNodeRunner, }, render_resource::{ binding_types::{sampler, texture_2d, uniform_buffer}, BindGroupEntries, BindGroupLayoutDescriptor, BindGroupLayoutEntries, CachedRenderPipelineId, ColorTargetState, ColorWrites, DynamicUniformBuffer, Extent3d, FilterMode, FragmentState, Operations, PipelineCache, RenderPassColorAttachment, RenderPassDescriptor, RenderPipelineDescriptor, Sampler, SamplerBindingType, SamplerDescriptor, ShaderStages, ShaderType, SpecializedRenderPipeline, SpecializedRenderPipelines, TextureDimension, TextureFormat, TextureSampleType, }, renderer::{RenderContext, RenderDevice, RenderQueue}, texture::GpuImage, view::{ExtractedView, ViewTarget}, Render, RenderApp, RenderStartup, RenderSystems, }; use bevy_shader::{load_shader_library, Shader}; use bevy_utils::prelude::default; use bevy_core_pipeline::{ core_2d::graph::{Core2d, Node2d}, core_3d::graph::{Core3d, Node3d}, FullscreenShader, }; /// The default chromatic aberration intensity amount, in a fraction of the /// window size. const DEFAULT_CHROMATIC_ABERRATION_INTENSITY: f32 = 0.02; /// The default maximum number of samples for chromatic aberration. const DEFAULT_CHROMATIC_ABERRATION_MAX_SAMPLES: u32 = 8; /// The raw RGBA data for the default chromatic aberration gradient. /// /// This consists of one red pixel, one green pixel, and one blue pixel, in that /// order. static DEFAULT_CHROMATIC_ABERRATION_LUT_DATA: [u8; 12] = [255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255]; #[derive(Resource)] struct DefaultChromaticAberrationLut(Handle<Image>); /// A plugin that implements a built-in postprocessing stack with some common /// effects. /// /// Currently, this only consists of chromatic aberration. #[derive(Default)] pub struct EffectStackPlugin; /// Adds colored fringes to the edges of objects in the scene. /// /// [Chromatic aberration] simulates the effect when lenses fail to focus all /// colors of light toward a single point. It causes rainbow-colored streaks to /// appear, which are especially apparent on the edges of objects. Chromatic /// aberration is commonly used for collision effects, especially in horror /// games. /// /// Bevy's implementation is based on that of *Inside* ([Gjøl & Svendsen 2016]). /// It's based on a customizable lookup texture, which allows for changing the /// color pattern. By default, the color pattern is simply a 3×1 pixel texture /// consisting of red, green, and blue, in that order, but you can change it to /// any image in order to achieve different effects. /// /// [Chromatic aberration]: https://en.wikipedia.org/wiki/Chromatic_aberration /// /// [Gjøl & Svendsen 2016]: https://github.com/playdeadgames/publications/blob/master/INSIDE/rendering_inside_gdc2016.pdf #[derive(Reflect, Component, Clone)] #[reflect(Component, Default, Clone)] pub struct ChromaticAberration { /// The lookup texture that determines the color gradient. /// /// By default (if None), this is a 3×1 texel texture consisting of one red /// pixel, one green pixel, and one blue texel, in that order. This /// recreates the most typical chromatic aberration pattern. However, you /// can change it to achieve different artistic effects. /// /// The texture is always sampled in its vertical center, so it should /// ordinarily have a height of 1 texel. pub color_lut: Option<Handle<Image>>, /// The size of the streaks around the edges of objects, as a fraction of /// the window size. /// /// The default value is 0.02. pub intensity: f32, /// A cap on the number of texture samples that will be performed. /// /// Higher values result in smoother-looking streaks but are slower. /// /// The default value is 8. pub max_samples: u32, } /// GPU pipeline data for the built-in postprocessing stack. /// /// This is stored in the render world. #[derive(Resource)] pub struct PostProcessingPipeline { /// The layout of bind group 0, containing the source, LUT, and settings. bind_group_layout: BindGroupLayoutDescriptor, /// Specifies how to sample the source framebuffer texture. source_sampler: Sampler, /// Specifies how to sample the chromatic aberration gradient. chromatic_aberration_lut_sampler: Sampler, /// The asset handle for the fullscreen vertex shader. fullscreen_shader: FullscreenShader, /// The fragment shader asset handle. fragment_shader: Handle<Shader>, } /// A key that uniquely identifies a built-in postprocessing pipeline. #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct PostProcessingPipelineKey { /// The format of the source and destination textures. texture_format: TextureFormat, } /// A component attached to cameras in the render world that stores the /// specialized pipeline ID for the built-in postprocessing stack. #[derive(Component, Deref, DerefMut)] pub struct PostProcessingPipelineId(CachedRenderPipelineId); /// The on-GPU version of the [`ChromaticAberration`] settings. /// /// See the documentation for [`ChromaticAberration`] for more information on /// each of these fields. #[derive(ShaderType)] pub struct ChromaticAberrationUniform { /// The intensity of the effect, in a fraction of the screen. intensity: f32, /// A cap on the number of samples of the source texture that the shader /// will perform. max_samples: u32, /// Padding data. unused_1: u32, /// Padding data. unused_2: u32, } /// A resource, part of the render world, that stores the /// [`ChromaticAberrationUniform`]s for each view. #[derive(Resource, Deref, DerefMut, Default)] pub struct PostProcessingUniformBuffers { chromatic_aberration: DynamicUniformBuffer<ChromaticAberrationUniform>, } /// A component, part of the render world, that stores the appropriate byte /// offset within the [`PostProcessingUniformBuffers`] for the camera it's /// attached to. #[derive(Component, Deref, DerefMut)] pub struct PostProcessingUniformBufferOffsets { chromatic_aberration: u32, } /// The render node that runs the built-in postprocessing stack. #[derive(Default)] pub struct PostProcessingNode; impl Plugin for EffectStackPlugin { fn build(&self, app: &mut App) { load_shader_library!(app, "chromatic_aberration.wgsl"); embedded_asset!(app, "post_process.wgsl"); // Load the default chromatic aberration LUT. let mut assets = app.world_mut().resource_mut::<Assets<_>>(); let default_lut = assets.add(Image::new( Extent3d { width: 3, height: 1, depth_or_array_layers: 1, }, TextureDimension::D2, DEFAULT_CHROMATIC_ABERRATION_LUT_DATA.to_vec(), TextureFormat::Rgba8UnormSrgb, RenderAssetUsages::RENDER_WORLD, )); app.add_plugins(ExtractComponentPlugin::<ChromaticAberration>::default()); let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return; }; render_app .insert_resource(DefaultChromaticAberrationLut(default_lut)) .init_resource::<SpecializedRenderPipelines<PostProcessingPipeline>>() .init_resource::<PostProcessingUniformBuffers>() .add_systems(RenderStartup, init_post_processing_pipeline) .add_systems( Render, ( prepare_post_processing_pipelines, prepare_post_processing_uniforms, ) .in_set(RenderSystems::Prepare), ) .add_render_graph_node::<ViewNodeRunner<PostProcessingNode>>( Core3d, Node3d::PostProcessing, ) .add_render_graph_edges( Core3d, ( Node3d::DepthOfField, Node3d::PostProcessing, Node3d::Tonemapping, ), ) .add_render_graph_node::<ViewNodeRunner<PostProcessingNode>>( Core2d, Node2d::PostProcessing, ) .add_render_graph_edges( Core2d, (Node2d::Bloom, Node2d::PostProcessing, Node2d::Tonemapping), ); } } impl Default for ChromaticAberration { fn default() -> Self { Self { color_lut: None, intensity: DEFAULT_CHROMATIC_ABERRATION_INTENSITY, max_samples: DEFAULT_CHROMATIC_ABERRATION_MAX_SAMPLES, } } } pub fn init_post_processing_pipeline( mut commands: Commands, render_device: Res<RenderDevice>, fullscreen_shader: Res<FullscreenShader>, asset_server: Res<AssetServer>, ) { // Create our single bind group layout. let bind_group_layout = BindGroupLayoutDescriptor::new( "postprocessing bind group layout", &BindGroupLayoutEntries::sequential( ShaderStages::FRAGMENT, ( // Chromatic aberration source: texture_2d(TextureSampleType::Float { filterable: true }), // Chromatic aberration source sampler: sampler(SamplerBindingType::Filtering), // Chromatic aberration LUT: texture_2d(TextureSampleType::Float { filterable: true }), // Chromatic aberration LUT sampler: sampler(SamplerBindingType::Filtering), // Chromatic aberration settings: uniform_buffer::<ChromaticAberrationUniform>(true), ), ), ); // Both source and chromatic aberration LUTs should be sampled // bilinearly. let source_sampler = render_device.create_sampler(&SamplerDescriptor { mipmap_filter: FilterMode::Linear, min_filter: FilterMode::Linear, mag_filter: FilterMode::Linear, ..default() }); let chromatic_aberration_lut_sampler = render_device.create_sampler(&SamplerDescriptor { mipmap_filter: FilterMode::Linear, min_filter: FilterMode::Linear, mag_filter: FilterMode::Linear, ..default() }); commands.insert_resource(PostProcessingPipeline { bind_group_layout, source_sampler, chromatic_aberration_lut_sampler, fullscreen_shader: fullscreen_shader.clone(), fragment_shader: load_embedded_asset!(asset_server.as_ref(), "post_process.wgsl"), }); } impl SpecializedRenderPipeline for PostProcessingPipeline { type Key = PostProcessingPipelineKey; fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor { RenderPipelineDescriptor { label: Some("postprocessing".into()), layout: vec![self.bind_group_layout.clone()], vertex: self.fullscreen_shader.to_vertex_state(), fragment: Some(FragmentState { shader: self.fragment_shader.clone(), targets: vec![Some(ColorTargetState { format: key.texture_format, blend: None, write_mask: ColorWrites::ALL, })], ..default() }), ..default() } } } impl ViewNode for PostProcessingNode { type ViewQuery = ( Read<ViewTarget>, Read<PostProcessingPipelineId>, Read<ChromaticAberration>, Read<PostProcessingUniformBufferOffsets>, ); fn run<'w>( &self, _: &mut RenderGraphContext, render_context: &mut RenderContext<'w>, (view_target, pipeline_id, chromatic_aberration, post_processing_uniform_buffer_offsets): QueryItem<'w, '_, Self::ViewQuery>, world: &'w World, ) -> Result<(), NodeRunError> { let pipeline_cache = world.resource::<PipelineCache>(); let post_processing_pipeline = world.resource::<PostProcessingPipeline>(); let post_processing_uniform_buffers = world.resource::<PostProcessingUniformBuffers>(); let gpu_image_assets = world.resource::<RenderAssets<GpuImage>>(); let default_lut = world.resource::<DefaultChromaticAberrationLut>(); // We need a render pipeline to be prepared. let Some(pipeline) = pipeline_cache.get_render_pipeline(**pipeline_id) else { return Ok(()); }; // We need the chromatic aberration LUT to be present. let Some(chromatic_aberration_lut) = gpu_image_assets.get( chromatic_aberration .color_lut .as_ref() .unwrap_or(&default_lut.0), ) else { return Ok(()); }; // We need the postprocessing settings to be uploaded to the GPU. let Some(chromatic_aberration_uniform_buffer_binding) = post_processing_uniform_buffers .chromatic_aberration .binding() else { return Ok(()); }; let diagnostics = render_context.diagnostic_recorder(); // Use the [`PostProcessWrite`] infrastructure, since this is a // full-screen pass. let post_process = view_target.post_process_write(); let pass_descriptor = RenderPassDescriptor { label: Some("postprocessing"), color_attachments: &[Some(RenderPassColorAttachment { view: post_process.destination, depth_slice: None, resolve_target: None, ops: Operations::default(), })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, }; let bind_group = render_context.render_device().create_bind_group( Some("postprocessing bind group"), &pipeline_cache.get_bind_group_layout(&post_processing_pipeline.bind_group_layout), &BindGroupEntries::sequential(( post_process.source, &post_processing_pipeline.source_sampler, &chromatic_aberration_lut.texture_view, &post_processing_pipeline.chromatic_aberration_lut_sampler, chromatic_aberration_uniform_buffer_binding, )), ); let mut render_pass = render_context .command_encoder() .begin_render_pass(&pass_descriptor); let pass_span = diagnostics.pass_span(&mut render_pass, "postprocessing"); render_pass.set_pipeline(pipeline); render_pass.set_bind_group(0, &bind_group, &[**post_processing_uniform_buffer_offsets]); render_pass.draw(0..3, 0..1); pass_span.end(&mut render_pass); Ok(()) } } /// Specializes the built-in postprocessing pipeline for each applicable view. pub fn prepare_post_processing_pipelines( mut commands: Commands, pipeline_cache: Res<PipelineCache>, mut pipelines: ResMut<SpecializedRenderPipelines<PostProcessingPipeline>>, post_processing_pipeline: Res<PostProcessingPipeline>, views: Query<(Entity, &ExtractedView), With<ChromaticAberration>>, ) { for (entity, view) in views.iter() { let pipeline_id = pipelines.specialize( &pipeline_cache, &post_processing_pipeline, PostProcessingPipelineKey { texture_format: if view.hdr { ViewTarget::TEXTURE_FORMAT_HDR } else { TextureFormat::bevy_default() }, }, ); commands .entity(entity) .insert(PostProcessingPipelineId(pipeline_id)); } } /// Gathers the built-in postprocessing settings for every view and uploads them /// to the GPU. pub fn prepare_post_processing_uniforms( mut commands: Commands, mut post_processing_uniform_buffers: ResMut<PostProcessingUniformBuffers>, render_device: Res<RenderDevice>, render_queue: Res<RenderQueue>, mut views: Query<(Entity, &ChromaticAberration)>, ) { post_processing_uniform_buffers.clear(); // Gather up all the postprocessing settings. for (view_entity, chromatic_aberration) in views.iter_mut() { let chromatic_aberration_uniform_buffer_offset = post_processing_uniform_buffers.push(&ChromaticAberrationUniform { intensity: chromatic_aberration.intensity, max_samples: chromatic_aberration.max_samples, unused_1: 0, unused_2: 0, }); commands .entity(view_entity) .insert(PostProcessingUniformBufferOffsets { chromatic_aberration: chromatic_aberration_uniform_buffer_offset, }); } // Upload to the GPU. post_processing_uniform_buffers.write_buffer(&render_device, &render_queue); } impl ExtractComponent for ChromaticAberration { type QueryData = Read<ChromaticAberration>; type QueryFilter = With<Camera>; type Out = ChromaticAberration; fn extract_component( chromatic_aberration: QueryItem<'_, '_, Self::QueryData>, ) -> Option<Self::Out> { // Skip the postprocessing phase entirely if the intensity is zero. if chromatic_aberration.intensity > 0.0 { Some(chromatic_aberration.clone()) } else { None } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_post_process/src/dof/mod.rs
crates/bevy_post_process/src/dof/mod.rs
//! Depth of field, a postprocessing effect that simulates camera focus. //! //! By default, Bevy renders all objects in full focus: regardless of depth, all //! objects are rendered perfectly sharp (up to output resolution). Real lenses, //! however, can only focus on objects at a specific distance. The distance //! between the nearest and furthest objects that are in focus is known as //! [depth of field], and this term is used more generally in computer graphics //! to refer to the effect that simulates focus of lenses. //! //! Attaching [`DepthOfField`] to a camera causes Bevy to simulate the //! focus of a camera lens. Generally, Bevy's implementation of depth of field //! is optimized for speed instead of physical accuracy. Nevertheless, the depth //! of field effect in Bevy is based on physical parameters. //! //! [Depth of field]: https://en.wikipedia.org/wiki/Depth_of_field use bevy_app::{App, Plugin}; use bevy_asset::{embedded_asset, load_embedded_asset, AssetServer, Handle}; use bevy_camera::{Camera3d, PhysicalCameraParameters, Projection}; use bevy_derive::{Deref, DerefMut}; use bevy_ecs::{ component::Component, entity::Entity, query::{QueryItem, With}, reflect::ReflectComponent, resource::Resource, schedule::IntoScheduleConfigs as _, system::{lifetimeless::Read, Commands, Query, Res, ResMut}, world::World, }; use bevy_image::BevyDefault as _; use bevy_math::ops; use bevy_reflect::{prelude::ReflectDefault, Reflect}; use bevy_render::{ diagnostic::RecordDiagnostics, extract_component::{ComponentUniforms, DynamicUniformIndex, UniformComponentPlugin}, render_graph::{ NodeRunError, RenderGraphContext, RenderGraphExt as _, ViewNode, ViewNodeRunner, }, render_resource::{ binding_types::{ sampler, texture_2d, texture_depth_2d, texture_depth_2d_multisampled, uniform_buffer, }, BindGroup, BindGroupEntries, BindGroupLayoutDescriptor, BindGroupLayoutEntries, CachedRenderPipelineId, ColorTargetState, ColorWrites, FilterMode, FragmentState, LoadOp, Operations, PipelineCache, RenderPassColorAttachment, RenderPassDescriptor, RenderPipelineDescriptor, Sampler, SamplerBindingType, SamplerDescriptor, ShaderStages, ShaderType, SpecializedRenderPipeline, SpecializedRenderPipelines, StoreOp, TextureDescriptor, TextureDimension, TextureFormat, TextureSampleType, TextureUsages, }, renderer::{RenderContext, RenderDevice}, sync_component::SyncComponentPlugin, sync_world::RenderEntity, texture::{CachedTexture, TextureCache}, view::{ prepare_view_targets, ExtractedView, Msaa, ViewDepthTexture, ViewTarget, ViewUniform, ViewUniformOffset, ViewUniforms, }, Extract, ExtractSchedule, Render, RenderApp, RenderStartup, RenderSystems, }; use bevy_shader::Shader; use bevy_utils::{default, once}; use smallvec::SmallVec; use tracing::{info, warn}; use bevy_core_pipeline::{ core_3d::{ graph::{Core3d, Node3d}, DEPTH_TEXTURE_SAMPLING_SUPPORTED, }, FullscreenShader, }; /// A plugin that adds support for the depth of field effect to Bevy. #[derive(Default)] pub struct DepthOfFieldPlugin; /// A component that enables a [depth of field] postprocessing effect when attached to a [`Camera3d`], /// simulating the focus of a camera lens. /// /// [depth of field]: https://en.wikipedia.org/wiki/Depth_of_field #[derive(Component, Clone, Copy, Reflect)] #[reflect(Component, Clone, Default)] pub struct DepthOfField { /// The appearance of the effect. pub mode: DepthOfFieldMode, /// The distance in meters to the location in focus. pub focal_distance: f32, /// The height of the [image sensor format] in meters. /// /// Focal length is derived from the FOV and this value. The default is /// 18.66mm, matching the [Super 35] format, which is popular in cinema. /// /// [image sensor format]: https://en.wikipedia.org/wiki/Image_sensor_format /// /// [Super 35]: https://en.wikipedia.org/wiki/Super_35 pub sensor_height: f32, /// Along with the focal length, controls how much objects not in focus are /// blurred. pub aperture_f_stops: f32, /// The maximum diameter, in pixels, that we allow a circle of confusion to be. /// /// A circle of confusion essentially describes the size of a blur. /// /// This value is nonphysical but is useful for avoiding pathologically-slow /// behavior. pub max_circle_of_confusion_diameter: f32, /// Objects are never considered to be farther away than this distance as /// far as depth of field is concerned, even if they actually are. /// /// This is primarily useful for skyboxes and background colors. The Bevy /// renderer considers them to be infinitely far away. Without this value, /// that would cause the circle of confusion to be infinitely large, capped /// only by the `max_circle_of_confusion_diameter`. As that's unsightly, /// this value can be used to essentially adjust how "far away" the skybox /// or background are. pub max_depth: f32, } /// Controls the appearance of the effect. #[derive(Clone, Copy, Default, PartialEq, Debug, Reflect)] #[reflect(Default, Clone, PartialEq)] pub enum DepthOfFieldMode { /// A more accurate simulation, in which circles of confusion generate /// "spots" of light. /// /// For more information, see [Wikipedia's article on *bokeh*]. /// /// This doesn't work on WebGPU. /// /// [Wikipedia's article on *bokeh*]: https://en.wikipedia.org/wiki/Bokeh Bokeh, /// A faster simulation, in which out-of-focus areas are simply blurred. /// /// This is less accurate to actual lens behavior and is generally less /// aesthetically pleasing but requires less video memory bandwidth. /// /// This is the default. /// /// This works on native and WebGPU. /// If targeting native platforms, consider using [`DepthOfFieldMode::Bokeh`] instead. #[default] Gaussian, } /// Data about the depth of field effect that's uploaded to the GPU. #[derive(Clone, Copy, Component, ShaderType)] pub struct DepthOfFieldUniform { /// The distance in meters to the location in focus. focal_distance: f32, /// The focal length. See the comment in `DepthOfFieldParams` in `dof.wgsl` /// for more information. focal_length: f32, /// The premultiplied factor that we scale the circle of confusion by. /// /// This is calculated as `focal_length² / (sensor_height * /// aperture_f_stops)`. coc_scale_factor: f32, /// The maximum circle of confusion diameter in pixels. See the comment in /// [`DepthOfField`] for more information. max_circle_of_confusion_diameter: f32, /// The depth value that we clamp distant objects to. See the comment in /// [`DepthOfField`] for more information. max_depth: f32, /// Padding. pad_a: u32, /// Padding. pad_b: u32, /// Padding. pad_c: u32, } /// A key that uniquely identifies depth of field pipelines. #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct DepthOfFieldPipelineKey { /// Whether we're doing Gaussian or bokeh blur. pass: DofPass, /// Whether we're using HDR. hdr: bool, /// Whether the render target is multisampled. multisample: bool, } /// Identifies a specific depth of field render pass. #[derive(Clone, Copy, PartialEq, Eq, Hash)] enum DofPass { /// The first, horizontal, Gaussian blur pass. GaussianHorizontal, /// The second, vertical, Gaussian blur pass. GaussianVertical, /// The first bokeh pass: vertical and diagonal. BokehPass0, /// The second bokeh pass: two diagonals. BokehPass1, } impl Plugin for DepthOfFieldPlugin { fn build(&self, app: &mut App) { embedded_asset!(app, "dof.wgsl"); app.add_plugins(UniformComponentPlugin::<DepthOfFieldUniform>::default()); app.add_plugins(SyncComponentPlugin::<DepthOfField>::default()); let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return; }; render_app .init_resource::<SpecializedRenderPipelines<DepthOfFieldPipeline>>() .init_resource::<DepthOfFieldGlobalBindGroup>() .add_systems(RenderStartup, init_dof_global_bind_group_layout) .add_systems(ExtractSchedule, extract_depth_of_field_settings) .add_systems( Render, ( configure_depth_of_field_view_targets, prepare_auxiliary_depth_of_field_textures, ) .after(prepare_view_targets) .in_set(RenderSystems::ManageViews), ) .add_systems( Render, ( prepare_depth_of_field_view_bind_group_layouts, prepare_depth_of_field_pipelines, ) .chain() .in_set(RenderSystems::Prepare), ) .add_systems( Render, prepare_depth_of_field_global_bind_group.in_set(RenderSystems::PrepareBindGroups), ) .add_render_graph_node::<ViewNodeRunner<DepthOfFieldNode>>(Core3d, Node3d::DepthOfField) .add_render_graph_edges( Core3d, (Node3d::Bloom, Node3d::DepthOfField, Node3d::Tonemapping), ); } } /// The node in the render graph for depth of field. #[derive(Default)] pub struct DepthOfFieldNode; /// The layout for the bind group shared among all invocations of the depth of /// field shader. #[derive(Resource, Clone)] pub struct DepthOfFieldGlobalBindGroupLayout { /// The layout. layout: BindGroupLayoutDescriptor, /// The sampler used to sample from the color buffer or buffers. color_texture_sampler: Sampler, } /// The bind group shared among all invocations of the depth of field shader, /// regardless of view. #[derive(Resource, Default, Deref, DerefMut)] pub struct DepthOfFieldGlobalBindGroup(Option<BindGroup>); #[derive(Component)] pub enum DepthOfFieldPipelines { Gaussian { horizontal: CachedRenderPipelineId, vertical: CachedRenderPipelineId, }, Bokeh { pass_0: CachedRenderPipelineId, pass_1: CachedRenderPipelineId, }, } struct DepthOfFieldPipelineRenderInfo { pass_label: &'static str, view_bind_group_label: &'static str, pipeline: CachedRenderPipelineId, is_dual_input: bool, is_dual_output: bool, } /// The extra texture used as the second render target for the hexagonal bokeh /// blur. /// /// This is the same size and format as the main view target texture. It'll only /// be present if bokeh is being used. #[derive(Component, Deref, DerefMut)] pub struct AuxiliaryDepthOfFieldTexture(CachedTexture); /// Bind group layouts for depth of field specific to a single view. #[derive(Component, Clone)] pub struct ViewDepthOfFieldBindGroupLayouts { /// The bind group layout for passes that take only one input. single_input: BindGroupLayoutDescriptor, /// The bind group layout for the second bokeh pass, which takes two inputs. /// /// This will only be present if bokeh is in use. dual_input: Option<BindGroupLayoutDescriptor>, } /// Information needed to specialize the pipeline corresponding to a pass of the /// depth of field shader. pub struct DepthOfFieldPipeline { /// The bind group layouts specific to each view. view_bind_group_layouts: ViewDepthOfFieldBindGroupLayouts, /// The bind group layout shared among all invocations of the depth of field /// shader. global_bind_group_layout: BindGroupLayoutDescriptor, /// The asset handle for the fullscreen vertex shader. fullscreen_shader: FullscreenShader, /// The fragment shader asset handle. fragment_shader: Handle<Shader>, } impl ViewNode for DepthOfFieldNode { type ViewQuery = ( Read<ViewUniformOffset>, Read<ViewTarget>, Read<ViewDepthTexture>, Read<DepthOfFieldPipelines>, Read<ViewDepthOfFieldBindGroupLayouts>, Read<DynamicUniformIndex<DepthOfFieldUniform>>, Option<Read<AuxiliaryDepthOfFieldTexture>>, ); fn run<'w>( &self, _: &mut RenderGraphContext, render_context: &mut RenderContext<'w>, ( view_uniform_offset, view_target, view_depth_texture, view_pipelines, view_bind_group_layouts, depth_of_field_uniform_index, auxiliary_dof_texture, ): QueryItem<'w, '_, Self::ViewQuery>, world: &'w World, ) -> Result<(), NodeRunError> { let pipeline_cache = world.resource::<PipelineCache>(); let view_uniforms = world.resource::<ViewUniforms>(); let global_bind_group = world.resource::<DepthOfFieldGlobalBindGroup>(); let diagnostics = render_context.diagnostic_recorder(); // We can be in either Gaussian blur or bokeh mode here. Both modes are // similar, consisting of two passes each. We factor out the information // specific to each pass into // [`DepthOfFieldPipelines::pipeline_render_info`]. for pipeline_render_info in view_pipelines.pipeline_render_info().iter() { let (Some(render_pipeline), Some(view_uniforms_binding), Some(global_bind_group)) = ( pipeline_cache.get_render_pipeline(pipeline_render_info.pipeline), view_uniforms.uniforms.binding(), &**global_bind_group, ) else { return Ok(()); }; // We use most of the postprocess infrastructure here. However, // because the bokeh pass has an additional render target, we have // to manage a secondary *auxiliary* texture alongside the textures // managed by the postprocessing logic. let postprocess = view_target.post_process_write(); let view_bind_group = if pipeline_render_info.is_dual_input { let (Some(auxiliary_dof_texture), Some(dual_input_bind_group_layout)) = ( auxiliary_dof_texture, view_bind_group_layouts.dual_input.as_ref(), ) else { once!(warn!( "Should have created the auxiliary depth of field texture by now" )); continue; }; render_context.render_device().create_bind_group( Some(pipeline_render_info.view_bind_group_label), &pipeline_cache.get_bind_group_layout(dual_input_bind_group_layout), &BindGroupEntries::sequential(( view_uniforms_binding, view_depth_texture.view(), postprocess.source, &auxiliary_dof_texture.default_view, )), ) } else { render_context.render_device().create_bind_group( Some(pipeline_render_info.view_bind_group_label), &pipeline_cache.get_bind_group_layout(&view_bind_group_layouts.single_input), &BindGroupEntries::sequential(( view_uniforms_binding, view_depth_texture.view(), postprocess.source, )), ) }; // Push the first input attachment. let mut color_attachments: SmallVec<[_; 2]> = SmallVec::new(); color_attachments.push(Some(RenderPassColorAttachment { view: postprocess.destination, depth_slice: None, resolve_target: None, ops: Operations { load: LoadOp::Clear(default()), store: StoreOp::Store, }, })); // The first pass of the bokeh shader has two color outputs, not // one. Handle this case by attaching the auxiliary texture, which // should have been created by now in // `prepare_auxiliary_depth_of_field_textures``. if pipeline_render_info.is_dual_output { let Some(auxiliary_dof_texture) = auxiliary_dof_texture else { once!(warn!( "Should have created the auxiliary depth of field texture by now" )); continue; }; color_attachments.push(Some(RenderPassColorAttachment { view: &auxiliary_dof_texture.default_view, depth_slice: None, resolve_target: None, ops: Operations { load: LoadOp::Clear(default()), store: StoreOp::Store, }, })); } let render_pass_descriptor = RenderPassDescriptor { label: Some(pipeline_render_info.pass_label), color_attachments: &color_attachments, ..default() }; let mut render_pass = render_context .command_encoder() .begin_render_pass(&render_pass_descriptor); let pass_span = diagnostics.pass_span(&mut render_pass, pipeline_render_info.pass_label); render_pass.set_pipeline(render_pipeline); // Set the per-view bind group. render_pass.set_bind_group(0, &view_bind_group, &[view_uniform_offset.offset]); // Set the global bind group shared among all invocations of the shader. render_pass.set_bind_group( 1, global_bind_group, &[depth_of_field_uniform_index.index()], ); // Render the full-screen pass. render_pass.draw(0..3, 0..1); pass_span.end(&mut render_pass); } Ok(()) } } impl Default for DepthOfField { fn default() -> Self { let physical_camera_default = PhysicalCameraParameters::default(); Self { focal_distance: 10.0, aperture_f_stops: physical_camera_default.aperture_f_stops, sensor_height: physical_camera_default.sensor_height, max_circle_of_confusion_diameter: 64.0, max_depth: f32::INFINITY, mode: DepthOfFieldMode::Bokeh, } } } impl DepthOfField { /// Initializes [`DepthOfField`] from a set of /// [`PhysicalCameraParameters`]. /// /// By passing the same [`PhysicalCameraParameters`] object to this function /// and to [`bevy_camera::Exposure::from_physical_camera`], matching /// results for both the exposure and depth of field effects can be /// obtained. /// /// All fields of the returned [`DepthOfField`] other than /// `focal_length` and `aperture_f_stops` are set to their default values. pub fn from_physical_camera(camera: &PhysicalCameraParameters) -> DepthOfField { DepthOfField { sensor_height: camera.sensor_height, aperture_f_stops: camera.aperture_f_stops, ..default() } } } pub fn init_dof_global_bind_group_layout(mut commands: Commands, render_device: Res<RenderDevice>) { // Create the bind group layout that will be shared among all instances // of the depth of field shader. let layout = BindGroupLayoutDescriptor::new( "depth of field global bind group layout", &BindGroupLayoutEntries::sequential( ShaderStages::FRAGMENT, ( // `dof_params` uniform_buffer::<DepthOfFieldUniform>(true), // `color_texture_sampler` sampler(SamplerBindingType::Filtering), ), ), ); // Create the color texture sampler. let sampler = render_device.create_sampler(&SamplerDescriptor { label: Some("depth of field sampler"), mag_filter: FilterMode::Linear, min_filter: FilterMode::Linear, ..default() }); commands.insert_resource(DepthOfFieldGlobalBindGroupLayout { color_texture_sampler: sampler, layout, }); } /// Creates the bind group layouts for the depth of field effect that are /// specific to each view. pub fn prepare_depth_of_field_view_bind_group_layouts( mut commands: Commands, view_targets: Query<(Entity, &DepthOfField, &Msaa)>, ) { for (view, depth_of_field, msaa) in view_targets.iter() { // Create the bind group layout for the passes that take one input. let single_input = BindGroupLayoutDescriptor::new( "depth of field bind group layout (single input)", &BindGroupLayoutEntries::sequential( ShaderStages::FRAGMENT, ( uniform_buffer::<ViewUniform>(true), if *msaa != Msaa::Off { texture_depth_2d_multisampled() } else { texture_depth_2d() }, texture_2d(TextureSampleType::Float { filterable: true }), ), ), ); // If needed, create the bind group layout for the second bokeh pass, // which takes two inputs. We only need to do this if bokeh is in use. let dual_input = match depth_of_field.mode { DepthOfFieldMode::Gaussian => None, DepthOfFieldMode::Bokeh => Some(BindGroupLayoutDescriptor::new( "depth of field bind group layout (dual input)", &BindGroupLayoutEntries::sequential( ShaderStages::FRAGMENT, ( uniform_buffer::<ViewUniform>(true), if *msaa != Msaa::Off { texture_depth_2d_multisampled() } else { texture_depth_2d() }, texture_2d(TextureSampleType::Float { filterable: true }), texture_2d(TextureSampleType::Float { filterable: true }), ), ), )), }; commands .entity(view) .insert(ViewDepthOfFieldBindGroupLayouts { single_input, dual_input, }); } } /// Configures depth textures so that the depth of field shader can read from /// them. /// /// By default, the depth buffers that Bevy creates aren't able to be bound as /// textures. The depth of field shader, however, needs to read from them. So we /// need to set the appropriate flag to tell Bevy to make samplable depth /// buffers. pub fn configure_depth_of_field_view_targets( mut view_targets: Query<&mut Camera3d, With<DepthOfField>>, ) { for mut camera_3d in view_targets.iter_mut() { let mut depth_texture_usages = TextureUsages::from(camera_3d.depth_texture_usages); depth_texture_usages |= TextureUsages::TEXTURE_BINDING; camera_3d.depth_texture_usages = depth_texture_usages.into(); } } /// Creates depth of field bind group 1, which is shared among all instances of /// the depth of field shader. pub fn prepare_depth_of_field_global_bind_group( global_bind_group_layout: Res<DepthOfFieldGlobalBindGroupLayout>, mut dof_bind_group: ResMut<DepthOfFieldGlobalBindGroup>, depth_of_field_uniforms: Res<ComponentUniforms<DepthOfFieldUniform>>, render_device: Res<RenderDevice>, pipeline_cache: Res<PipelineCache>, ) { let Some(depth_of_field_uniforms) = depth_of_field_uniforms.binding() else { return; }; **dof_bind_group = Some(render_device.create_bind_group( Some("depth of field global bind group"), &pipeline_cache.get_bind_group_layout(&global_bind_group_layout.layout), &BindGroupEntries::sequential(( depth_of_field_uniforms, // `dof_params` &global_bind_group_layout.color_texture_sampler, // `color_texture_sampler` )), )); } /// Creates the second render target texture that the first pass of the bokeh /// effect needs. pub fn prepare_auxiliary_depth_of_field_textures( mut commands: Commands, render_device: Res<RenderDevice>, mut texture_cache: ResMut<TextureCache>, mut view_targets: Query<(Entity, &ViewTarget, &DepthOfField)>, ) { for (entity, view_target, depth_of_field) in view_targets.iter_mut() { // An auxiliary texture is only needed for bokeh. if depth_of_field.mode != DepthOfFieldMode::Bokeh { continue; } // The texture matches the main view target texture. let texture_descriptor = TextureDescriptor { label: Some("depth of field auxiliary texture"), size: view_target.main_texture().size(), mip_level_count: 1, sample_count: view_target.main_texture().sample_count(), dimension: TextureDimension::D2, format: view_target.main_texture_format(), usage: TextureUsages::RENDER_ATTACHMENT | TextureUsages::TEXTURE_BINDING, view_formats: &[], }; let texture = texture_cache.get(&render_device, texture_descriptor); commands .entity(entity) .insert(AuxiliaryDepthOfFieldTexture(texture)); } } /// Specializes the depth of field pipelines specific to a view. pub fn prepare_depth_of_field_pipelines( mut commands: Commands, pipeline_cache: Res<PipelineCache>, mut pipelines: ResMut<SpecializedRenderPipelines<DepthOfFieldPipeline>>, global_bind_group_layout: Res<DepthOfFieldGlobalBindGroupLayout>, view_targets: Query<( Entity, &ExtractedView, &DepthOfField, &ViewDepthOfFieldBindGroupLayouts, &Msaa, )>, fullscreen_shader: Res<FullscreenShader>, asset_server: Res<AssetServer>, ) { for (entity, view, depth_of_field, view_bind_group_layouts, msaa) in view_targets.iter() { let dof_pipeline = DepthOfFieldPipeline { view_bind_group_layouts: view_bind_group_layouts.clone(), global_bind_group_layout: global_bind_group_layout.layout.clone(), fullscreen_shader: fullscreen_shader.clone(), fragment_shader: load_embedded_asset!(asset_server.as_ref(), "dof.wgsl"), }; // We'll need these two flags to create the `DepthOfFieldPipelineKey`s. let (hdr, multisample) = (view.hdr, *msaa != Msaa::Off); // Go ahead and specialize the pipelines. match depth_of_field.mode { DepthOfFieldMode::Gaussian => { commands .entity(entity) .insert(DepthOfFieldPipelines::Gaussian { horizontal: pipelines.specialize( &pipeline_cache, &dof_pipeline, DepthOfFieldPipelineKey { hdr, multisample, pass: DofPass::GaussianHorizontal, }, ), vertical: pipelines.specialize( &pipeline_cache, &dof_pipeline, DepthOfFieldPipelineKey { hdr, multisample, pass: DofPass::GaussianVertical, }, ), }); } DepthOfFieldMode::Bokeh => { commands .entity(entity) .insert(DepthOfFieldPipelines::Bokeh { pass_0: pipelines.specialize( &pipeline_cache, &dof_pipeline, DepthOfFieldPipelineKey { hdr, multisample, pass: DofPass::BokehPass0, }, ), pass_1: pipelines.specialize( &pipeline_cache, &dof_pipeline, DepthOfFieldPipelineKey { hdr, multisample, pass: DofPass::BokehPass1, }, ), }); } } } } impl SpecializedRenderPipeline for DepthOfFieldPipeline { type Key = DepthOfFieldPipelineKey; fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor { // Build up our pipeline layout. let (mut layout, mut shader_defs) = (vec![], vec![]); let mut targets = vec![Some(ColorTargetState { format: if key.hdr { ViewTarget::TEXTURE_FORMAT_HDR } else { TextureFormat::bevy_default() }, blend: None, write_mask: ColorWrites::ALL, })]; // Select bind group 0, the view-specific bind group. match key.pass { DofPass::GaussianHorizontal | DofPass::GaussianVertical => { // Gaussian blurs take only a single input and output. layout.push(self.view_bind_group_layouts.single_input.clone()); } DofPass::BokehPass0 => { // The first bokeh pass takes one input and produces two outputs. layout.push(self.view_bind_group_layouts.single_input.clone()); targets.push(targets[0].clone()); } DofPass::BokehPass1 => { // The second bokeh pass takes the two outputs from the first // bokeh pass and produces a single output. let dual_input_bind_group_layout = self .view_bind_group_layouts .dual_input .as_ref() .expect("Dual-input depth of field bind group should have been created by now") .clone(); layout.push(dual_input_bind_group_layout); shader_defs.push("DUAL_INPUT".into()); } } // Add bind group 1, the global bind group. layout.push(self.global_bind_group_layout.clone()); if key.multisample { shader_defs.push("MULTISAMPLED".into()); } RenderPipelineDescriptor { label: Some("depth of field pipeline".into()), layout, vertex: self.fullscreen_shader.to_vertex_state(), fragment: Some(FragmentState { shader: self.fragment_shader.clone(), shader_defs, entry_point: Some(match key.pass { DofPass::GaussianHorizontal => "gaussian_horizontal".into(), DofPass::GaussianVertical => "gaussian_vertical".into(), DofPass::BokehPass0 => "bokeh_pass_0".into(), DofPass::BokehPass1 => "bokeh_pass_1".into(), }), targets, }), ..default() } } } /// Extracts all [`DepthOfField`] components into the render world. fn extract_depth_of_field_settings( mut commands: Commands, mut query: Extract<Query<(RenderEntity, &DepthOfField, &Projection)>>, ) { if !DEPTH_TEXTURE_SAMPLING_SUPPORTED { once!(info!( "Disabling depth of field on this platform because depth textures aren't supported correctly" )); return; } for (entity, depth_of_field, projection) in query.iter_mut() { let mut entity_commands = commands .get_entity(entity) .expect("Depth of field entity wasn't synced."); // Depth of field is nonsensical without a perspective projection. let Projection::Perspective(ref perspective_projection) = *projection else { // TODO: needs better strategy for cleaning up entity_commands.remove::<( DepthOfField, DepthOfFieldUniform,
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/focus.rs
crates/bevy_ui/src/focus.rs
use crate::{ ui_transform::UiGlobalTransform, ComputedNode, ComputedUiTargetCamera, Node, OverrideClip, UiStack, }; use bevy_camera::{visibility::InheritedVisibility, Camera, NormalizedRenderTarget, RenderTarget}; use bevy_ecs::{ change_detection::DetectChangesMut, entity::{ContainsEntity, Entity}, hierarchy::ChildOf, prelude::{Component, With}, query::{QueryData, Without}, reflect::ReflectComponent, system::{Local, Query, Res}, }; use bevy_input::{mouse::MouseButton, touch::Touches, ButtonInput}; use bevy_math::Vec2; use bevy_platform::collections::HashMap; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_window::{PrimaryWindow, Window}; use smallvec::SmallVec; #[cfg(feature = "serialize")] use bevy_reflect::{ReflectDeserialize, ReflectSerialize}; /// Describes what type of input interaction has occurred for a UI node. /// /// This is commonly queried with a `Changed<Interaction>` filter. /// /// Updated in [`ui_focus_system`]. /// /// If a UI node has both [`Interaction`] and [`InheritedVisibility`] components, /// [`Interaction`] will always be [`Interaction::None`] /// when [`InheritedVisibility::get()`] is false. /// This ensures that hidden UI nodes are not interactable, /// and do not end up stuck in an active state if hidden at the wrong time. /// /// Note that you can also control the visibility of a node using the [`Display`](crate::ui_node::Display) property, /// which fully collapses it during layout calculations. /// /// # See also /// /// - [`Button`](crate::widget::Button) which requires this component /// - [`RelativeCursorPosition`] to obtain the position of the cursor relative to current node #[derive(Component, Copy, Clone, Eq, PartialEq, Debug, Reflect)] #[reflect(Component, Default, PartialEq, Debug, Clone)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] pub enum Interaction { /// The node has been pressed. /// /// Note: This does not capture click/press-release action. Pressed, /// The node has been hovered over Hovered, /// Nothing has happened None, } impl Interaction { const DEFAULT: Self = Self::None; } impl Default for Interaction { fn default() -> Self { Self::DEFAULT } } /// A component storing the position of the mouse relative to the node, (0., 0.) being the center and (0.5, 0.5) being the bottom-right /// If the mouse is not over the node, the value will go beyond the range of (-0.5, -0.5) to (0.5, 0.5) /// /// It can be used alongside [`Interaction`] to get the position of the press. /// /// The component is updated when it is in the same entity with [`Node`]. #[derive(Component, Copy, Clone, Default, PartialEq, Debug, Reflect)] #[reflect(Component, Default, PartialEq, Debug, Clone)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] pub struct RelativeCursorPosition { /// True if the cursor position is over an unclipped area of the Node. pub cursor_over: bool, /// Cursor position relative to the size and position of the Node. /// A None value indicates that the cursor position is unknown. pub normalized: Option<Vec2>, } impl RelativeCursorPosition { /// A helper function to check if the mouse is over the node pub fn cursor_over(&self) -> bool { self.cursor_over } } /// Describes whether the node should block interactions with lower nodes #[derive(Component, Copy, Clone, Eq, PartialEq, Debug, Reflect)] #[reflect(Component, Default, PartialEq, Debug, Clone)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] pub enum FocusPolicy { /// Blocks interaction Block, /// Lets interaction pass through Pass, } impl FocusPolicy { const DEFAULT: Self = Self::Pass; } impl Default for FocusPolicy { fn default() -> Self { Self::DEFAULT } } /// Contains entities whose Interaction should be set to None #[derive(Default)] pub struct State { entities_to_reset: SmallVec<[Entity; 1]>, } /// Main query for [`ui_focus_system`] #[derive(QueryData)] #[query_data(mutable)] pub struct NodeQuery { entity: Entity, node: &'static ComputedNode, transform: &'static UiGlobalTransform, interaction: Option<&'static mut Interaction>, relative_cursor_position: Option<&'static mut RelativeCursorPosition>, focus_policy: Option<&'static FocusPolicy>, inherited_visibility: Option<&'static InheritedVisibility>, target_camera: &'static ComputedUiTargetCamera, } /// The system that sets Interaction for all UI elements based on the mouse cursor activity /// /// Entities with a hidden [`InheritedVisibility`] are always treated as released. pub fn ui_focus_system( mut hovered_nodes: Local<Vec<Entity>>, mut state: Local<State>, camera_query: Query<(Entity, &Camera, &RenderTarget)>, primary_window: Query<Entity, With<PrimaryWindow>>, windows: Query<&Window>, mouse_button_input: Res<ButtonInput<MouseButton>>, touches_input: Res<Touches>, ui_stack: Res<UiStack>, mut node_query: Query<NodeQuery>, clipping_query: Query<(&ComputedNode, &UiGlobalTransform, &Node)>, child_of_query: Query<&ChildOf, Without<OverrideClip>>, ) { let primary_window = primary_window.iter().next(); // reset entities that were both clicked and released in the last frame for entity in state.entities_to_reset.drain(..) { if let Ok(NodeQueryItem { interaction: Some(mut interaction), .. }) = node_query.get_mut(entity) { *interaction = Interaction::None; } } let mouse_released = mouse_button_input.just_released(MouseButton::Left) || touches_input.any_just_released(); if mouse_released { for node in &mut node_query { if let Some(mut interaction) = node.interaction && *interaction == Interaction::Pressed { *interaction = Interaction::None; } } } let mouse_clicked = mouse_button_input.just_pressed(MouseButton::Left) || touches_input.any_just_pressed(); let camera_cursor_positions: HashMap<Entity, Vec2> = camera_query .iter() .filter_map(|(entity, camera, render_target)| { // Interactions are only supported for cameras rendering to a window. let Some(NormalizedRenderTarget::Window(window_ref)) = render_target.normalize(primary_window) else { return None; }; let window = windows.get(window_ref.entity()).ok()?; let viewport_position = camera .physical_viewport_rect() .map(|rect| rect.min.as_vec2()) .unwrap_or_default(); window .physical_cursor_position() .or_else(|| { touches_input .first_pressed_position() .map(|pos| pos * window.scale_factor()) }) .map(|cursor_position| (entity, cursor_position - viewport_position)) }) .collect(); // prepare an iterator that contains all the nodes that have the cursor in their rect, // from the top node to the bottom one. this will also reset the interaction to `None` // for all nodes encountered that are no longer hovered. hovered_nodes.clear(); // reverse the iterator to traverse the tree from closest slice to furthest for uinodes in ui_stack .partition .iter() .rev() .map(|range| &ui_stack.uinodes[range.clone()]) { // Retrieve the first node and resolve its camera target. // Only need to do this once per slice, as all the nodes in the slice share the same camera. let Ok(root_node) = node_query.get_mut(uinodes[0]) else { continue; }; let Some(camera_entity) = root_node.target_camera.get() else { continue; }; let cursor_position = camera_cursor_positions.get(&camera_entity); for entity in uinodes.iter().rev().cloned() { let Ok(node) = node_query.get_mut(entity) else { continue; }; let Some(inherited_visibility) = node.inherited_visibility else { continue; }; // Nodes that are not rendered should not be interactable if !inherited_visibility.get() { // Reset their interaction to None to avoid strange stuck state if let Some(mut interaction) = node.interaction { // We cannot simply set the interaction to None, as that will trigger change detection repeatedly interaction.set_if_neq(Interaction::None); } continue; } let contains_cursor = cursor_position.is_some_and(|point| { node.node.contains_point(*node.transform, *point) && clip_check_recursive(*point, entity, &clipping_query, &child_of_query) }); // The mouse position relative to the node // (-0.5, -0.5) is the top-left corner, (0.5, 0.5) is the bottom-right corner // Coordinates are relative to the entire node, not just the visible region. let normalized_cursor_position = cursor_position.and_then(|cursor_position| { // ensure node size is non-zero in all dimensions, otherwise relative position will be // +/-inf. if the node is hidden, the visible rect min/max will also be -inf leading to // false positives for mouse_over (#12395) node.node.normalize_point(*node.transform, *cursor_position) }); // If the current cursor position is within the bounds of the node's visible area, consider it for // clicking let relative_cursor_position_component = RelativeCursorPosition { cursor_over: contains_cursor, normalized: normalized_cursor_position, }; // Save the relative cursor position to the correct component if let Some(mut node_relative_cursor_position_component) = node.relative_cursor_position { // Avoid triggering change detection when not necessary. node_relative_cursor_position_component .set_if_neq(relative_cursor_position_component); } if contains_cursor { hovered_nodes.push(entity); } else { if let Some(mut interaction) = node.interaction && (*interaction == Interaction::Hovered || (normalized_cursor_position.is_none())) { interaction.set_if_neq(Interaction::None); } continue; } } } // set Pressed or Hovered on top nodes. as soon as a node with a `Block` focus policy is detected, // the iteration will stop on it because it "captures" the interaction. let mut hovered_nodes = hovered_nodes.iter(); let mut iter = node_query.iter_many_mut(hovered_nodes.by_ref()); while let Some(node) = iter.fetch_next() { if let Some(mut interaction) = node.interaction { if mouse_clicked { // only consider nodes with Interaction "pressed" if *interaction != Interaction::Pressed { *interaction = Interaction::Pressed; // if the mouse was simultaneously released, reset this Interaction in the next // frame if mouse_released { state.entities_to_reset.push(node.entity); } } } else if *interaction == Interaction::None { *interaction = Interaction::Hovered; } } match node.focus_policy.unwrap_or(&FocusPolicy::Block) { FocusPolicy::Block => { break; } FocusPolicy::Pass => { /* allow the next node to be hovered/pressed */ } } } // reset `Interaction` for the remaining lower nodes to `None`. those are the nodes that remain in // `moused_over_nodes` after the previous loop is exited. let mut iter = node_query.iter_many_mut(hovered_nodes); while let Some(node) = iter.fetch_next() { if let Some(mut interaction) = node.interaction { // don't reset pressed nodes because they're handled separately if *interaction != Interaction::Pressed { interaction.set_if_neq(Interaction::None); } } } } /// Walk up the tree child-to-parent checking that `point` is not clipped by any ancestor node. /// If `entity` has an [`OverrideClip`] component it ignores any inherited clipping and returns true. pub fn clip_check_recursive( point: Vec2, entity: Entity, clipping_query: &Query<'_, '_, (&ComputedNode, &UiGlobalTransform, &Node)>, child_of_query: &Query<&ChildOf, Without<OverrideClip>>, ) -> bool { if let Ok(child_of) = child_of_query.get(entity) { let parent = child_of.0; if let Ok((computed_node, transform, node)) = clipping_query.get(parent) && !computed_node .resolve_clip_rect(node.overflow, node.overflow_clip_margin) .contains(transform.inverse().transform_point2(point)) { // The point is clipped and should be ignored by picking return false; } return clip_check_recursive(point, parent, clipping_query, child_of_query); } // Reached root, point unclipped by all ancestors true }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/ui_transform.rs
crates/bevy_ui/src/ui_transform.rs
use crate::Val; use bevy_derive::Deref; use bevy_ecs::component::Component; use bevy_ecs::prelude::ReflectComponent; use bevy_math::Affine2; use bevy_math::Mat2; use bevy_math::Rot2; use bevy_math::Vec2; use bevy_reflect::prelude::*; use core::ops::Mul; /// A pair of [`Val`]s used to represent a 2-dimensional size or offset. #[derive(Debug, PartialEq, Clone, Copy, Reflect)] #[reflect(Default, PartialEq, Debug, Clone)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] pub struct Val2 { /// Translate the node along the x-axis. /// `Val::Percent` values are resolved based on the computed width of the Ui Node. /// `Val::Auto` is resolved to `0.`. pub x: Val, /// Translate the node along the y-axis. /// `Val::Percent` values are resolved based on the computed height of the UI Node. /// `Val::Auto` is resolved to `0.`. pub y: Val, } impl Val2 { pub const ZERO: Self = Self { x: Val::ZERO, y: Val::ZERO, }; /// Creates a new [`Val2`] where both components are in logical pixels pub const fn px(x: f32, y: f32) -> Self { Self { x: Val::Px(x), y: Val::Px(y), } } /// Creates a new [`Val2`] where both components are percentage values pub const fn percent(x: f32, y: f32) -> Self { Self { x: Val::Percent(x), y: Val::Percent(y), } } /// Creates a new [`Val2`] pub const fn new(x: Val, y: Val) -> Self { Self { x, y } } /// Resolves this [`Val2`] from the given `scale_factor`, `parent_size`, /// and `viewport_size`. /// /// Component values of [`Val::Auto`] are resolved to 0. pub fn resolve(&self, scale_factor: f32, base_size: Vec2, viewport_size: Vec2) -> Vec2 { Vec2::new( self.x .resolve(scale_factor, base_size.x, viewport_size) .unwrap_or(0.), self.y .resolve(scale_factor, base_size.y, viewport_size) .unwrap_or(0.), ) } } impl Default for Val2 { fn default() -> Self { Self::ZERO } } /// Relative 2D transform for UI nodes /// /// [`UiGlobalTransform`] is automatically inserted whenever [`UiTransform`] is inserted. #[derive(Component, Debug, PartialEq, Clone, Copy, Reflect)] #[reflect(Component, Default, PartialEq, Debug, Clone)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] #[require(UiGlobalTransform)] pub struct UiTransform { /// Translate the node. pub translation: Val2, /// Scale the node. A negative value reflects the node in that axis. pub scale: Vec2, /// Rotate the node clockwise. pub rotation: Rot2, } impl UiTransform { pub const IDENTITY: Self = Self { translation: Val2::ZERO, scale: Vec2::ONE, rotation: Rot2::IDENTITY, }; /// Creates a UI transform representing a rotation. pub const fn from_rotation(rotation: Rot2) -> Self { Self { rotation, ..Self::IDENTITY } } /// Creates a UI transform representing a responsive translation. pub const fn from_translation(translation: Val2) -> Self { Self { translation, ..Self::IDENTITY } } /// Creates a UI transform representing a scaling. pub const fn from_scale(scale: Vec2) -> Self { Self { scale, ..Self::IDENTITY } } /// Resolves the translation from the given `scale_factor`, `base_value`, and `target_size` /// and returns a 2d affine transform from the resolved translation, and the `UiTransform`'s rotation, and scale. pub fn compute_affine(&self, scale_factor: f32, base_size: Vec2, target_size: Vec2) -> Affine2 { Affine2::from_mat2_translation( Mat2::from(self.rotation) * Mat2::from_diagonal(self.scale), self.translation .resolve(scale_factor, base_size, target_size), ) } } impl Default for UiTransform { fn default() -> Self { Self::IDENTITY } } /// Absolute 2D transform for UI nodes /// /// [`UiGlobalTransform`]s are updated from [`UiTransform`] and [`Node`](crate::ui_node::Node) /// in [`ui_layout_system`](crate::layout::ui_layout_system) #[derive(Component, Debug, PartialEq, Clone, Copy, Reflect, Deref)] #[reflect(Component, Default, PartialEq, Debug, Clone)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] pub struct UiGlobalTransform(Affine2); impl Default for UiGlobalTransform { fn default() -> Self { Self(Affine2::IDENTITY) } } impl UiGlobalTransform { /// If the transform is invertible returns its inverse. /// Otherwise returns `None`. #[inline] pub fn try_inverse(&self) -> Option<Affine2> { (self.matrix2.determinant() != 0.).then_some(self.inverse()) } /// Creates a `UiGlobalTransform` from the given 2D translation. #[inline] pub fn from_translation(translation: Vec2) -> Self { Self(Affine2::from_translation(translation)) } /// Creates a `UiGlobalTransform` from the given 2D translation. #[inline] pub fn from_xy(x: f32, y: f32) -> Self { Self::from_translation(Vec2::new(x, y)) } /// Creates a `UiGlobalTransform` from the given rotation. #[inline] pub fn from_rotation(rotation: Rot2) -> Self { Self(Affine2::from_mat2(rotation.into())) } /// Creates a `UiGlobalTransform` from the given scaling. #[inline] pub fn from_scale(scale: Vec2) -> Self { Self(Affine2::from_scale(scale)) } /// Extracts scale, angle and translation from self. /// The transform is expected to be non-degenerate and without shearing, or the output will be invalid. #[inline] pub fn to_scale_angle_translation(&self) -> (Vec2, f32, Vec2) { self.0.to_scale_angle_translation() } /// Returns the transform as an [`Affine2`] #[inline] pub fn affine(&self) -> Affine2 { self.0 } } impl From<Affine2> for UiGlobalTransform { fn from(value: Affine2) -> Self { Self(value) } } impl From<UiGlobalTransform> for Affine2 { fn from(value: UiGlobalTransform) -> Self { value.0 } } impl From<&UiGlobalTransform> for Affine2 { fn from(value: &UiGlobalTransform) -> Self { value.0 } } impl Mul for UiGlobalTransform { type Output = Self; #[inline] fn mul(self, value: Self) -> Self::Output { Self(self.0 * value.0) } } impl Mul<Affine2> for UiGlobalTransform { type Output = Affine2; #[inline] fn mul(self, affine2: Affine2) -> Self::Output { self.0 * affine2 } } impl Mul<UiGlobalTransform> for Affine2 { type Output = Affine2; #[inline] fn mul(self, transform: UiGlobalTransform) -> Self::Output { self * transform.0 } } impl Mul<Vec2> for UiGlobalTransform { type Output = Vec2; #[inline] fn mul(self, value: Vec2) -> Vec2 { self.transform_point2(value) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/lib.rs
crates/bevy_ui/src/lib.rs
#![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")] #![cfg_attr(docsrs, feature(doc_cfg))] #![doc( html_logo_url = "https://bevy.org/assets/icon.png", html_favicon_url = "https://bevy.org/assets/icon.png" )] //! This crate contains Bevy's UI system, which can be used to create UI for both 2D and 3D games //! # Basic usage //! Spawn UI elements with [`widget::Button`], [`ImageNode`](widget::ImageNode), [`Text`](prelude::Text) and [`Node`] //! This UI is laid out with the Flexbox and CSS Grid layout models (see <https://cssreference.io/flexbox/>) pub mod interaction_states; pub mod measurement; pub mod update; pub mod widget; pub mod gradients; #[cfg(feature = "bevy_picking")] pub mod picking_backend; pub mod ui_transform; use bevy_derive::{Deref, DerefMut}; #[cfg(feature = "bevy_picking")] use bevy_picking::PickingSystems; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; mod accessibility; // This module is not re-exported, but is instead made public. // This is intended to discourage accidental use of the experimental API. pub mod experimental; mod focus; mod geometry; mod layout; mod stack; mod ui_node; pub use focus::*; pub use geometry::*; pub use gradients::*; pub use interaction_states::{Checkable, Checked, InteractionDisabled, Pressed}; pub use layout::*; pub use measurement::*; pub use ui_node::*; pub use ui_transform::*; /// The UI prelude. /// /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { #[doc(hidden)] #[cfg(feature = "bevy_picking")] pub use crate::picking_backend::{UiPickingCamera, UiPickingPlugin, UiPickingSettings}; #[doc(hidden)] pub use crate::widget::{Text, TextShadow, TextUiReader, TextUiWriter}; #[doc(hidden)] pub use { crate::{ geometry::*, gradients::*, ui_node::*, ui_transform::*, widget::{Button, ImageNode, Label, NodeImageMode, ViewportNode}, Interaction, UiScale, }, // `bevy_sprite` re-exports for texture slicing bevy_sprite::{BorderRect, SliceScaleMode, SpriteImageMode, TextureSlicer}, bevy_text::TextBackgroundColor, }; } use bevy_app::{prelude::*, AnimationSystems, HierarchyPropagatePlugin, PropagateSet}; use bevy_camera::CameraUpdateSystems; use bevy_ecs::prelude::*; use bevy_input::InputSystems; use bevy_transform::TransformSystems; use layout::ui_surface::UiSurface; use stack::ui_stack_system; pub use stack::UiStack; use update::{propagate_ui_target_cameras, update_clipping_system}; /// The basic plugin for Bevy UI #[derive(Default)] pub struct UiPlugin; /// The label enum labeling the types of systems in the Bevy UI #[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)] pub enum UiSystems { /// After this label, input interactions with UI entities have been updated for this frame. /// /// Runs in [`PreUpdate`]. Focus, /// All UI systems in [`PostUpdate`] will run in or after this label. Prepare, /// Propagate UI component values needed by layout. Propagate, /// Update content requirements before layout. Content, /// After this label, the ui layout state has been updated. /// /// Runs in [`PostUpdate`]. Layout, /// UI systems ordered after [`UiSystems::Layout`]. /// /// Runs in [`PostUpdate`]. PostLayout, /// After this label, the [`UiStack`] resource has been updated. /// /// Runs in [`PostUpdate`]. Stack, } /// The current scale of the UI. /// /// A multiplier to fixed-sized ui values. /// **Note:** This will only affect fixed ui values like [`Val::Px`] #[derive(Debug, Reflect, Resource, Deref, DerefMut)] #[reflect(Resource, Debug, Default)] pub struct UiScale(pub f32); impl Default for UiScale { fn default() -> Self { Self(1.0) } } // Marks systems that can be ambiguous with [`widget::text_system`] if the `bevy_text` feature is enabled. // See https://github.com/bevyengine/bevy/pull/11391 for more details. #[derive(SystemSet, Debug, Hash, PartialEq, Eq, Clone)] struct AmbiguousWithText; #[derive(SystemSet, Debug, Hash, PartialEq, Eq, Clone)] struct AmbiguousWithUpdateText2dLayout; impl Plugin for UiPlugin { fn build(&self, app: &mut App) { app.init_resource::<UiSurface>() .init_resource::<UiScale>() .init_resource::<UiStack>() .configure_sets( PostUpdate, ( CameraUpdateSystems, UiSystems::Prepare.after(AnimationSystems), UiSystems::Propagate, UiSystems::Content, UiSystems::Layout, UiSystems::PostLayout, ) .chain(), ) .configure_sets( PostUpdate, PropagateSet::<ComputedUiTargetCamera>::default().in_set(UiSystems::Propagate), ) .add_plugins(HierarchyPropagatePlugin::<ComputedUiTargetCamera>::new( PostUpdate, )) .configure_sets( PostUpdate, PropagateSet::<ComputedUiRenderTargetInfo>::default().in_set(UiSystems::Propagate), ) .add_plugins(HierarchyPropagatePlugin::<ComputedUiRenderTargetInfo>::new( PostUpdate, )) .add_systems( PreUpdate, ui_focus_system.in_set(UiSystems::Focus).after(InputSystems), ); #[cfg(feature = "bevy_picking")] app.add_plugins(picking_backend::UiPickingPlugin) .add_systems( First, widget::viewport_picking.in_set(PickingSystems::PostInput), ); let ui_layout_system_config = ui_layout_system .in_set(UiSystems::Layout) .before(TransformSystems::Propagate); let ui_layout_system_config = ui_layout_system_config // Text and Text2D operate on disjoint sets of entities .ambiguous_with(bevy_sprite::update_text2d_layout) .ambiguous_with(bevy_text::detect_text_needs_rerender::<bevy_sprite::Text2d>); app.add_systems( PostUpdate, ( propagate_ui_target_cameras.in_set(UiSystems::Prepare), ui_layout_system_config, ui_stack_system .in_set(UiSystems::Stack) // These systems don't care about stack index .ambiguous_with(widget::measure_text_system) .ambiguous_with(update_clipping_system) .ambiguous_with(ui_layout_system) .ambiguous_with(widget::update_viewport_render_target_size) .in_set(AmbiguousWithText), update_clipping_system.after(TransformSystems::Propagate), // Potential conflicts: `Assets<Image>` // They run independently since `widget::image_node_system` will only ever observe // its own ImageNode, and `widget::text_system` & `bevy_text::update_text2d_layout` // will never modify a pre-existing `Image` asset. widget::update_image_content_size_system .in_set(UiSystems::Content) .in_set(AmbiguousWithText) .in_set(AmbiguousWithUpdateText2dLayout), // Potential conflicts: `Assets<Image>` // `widget::text_system` and `bevy_text::update_text2d_layout` run independently // since this system will only ever update viewport images. widget::update_viewport_render_target_size .in_set(UiSystems::PostLayout) .in_set(AmbiguousWithText) .in_set(AmbiguousWithUpdateText2dLayout), ), ); build_text_interop(app); } } fn build_text_interop(app: &mut App) { use widget::Text; app.add_systems( PostUpdate, ( ( bevy_text::detect_text_needs_rerender::<Text>, widget::measure_text_system, ) .chain() .after(bevy_text::load_font_assets_into_fontdb_system) .in_set(UiSystems::Content) // Text and Text2d are independent. .ambiguous_with(bevy_text::detect_text_needs_rerender::<bevy_sprite::Text2d>) // Potential conflict: `Assets<Image>` // Since both systems will only ever insert new [`Image`] assets, // they will never observe each other's effects. .ambiguous_with(bevy_sprite::update_text2d_layout) // We assume Text is on disjoint UI entities to ImageNode and UiTextureAtlasImage // FIXME: Add an archetype invariant for this https://github.com/bevyengine/bevy/issues/1481. .ambiguous_with(widget::update_image_content_size_system), widget::text_system .in_set(UiSystems::PostLayout) .after(bevy_text::load_font_assets_into_fontdb_system) .after(bevy_asset::AssetEventSystems) // Text2d and bevy_ui text are entirely on separate entities .ambiguous_with(bevy_text::detect_text_needs_rerender::<bevy_sprite::Text2d>) .ambiguous_with(bevy_sprite::update_text2d_layout) .ambiguous_with(bevy_sprite::calculate_bounds_text2d), ), ); app.add_plugins(accessibility::AccessibilityPlugin); app.add_observer(interaction_states::on_add_disabled) .add_observer(interaction_states::on_remove_disabled) .add_observer(interaction_states::on_add_checkable) .add_observer(interaction_states::on_remove_checkable) .add_observer(interaction_states::on_add_checked) .add_observer(interaction_states::on_remove_checked); app.configure_sets( PostUpdate, AmbiguousWithText.ambiguous_with(widget::text_system), ); app.configure_sets( PostUpdate, AmbiguousWithUpdateText2dLayout.ambiguous_with(bevy_sprite::update_text2d_layout), ); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/update.rs
crates/bevy_ui/src/update.rs
//! This module contains systems that update the UI when something changes use crate::{ experimental::{UiChildren, UiRootNodes}, ui_transform::UiGlobalTransform, CalculatedClip, ComputedUiRenderTargetInfo, ComputedUiTargetCamera, DefaultUiCamera, Display, Node, OverflowAxis, OverrideClip, UiScale, UiTargetCamera, }; use super::ComputedNode; use bevy_app::Propagate; use bevy_camera::Camera; use bevy_ecs::{ entity::Entity, query::Has, system::{Commands, Query, Res}, }; use bevy_math::{Rect, UVec2}; use bevy_sprite::BorderRect; /// Updates clipping for all nodes pub fn update_clipping_system( mut commands: Commands, root_nodes: UiRootNodes, mut node_query: Query<( &Node, &ComputedNode, &UiGlobalTransform, Option<&mut CalculatedClip>, Has<OverrideClip>, )>, ui_children: UiChildren, ) { for root_node in root_nodes.iter() { update_clipping( &mut commands, &ui_children, &mut node_query, root_node, None, ); } } fn update_clipping( commands: &mut Commands, ui_children: &UiChildren, node_query: &mut Query<( &Node, &ComputedNode, &UiGlobalTransform, Option<&mut CalculatedClip>, Has<OverrideClip>, )>, entity: Entity, mut maybe_inherited_clip: Option<Rect>, ) { let Ok((node, computed_node, transform, maybe_calculated_clip, has_override_clip)) = node_query.get_mut(entity) else { return; }; // If the UI node entity has an `OverrideClip` component, discard any inherited clip rect if has_override_clip { maybe_inherited_clip = None; } // If `display` is None, clip the entire node and all its descendants by replacing the inherited clip with a default rect (which is empty) if node.display == Display::None { maybe_inherited_clip = Some(Rect::default()); } // Update this node's CalculatedClip component if let Some(mut calculated_clip) = maybe_calculated_clip { if let Some(inherited_clip) = maybe_inherited_clip { // Replace the previous calculated clip with the inherited clipping rect if calculated_clip.clip != inherited_clip { *calculated_clip = CalculatedClip { clip: inherited_clip, }; } } else { // No inherited clipping rect, remove the component commands.entity(entity).remove::<CalculatedClip>(); } } else if let Some(inherited_clip) = maybe_inherited_clip { // No previous calculated clip, add a new CalculatedClip component with the inherited clipping rect commands.entity(entity).try_insert(CalculatedClip { clip: inherited_clip, }); } // Calculate new clip rectangle for children nodes let children_clip = if node.overflow.is_visible() { // The current node doesn't clip, propagate the optional inherited clipping rect to any children maybe_inherited_clip } else { // Find the current node's clipping rect and intersect it with the inherited clipping rect, if one exists let mut clip_rect = Rect::from_center_size(transform.translation, computed_node.size()); // Content isn't clipped at the edges of the node but at the edges of the region specified by [`Node::overflow_clip_margin`]. // // `clip_inset` should always fit inside `node_rect`. // Even if `clip_inset` were to overflow, we won't return a degenerate result as `Rect::intersect` will clamp the intersection, leaving it empty. let clip_inset = match node.overflow_clip_margin.visual_box { crate::OverflowClipBox::BorderBox => BorderRect::ZERO, crate::OverflowClipBox::ContentBox => computed_node.content_inset(), crate::OverflowClipBox::PaddingBox => computed_node.border(), }; clip_rect.min += clip_inset.min_inset; clip_rect.max -= clip_inset.max_inset; clip_rect = clip_rect .inflate(node.overflow_clip_margin.margin.max(0.) / computed_node.inverse_scale_factor); if node.overflow.x == OverflowAxis::Visible { clip_rect.min.x = -f32::INFINITY; clip_rect.max.x = f32::INFINITY; } if node.overflow.y == OverflowAxis::Visible { clip_rect.min.y = -f32::INFINITY; clip_rect.max.y = f32::INFINITY; } Some(maybe_inherited_clip.map_or(clip_rect, |c| c.intersect(clip_rect))) }; for child in ui_children.iter_ui_children(entity) { update_clipping(commands, ui_children, node_query, child, children_clip); } } pub fn propagate_ui_target_cameras( mut commands: Commands, default_ui_camera: DefaultUiCamera, ui_scale: Res<UiScale>, camera_query: Query<&Camera>, target_camera_query: Query<&UiTargetCamera>, ui_root_nodes: UiRootNodes, ) { let default_camera_entity = default_ui_camera.get(); for root_entity in ui_root_nodes.iter() { let camera = target_camera_query .get(root_entity) .ok() .map(UiTargetCamera::entity) .or(default_camera_entity) .unwrap_or(Entity::PLACEHOLDER); commands .entity(root_entity) .try_insert(Propagate(ComputedUiTargetCamera { camera })); let (scale_factor, physical_size) = camera_query .get(camera) .ok() .map(|camera| { ( camera.target_scaling_factor().unwrap_or(1.) * ui_scale.0, camera.physical_viewport_size().unwrap_or(UVec2::ZERO), ) }) .unwrap_or((1., UVec2::ZERO)); commands .entity(root_entity) .try_insert(Propagate(ComputedUiRenderTargetInfo { scale_factor, physical_size, })); } } #[cfg(test)] mod tests { use crate::update::propagate_ui_target_cameras; use crate::ComputedUiRenderTargetInfo; use crate::ComputedUiTargetCamera; use crate::IsDefaultUiCamera; use crate::Node; use crate::UiScale; use crate::UiTargetCamera; use bevy_app::App; use bevy_app::HierarchyPropagatePlugin; use bevy_app::PostUpdate; use bevy_app::PropagateSet; use bevy_camera::Camera; use bevy_camera::Camera2d; use bevy_camera::ComputedCameraValues; use bevy_camera::RenderTargetInfo; use bevy_ecs::hierarchy::ChildOf; use bevy_math::UVec2; use bevy_utils::default; fn setup_test_app() -> App { let mut app = App::new(); app.init_resource::<UiScale>(); app.add_plugins(HierarchyPropagatePlugin::<ComputedUiTargetCamera>::new( PostUpdate, )); app.configure_sets( PostUpdate, PropagateSet::<ComputedUiTargetCamera>::default(), ); app.add_plugins(HierarchyPropagatePlugin::<ComputedUiRenderTargetInfo>::new( PostUpdate, )); app.configure_sets( PostUpdate, PropagateSet::<ComputedUiRenderTargetInfo>::default(), ); app.add_systems(bevy_app::Update, propagate_ui_target_cameras); app } #[test] fn update_context_for_single_ui_root() { let mut app = setup_test_app(); let world = app.world_mut(); let scale_factor = 10.; let physical_size = UVec2::new(1000, 500); let camera = world .spawn(( Camera2d, Camera { computed: ComputedCameraValues { target_info: Some(RenderTargetInfo { physical_size, scale_factor, }), ..Default::default() }, ..Default::default() }, )) .id(); let uinode = world.spawn(Node::default()).id(); app.update(); let world = app.world_mut(); assert_eq!( *world.get::<ComputedUiTargetCamera>(uinode).unwrap(), ComputedUiTargetCamera { camera } ); assert_eq!( *world.get::<ComputedUiRenderTargetInfo>(uinode).unwrap(), ComputedUiRenderTargetInfo { physical_size, scale_factor, } ); } #[test] fn update_multiple_context_for_multiple_ui_roots() { let mut app = setup_test_app(); let world = app.world_mut(); let scale1 = 1.; let size1 = UVec2::new(100, 100); let scale2 = 2.; let size2 = UVec2::new(200, 200); let camera1 = world .spawn(( Camera2d, IsDefaultUiCamera, Camera { computed: ComputedCameraValues { target_info: Some(RenderTargetInfo { physical_size: size1, scale_factor: scale1, }), ..Default::default() }, ..Default::default() }, )) .id(); let camera2 = world .spawn(( Camera2d, Camera { computed: ComputedCameraValues { target_info: Some(RenderTargetInfo { physical_size: size2, scale_factor: scale2, }), ..Default::default() }, ..default() }, )) .id(); let uinode1a = world.spawn(Node::default()).id(); let uinode2a = world.spawn((Node::default(), UiTargetCamera(camera2))).id(); let uinode2b = world.spawn((Node::default(), UiTargetCamera(camera2))).id(); let uinode2c = world.spawn((Node::default(), UiTargetCamera(camera2))).id(); let uinode1b = world.spawn(Node::default()).id(); app.update(); let world = app.world_mut(); for (uinode, camera, scale_factor, physical_size) in [ (uinode1a, camera1, scale1, size1), (uinode1b, camera1, scale1, size1), (uinode2a, camera2, scale2, size2), (uinode2b, camera2, scale2, size2), (uinode2c, camera2, scale2, size2), ] { assert_eq!( *world.get::<ComputedUiTargetCamera>(uinode).unwrap(), ComputedUiTargetCamera { camera } ); assert_eq!( *world.get::<ComputedUiRenderTargetInfo>(uinode).unwrap(), ComputedUiRenderTargetInfo { physical_size, scale_factor, } ); } } #[test] fn update_context_on_changed_camera() { let mut app = setup_test_app(); let world = app.world_mut(); let scale1 = 1.; let size1 = UVec2::new(100, 100); let scale2 = 2.; let size2 = UVec2::new(200, 200); let camera1 = world .spawn(( Camera2d, IsDefaultUiCamera, Camera { computed: ComputedCameraValues { target_info: Some(RenderTargetInfo { physical_size: size1, scale_factor: scale1, }), ..Default::default() }, ..Default::default() }, )) .id(); let camera2 = world .spawn(( Camera2d, Camera { computed: ComputedCameraValues { target_info: Some(RenderTargetInfo { physical_size: size2, scale_factor: scale2, }), ..Default::default() }, ..default() }, )) .id(); let uinode = world.spawn(Node::default()).id(); app.update(); let world = app.world_mut(); assert_eq!( world .get::<ComputedUiRenderTargetInfo>(uinode) .unwrap() .scale_factor, scale1 ); assert_eq!( world .get::<ComputedUiRenderTargetInfo>(uinode) .unwrap() .physical_size, size1 ); assert_eq!( world .get::<ComputedUiTargetCamera>(uinode) .unwrap() .get() .unwrap(), camera1 ); world.entity_mut(uinode).insert(UiTargetCamera(camera2)); app.update(); let world = app.world_mut(); assert_eq!( world .get::<ComputedUiRenderTargetInfo>(uinode) .unwrap() .scale_factor, scale2 ); assert_eq!( world .get::<ComputedUiRenderTargetInfo>(uinode) .unwrap() .physical_size, size2 ); assert_eq!( world .get::<ComputedUiTargetCamera>(uinode) .unwrap() .get() .unwrap(), camera2 ); } #[test] fn update_context_after_parent_removed() { let mut app = setup_test_app(); let world = app.world_mut(); let scale1 = 1.; let size1 = UVec2::new(100, 100); let scale2 = 2.; let size2 = UVec2::new(200, 200); let camera1 = world .spawn(( Camera2d, IsDefaultUiCamera, Camera { computed: ComputedCameraValues { target_info: Some(RenderTargetInfo { physical_size: size1, scale_factor: scale1, }), ..Default::default() }, ..Default::default() }, )) .id(); let camera2 = world .spawn(( Camera2d, Camera { computed: ComputedCameraValues { target_info: Some(RenderTargetInfo { physical_size: size2, scale_factor: scale2, }), ..Default::default() }, ..default() }, )) .id(); // `UiTargetCamera` is ignored on non-root UI nodes let uinode1 = world.spawn((Node::default(), UiTargetCamera(camera2))).id(); let uinode2 = world.spawn(Node::default()).add_child(uinode1).id(); app.update(); let world = app.world_mut(); assert_eq!( world .get::<ComputedUiRenderTargetInfo>(uinode1) .unwrap() .scale_factor(), scale1 ); assert_eq!( world .get::<ComputedUiRenderTargetInfo>(uinode1) .unwrap() .physical_size(), size1 ); assert_eq!( world .get::<ComputedUiTargetCamera>(uinode1) .unwrap() .get() .unwrap(), camera1 ); assert_eq!( world .get::<ComputedUiTargetCamera>(uinode2) .unwrap() .get() .unwrap(), camera1 ); // Now `uinode1` is a root UI node its `UiTargetCamera` component will be used and its camera target set to `camera2`. world.entity_mut(uinode1).remove::<ChildOf>(); app.update(); let world = app.world_mut(); assert_eq!( world .get::<ComputedUiRenderTargetInfo>(uinode1) .unwrap() .scale_factor(), scale2 ); assert_eq!( world .get::<ComputedUiRenderTargetInfo>(uinode1) .unwrap() .physical_size(), size2 ); assert_eq!( world .get::<ComputedUiTargetCamera>(uinode1) .unwrap() .get() .unwrap(), camera2 ); assert_eq!( world .get::<ComputedUiTargetCamera>(uinode2) .unwrap() .get() .unwrap(), camera1 ); } #[test] fn update_great_grandchild() { let mut app = setup_test_app(); let world = app.world_mut(); let scale = 1.; let size = UVec2::new(100, 100); let camera = world .spawn(( Camera2d, Camera { computed: ComputedCameraValues { target_info: Some(RenderTargetInfo { physical_size: size, scale_factor: scale, }), ..Default::default() }, ..Default::default() }, )) .id(); let uinode = world.spawn(Node::default()).id(); world.spawn(Node::default()).with_children(|builder| { builder.spawn(Node::default()).with_children(|builder| { builder.spawn(Node::default()).add_child(uinode); }); }); app.update(); let world = app.world_mut(); assert_eq!( world .get::<ComputedUiRenderTargetInfo>(uinode) .unwrap() .scale_factor, scale ); assert_eq!( world .get::<ComputedUiRenderTargetInfo>(uinode) .unwrap() .physical_size, size ); assert_eq!( world .get::<ComputedUiTargetCamera>(uinode) .unwrap() .get() .unwrap(), camera ); world.resource_mut::<UiScale>().0 = 2.; app.update(); let world = app.world_mut(); assert_eq!( world .get::<ComputedUiRenderTargetInfo>(uinode) .unwrap() .scale_factor(), 2. ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/geometry.rs
crates/bevy_ui/src/geometry.rs
use bevy_math::{MismatchedUnitsError, StableInterpolate as _, TryStableInterpolate, Vec2}; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_utils::default; use core::ops::{Div, DivAssign, Mul, MulAssign, Neg}; use thiserror::Error; #[cfg(feature = "serialize")] use bevy_reflect::{ReflectDeserialize, ReflectSerialize}; /// Represents the possible value types for layout properties. /// /// This enum allows specifying values for various [`Node`](crate::Node) properties in different units, /// such as logical pixels, percentages, or automatically determined values. /// /// `Val` also implements [`core::str::FromStr`] to allow parsing values from strings in the format `#.#px`. Whitespaces between the value and unit is allowed. The following units are supported: /// * `px`: logical pixels /// * `%`: percentage /// * `vw`: percentage of the viewport width /// * `vh`: percentage of the viewport height /// * `vmin`: percentage of the viewport's smaller dimension /// * `vmax`: percentage of the viewport's larger dimension /// /// Additionally, `auto` will be parsed as [`Val::Auto`]. #[derive(Copy, Clone, Debug, Reflect)] #[reflect(Default, PartialEq, Debug, Clone)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] pub enum Val { /// Automatically determine the value based on the context and other [`Node`](crate::Node) properties. Auto, /// Set this value in logical pixels. Px(f32), /// Set the value as a percentage of its parent node's length along a specific axis. /// /// If the UI node has no parent, the percentage is calculated based on the window's length /// along the corresponding axis. /// /// The chosen axis depends on the [`Node`](crate::Node) field set: /// * For `flex_basis`, the percentage is relative to the main-axis length determined by the `flex_direction`. /// * For `gap`, `min_size`, `size`, and `max_size`: /// - `width` is relative to the parent's width. /// - `height` is relative to the parent's height. /// * For `margin`, `padding`, and `border` values: the percentage is relative to the parent node's width. /// * For positions, `left` and `right` are relative to the parent's width, while `bottom` and `top` are relative to the parent's height. Percent(f32), /// Set this value in percent of the viewport width Vw(f32), /// Set this value in percent of the viewport height Vh(f32), /// Set this value in percent of the viewport's smaller dimension. VMin(f32), /// Set this value in percent of the viewport's larger dimension. VMax(f32), } #[derive(Debug, Error, PartialEq, Eq)] pub enum ValParseError { UnitMissing, ValueMissing, InvalidValue, InvalidUnit, } impl core::fmt::Display for ValParseError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { ValParseError::UnitMissing => write!(f, "unit missing"), ValParseError::ValueMissing => write!(f, "value missing"), ValParseError::InvalidValue => write!(f, "invalid value"), ValParseError::InvalidUnit => write!(f, "invalid unit"), } } } impl core::str::FromStr for Val { type Err = ValParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { let s = s.trim(); if s.eq_ignore_ascii_case("auto") { return Ok(Val::Auto); } let Some(end_of_number) = s .bytes() .position(|c| !(c.is_ascii_digit() || c == b'.' || c == b'-' || c == b'+')) else { return Err(ValParseError::UnitMissing); }; if end_of_number == 0 { return Err(ValParseError::ValueMissing); } let (value, unit) = s.split_at(end_of_number); let value: f32 = value.parse().map_err(|_| ValParseError::InvalidValue)?; let unit = unit.trim(); if unit.eq_ignore_ascii_case("px") { Ok(Val::Px(value)) } else if unit.eq_ignore_ascii_case("%") { Ok(Val::Percent(value)) } else if unit.eq_ignore_ascii_case("vw") { Ok(Val::Vw(value)) } else if unit.eq_ignore_ascii_case("vh") { Ok(Val::Vh(value)) } else if unit.eq_ignore_ascii_case("vmin") { Ok(Val::VMin(value)) } else if unit.eq_ignore_ascii_case("vmax") { Ok(Val::VMax(value)) } else { Err(ValParseError::InvalidUnit) } } } impl PartialEq for Val { fn eq(&self, other: &Self) -> bool { let same_unit = matches!( (self, other), (Self::Auto, Self::Auto) | (Self::Px(_), Self::Px(_)) | (Self::Percent(_), Self::Percent(_)) | (Self::Vw(_), Self::Vw(_)) | (Self::Vh(_), Self::Vh(_)) | (Self::VMin(_), Self::VMin(_)) | (Self::VMax(_), Self::VMax(_)) ); let left = match self { Self::Auto => None, Self::Px(v) | Self::Percent(v) | Self::Vw(v) | Self::Vh(v) | Self::VMin(v) | Self::VMax(v) => Some(v), }; let right = match other { Self::Auto => None, Self::Px(v) | Self::Percent(v) | Self::Vw(v) | Self::Vh(v) | Self::VMin(v) | Self::VMax(v) => Some(v), }; match (same_unit, left, right) { (true, a, b) => a == b, // All zero-value variants are considered equal. (false, Some(&a), Some(&b)) => a == 0. && b == 0., _ => false, } } } impl Val { pub const DEFAULT: Self = Self::Auto; pub const ZERO: Self = Self::Px(0.0); /// Returns a [`UiRect`] with its `left` equal to this value, /// and all other fields set to `Val::ZERO`. /// /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = Val::Px(1.).left(); /// /// assert_eq!(ui_rect.left, Val::Px(1.)); /// assert_eq!(ui_rect.right, Val::ZERO); /// assert_eq!(ui_rect.top, Val::ZERO); /// assert_eq!(ui_rect.bottom, Val::ZERO); /// ``` pub const fn left(self) -> UiRect { UiRect::left(self) } /// Returns a [`UiRect`] with its `right` equal to this value, /// and all other fields set to `Val::ZERO`. /// /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = Val::Px(1.).right(); /// /// assert_eq!(ui_rect.left, Val::ZERO); /// assert_eq!(ui_rect.right, Val::Px(1.)); /// assert_eq!(ui_rect.top, Val::ZERO); /// assert_eq!(ui_rect.bottom, Val::ZERO); /// ``` pub const fn right(self) -> UiRect { UiRect::right(self) } /// Returns a [`UiRect`] with its `top` equal to this value, /// and all other fields set to `Val::ZERO`. /// /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = Val::Px(1.).top(); /// /// assert_eq!(ui_rect.left, Val::ZERO); /// assert_eq!(ui_rect.right, Val::ZERO); /// assert_eq!(ui_rect.top, Val::Px(1.)); /// assert_eq!(ui_rect.bottom, Val::ZERO); /// ``` pub const fn top(self) -> UiRect { UiRect::top(self) } /// Returns a [`UiRect`] with its `bottom` equal to this value, /// and all other fields set to `Val::ZERO`. /// /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = Val::Px(1.).bottom(); /// /// assert_eq!(ui_rect.left, Val::ZERO); /// assert_eq!(ui_rect.right, Val::ZERO); /// assert_eq!(ui_rect.top, Val::ZERO); /// assert_eq!(ui_rect.bottom, Val::Px(1.)); /// ``` pub const fn bottom(self) -> UiRect { UiRect::bottom(self) } /// Returns a [`UiRect`] with all its fields equal to this value. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = Val::Px(1.).all(); /// /// assert_eq!(ui_rect.left, Val::Px(1.)); /// assert_eq!(ui_rect.right, Val::Px(1.)); /// assert_eq!(ui_rect.top, Val::Px(1.)); /// assert_eq!(ui_rect.bottom, Val::Px(1.)); /// ``` pub const fn all(self) -> UiRect { UiRect::all(self) } /// Returns a [`UiRect`] with all its `left` and `right` equal to this value, /// and its `top` and `bottom` set to `Val::ZERO`. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = Val::Px(1.).horizontal(); /// /// assert_eq!(ui_rect.left, Val::Px(1.)); /// assert_eq!(ui_rect.right, Val::Px(1.)); /// assert_eq!(ui_rect.top, Val::ZERO); /// assert_eq!(ui_rect.bottom, Val::ZERO); /// ``` pub const fn horizontal(self) -> UiRect { UiRect::horizontal(self) } /// Returns a [`UiRect`] with all its `top` and `bottom` equal to this value, /// and its `left` and `right` set to `Val::ZERO`. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = Val::Px(1.).vertical(); /// /// assert_eq!(ui_rect.left, Val::ZERO); /// assert_eq!(ui_rect.right, Val::ZERO); /// assert_eq!(ui_rect.top, Val::Px(1.)); /// assert_eq!(ui_rect.bottom, Val::Px(1.)); /// ``` pub const fn vertical(self) -> UiRect { UiRect::vertical(self) } } impl Default for Val { fn default() -> Self { Self::DEFAULT } } impl Mul<f32> for Val { type Output = Val; fn mul(self, rhs: f32) -> Self::Output { match self { Val::Auto => Val::Auto, Val::Px(value) => Val::Px(value * rhs), Val::Percent(value) => Val::Percent(value * rhs), Val::Vw(value) => Val::Vw(value * rhs), Val::Vh(value) => Val::Vh(value * rhs), Val::VMin(value) => Val::VMin(value * rhs), Val::VMax(value) => Val::VMax(value * rhs), } } } impl MulAssign<f32> for Val { fn mul_assign(&mut self, rhs: f32) { match self { Val::Auto => {} Val::Px(value) | Val::Percent(value) | Val::Vw(value) | Val::Vh(value) | Val::VMin(value) | Val::VMax(value) => *value *= rhs, } } } impl Div<f32> for Val { type Output = Val; fn div(self, rhs: f32) -> Self::Output { match self { Val::Auto => Val::Auto, Val::Px(value) => Val::Px(value / rhs), Val::Percent(value) => Val::Percent(value / rhs), Val::Vw(value) => Val::Vw(value / rhs), Val::Vh(value) => Val::Vh(value / rhs), Val::VMin(value) => Val::VMin(value / rhs), Val::VMax(value) => Val::VMax(value / rhs), } } } impl DivAssign<f32> for Val { fn div_assign(&mut self, rhs: f32) { match self { Val::Auto => {} Val::Px(value) | Val::Percent(value) | Val::Vw(value) | Val::Vh(value) | Val::VMin(value) | Val::VMax(value) => *value /= rhs, } } } impl Neg for Val { type Output = Val; fn neg(self) -> Self::Output { match self { Val::Px(value) => Val::Px(-value), Val::Percent(value) => Val::Percent(-value), Val::Vw(value) => Val::Vw(-value), Val::Vh(value) => Val::Vh(-value), Val::VMin(value) => Val::VMin(-value), Val::VMax(value) => Val::VMax(-value), _ => self, } } } #[derive(Debug, Eq, PartialEq, Clone, Copy, Error)] pub enum ValArithmeticError { #[error("the given variant of Val is not evaluable (non-numeric)")] NonEvaluable, } impl Val { /// Resolves this [`Val`] to a value in physical pixels from the given `scale_factor`, `physical_base_value`, /// and `physical_target_size` context values. /// /// Returns a [`ValArithmeticError::NonEvaluable`] if the [`Val`] is impossible to resolve into a concrete value. pub const fn resolve( self, scale_factor: f32, physical_base_value: f32, physical_target_size: Vec2, ) -> Result<f32, ValArithmeticError> { match self { Val::Percent(value) => Ok(physical_base_value * value / 100.0), Val::Px(value) => Ok(value * scale_factor), Val::Vw(value) => Ok(physical_target_size.x * value / 100.0), Val::Vh(value) => Ok(physical_target_size.y * value / 100.0), Val::VMin(value) => { Ok(physical_target_size.x.min(physical_target_size.y) * value / 100.0) } Val::VMax(value) => { Ok(physical_target_size.x.max(physical_target_size.y) * value / 100.0) } Val::Auto => Err(ValArithmeticError::NonEvaluable), } } } impl TryStableInterpolate for Val { type Error = MismatchedUnitsError; /// # Example /// /// ``` /// # use bevy_ui::Val; /// # use bevy_math::TryStableInterpolate; /// assert!(matches!(Val::Px(0.0).try_interpolate_stable(&Val::Px(10.0), 0.5), Ok(Val::Px(5.0)))); /// ``` fn try_interpolate_stable(&self, other: &Self, t: f32) -> Result<Self, Self::Error> { match (self, other) { (Val::Px(a), Val::Px(b)) => Ok(Val::Px(a.interpolate_stable(b, t))), (Val::Percent(a), Val::Percent(b)) => Ok(Val::Percent(a.interpolate_stable(b, t))), (Val::Vw(a), Val::Vw(b)) => Ok(Val::Vw(a.interpolate_stable(b, t))), (Val::Vh(a), Val::Vh(b)) => Ok(Val::Vh(a.interpolate_stable(b, t))), (Val::VMin(a), Val::VMin(b)) => Ok(Val::VMin(a.interpolate_stable(b, t))), (Val::VMax(a), Val::VMax(b)) => Ok(Val::VMax(a.interpolate_stable(b, t))), (Val::Auto, Val::Auto) => Ok(Val::Auto), _ => Err(MismatchedUnitsError), } } } /// All the types that should be able to be used in the [`Val`] enum should implement this trait. /// /// Instead of just implementing `Into<Val>` a custom trait is added. /// This is done in order to prevent having to define a default unit, which could lead to confusion especially for newcomers. pub trait ValNum { /// Called by the [`Val`] helper functions to convert the implementing type to an `f32` that can /// be used by [`Val`]. fn val_num_f32(self) -> f32; } macro_rules! impl_to_val_num { ($($impl_type:ty),*$(,)?) => { $( impl ValNum for $impl_type { fn val_num_f32(self) -> f32 { self as f32 } } )* }; } impl_to_val_num!(f32, f64, i8, i16, i32, i64, u8, u16, u32, u64, usize, isize); /// Returns a [`Val::Auto`] where the value is automatically determined /// based on the context and other [`Node`](crate::Node) properties. pub const fn auto() -> Val { Val::Auto } /// Returns a [`Val::Px`] representing a value in logical pixels. pub fn px<T: ValNum>(value: T) -> Val { Val::Px(value.val_num_f32()) } /// Returns a [`Val::Percent`] representing a percentage of the parent node's length /// along a specific axis. /// /// If the UI node has no parent, the percentage is based on the window's length /// along that axis. /// /// Axis rules: /// * For `flex_basis`, the percentage is relative to the main-axis length determined by the `flex_direction`. /// * For `gap`, `min_size`, `size`, and `max_size`: /// - `width` is relative to the parent's width. /// - `height` is relative to the parent's height. /// * For `margin`, `padding`, and `border` values: the percentage is relative to the parent's width. /// * For positions, `left` and `right` are relative to the parent's width, while `bottom` and `top` are relative to the parent's height. pub fn percent<T: ValNum>(value: T) -> Val { Val::Percent(value.val_num_f32()) } /// Returns a [`Val::Vw`] representing a percentage of the viewport width. pub fn vw<T: ValNum>(value: T) -> Val { Val::Vw(value.val_num_f32()) } /// Returns a [`Val::Vh`] representing a percentage of the viewport height. pub fn vh<T: ValNum>(value: T) -> Val { Val::Vh(value.val_num_f32()) } /// Returns a [`Val::VMin`] representing a percentage of the viewport's smaller dimension. pub fn vmin<T: ValNum>(value: T) -> Val { Val::VMin(value.val_num_f32()) } /// Returns a [`Val::VMax`] representing a percentage of the viewport's larger dimension. pub fn vmax<T: ValNum>(value: T) -> Val { Val::VMax(value.val_num_f32()) } /// A type which is commonly used to define margins, paddings and borders. /// /// # Examples /// /// ## Margin /// /// A margin is used to create space around UI elements, outside of any defined borders. /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let margin = UiRect::all(Val::Auto); // Centers the UI element /// ``` /// /// ## Padding /// /// A padding is used to create space around UI elements, inside of any defined borders. /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let padding = UiRect { /// left: Val::Px(10.0), /// right: Val::Px(20.0), /// top: Val::Px(30.0), /// bottom: Val::Px(40.0), /// }; /// ``` /// /// ## Borders /// /// A border is used to define the width of the border of a UI element. /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let border = UiRect { /// left: Val::Px(10.0), /// right: Val::Px(20.0), /// top: Val::Px(30.0), /// bottom: Val::Px(40.0), /// }; /// ``` #[derive(Copy, Clone, PartialEq, Debug, Reflect)] #[reflect(Default, PartialEq, Debug, Clone)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] pub struct UiRect { /// The value corresponding to the left side of the UI rect. pub left: Val, /// The value corresponding to the right side of the UI rect. pub right: Val, /// The value corresponding to the top side of the UI rect. pub top: Val, /// The value corresponding to the bottom side of the UI rect. pub bottom: Val, } impl UiRect { pub const DEFAULT: Self = Self::all(Val::ZERO); pub const ZERO: Self = Self::all(Val::ZERO); pub const AUTO: Self = Self::all(Val::Auto); /// Creates a new [`UiRect`] from the values specified. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = UiRect::new( /// Val::Px(10.0), /// Val::Px(20.0), /// Val::Px(30.0), /// Val::Px(40.0), /// ); /// /// assert_eq!(ui_rect.left, Val::Px(10.0)); /// assert_eq!(ui_rect.right, Val::Px(20.0)); /// assert_eq!(ui_rect.top, Val::Px(30.0)); /// assert_eq!(ui_rect.bottom, Val::Px(40.0)); /// ``` pub const fn new(left: Val, right: Val, top: Val, bottom: Val) -> Self { UiRect { left, right, top, bottom, } } /// Creates a new [`UiRect`] where all sides have the same value. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = UiRect::all(Val::Px(10.0)); /// /// assert_eq!(ui_rect.left, Val::Px(10.0)); /// assert_eq!(ui_rect.right, Val::Px(10.0)); /// assert_eq!(ui_rect.top, Val::Px(10.0)); /// assert_eq!(ui_rect.bottom, Val::Px(10.0)); /// ``` pub const fn all(value: Val) -> Self { UiRect { left: value, right: value, top: value, bottom: value, } } /// Creates a new [`UiRect`] from the values specified in logical pixels. /// /// This is a shortcut for [`UiRect::new()`], applying [`Val::Px`] to all arguments. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = UiRect::px(10., 20., 30., 40.); /// assert_eq!(ui_rect.left, Val::Px(10.)); /// assert_eq!(ui_rect.right, Val::Px(20.)); /// assert_eq!(ui_rect.top, Val::Px(30.)); /// assert_eq!(ui_rect.bottom, Val::Px(40.)); /// ``` pub const fn px(left: f32, right: f32, top: f32, bottom: f32) -> Self { UiRect { left: Val::Px(left), right: Val::Px(right), top: Val::Px(top), bottom: Val::Px(bottom), } } /// Creates a new [`UiRect`] from the values specified in percentages. /// /// This is a shortcut for [`UiRect::new()`], applying [`Val::Percent`] to all arguments. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = UiRect::percent(5., 10., 2., 1.); /// assert_eq!(ui_rect.left, Val::Percent(5.)); /// assert_eq!(ui_rect.right, Val::Percent(10.)); /// assert_eq!(ui_rect.top, Val::Percent(2.)); /// assert_eq!(ui_rect.bottom, Val::Percent(1.)); /// ``` pub const fn percent(left: f32, right: f32, top: f32, bottom: f32) -> Self { UiRect { left: Val::Percent(left), right: Val::Percent(right), top: Val::Percent(top), bottom: Val::Percent(bottom), } } /// Creates a new [`UiRect`] where `left` and `right` take the given value, /// and `top` and `bottom` set to zero `Val::ZERO`. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = UiRect::horizontal(Val::Px(10.0)); /// /// assert_eq!(ui_rect.left, Val::Px(10.0)); /// assert_eq!(ui_rect.right, Val::Px(10.0)); /// assert_eq!(ui_rect.top, Val::ZERO); /// assert_eq!(ui_rect.bottom, Val::ZERO); /// ``` pub const fn horizontal(value: Val) -> Self { Self { left: value, right: value, ..Self::DEFAULT } } /// Creates a new [`UiRect`] where `top` and `bottom` take the given value, /// and `left` and `right` are set to `Val::ZERO`. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = UiRect::vertical(Val::Px(10.0)); /// /// assert_eq!(ui_rect.left, Val::ZERO); /// assert_eq!(ui_rect.right, Val::ZERO); /// assert_eq!(ui_rect.top, Val::Px(10.0)); /// assert_eq!(ui_rect.bottom, Val::Px(10.0)); /// ``` pub const fn vertical(value: Val) -> Self { Self { top: value, bottom: value, ..Self::DEFAULT } } /// Creates a new [`UiRect`] where both `left` and `right` take the value of `horizontal`, and both `top` and `bottom` take the value of `vertical`. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = UiRect::axes(Val::Px(10.0), Val::Percent(15.0)); /// /// assert_eq!(ui_rect.left, Val::Px(10.0)); /// assert_eq!(ui_rect.right, Val::Px(10.0)); /// assert_eq!(ui_rect.top, Val::Percent(15.0)); /// assert_eq!(ui_rect.bottom, Val::Percent(15.0)); /// ``` pub const fn axes(horizontal: Val, vertical: Val) -> Self { Self { left: horizontal, right: horizontal, top: vertical, bottom: vertical, } } /// Creates a new [`UiRect`] where `left` takes the given value, and /// the other fields are set to `Val::ZERO`. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = UiRect::left(Val::Px(10.0)); /// /// assert_eq!(ui_rect.left, Val::Px(10.0)); /// assert_eq!(ui_rect.right, Val::ZERO); /// assert_eq!(ui_rect.top, Val::ZERO); /// assert_eq!(ui_rect.bottom, Val::ZERO); /// ``` pub const fn left(left: Val) -> Self { Self { left, ..Self::DEFAULT } } /// Creates a new [`UiRect`] where `right` takes the given value, /// and the other fields are set to `Val::ZERO`. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = UiRect::right(Val::Px(10.0)); /// /// assert_eq!(ui_rect.left, Val::ZERO); /// assert_eq!(ui_rect.right, Val::Px(10.0)); /// assert_eq!(ui_rect.top, Val::ZERO); /// assert_eq!(ui_rect.bottom, Val::ZERO); /// ``` pub const fn right(right: Val) -> Self { Self { right, ..Self::DEFAULT } } /// Creates a new [`UiRect`] where `top` takes the given value, /// and the other fields are set to `Val::ZERO`. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = UiRect::top(Val::Px(10.0)); /// /// assert_eq!(ui_rect.left, Val::ZERO); /// assert_eq!(ui_rect.right, Val::ZERO); /// assert_eq!(ui_rect.top, Val::Px(10.0)); /// assert_eq!(ui_rect.bottom, Val::ZERO); /// ``` pub const fn top(top: Val) -> Self { Self { top, ..Self::DEFAULT } } /// Creates a new [`UiRect`] where `bottom` takes the given value, /// and the other fields are set to `Val::ZERO`. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = UiRect::bottom(Val::Px(10.0)); /// /// assert_eq!(ui_rect.left, Val::ZERO); /// assert_eq!(ui_rect.right, Val::ZERO); /// assert_eq!(ui_rect.top, Val::ZERO); /// assert_eq!(ui_rect.bottom, Val::Px(10.0)); /// ``` pub const fn bottom(bottom: Val) -> Self { Self { bottom, ..Self::DEFAULT } } /// Returns the [`UiRect`] with its `left` field set to the given value. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = UiRect::all(Val::Px(20.0)).with_left(Val::Px(10.0)); /// assert_eq!(ui_rect.left, Val::Px(10.0)); /// assert_eq!(ui_rect.right, Val::Px(20.0)); /// assert_eq!(ui_rect.top, Val::Px(20.0)); /// assert_eq!(ui_rect.bottom, Val::Px(20.0)); /// ``` #[inline] pub const fn with_left(mut self, left: Val) -> Self { self.left = left; self } /// Returns the [`UiRect`] with its `right` field set to the given value. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = UiRect::all(Val::Px(20.0)).with_right(Val::Px(10.0)); /// assert_eq!(ui_rect.left, Val::Px(20.0)); /// assert_eq!(ui_rect.right, Val::Px(10.0)); /// assert_eq!(ui_rect.top, Val::Px(20.0)); /// assert_eq!(ui_rect.bottom, Val::Px(20.0)); /// ``` #[inline] pub const fn with_right(mut self, right: Val) -> Self { self.right = right; self } /// Returns the [`UiRect`] with its `top` field set to the given value. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = UiRect::all(Val::Px(20.0)).with_top(Val::Px(10.0)); /// assert_eq!(ui_rect.left, Val::Px(20.0)); /// assert_eq!(ui_rect.right, Val::Px(20.0)); /// assert_eq!(ui_rect.top, Val::Px(10.0)); /// assert_eq!(ui_rect.bottom, Val::Px(20.0)); /// ``` #[inline] pub const fn with_top(mut self, top: Val) -> Self { self.top = top; self } /// Returns the [`UiRect`] with its `bottom` field set to the given value. /// /// # Example /// /// ``` /// # use bevy_ui::{UiRect, Val}; /// # /// let ui_rect = UiRect::all(Val::Px(20.0)).with_bottom(Val::Px(10.0)); /// assert_eq!(ui_rect.left, Val::Px(20.0)); /// assert_eq!(ui_rect.right, Val::Px(20.0)); /// assert_eq!(ui_rect.top, Val::Px(20.0)); /// assert_eq!(ui_rect.bottom, Val::Px(10.0)); /// ``` #[inline] pub const fn with_bottom(mut self, bottom: Val) -> Self { self.bottom = bottom; self } } impl Default for UiRect { fn default() -> Self { Self::DEFAULT } } impl From<Val> for UiRect { fn from(value: Val) -> Self { UiRect::all(value) } } #[derive(Debug, Clone, Copy, PartialEq, Reflect)] #[reflect(Default, Debug, PartialEq)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] /// Responsive position relative to a UI node. pub struct UiPosition { /// Normalized anchor point pub anchor: Vec2, /// Responsive horizontal position relative to the anchor point pub x: Val, /// Responsive vertical position relative to the anchor point pub y: Val, } impl Default for UiPosition { fn default() -> Self { Self::CENTER } } impl UiPosition { /// Position at the given normalized anchor point pub const fn anchor(anchor: Vec2) -> Self { Self { anchor, x: Val::ZERO, y: Val::ZERO, } } /// Position at the top-left corner pub const TOP_LEFT: Self = Self::anchor(Vec2::new(-0.5, -0.5)); /// Position at the center of the left edge pub const LEFT: Self = Self::anchor(Vec2::new(-0.5, 0.0)); /// Position at the bottom-left corner pub const BOTTOM_LEFT: Self = Self::anchor(Vec2::new(-0.5, 0.5)); /// Position at the center of the top edge pub const TOP: Self = Self::anchor(Vec2::new(0.0, -0.5)); /// Position at the center of the element pub const CENTER: Self = Self::anchor(Vec2::new(0.0, 0.0)); /// Position at the center of the bottom edge pub const BOTTOM: Self = Self::anchor(Vec2::new(0.0, 0.5)); /// Position at the top-right corner pub const TOP_RIGHT: Self = Self::anchor(Vec2::new(0.5, -0.5)); /// Position at the center of the right edge pub const RIGHT: Self = Self::anchor(Vec2::new(0.5, 0.0)); /// Position at the bottom-right corner pub const BOTTOM_RIGHT: Self = Self::anchor(Vec2::new(0.5, 0.5)); /// Create a new position pub const fn new(anchor: Vec2, x: Val, y: Val) -> Self { Self { anchor, x, y } } /// Creates a position from self with the given `x` and `y` coordinates pub const fn at(self, x: Val, y: Val) -> Self { Self { x, y, ..self } } /// Creates a position from self with the given `x` coordinate pub const fn at_x(self, x: Val) -> Self { Self { x, ..self } } /// Creates a position from self with the given `y` coordinate pub const fn at_y(self, y: Val) -> Self { Self { y, ..self } } /// Creates a position in logical pixels from self with the given `x` and `y` coordinates pub const fn at_px(self, x: f32, y: f32) -> Self { self.at(Val::Px(x), Val::Px(y)) } /// Creates a percentage position from self with the given `x` and `y` coordinates pub const fn at_percent(self, x: f32, y: f32) -> Self { self.at(Val::Percent(x), Val::Percent(y)) } /// Creates a position from self with the given `anchor` point pub const fn with_anchor(self, anchor: Vec2) -> Self { Self { anchor, ..self } } /// Position relative to the top-left corner pub const fn top_left(x: Val, y: Val) -> Self { Self::TOP_LEFT.at(x, y) } /// Position relative to the left edge pub const fn left(x: Val, y: Val) -> Self { Self::LEFT.at(x, y) } /// Position relative to the bottom-left corner pub const fn bottom_left(x: Val, y: Val) -> Self { Self::BOTTOM_LEFT.at(x, y) } /// Position relative to the top edge pub const fn top(x: Val, y: Val) -> Self { Self::TOP.at(x, y) } /// Position relative to the center pub const fn center(x: Val, y: Val) -> Self { Self::CENTER.at(x, y) } /// Position relative to the bottom edge pub const fn bottom(x: Val, y: Val) -> Self { Self::BOTTOM.at(x, y) } /// Position relative to the top-right corner pub const fn top_right(x: Val, y: Val) -> Self { Self::TOP_RIGHT.at(x, y) } /// Position relative to the right edge pub const fn right(x: Val, y: Val) -> Self { Self::RIGHT.at(x, y) } /// Position relative to the bottom-right corner pub const fn bottom_right(x: Val, y: Val) -> Self { Self::BOTTOM_RIGHT.at(x, y) } /// Resolves the `Position` into physical coordinates. pub fn resolve( self, scale_factor: f32,
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/measurement.rs
crates/bevy_ui/src/measurement.rs
use bevy_ecs::{prelude::Component, reflect::ReflectComponent}; use bevy_math::Vec2; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_text::CosmicFontSystem; use core::fmt::Formatter; pub use taffy::style::AvailableSpace; use crate::widget::ImageMeasure; use crate::widget::TextMeasure; impl core::fmt::Debug for ContentSize { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { f.debug_struct("ContentSize").finish() } } pub struct MeasureArgs<'a> { pub width: Option<f32>, pub height: Option<f32>, pub available_width: AvailableSpace, pub available_height: AvailableSpace, pub font_system: &'a mut CosmicFontSystem, pub buffer: Option<&'a mut bevy_text::ComputedTextBlock>, } /// A `Measure` is used to compute the size of a ui node /// when the size of that node is based on its content. pub trait Measure: Send + Sync + 'static { /// Calculate the size of the node given the constraints. fn measure(&mut self, measure_args: MeasureArgs<'_>, style: &taffy::Style) -> Vec2; } /// A type to serve as Taffy's node context (which allows the content size of leaf nodes to be computed) /// /// It has specific variants for common built-in types to avoid making them opaque and needing to box them /// by wrapping them in a closure and a Custom variant that allows arbitrary measurement closures if required. pub enum NodeMeasure { Fixed(FixedMeasure), Text(TextMeasure), Image(ImageMeasure), Custom(Box<dyn Measure>), } impl Measure for NodeMeasure { fn measure(&mut self, measure_args: MeasureArgs, style: &taffy::Style) -> Vec2 { match self { NodeMeasure::Fixed(fixed) => fixed.measure(measure_args, style), NodeMeasure::Text(text) => text.measure(measure_args, style), NodeMeasure::Image(image) => image.measure(measure_args, style), NodeMeasure::Custom(custom) => custom.measure(measure_args, style), } } } /// A `FixedMeasure` is a `Measure` that ignores all constraints and /// always returns the same size. #[derive(Default, Clone)] pub struct FixedMeasure { pub size: Vec2, } impl Measure for FixedMeasure { fn measure(&mut self, _: MeasureArgs, _: &taffy::Style) -> Vec2 { self.size } } /// A node with a `ContentSize` component is a node where its size /// is based on its content. #[derive(Component, Reflect, Default)] #[reflect(Component, Default)] pub struct ContentSize { /// The `Measure` used to compute the intrinsic size #[reflect(ignore)] pub(crate) measure: Option<NodeMeasure>, } impl ContentSize { /// Set a `Measure` for the UI node entity with this component pub fn set(&mut self, measure: NodeMeasure) { self.measure = Some(measure); } /// Creates a `ContentSize` with a `Measure` that always returns given `size` argument, regardless of the UI layout's constraints. pub fn fixed_size(size: Vec2) -> ContentSize { let mut content_size = Self::default(); content_size.set(NodeMeasure::Fixed(FixedMeasure { size })); content_size } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/ui_node.rs
crates/bevy_ui/src/ui_node.rs
use crate::{ ui_transform::{UiGlobalTransform, UiTransform}, FocusPolicy, UiRect, Val, }; use bevy_camera::{visibility::Visibility, Camera, RenderTarget}; use bevy_color::{Alpha, Color}; use bevy_derive::{Deref, DerefMut}; use bevy_ecs::{prelude::*, system::SystemParam}; use bevy_math::{BVec2, Rect, UVec2, Vec2, Vec4, Vec4Swizzles}; use bevy_reflect::prelude::*; use bevy_sprite::BorderRect; use bevy_utils::once; use bevy_window::{PrimaryWindow, WindowRef}; use core::{f32, num::NonZero}; use derive_more::derive::From; use smallvec::SmallVec; use thiserror::Error; use tracing::warn; /// Provides the computed size and layout properties of the node. /// /// Fields in this struct are public but should not be modified under most circumstances. /// For example, in a scrollbar you may want to derive the handle's size from the proportion of /// scrollable content in-view. You can directly modify `ComputedNode` after layout to set the /// handle size without any delays. #[derive(Component, Debug, Copy, Clone, PartialEq, Reflect)] #[reflect(Component, Default, Debug, Clone)] pub struct ComputedNode { /// The order of the node in the UI layout. /// Nodes with a higher stack index are drawn on top of and receive interactions before nodes with lower stack indices. /// /// Automatically calculated in [`UiSystems::Stack`](`super::UiSystems::Stack`). pub stack_index: u32, /// The size of the node as width and height in physical pixels. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). pub size: Vec2, /// Size of this node's content. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). pub content_size: Vec2, /// Space allocated for scrollbars. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). pub scrollbar_size: Vec2, /// Resolved offset of scrolled content /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). pub scroll_position: Vec2, /// The width of this node's outline. /// If this value is `Auto`, negative or `0.` then no outline will be rendered. /// Outline updates bypass change detection. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). pub outline_width: f32, /// The amount of space between the outline and the edge of the node. /// Outline updates bypass change detection. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). pub outline_offset: f32, /// The unrounded size of the node as width and height in physical pixels. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). pub unrounded_size: Vec2, /// Resolved border values in physical pixels. /// Border updates bypass change detection. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). pub border: BorderRect, /// Resolved border radius values in physical pixels. /// Border radius updates bypass change detection. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). pub border_radius: ResolvedBorderRadius, /// Resolved padding values in physical pixels. /// Padding updates bypass change detection. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). pub padding: BorderRect, /// Inverse scale factor for this Node. /// Multiply physical coordinates by the inverse scale factor to give logical coordinates. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). pub inverse_scale_factor: f32, } impl ComputedNode { /// The calculated node size as width and height in physical pixels. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). #[inline] pub const fn size(&self) -> Vec2 { self.size } /// The calculated node content size as width and height in physical pixels. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). #[inline] pub const fn content_size(&self) -> Vec2 { self.content_size } /// Check if the node is empty. /// A node is considered empty if it has a zero or negative extent along either of its axes. #[inline] pub const fn is_empty(&self) -> bool { self.size.x <= 0. || self.size.y <= 0. } /// The order of the node in the UI layout. /// Nodes with a higher stack index are drawn on top of and receive interactions before nodes with lower stack indices. /// /// Automatically calculated in [`UiSystems::Stack`](super::UiSystems::Stack). pub const fn stack_index(&self) -> u32 { self.stack_index } /// The calculated node size as width and height in physical pixels before rounding. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). #[inline] pub const fn unrounded_size(&self) -> Vec2 { self.unrounded_size } /// Returns the thickness of the UI node's outline in physical pixels. /// If this value is negative or `0.` then no outline will be rendered. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). #[inline] pub const fn outline_width(&self) -> f32 { self.outline_width } /// Returns the amount of space between the outline and the edge of the node in physical pixels. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). #[inline] pub const fn outline_offset(&self) -> f32 { self.outline_offset } /// Returns the size of the node when including its outline. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). #[inline] pub const fn outlined_node_size(&self) -> Vec2 { let offset = 2. * (self.outline_offset + self.outline_width); Vec2::new(self.size.x + offset, self.size.y + offset) } /// Returns the border radius for each corner of the outline /// An outline's border radius is derived from the node's border-radius /// so that the outline wraps the border equally at all points. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). #[inline] pub const fn outline_radius(&self) -> ResolvedBorderRadius { let outer_distance = self.outline_width + self.outline_offset; const fn compute_radius(radius: f32, outer_distance: f32) -> f32 { if radius > 0. { radius + outer_distance } else { 0. } } ResolvedBorderRadius { top_left: compute_radius(self.border_radius.top_left, outer_distance), top_right: compute_radius(self.border_radius.top_right, outer_distance), bottom_right: compute_radius(self.border_radius.bottom_right, outer_distance), bottom_left: compute_radius(self.border_radius.bottom_left, outer_distance), } } /// Returns the thickness of the node's border on each edge in physical pixels. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). #[inline] pub const fn border(&self) -> BorderRect { self.border } /// Returns the border radius for each of the node's corners in physical pixels. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). #[inline] pub const fn border_radius(&self) -> ResolvedBorderRadius { self.border_radius } /// Returns the inner border radius for each of the node's corners in physical pixels. pub fn inner_radius(&self) -> ResolvedBorderRadius { fn clamp_corner(r: f32, size: Vec2, offset: Vec2) -> f32 { let s = 0.5 * size + offset; let sm = s.x.min(s.y); r.min(sm) } let b = Vec4::from((self.border.min_inset, self.border.max_inset)); let s = self.size() - b.xy() - b.zw(); ResolvedBorderRadius { top_left: clamp_corner(self.border_radius.top_left, s, b.xy()), top_right: clamp_corner(self.border_radius.top_right, s, b.zy()), bottom_right: clamp_corner(self.border_radius.bottom_left, s, b.xw()), bottom_left: clamp_corner(self.border_radius.bottom_right, s, b.zw()), } } /// Returns the thickness of the node's padding on each edge in physical pixels. /// /// Automatically calculated by [`ui_layout_system`](`super::layout::ui_layout_system`). #[inline] pub const fn padding(&self) -> BorderRect { self.padding } /// Returns the combined inset on each edge including both padding and border thickness in physical pixels. #[inline] pub fn content_inset(&self) -> BorderRect { let mut content_inset = self.border + self.padding; content_inset.max_inset += self.scrollbar_size; content_inset } /// Returns the inverse of the scale factor for this node. /// To convert from physical coordinates to logical coordinates multiply by this value. #[inline] pub const fn inverse_scale_factor(&self) -> f32 { self.inverse_scale_factor } // Returns true if `point` within the node. // // Matches the sdf function in `ui.wgsl` that is used by the UI renderer to draw rounded rectangles. pub fn contains_point(&self, transform: UiGlobalTransform, point: Vec2) -> bool { let Some(local_point) = transform .try_inverse() .map(|transform| transform.transform_point2(point)) else { return false; }; let [top, bottom] = if local_point.x < 0. { [self.border_radius.top_left, self.border_radius.bottom_left] } else { [ self.border_radius.top_right, self.border_radius.bottom_right, ] }; let r = if local_point.y < 0. { top } else { bottom }; let corner_to_point = local_point.abs() - 0.5 * self.size; let q = corner_to_point + r; let l = q.max(Vec2::ZERO).length(); let m = q.max_element().min(0.); l + m - r < 0. } /// Transform a point to normalized node space with the center of the node at the origin and the corners at [+/-0.5, +/-0.5] pub fn normalize_point(&self, transform: UiGlobalTransform, point: Vec2) -> Option<Vec2> { self.size .cmpgt(Vec2::ZERO) .all() .then(|| transform.try_inverse()) .flatten() .map(|transform| transform.transform_point2(point) / self.size) } /// Resolve the node's clipping rect in local space pub fn resolve_clip_rect( &self, overflow: Overflow, overflow_clip_margin: OverflowClipMargin, ) -> Rect { let mut clip_rect = Rect::from_center_size(Vec2::ZERO, self.size); let clip_inset = match overflow_clip_margin.visual_box { OverflowClipBox::BorderBox => BorderRect::ZERO, OverflowClipBox::ContentBox => self.content_inset(), OverflowClipBox::PaddingBox => self.border(), }; clip_rect.min += clip_inset.min_inset; clip_rect.max -= clip_inset.max_inset; if overflow.x == OverflowAxis::Visible { clip_rect.min.x = -f32::INFINITY; clip_rect.max.x = f32::INFINITY; } if overflow.y == OverflowAxis::Visible { clip_rect.min.y = -f32::INFINITY; clip_rect.max.y = f32::INFINITY; } clip_rect } /// Returns the node's border-box in object-centered physical coordinates. /// This is the full rectangle enclosing the node. #[inline] pub fn border_box(&self) -> Rect { Rect::from_center_size(Vec2::ZERO, self.size) } /// Returns the node's padding-box in object-centered physical coordinates. /// This is the region inside the border containing the node's padding and content areas. #[inline] pub fn padding_box(&self) -> Rect { let mut out = self.border_box(); out.min += self.border.min_inset; out.max -= self.border.max_inset; out } /// Returns the node's content-box in object-centered physical coordinates. /// This is the innermost region of the node, where its content is placed. #[inline] pub fn content_box(&self) -> Rect { let mut out = self.border_box(); let content_inset = self.content_inset(); out.min += content_inset.min_inset; out.max -= content_inset.max_inset; out } const fn compute_thumb( gutter_min: f32, content_length: f32, gutter_length: f32, scroll_position: f32, ) -> [f32; 2] { if content_length <= gutter_length { return [gutter_min, gutter_min + gutter_length]; } let thumb_len = gutter_length * gutter_length / content_length; let thumb_min = gutter_min + scroll_position * gutter_length / content_length; [thumb_min, thumb_min + thumb_len] } /// Compute the bounds of the horizontal scrollbar and the thumb /// in object-centered coordinates. pub fn horizontal_scrollbar(&self) -> Option<(Rect, [f32; 2])> { if self.scrollbar_size.y <= 0. { return None; } let content_inset = self.content_inset(); let half_size = 0.5 * self.size; let min_x = -half_size.x + content_inset.min_inset.x; let max_x = half_size.x - content_inset.max_inset.x; let min_y = half_size.y - content_inset.max_inset.y; let max_y = min_y + self.scrollbar_size.y; let gutter = Rect { min: Vec2::new(min_x, min_y), max: Vec2::new(max_x, max_y), }; Some(( gutter, Self::compute_thumb( gutter.min.x, self.content_size.x, gutter.size().x, self.scroll_position.x, ), )) } /// Compute the bounds of the vertical scrollbar and the thumb /// in object-centered coordinates. pub fn vertical_scrollbar(&self) -> Option<(Rect, [f32; 2])> { if self.scrollbar_size.x <= 0. { return None; } let content_inset = self.content_inset(); let half_size = 0.5 * self.size; let min_x = half_size.x - content_inset.max_inset.x; let max_x = min_x + self.scrollbar_size.x; let min_y = -half_size.y + content_inset.min_inset.y; let max_y = half_size.y - content_inset.max_inset.y; let gutter = Rect { min: Vec2::new(min_x, min_y), max: Vec2::new(max_x, max_y), }; Some(( gutter, Self::compute_thumb( gutter.min.y, self.content_size.y, gutter.size().y, self.scroll_position.y, ), )) } } impl ComputedNode { pub const DEFAULT: Self = Self { stack_index: 0, size: Vec2::ZERO, content_size: Vec2::ZERO, scrollbar_size: Vec2::ZERO, scroll_position: Vec2::ZERO, outline_width: 0., outline_offset: 0., unrounded_size: Vec2::ZERO, border_radius: ResolvedBorderRadius::ZERO, border: BorderRect::ZERO, padding: BorderRect::ZERO, inverse_scale_factor: 1., }; } impl Default for ComputedNode { fn default() -> Self { Self::DEFAULT } } /// The scroll position of the node. Values are in logical pixels, increasing from top-left to bottom-right. /// /// Increasing the x-coordinate causes the scrolled content to visibly move left on the screen, while increasing the y-coordinate causes the scrolled content to move up. /// This might seem backwards, however what's really happening is that /// the scroll position is moving the visible "window" in the local coordinate system of the scrolled content - /// moving the window down causes the content to move up. /// /// Updating the values of `ScrollPosition` will reposition the children of the node by the offset amount in logical pixels. /// `ScrollPosition` may be updated by the layout system when a layout change makes a previously valid `ScrollPosition` invalid. /// Changing this does nothing on a `Node` without setting at least one `OverflowAxis` to `OverflowAxis::Scroll`. #[derive(Component, Debug, Clone, Default, Deref, DerefMut, Reflect)] #[reflect(Component, Default, Clone)] pub struct ScrollPosition(pub Vec2); impl ScrollPosition { pub const DEFAULT: Self = Self(Vec2::ZERO); } impl From<Vec2> for ScrollPosition { fn from(value: Vec2) -> Self { Self(value) } } /// Controls whether a UI element ignores its parent's [`ScrollPosition`] along specific axes. /// /// When an axis is set to `true`, the node will not have the parent’s scroll position applied /// on that axis. This can be used to keep an element visually fixed along one or both axes /// even when its parent UI element is scrolled. #[derive(Component, Debug, Clone, Default, Deref, DerefMut, Reflect)] #[reflect(Component, Default, Clone)] pub struct IgnoreScroll(pub BVec2); impl From<BVec2> for IgnoreScroll { fn from(value: BVec2) -> Self { Self(value) } } /// The base component for UI entities. It describes UI layout and style properties. /// /// When defining new types of UI entities, require [`Node`] to make them behave like UI nodes. /// /// Nodes can be laid out using either Flexbox or CSS Grid Layout. /// /// See below for general learning resources and for documentation on the individual style properties. /// /// ### Flexbox /// /// - [MDN: Basic Concepts of Flexbox](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox) /// - [A Complete Guide To Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) by CSS Tricks. This is detailed guide with illustrations and comprehensive written explanation of the different Flexbox properties and how they work. /// - [Flexbox Froggy](https://flexboxfroggy.com/). An interactive tutorial/game that teaches the essential parts of Flexbox in a fun engaging way. /// /// ### CSS Grid /// /// - [MDN: Basic Concepts of Grid Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout) /// - [A Complete Guide To CSS Grid](https://css-tricks.com/snippets/css/complete-guide-grid/) by CSS Tricks. This is detailed guide with illustrations and comprehensive written explanation of the different CSS Grid properties and how they work. /// - [CSS Grid Garden](https://cssgridgarden.com/). An interactive tutorial/game that teaches the essential parts of CSS Grid in a fun engaging way. /// /// # See also /// /// - [`RelativeCursorPosition`](crate::RelativeCursorPosition) to obtain the cursor position relative to this node /// - [`Interaction`](crate::Interaction) to obtain the interaction state of this node #[derive(Component, Clone, PartialEq, Debug, Reflect)] #[require( ComputedNode, ComputedUiTargetCamera, ComputedUiRenderTargetInfo, UiTransform, BackgroundColor, BorderColor, FocusPolicy, ScrollPosition, Visibility, ZIndex )] #[reflect(Component, Default, PartialEq, Debug, Clone)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] pub struct Node { /// Which layout algorithm to use when laying out this node's contents: /// - [`Display::Flex`]: Use the Flexbox layout algorithm /// - [`Display::Grid`]: Use the CSS Grid layout algorithm /// - [`Display::None`]: Hide this node and perform layout as if it does not exist. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/display> pub display: Display, /// Which part of a Node's box length styles like width and height control /// - [`BoxSizing::BorderBox`]: They refer to the "border box" size (size including padding and border) /// - [`BoxSizing::ContentBox`]: They refer to the "content box" size (size excluding padding and border) /// /// `BoxSizing::BorderBox` is generally considered more intuitive and is the default in Bevy even though it is not on the web. /// /// See: <https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing> pub box_sizing: BoxSizing, /// Whether a node should be laid out in-flow with, or independently of its siblings: /// - [`PositionType::Relative`]: Layout this node in-flow with other nodes using the usual (flexbox/grid) layout algorithm. /// - [`PositionType::Absolute`]: Layout this node on top and independently of other nodes. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/position> pub position_type: PositionType, /// Whether overflowing content should be displayed or clipped. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/overflow> pub overflow: Overflow, /// How much space in logical pixels should be reserved for scrollbars when overflow is set to scroll or auto on an axis. pub scrollbar_width: f32, /// How the bounds of clipped content should be determined /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-clip-margin> pub overflow_clip_margin: OverflowClipMargin, /// The horizontal position of the left edge of the node. /// - For relatively positioned nodes, this is relative to the node's position as computed during regular layout. /// - For absolutely positioned nodes, this is relative to the *parent* node's bounding box. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/left> pub left: Val, /// The horizontal position of the right edge of the node. /// - For relatively positioned nodes, this is relative to the node's position as computed during regular layout. /// - For absolutely positioned nodes, this is relative to the *parent* node's bounding box. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/right> pub right: Val, /// The vertical position of the top edge of the node. /// - For relatively positioned nodes, this is relative to the node's position as computed during regular layout. /// - For absolutely positioned nodes, this is relative to the *parent* node's bounding box. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/top> pub top: Val, /// The vertical position of the bottom edge of the node. /// - For relatively positioned nodes, this is relative to the node's position as computed during regular layout. /// - For absolutely positioned nodes, this is relative to the *parent* node's bounding box. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/bottom> pub bottom: Val, /// The ideal width of the node. `width` is used when it is within the bounds defined by `min_width` and `max_width`. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/width> pub width: Val, /// The ideal height of the node. `height` is used when it is within the bounds defined by `min_height` and `max_height`. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/height> pub height: Val, /// The minimum width of the node. `min_width` is used if it is greater than `width` and/or `max_width`. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/min-width> pub min_width: Val, /// The minimum height of the node. `min_height` is used if it is greater than `height` and/or `max_height`. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/min-height> pub min_height: Val, /// The maximum width of the node. `max_width` is used if it is within the bounds defined by `min_width` and `width`. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/max-width> pub max_width: Val, /// The maximum height of the node. `max_height` is used if it is within the bounds defined by `min_height` and `height`. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/max-height> pub max_height: Val, /// The aspect ratio of the node (defined as `width / height`) /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio> pub aspect_ratio: Option<f32>, /// Used to control how each individual item is aligned by default within the space they're given. /// - For Flexbox containers, sets default cross axis alignment of the child items. /// - For CSS Grid containers, controls block (vertical) axis alignment of children of this grid container within their grid areas. /// /// This value is overridden if [`AlignSelf`] on the child node is set. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/align-items> pub align_items: AlignItems, /// Used to control how each individual item is aligned by default within the space they're given. /// - For Flexbox containers, this property has no effect. See `justify_content` for main axis alignment of flex items. /// - For CSS Grid containers, sets default inline (horizontal) axis alignment of child items within their grid areas. /// /// This value is overridden if [`JustifySelf`] on the child node is set. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items> pub justify_items: JustifyItems, /// Used to control how the specified item is aligned within the space it's given. /// - For Flexbox items, controls cross axis alignment of the item. /// - For CSS Grid items, controls block (vertical) axis alignment of a grid item within its grid area. /// /// If set to `Auto`, alignment is inherited from the value of [`AlignItems`] set on the parent node. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/align-self> pub align_self: AlignSelf, /// Used to control how the specified item is aligned within the space it's given. /// - For Flexbox items, this property has no effect. See `justify_content` for main axis alignment of flex items. /// - For CSS Grid items, controls inline (horizontal) axis alignment of a grid item within its grid area. /// /// If set to `Auto`, alignment is inherited from the value of [`JustifyItems`] set on the parent node. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/justify-self> pub justify_self: JustifySelf, /// Used to control how items are distributed. /// - For Flexbox containers, controls alignment of lines if `flex_wrap` is set to [`FlexWrap::Wrap`] and there are multiple lines of items. /// - For CSS Grid containers, controls alignment of grid rows. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/align-content> pub align_content: AlignContent, /// Used to control how items are distributed. /// - For Flexbox containers, controls alignment of items in the main axis. /// - For CSS Grid containers, controls alignment of grid columns. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content> pub justify_content: JustifyContent, /// The amount of space around a node outside its border. /// /// If a percentage value is used, the percentage is calculated based on the width of the parent node. /// /// # Example /// ``` /// # use bevy_ui::{Node, UiRect, Val}; /// let node = Node { /// margin: UiRect { /// left: Val::Percent(10.), /// right: Val::Percent(10.), /// top: Val::Percent(15.), /// bottom: Val::Percent(15.) /// }, /// ..Default::default() /// }; /// ``` /// A node with this style and a parent with dimensions of 100px by 300px will have calculated margins of 10px on both left and right edges, and 15px on both top and bottom edges. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/margin> pub margin: UiRect, /// The amount of space between the edges of a node and its contents. /// /// If a percentage value is used, the percentage is calculated based on the width of the parent node. /// /// # Example /// ``` /// # use bevy_ui::{Node, UiRect, Val}; /// let node = Node { /// padding: UiRect { /// left: Val::Percent(1.), /// right: Val::Percent(2.), /// top: Val::Percent(3.), /// bottom: Val::Percent(4.) /// }, /// ..Default::default() /// }; /// ``` /// A node with this style and a parent with dimensions of 300px by 100px will have calculated padding of 3px on the left, 6px on the right, 9px on the top and 12px on the bottom. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/padding> pub padding: UiRect, /// The amount of space between the margins of a node and its padding. /// /// If a percentage value is used, the percentage is calculated based on the width of the parent node. /// /// The size of the node will be expanded if there are constraints that prevent the layout algorithm from placing the border within the existing node boundary. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-width> pub border: UiRect, /// Used to add rounded corners to a UI node. You can set a UI node to have uniformly /// rounded corners or specify different radii for each corner. If a given radius exceeds half /// the length of the smallest dimension between the node's height or width, the radius will /// calculated as half the smallest dimension. /// /// Elliptical nodes are not supported yet. Percentage values are based on the node's smallest /// dimension, either width or height. /// /// # Example /// ```rust /// # use bevy_ecs::prelude::*; /// # use bevy_ui::prelude::*; /// # use bevy_color::palettes::basic::{BLUE}; /// fn setup_ui(mut commands: Commands) { /// commands.spawn(( /// Node { /// width: Val::Px(100.), /// height: Val::Px(100.), /// border: UiRect::all(Val::Px(2.)), /// border_radius: BorderRadius::new( /// // top left /// Val::Px(10.), /// // top right /// Val::Px(20.), /// // bottom right /// Val::Px(30.), /// // bottom left /// Val::Px(40.), /// ), /// ..Default::default() /// }, /// BackgroundColor(BLUE.into()), /// )); /// } /// ``` /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius> pub border_radius: BorderRadius, /// Whether a Flexbox container should be a row or a column. This property has no effect on Grid nodes. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/flex-direction> pub flex_direction: FlexDirection, /// Whether a Flexbox container should wrap its contents onto multiple lines if they overflow. This property has no effect on Grid nodes. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/flex-wrap> pub flex_wrap: FlexWrap, /// Defines how much a flexbox item should grow if there's space available. Defaults to 0 (don't grow at all). /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/flex-grow> pub flex_grow: f32, /// Defines how much a flexbox item should shrink if there's not enough space available. Defaults to 1. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/flex-shrink> pub flex_shrink: f32, /// The initial length of a flexbox in the main axis, before flex growing/shrinking properties are applied. /// /// `flex_basis` overrides `width` (if the main axis is horizontal) or `height` (if the main axis is vertical) when both are set, but it obeys the constraints defined by `min_width`/`min_height` and `max_width`/`max_height`. /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/flex-basis> pub flex_basis: Val,
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/picking_backend.rs
crates/bevy_ui/src/picking_backend.rs
//! A picking backend for UI nodes. //! //! # Usage //! //! This backend does not require markers on cameras or entities to function. It will look for any //! pointers using the same render target as the UI camera, and run hit tests on the UI node tree. //! //! ## Important Note //! //! This backend completely ignores [`FocusPolicy`](crate::FocusPolicy). The design of `bevy_ui`'s //! focus systems and the picking plugin are not compatible. Instead, use the optional [`Pickable`] component //! to override how an entity responds to picking focus. Nodes without the [`Pickable`] component //! will still trigger events and block items below it from being hovered. //! //! ## Implementation Notes //! //! - `bevy_ui` can render on any camera with a flag, it is special, and is not tied to a particular //! camera. //! - To correctly sort picks, the order of `bevy_ui` is set to be the camera order plus 0.5. //! - The `position` reported in `HitData` is normalized relative to the node, with //! `(-0.5, -0.5, 0.)` at the top left and `(0.5, 0.5, 0.)` in the bottom right. Coordinates are //! relative to the entire node, not just the visible region. This backend does not provide a `normal`. #![deny(missing_docs)] use crate::{clip_check_recursive, prelude::*, ui_transform::UiGlobalTransform, UiStack}; use bevy_app::prelude::*; use bevy_camera::{visibility::InheritedVisibility, Camera, RenderTarget}; use bevy_ecs::{prelude::*, query::QueryData}; use bevy_math::Vec2; use bevy_platform::collections::HashMap; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_text::{ComputedTextBlock, TextLayoutInfo}; use bevy_window::PrimaryWindow; use bevy_picking::backend::prelude::*; /// An optional component that marks cameras that should be used in the [`UiPickingPlugin`]. /// /// Only needed if [`UiPickingSettings::require_markers`] is set to `true`, and ignored /// otherwise. #[derive(Debug, Clone, Default, Component, Reflect)] #[reflect(Debug, Default, Component)] pub struct UiPickingCamera; /// Runtime settings for the [`UiPickingPlugin`]. #[derive(Resource, Reflect)] #[reflect(Resource, Default)] pub struct UiPickingSettings { /// When set to `true` UI picking will only consider cameras marked with /// [`UiPickingCamera`] and entities marked with [`Pickable`]. `false` by default. /// /// This setting is provided to give you fine-grained control over which cameras and entities /// should be used by the UI picking backend at runtime. pub require_markers: bool, } #[expect( clippy::allow_attributes, reason = "clippy::derivable_impls is not always linted" )] #[allow( clippy::derivable_impls, reason = "Known false positive with clippy: <https://github.com/rust-lang/rust-clippy/issues/13160>" )] impl Default for UiPickingSettings { fn default() -> Self { Self { require_markers: false, } } } /// A plugin that adds picking support for UI nodes. /// /// This is included by default in [`UiPlugin`](crate::UiPlugin). #[derive(Clone)] pub struct UiPickingPlugin; impl Plugin for UiPickingPlugin { fn build(&self, app: &mut App) { app.init_resource::<UiPickingSettings>() .add_systems(PreUpdate, ui_picking.in_set(PickingSystems::Backend)); } } /// Main query from bevy's `ui_focus_system` #[derive(QueryData)] #[query_data(mutable)] pub struct NodeQuery { entity: Entity, node: &'static ComputedNode, transform: &'static UiGlobalTransform, pickable: Option<&'static Pickable>, inherited_visibility: Option<&'static InheritedVisibility>, target_camera: &'static ComputedUiTargetCamera, text_node: Option<(&'static TextLayoutInfo, &'static ComputedTextBlock)>, } /// Computes the UI node entities under each pointer. /// /// Bevy's [`UiStack`] orders all nodes in the order they will be rendered, which is the same order /// we need for determining picking. pub fn ui_picking( pointers: Query<(&PointerId, &PointerLocation)>, camera_query: Query<(Entity, &Camera, &RenderTarget, Has<UiPickingCamera>)>, primary_window: Query<Entity, With<PrimaryWindow>>, settings: Res<UiPickingSettings>, ui_stack: Res<UiStack>, node_query: Query<NodeQuery>, mut output: MessageWriter<PointerHits>, clipping_query: Query<(&ComputedNode, &UiGlobalTransform, &Node)>, child_of_query: Query<&ChildOf, Without<OverrideClip>>, pickable_query: Query<&Pickable>, ) { // Map from each camera to its active pointers and their positions in viewport space let mut pointer_pos_by_camera = HashMap::<Entity, HashMap<PointerId, Vec2>>::default(); for (pointer_id, pointer_location) in pointers.iter().filter_map(|(pointer, pointer_location)| { Some(*pointer).zip(pointer_location.location().cloned()) }) { // This pointer is associated with a render target, which could be used by multiple // cameras. We want to ensure we return all cameras with a matching target. for (entity, camera, _, _) in camera_query .iter() .filter(|(_, _, render_target, cam_can_pick)| { (!settings.require_markers || *cam_can_pick) && render_target .normalize(primary_window.single().ok()) .is_some_and(|target| target == pointer_location.target) }) { let mut pointer_pos = pointer_location.position * camera.target_scaling_factor().unwrap_or(1.); if let Some(viewport) = camera.physical_viewport_rect() { if !viewport.as_rect().contains(pointer_pos) { // The pointer is outside the viewport, skip it continue; } pointer_pos -= viewport.min.as_vec2(); } pointer_pos_by_camera .entry(entity) .or_default() .insert(pointer_id, pointer_pos); } } // The list of node entities hovered for each (camera, pointer) combo let mut hit_nodes = HashMap::<(Entity, PointerId), Vec<(Entity, Entity, Option<Pickable>, Vec2)>>::default(); // prepare an iterator that contains all the nodes that have the cursor in their rect, // from the top node to the bottom one. this will also reset the interaction to `None` // for all nodes encountered that are no longer hovered. // Reverse the iterator to traverse the tree from closest slice to furthest for uinodes in ui_stack .partition .iter() .rev() .map(|range| &ui_stack.uinodes[range.clone()]) { // Retrieve the first node and resolve its camera target. // Only need to do this once per slice, as all the nodes in the same slice share the same camera. let Ok(uinode) = node_query.get(uinodes[0]) else { continue; }; let Some(camera_entity) = uinode.target_camera.get() else { continue; }; let Some(pointers_on_this_cam) = pointer_pos_by_camera.get(&camera_entity) else { continue; }; // Reverse the iterator to traverse the tree from closest nodes to furthest for node_entity in uinodes.iter().rev().cloned() { let Ok(node) = node_query.get(node_entity) else { continue; }; // Nodes with Display::None have a (0., 0.) logical rect and can be ignored if node.node.size() == Vec2::ZERO { continue; } // Nodes that are not rendered should not be interactable if node .inherited_visibility .map(|inherited_visibility| inherited_visibility.get()) != Some(true) { continue; } // If this is a text node, need to do this check per section. if node.text_node.is_none() && settings.require_markers && node.pickable.is_none() { continue; } // Find the normalized cursor position relative to the node. // (±0., 0.) is the center with the corners at points (±0.5, ±0.5). // Coordinates are relative to the entire node, not just the visible region. for (pointer_id, cursor_position) in pointers_on_this_cam.iter() { if let Some((text_layout_info, text_block)) = node.text_node { if let Some(text_entity) = pick_ui_text_section( node.node, node.transform, *cursor_position, text_layout_info, text_block, ) { if settings.require_markers && !pickable_query.contains(text_entity) { continue; } hit_nodes .entry((camera_entity, *pointer_id)) .or_default() .push(( text_entity, camera_entity, node.pickable.cloned(), node.transform.inverse().transform_point2(*cursor_position) / node.node.size(), )); } } else if node.node.contains_point(*node.transform, *cursor_position) && clip_check_recursive( *cursor_position, node_entity, &clipping_query, &child_of_query, ) { hit_nodes .entry((camera_entity, *pointer_id)) .or_default() .push(( node_entity, camera_entity, node.pickable.cloned(), node.transform.inverse().transform_point2(*cursor_position) / node.node.size(), )); } } } } for ((camera, pointer), hovered) in hit_nodes.iter() { // As soon as a node with a `Block` focus policy is detected, the iteration will stop on it // because it "captures" the interaction. let mut picks = Vec::new(); let mut depth = 0.0; for (hovered_node, camera_entity, pickable, position) in hovered { picks.push(( *hovered_node, HitData::new(*camera_entity, depth, Some(position.extend(0.0)), None), )); if let Some(pickable) = pickable { // If an entity has a `Pickable` component, we will use that as the source of truth. if pickable.should_block_lower { break; } } else { // If the `Pickable` component doesn't exist, default behavior is to block. break; } depth += 0.00001; // keep depth near 0 for precision } let order = camera_query .get(*camera) .map(|(_, cam, _, _)| cam.order) .unwrap_or_default() as f32 + 0.5; // bevy ui can run on any camera, it's a special case output.write(PointerHits::new(*pointer, picks, order)); } } fn pick_ui_text_section( uinode: &ComputedNode, global_transform: &UiGlobalTransform, point: Vec2, text_layout_info: &TextLayoutInfo, text_block: &ComputedTextBlock, ) -> Option<Entity> { let local_point = global_transform .try_inverse() .map(|transform| transform.transform_point2(point) + 0.5 * uinode.size())?; for run in text_layout_info.run_geometry.iter() { if run.bounds.contains(local_point) { return text_block.entities().get(run.span_index).map(|e| e.entity); } } None }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/interaction_states.rs
crates/bevy_ui/src/interaction_states.rs
/// This module contains components that are used to track the interaction state of UI widgets. use bevy_a11y::AccessibilityNode; use bevy_ecs::{ component::Component, lifecycle::{Add, Remove}, observer::On, world::DeferredWorld, }; /// A component indicating that a widget is disabled and should be "grayed out". /// This is used to prevent user interaction with the widget. It should not, however, prevent /// the widget from being updated or rendered, or from acquiring keyboard focus. /// /// For apps which support a11y: if a widget (such as a slider) contains multiple entities, /// the `InteractionDisabled` component should be added to the root entity of the widget - the /// same entity that contains the `AccessibilityNode` component. This will ensure that /// the a11y tree is updated correctly. #[derive(Component, Debug, Clone, Copy, Default)] pub struct InteractionDisabled; pub(crate) fn on_add_disabled(add: On<Add, InteractionDisabled>, mut world: DeferredWorld) { let mut entity = world.entity_mut(add.entity); if let Some(mut accessibility) = entity.get_mut::<AccessibilityNode>() { accessibility.set_disabled(); } } pub(crate) fn on_remove_disabled( remove: On<Remove, InteractionDisabled>, mut world: DeferredWorld, ) { let mut entity = world.entity_mut(remove.entity); if let Some(mut accessibility) = entity.get_mut::<AccessibilityNode>() { accessibility.clear_disabled(); } } /// Component that indicates whether a button or widget is currently in a pressed or "held down" /// state. #[derive(Component, Debug, Clone, Copy, Default)] pub struct Pressed; /// Component that indicates that a widget can be checked. #[derive(Component, Debug, Clone, Copy, Default)] pub struct Checkable; /// Component that indicates whether a checkbox or radio button is in a checked state. #[derive(Component, Debug, Clone, Copy, Default)] pub struct Checked; pub(crate) fn on_add_checkable(add: On<Add, Checked>, mut world: DeferredWorld) { let mut entity = world.entity_mut(add.entity); let checked = entity.get::<Checked>().is_some(); if let Some(mut accessibility) = entity.get_mut::<AccessibilityNode>() { accessibility.set_toggled(match checked { true => accesskit::Toggled::True, false => accesskit::Toggled::False, }); } } pub(crate) fn on_remove_checkable(add: On<Add, Checked>, mut world: DeferredWorld) { // Remove the 'toggled' attribute entirely. let mut entity = world.entity_mut(add.entity); if let Some(mut accessibility) = entity.get_mut::<AccessibilityNode>() { accessibility.clear_toggled(); } } pub(crate) fn on_add_checked(add: On<Add, Checked>, mut world: DeferredWorld) { let mut entity = world.entity_mut(add.entity); if let Some(mut accessibility) = entity.get_mut::<AccessibilityNode>() { accessibility.set_toggled(accesskit::Toggled::True); } } pub(crate) fn on_remove_checked(remove: On<Remove, Checked>, mut world: DeferredWorld) { let mut entity = world.entity_mut(remove.entity); if let Some(mut accessibility) = entity.get_mut::<AccessibilityNode>() { accessibility.set_toggled(accesskit::Toggled::False); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/stack.rs
crates/bevy_ui/src/stack.rs
//! This module contains the systems that update the stored UI nodes stack use crate::{ experimental::{UiChildren, UiRootNodes}, ComputedNode, GlobalZIndex, ZIndex, }; use bevy_ecs::prelude::*; use bevy_platform::collections::HashSet; use core::ops::Range; /// The current UI stack, which contains all UI nodes ordered by their depth (back-to-front). /// /// The first entry is the furthest node from the camera and is the first one to get rendered /// while the last entry is the first node to receive interactions. #[derive(Debug, Resource, Default)] pub struct UiStack { /// Partition of the `uinodes` list into disjoint slices of nodes that all share the same camera target. pub partition: Vec<Range<usize>>, /// List of UI nodes ordered from back-to-front pub uinodes: Vec<Entity>, } #[derive(Default)] pub(crate) struct ChildBufferCache { pub inner: Vec<Vec<(Entity, i32)>>, } impl ChildBufferCache { fn pop(&mut self) -> Vec<(Entity, i32)> { self.inner.pop().unwrap_or_default() } fn push(&mut self, vec: Vec<(Entity, i32)>) { self.inner.push(vec); } } /// Generates the render stack for UI nodes. /// /// 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<GlobalZIndex>`so that we don't revisit nodes. pub fn ui_stack_system( mut cache: Local<ChildBufferCache>, mut root_nodes: Local<Vec<(Entity, (i32, i32))>>, mut visited_root_nodes: Local<HashSet<Entity>>, mut ui_stack: ResMut<UiStack>, ui_root_nodes: UiRootNodes, root_node_query: Query<(Entity, Option<&GlobalZIndex>, Option<&ZIndex>)>, zindex_global_node_query: Query<(Entity, &GlobalZIndex, Option<&ZIndex>), With<ComputedNode>>, ui_children: UiChildren, zindex_query: Query<Option<&ZIndex>, (With<ComputedNode>, Without<GlobalZIndex>)>, mut update_query: Query<&mut ComputedNode>, ) { ui_stack.partition.clear(); ui_stack.uinodes.clear(); visited_root_nodes.clear(); for (id, maybe_global_zindex, maybe_zindex) in root_node_query.iter_many(ui_root_nodes.iter()) { root_nodes.push(( id, ( maybe_global_zindex.map(|zindex| zindex.0).unwrap_or(0), maybe_zindex.map(|zindex| zindex.0).unwrap_or(0), ), )); visited_root_nodes.insert(id); } for (id, global_zindex, maybe_zindex) in zindex_global_node_query.iter() { if visited_root_nodes.contains(&id) { continue; } root_nodes.push(( id, ( global_zindex.0, maybe_zindex.map(|zindex| zindex.0).unwrap_or(0), ), )); } root_nodes.sort_by_key(|(_, z)| *z); for (root_entity, _) in root_nodes.drain(..) { let start = ui_stack.uinodes.len(); update_uistack_recursive( &mut cache, root_entity, &ui_children, &zindex_query, &mut ui_stack.uinodes, ); let end = ui_stack.uinodes.len(); ui_stack.partition.push(start..end); } for (i, entity) in ui_stack.uinodes.iter().enumerate() { if let Ok(mut node) = update_query.get_mut(*entity) { node.bypass_change_detection().stack_index = i as u32; } } } fn update_uistack_recursive( cache: &mut ChildBufferCache, node_entity: Entity, ui_children: &UiChildren, zindex_query: &Query<Option<&ZIndex>, (With<ComputedNode>, Without<GlobalZIndex>)>, ui_stack: &mut Vec<Entity>, ) { ui_stack.push(node_entity); let mut child_buffer = cache.pop(); child_buffer.extend( ui_children .iter_ui_children(node_entity) .filter_map(|child_entity| { zindex_query .get(child_entity) .ok() .map(|zindex| (child_entity, zindex.map(|zindex| zindex.0).unwrap_or(0))) }), ); child_buffer.sort_by_key(|k| k.1); for (child_entity, _) in child_buffer.drain(..) { update_uistack_recursive(cache, child_entity, ui_children, zindex_query, ui_stack); } cache.push(child_buffer); } #[cfg(test)] mod tests { use bevy_ecs::{ component::Component, schedule::Schedule, system::Commands, world::{CommandQueue, World}, }; use crate::{GlobalZIndex, Node, UiStack, ZIndex}; use super::ui_stack_system; #[derive(Component, PartialEq, Debug, Clone)] struct Label(&'static str); fn node_with_global_and_local_zindex( name: &'static str, global_zindex: i32, local_zindex: i32, ) -> (Label, Node, GlobalZIndex, ZIndex) { ( Label(name), Node::default(), GlobalZIndex(global_zindex), ZIndex(local_zindex), ) } fn node_with_global_zindex( name: &'static str, global_zindex: i32, ) -> (Label, Node, GlobalZIndex) { (Label(name), Node::default(), GlobalZIndex(global_zindex)) } fn node_with_zindex(name: &'static str, zindex: i32) -> (Label, Node, ZIndex) { (Label(name), Node::default(), ZIndex(zindex)) } fn node_without_zindex(name: &'static str) -> (Label, Node) { (Label(name), Node::default()) } /// Tests the UI Stack system. /// /// This tests for siblings default ordering according to their insertion order, but it /// can't test the same thing for UI roots. UI roots having no parents, they do not have /// a stable ordering that we can test against. If we test it, it may pass now and start /// failing randomly in the future because of some unrelated `bevy_ecs` change. #[test] fn test_ui_stack_system() { let mut world = World::default(); world.init_resource::<UiStack>(); let mut queue = CommandQueue::default(); let mut commands = Commands::new(&mut queue, &world); commands.spawn(node_with_global_zindex("0", 2)); commands .spawn(node_with_zindex("1", 1)) .with_children(|parent| { parent .spawn(node_without_zindex("1-0")) .with_children(|parent| { parent.spawn(node_without_zindex("1-0-0")); parent.spawn(node_without_zindex("1-0-1")); parent.spawn(node_with_zindex("1-0-2", -1)); }); parent.spawn(node_without_zindex("1-1")); parent .spawn(node_with_global_zindex("1-2", -1)) .with_children(|parent| { parent.spawn(node_without_zindex("1-2-0")); parent.spawn(node_with_global_zindex("1-2-1", -3)); parent .spawn(node_without_zindex("1-2-2")) .with_children(|_| ()); parent.spawn(node_without_zindex("1-2-3")); }); parent.spawn(node_without_zindex("1-3")); }); commands .spawn(node_without_zindex("2")) .with_children(|parent| { parent .spawn(node_without_zindex("2-0")) .with_children(|_parent| ()); parent .spawn(node_without_zindex("2-1")) .with_children(|parent| { parent.spawn(node_without_zindex("2-1-0")); }); }); commands.spawn(node_with_global_zindex("3", -2)); queue.apply(&mut world); let mut schedule = Schedule::default(); schedule.add_systems(ui_stack_system); schedule.run(&mut world); let mut query = world.query::<&Label>(); let ui_stack = world.resource::<UiStack>(); let actual_result = ui_stack .uinodes .iter() .map(|entity| query.get(&world, *entity).unwrap().clone()) .collect::<Vec<_>>(); let expected_result = vec![ (Label("1-2-1")), // GlobalZIndex(-3) (Label("3")), // GlobalZIndex(-2) (Label("1-2")), // GlobalZIndex(-1) (Label("1-2-0")), (Label("1-2-2")), (Label("1-2-3")), (Label("2")), (Label("2-0")), (Label("2-1")), (Label("2-1-0")), (Label("1")), // ZIndex(1) (Label("1-0")), (Label("1-0-2")), // ZIndex(-1) (Label("1-0-0")), (Label("1-0-1")), (Label("1-1")), (Label("1-3")), (Label("0")), // GlobalZIndex(2) ]; assert_eq!(actual_result, expected_result); // Test partitioning let last_part = ui_stack.partition.last().unwrap(); assert_eq!(last_part.len(), 1); let last_entity = ui_stack.uinodes[last_part.start]; assert_eq!(*query.get(&world, last_entity).unwrap(), Label("0")); let actual_result = ui_stack.uinodes[ui_stack.partition[4].clone()] .iter() .map(|entity| query.get(&world, *entity).unwrap().clone()) .collect::<Vec<_>>(); let expected_result = vec![ (Label("1")), // ZIndex(1) (Label("1-0")), (Label("1-0-2")), // ZIndex(-1) (Label("1-0-0")), (Label("1-0-1")), (Label("1-1")), (Label("1-3")), ]; assert_eq!(actual_result, expected_result); } #[test] fn test_with_equal_global_zindex_zindex_decides_order() { let mut world = World::default(); world.init_resource::<UiStack>(); let mut queue = CommandQueue::default(); let mut commands = Commands::new(&mut queue, &world); commands.spawn(node_with_global_and_local_zindex("0", -1, 1)); commands.spawn(node_with_global_and_local_zindex("1", -1, 2)); commands.spawn(node_with_global_and_local_zindex("2", 1, 3)); commands.spawn(node_with_global_and_local_zindex("3", 1, -3)); commands .spawn(node_without_zindex("4")) .with_children(|builder| { builder.spawn(node_with_global_and_local_zindex("5", 0, -1)); builder.spawn(node_with_global_and_local_zindex("6", 0, 1)); builder.spawn(node_with_global_and_local_zindex("7", -1, -1)); builder.spawn(node_with_global_zindex("8", 1)); }); queue.apply(&mut world); let mut schedule = Schedule::default(); schedule.add_systems(ui_stack_system); schedule.run(&mut world); let mut query = world.query::<&Label>(); let ui_stack = world.resource::<UiStack>(); let actual_result = ui_stack .uinodes .iter() .map(|entity| query.get(&world, *entity).unwrap().clone()) .collect::<Vec<_>>(); let expected_result = vec![ (Label("7")), (Label("0")), (Label("1")), (Label("5")), (Label("4")), (Label("6")), (Label("3")), (Label("8")), (Label("2")), ]; assert_eq!(actual_result, expected_result); assert_eq!(ui_stack.partition.len(), expected_result.len()); for (i, part) in ui_stack.partition.iter().enumerate() { assert_eq!(*part, i..i + 1); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/accessibility.rs
crates/bevy_ui/src/accessibility.rs
use crate::{ experimental::UiChildren, prelude::{Button, Label}, ui_transform::UiGlobalTransform, widget::{ImageNode, TextUiReader}, ComputedNode, }; use bevy_a11y::AccessibilityNode; use bevy_app::{App, Plugin, PostUpdate}; use bevy_ecs::{ prelude::{DetectChanges, Entity}, query::{Changed, Without}, schedule::IntoScheduleConfigs, system::{Commands, Query}, world::Ref, }; use accesskit::{Node, Rect, Role}; use bevy_camera::CameraUpdateSystems; fn calc_label( text_reader: &mut TextUiReader, children: impl Iterator<Item = Entity>, ) -> Option<Box<str>> { let mut name = None; for child in children { let values = text_reader .iter(child) .map(|(_, _, text, _, _, _)| text.into()) .collect::<Vec<String>>(); if !values.is_empty() { name = Some(values.join(" ")); } } name.map(String::into_boxed_str) } fn calc_bounds( mut nodes: Query<( &mut AccessibilityNode, Ref<ComputedNode>, Ref<UiGlobalTransform>, )>, ) { for (mut accessible, node, transform) in &mut nodes { if node.is_changed() || transform.is_changed() { let center = transform.translation; let half_size = 0.5 * node.size; let min = center - half_size; let max = center + half_size; let bounds = Rect::new(min.x as f64, min.y as f64, max.x as f64, max.y as f64); accessible.set_bounds(bounds); } } } fn button_changed( mut commands: Commands, mut query: Query<(Entity, Option<&mut AccessibilityNode>), Changed<Button>>, ui_children: UiChildren, mut text_reader: TextUiReader, ) { for (entity, accessible) in &mut query { let label = calc_label(&mut text_reader, ui_children.iter_ui_children(entity)); if let Some(mut accessible) = accessible { accessible.set_role(Role::Button); if let Some(name) = label { accessible.set_label(name); } else { accessible.clear_label(); } } else { let mut node = Node::new(Role::Button); if let Some(label) = label { node.set_label(label); } commands .entity(entity) .try_insert(AccessibilityNode::from(node)); } } } fn image_changed( mut commands: Commands, mut query: Query< (Entity, Option<&mut AccessibilityNode>), (Changed<ImageNode>, Without<Button>), >, ui_children: UiChildren, mut text_reader: TextUiReader, ) { for (entity, accessible) in &mut query { let label = calc_label(&mut text_reader, ui_children.iter_ui_children(entity)); if let Some(mut accessible) = accessible { accessible.set_role(Role::Image); if let Some(label) = label { accessible.set_label(label); } else { accessible.clear_label(); } } else { let mut node = Node::new(Role::Image); if let Some(label) = label { node.set_label(label); } commands .entity(entity) .try_insert(AccessibilityNode::from(node)); } } } fn label_changed( mut commands: Commands, mut query: Query<(Entity, Option<&mut AccessibilityNode>), Changed<Label>>, mut text_reader: TextUiReader, ) { for (entity, accessible) in &mut query { let values = text_reader .iter(entity) .map(|(_, _, text, _, _, _)| text.into()) .collect::<Vec<String>>(); let label = Some(values.join(" ").into_boxed_str()); if let Some(mut accessible) = accessible { accessible.set_role(Role::Label); if let Some(label) = label { accessible.set_value(label); } else { accessible.clear_value(); } } else { let mut node = Node::new(Role::Label); if let Some(label) = label { node.set_value(label); } commands .entity(entity) .try_insert(AccessibilityNode::from(node)); } } } /// `AccessKit` integration for `bevy_ui`. pub(crate) struct AccessibilityPlugin; impl Plugin for AccessibilityPlugin { fn build(&self, app: &mut App) { app.add_systems( PostUpdate, ( calc_bounds .after(bevy_transform::TransformSystems::Propagate) .after(CameraUpdateSystems) // the listed systems do not affect calculated size .ambiguous_with(crate::ui_stack_system), button_changed, image_changed, label_changed, ), ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/gradients.rs
crates/bevy_ui/src/gradients.rs
use crate::{UiPosition, Val}; use bevy_color::{Color, Srgba}; use bevy_ecs::{component::Component, reflect::ReflectComponent}; use bevy_math::Vec2; use bevy_reflect::prelude::*; use bevy_utils::default; use core::{f32, f32::consts::TAU}; /// A color stop for a gradient #[derive(Debug, Copy, Clone, PartialEq, Reflect)] #[reflect(Default, PartialEq, Debug)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] pub struct ColorStop { /// Color pub color: Color, /// Logical position along the gradient line. /// Stop positions are relative to the start of the gradient and not other stops. pub point: Val, /// Normalized position between this and the following stop of the interpolation midpoint. pub hint: f32, } impl ColorStop { /// Create a new color stop pub fn new(color: impl Into<Color>, point: Val) -> Self { Self { color: color.into(), point, hint: 0.5, } } /// An automatic color stop. /// The positions of automatic stops are interpolated evenly between explicit stops. pub fn auto(color: impl Into<Color>) -> Self { Self { color: color.into(), point: Val::Auto, hint: 0.5, } } /// A color stop with its position in logical pixels. pub fn px(color: impl Into<Color>, px: f32) -> Self { Self { color: color.into(), point: Val::Px(px), hint: 0.5, } } /// A color stop with a percentage position. pub fn percent(color: impl Into<Color>, percent: f32) -> Self { Self { color: color.into(), point: Val::Percent(percent), hint: 0.5, } } // Set the interpolation midpoint between this and the following stop pub const fn with_hint(mut self, hint: f32) -> Self { self.hint = hint; self } } impl From<(Color, Val)> for ColorStop { fn from((color, stop): (Color, Val)) -> Self { Self { color, point: stop, hint: 0.5, } } } impl From<Color> for ColorStop { fn from(color: Color) -> Self { Self { color, point: Val::Auto, hint: 0.5, } } } impl From<Srgba> for ColorStop { fn from(color: Srgba) -> Self { Self { color: color.into(), point: Val::Auto, hint: 0.5, } } } impl Default for ColorStop { fn default() -> Self { Self { color: Color::WHITE, point: Val::Auto, hint: 0.5, } } } /// An angular color stop for a conic gradient #[derive(Debug, Copy, Clone, PartialEq, Reflect)] #[reflect(Default, PartialEq, Debug)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] pub struct AngularColorStop { /// Color of the stop pub color: Color, /// The angle of the stop. /// Angles are relative to the start of the gradient and not other stops. /// If set to `None` the angle of the stop will be interpolated between the explicit stops or 0 and 2 PI degrees if there no explicit stops. /// Given angles are clamped to between `0.`, and [`TAU`]. /// This means that a list of stops: /// ``` /// # use std::f32::consts::TAU; /// # use bevy_ui::AngularColorStop; /// # use bevy_color::{Color, palettes::css::{RED, BLUE}}; /// let stops = [ /// AngularColorStop::new(Color::WHITE, 0.), /// AngularColorStop::new(Color::BLACK, -1.), /// AngularColorStop::new(RED, 2. * TAU), /// AngularColorStop::new(BLUE, TAU), /// ]; /// ``` /// is equivalent to: /// ``` /// # use std::f32::consts::TAU; /// # use bevy_ui::AngularColorStop; /// # use bevy_color::{Color, palettes::css::{RED, BLUE}}; /// let stops = [ /// AngularColorStop::new(Color::WHITE, 0.), /// AngularColorStop::new(Color::BLACK, 0.), /// AngularColorStop::new(RED, TAU), /// AngularColorStop::new(BLUE, TAU), /// ]; /// ``` /// Resulting in a black to red gradient, not white to blue. pub angle: Option<f32>, /// Normalized angle between this and the following stop of the interpolation midpoint. pub hint: f32, } impl AngularColorStop { // Create a new color stop pub fn new(color: impl Into<Color>, angle: f32) -> Self { Self { color: color.into(), angle: Some(angle), hint: 0.5, } } /// An angular stop without an explicit angle. The angles of automatic stops /// are interpolated evenly between explicit stops. pub fn auto(color: impl Into<Color>) -> Self { Self { color: color.into(), angle: None, hint: 0.5, } } // Set the interpolation midpoint between this and the following stop pub const fn with_hint(mut self, hint: f32) -> Self { self.hint = hint; self } } impl From<(Color, f32)> for AngularColorStop { fn from((color, angle): (Color, f32)) -> Self { Self { color, angle: Some(angle), hint: 0.5, } } } impl From<Color> for AngularColorStop { fn from(color: Color) -> Self { Self { color, angle: None, hint: 0.5, } } } impl From<Srgba> for AngularColorStop { fn from(color: Srgba) -> Self { Self { color: color.into(), angle: None, hint: 0.5, } } } impl Default for AngularColorStop { fn default() -> Self { Self { color: Color::WHITE, angle: None, hint: 0.5, } } } /// A linear gradient /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient> #[derive(Default, Clone, PartialEq, Debug, Reflect)] #[reflect(PartialEq)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] pub struct LinearGradient { /// The color space used for interpolation. pub color_space: InterpolationColorSpace, /// The direction of the gradient in radians. /// An angle of `0.` points upward, with the value increasing in the clockwise direction. pub angle: f32, /// The list of color stops pub stops: Vec<ColorStop>, } impl LinearGradient { /// Angle of a linear gradient transitioning from bottom to top pub const TO_TOP: f32 = 0.; /// Angle of a linear gradient transitioning from bottom-left to top-right pub const TO_TOP_RIGHT: f32 = TAU / 8.; /// Angle of a linear gradient transitioning from left to right pub const TO_RIGHT: f32 = 2. * Self::TO_TOP_RIGHT; /// Angle of a linear gradient transitioning from top-left to bottom-right pub const TO_BOTTOM_RIGHT: f32 = 3. * Self::TO_TOP_RIGHT; /// Angle of a linear gradient transitioning from top to bottom pub const TO_BOTTOM: f32 = 4. * Self::TO_TOP_RIGHT; /// Angle of a linear gradient transitioning from top-right to bottom-left pub const TO_BOTTOM_LEFT: f32 = 5. * Self::TO_TOP_RIGHT; /// Angle of a linear gradient transitioning from right to left pub const TO_LEFT: f32 = 6. * Self::TO_TOP_RIGHT; /// Angle of a linear gradient transitioning from bottom-right to top-left pub const TO_TOP_LEFT: f32 = 7. * Self::TO_TOP_RIGHT; /// Create a new linear gradient pub fn new(angle: f32, stops: Vec<ColorStop>) -> Self { Self { angle, stops, color_space: InterpolationColorSpace::default(), } } /// A linear gradient transitioning from bottom to top pub fn to_top(stops: Vec<ColorStop>) -> Self { Self { angle: Self::TO_TOP, stops, color_space: InterpolationColorSpace::default(), } } /// A linear gradient transitioning from bottom-left to top-right pub fn to_top_right(stops: Vec<ColorStop>) -> Self { Self { angle: Self::TO_TOP_RIGHT, stops, color_space: InterpolationColorSpace::default(), } } /// A linear gradient transitioning from left to right pub fn to_right(stops: Vec<ColorStop>) -> Self { Self { angle: Self::TO_RIGHT, stops, color_space: InterpolationColorSpace::default(), } } /// A linear gradient transitioning from top-left to bottom-right pub fn to_bottom_right(stops: Vec<ColorStop>) -> Self { Self { angle: Self::TO_BOTTOM_RIGHT, stops, color_space: InterpolationColorSpace::default(), } } /// A linear gradient transitioning from top to bottom pub fn to_bottom(stops: Vec<ColorStop>) -> Self { Self { angle: Self::TO_BOTTOM, stops, color_space: InterpolationColorSpace::default(), } } /// A linear gradient transitioning from top-right to bottom-left pub fn to_bottom_left(stops: Vec<ColorStop>) -> Self { Self { angle: Self::TO_BOTTOM_LEFT, stops, color_space: InterpolationColorSpace::default(), } } /// A linear gradient transitioning from right to left pub fn to_left(stops: Vec<ColorStop>) -> Self { Self { angle: Self::TO_LEFT, stops, color_space: InterpolationColorSpace::default(), } } /// A linear gradient transitioning from bottom-right to top-left pub fn to_top_left(stops: Vec<ColorStop>) -> Self { Self { angle: Self::TO_TOP_LEFT, stops, color_space: InterpolationColorSpace::default(), } } /// A linear gradient with the given angle in degrees pub fn degrees(degrees: f32, stops: Vec<ColorStop>) -> Self { Self { angle: degrees.to_radians(), stops, color_space: InterpolationColorSpace::default(), } } pub fn in_color_space(mut self, color_space: InterpolationColorSpace) -> Self { self.color_space = color_space; self } } /// A radial gradient /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/radial-gradient> #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(PartialEq)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] pub struct RadialGradient { /// The color space used for interpolation. pub color_space: InterpolationColorSpace, /// The center of the radial gradient pub position: UiPosition, /// Defines the end shape of the radial gradient pub shape: RadialGradientShape, /// The list of color stops pub stops: Vec<ColorStop>, } impl RadialGradient { /// Create a new radial gradient pub fn new(position: UiPosition, shape: RadialGradientShape, stops: Vec<ColorStop>) -> Self { Self { color_space: default(), position, shape, stops, } } pub const fn in_color_space(mut self, color_space: InterpolationColorSpace) -> Self { self.color_space = color_space; self } } impl Default for RadialGradient { fn default() -> Self { Self { position: UiPosition::CENTER, shape: RadialGradientShape::ClosestCorner, stops: Vec::new(), color_space: default(), } } } /// A conic gradient /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/conic-gradient> #[derive(Default, Clone, PartialEq, Debug, Reflect)] #[reflect(PartialEq)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] pub struct ConicGradient { /// The color space used for interpolation. pub color_space: InterpolationColorSpace, /// The starting angle of the gradient in radians pub start: f32, /// The center of the conic gradient pub position: UiPosition, /// The list of color stops pub stops: Vec<AngularColorStop>, } impl ConicGradient { /// Create a new conic gradient pub fn new(position: UiPosition, stops: Vec<AngularColorStop>) -> Self { Self { color_space: default(), start: 0., position, stops, } } /// Sets the starting angle of the gradient in radians pub const fn with_start(mut self, start: f32) -> Self { self.start = start; self } /// Sets the position of the gradient pub const fn with_position(mut self, position: UiPosition) -> Self { self.position = position; self } pub const fn in_color_space(mut self, color_space: InterpolationColorSpace) -> Self { self.color_space = color_space; self } } #[derive(Clone, PartialEq, Debug, Reflect)] #[reflect(PartialEq)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] pub enum Gradient { /// A linear gradient /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient> Linear(LinearGradient), /// A radial gradient /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/radial-gradient> Radial(RadialGradient), /// A conic gradient /// /// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/conic-gradient> Conic(ConicGradient), } impl Gradient { /// Returns true if the gradient has no stops. pub const fn is_empty(&self) -> bool { match self { Gradient::Linear(gradient) => gradient.stops.is_empty(), Gradient::Radial(gradient) => gradient.stops.is_empty(), Gradient::Conic(gradient) => gradient.stops.is_empty(), } } /// If the gradient has only a single color stop, `get_single` returns its color. pub fn get_single(&self) -> Option<Color> { match self { Gradient::Linear(gradient) => gradient .stops .first() .and_then(|stop| (gradient.stops.len() == 1).then_some(stop.color)), Gradient::Radial(gradient) => gradient .stops .first() .and_then(|stop| (gradient.stops.len() == 1).then_some(stop.color)), Gradient::Conic(gradient) => gradient .stops .first() .and_then(|stop| (gradient.stops.len() == 1).then_some(stop.color)), } } } impl From<LinearGradient> for Gradient { fn from(value: LinearGradient) -> Self { Self::Linear(value) } } impl From<RadialGradient> for Gradient { fn from(value: RadialGradient) -> Self { Self::Radial(value) } } impl From<ConicGradient> for Gradient { fn from(value: ConicGradient) -> Self { Self::Conic(value) } } #[derive(Component, Clone, PartialEq, Debug, Default, Reflect)] #[reflect(Component, Default, PartialEq, Debug, Clone)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] /// A UI node that displays a gradient pub struct BackgroundGradient(pub Vec<Gradient>); impl<T: Into<Gradient>> From<T> for BackgroundGradient { fn from(value: T) -> Self { Self(vec![value.into()]) } } #[derive(Component, Clone, PartialEq, Debug, Default, Reflect)] #[reflect(Component, Default, PartialEq, Debug, Clone)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] /// A UI node border that displays a gradient pub struct BorderGradient(pub Vec<Gradient>); impl<T: Into<Gradient>> From<T> for BorderGradient { fn from(value: T) -> Self { Self(vec![value.into()]) } } #[derive(Default, Copy, Clone, PartialEq, Debug, Reflect)] #[reflect(PartialEq, Default)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] pub enum RadialGradientShape { /// A circle with radius equal to the distance from its center to the closest side ClosestSide, /// A circle with radius equal to the distance from its center to the farthest side FarthestSide, /// An ellipse with extents equal to the distance from its center to the nearest corner #[default] ClosestCorner, /// An ellipse with extents equal to the distance from its center to the farthest corner FarthestCorner, /// A circle Circle(Val), /// An ellipse Ellipse(Val, Val), } const fn close_side(p: f32, h: f32) -> f32 { (-h - p).abs().min((h - p).abs()) } const fn far_side(p: f32, h: f32) -> f32 { (-h - p).abs().max((h - p).abs()) } const fn close_side2(p: Vec2, h: Vec2) -> f32 { close_side(p.x, h.x).min(close_side(p.y, h.y)) } const fn far_side2(p: Vec2, h: Vec2) -> f32 { far_side(p.x, h.x).max(far_side(p.y, h.y)) } impl RadialGradientShape { /// Resolve the physical dimensions of the end shape of the radial gradient pub fn resolve( self, position: Vec2, scale_factor: f32, physical_size: Vec2, physical_target_size: Vec2, ) -> Vec2 { let half_size = 0.5 * physical_size; match self { RadialGradientShape::ClosestSide => Vec2::splat(close_side2(position, half_size)), RadialGradientShape::FarthestSide => Vec2::splat(far_side2(position, half_size)), RadialGradientShape::ClosestCorner => Vec2::new( close_side(position.x, half_size.x), close_side(position.y, half_size.y), ), RadialGradientShape::FarthestCorner => Vec2::new( far_side(position.x, half_size.x), far_side(position.y, half_size.y), ), RadialGradientShape::Circle(radius) => Vec2::splat( radius .resolve(scale_factor, physical_size.x, physical_target_size) .unwrap_or(0.), ), RadialGradientShape::Ellipse(x, y) => Vec2::new( x.resolve(scale_factor, physical_size.x, physical_target_size) .unwrap_or(0.), y.resolve(scale_factor, physical_size.y, physical_target_size) .unwrap_or(0.), ), } } } /// The color space used for interpolation. #[derive(Default, Copy, Clone, Hash, Debug, PartialEq, Eq, Reflect)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), reflect(Serialize, Deserialize) )] pub enum InterpolationColorSpace { /// Interpolates in OKLABA space. #[default] Oklaba, /// Interpolates in OKLCHA space, taking the shortest hue path. Oklcha, /// Interpolates in OKLCHA space, taking the longest hue path. OklchaLong, /// Interpolates in sRGBA space. Srgba, /// Interpolates in linear sRGBA space. LinearRgba, /// Interpolates in HSLA space, taking the shortest hue path. Hsla, /// Interpolates in HSLA space, taking the longest hue path. HslaLong, /// Interpolates in HSVA space, taking the shortest hue path. Hsva, /// Interpolates in HSVA space, taking the longest hue path. HsvaLong, } /// Set the color space used for interpolation. pub trait InColorSpace: Sized { /// Interpolate in the given `color_space`. fn in_color_space(self, color_space: InterpolationColorSpace) -> Self; /// Interpolate in `OKLab` space. fn in_oklaba(self) -> Self { self.in_color_space(InterpolationColorSpace::Oklaba) } /// Interpolate in OKLCH space (short hue path). fn in_oklch(self) -> Self { self.in_color_space(InterpolationColorSpace::Oklcha) } /// Interpolate in OKLCH space (long hue path). fn in_oklch_long(self) -> Self { self.in_color_space(InterpolationColorSpace::OklchaLong) } /// Interpolate in sRGB space. fn in_srgb(self) -> Self { self.in_color_space(InterpolationColorSpace::Srgba) } /// Interpolate in linear sRGB space. fn in_linear_rgb(self) -> Self { self.in_color_space(InterpolationColorSpace::LinearRgba) } } impl InColorSpace for LinearGradient { /// Interpolate in the given `color_space`. fn in_color_space(mut self, color_space: InterpolationColorSpace) -> Self { self.color_space = color_space; self } } impl InColorSpace for RadialGradient { /// Interpolate in the given `color_space`. fn in_color_space(mut self, color_space: InterpolationColorSpace) -> Self { self.color_space = color_space; self } } impl InColorSpace for ConicGradient { /// Interpolate in the given `color_space`. fn in_color_space(mut self, color_space: InterpolationColorSpace) -> Self { self.color_space = color_space; self } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/layout/convert.rs
crates/bevy_ui/src/layout/convert.rs
use taffy::style_helpers; use crate::{ AlignContent, AlignItems, AlignSelf, BoxSizing, Display, FlexDirection, FlexWrap, GridAutoFlow, GridPlacement, GridTrack, GridTrackRepetition, JustifyContent, JustifyItems, JustifySelf, MaxTrackSizingFunction, MinTrackSizingFunction, Node, OverflowAxis, PositionType, RepeatedGridTrack, UiRect, Val, }; use super::LayoutContext; impl Val { fn into_length_percentage_auto( self, context: &LayoutContext, ) -> taffy::style::LengthPercentageAuto { match self { Val::Auto => style_helpers::auto(), Val::Percent(value) => style_helpers::percent(value / 100.), Val::Px(value) => style_helpers::length(context.scale_factor * value), Val::VMin(value) => { style_helpers::length(context.physical_size.min_element() * value / 100.) } Val::VMax(value) => { style_helpers::length(context.physical_size.max_element() * value / 100.) } Val::Vw(value) => style_helpers::length(context.physical_size.x * value / 100.), Val::Vh(value) => style_helpers::length(context.physical_size.y * value / 100.), } } fn into_length_percentage(self, context: &LayoutContext) -> taffy::style::LengthPercentage { match self { Val::Auto => style_helpers::length(0.), Val::Percent(value) => style_helpers::percent(value / 100.), Val::Px(value) => style_helpers::length(context.scale_factor * value), Val::VMin(value) => { style_helpers::length(context.physical_size.min_element() * value / 100.) } Val::VMax(value) => { style_helpers::length(context.physical_size.max_element() * value / 100.) } Val::Vw(value) => style_helpers::length(context.physical_size.x * value / 100.), Val::Vh(value) => style_helpers::length(context.physical_size.y * value / 100.), } } fn into_dimension(self, context: &LayoutContext) -> taffy::style::Dimension { self.into_length_percentage_auto(context).into() } } impl UiRect { fn map_to_taffy_rect<T>(self, map_fn: impl Fn(Val) -> T) -> taffy::geometry::Rect<T> { taffy::geometry::Rect { left: map_fn(self.left), right: map_fn(self.right), top: map_fn(self.top), bottom: map_fn(self.bottom), } } } pub fn from_node(node: &Node, context: &LayoutContext, ignore_border: bool) -> taffy::style::Style { taffy::style::Style { display: node.display.into(), box_sizing: node.box_sizing.into(), item_is_table: false, text_align: taffy::TextAlign::Auto, overflow: taffy::Point { x: node.overflow.x.into(), y: node.overflow.y.into(), }, scrollbar_width: node.scrollbar_width * context.scale_factor, position: node.position_type.into(), flex_direction: node.flex_direction.into(), flex_wrap: node.flex_wrap.into(), align_items: node.align_items.into(), justify_items: node.justify_items.into(), align_self: node.align_self.into(), justify_self: node.justify_self.into(), align_content: node.align_content.into(), justify_content: node.justify_content.into(), inset: taffy::Rect { left: node.left.into_length_percentage_auto(context), right: node.right.into_length_percentage_auto(context), top: node.top.into_length_percentage_auto(context), bottom: node.bottom.into_length_percentage_auto(context), }, margin: node .margin .map_to_taffy_rect(|m| m.into_length_percentage_auto(context)), padding: node .padding .map_to_taffy_rect(|m| m.into_length_percentage(context)), // Ignore border for leaf nodes as it isn't implemented in the rendering engine. // TODO: Implement rendering of border for leaf nodes border: if ignore_border { taffy::Rect::zero() } else { node.border .map_to_taffy_rect(|m| m.into_length_percentage(context)) }, flex_grow: node.flex_grow, flex_shrink: node.flex_shrink, flex_basis: node.flex_basis.into_dimension(context), size: taffy::Size { width: node.width.into_dimension(context), height: node.height.into_dimension(context), }, min_size: taffy::Size { width: node.min_width.into_dimension(context), height: node.min_height.into_dimension(context), }, max_size: taffy::Size { width: node.max_width.into_dimension(context), height: node.max_height.into_dimension(context), }, aspect_ratio: node.aspect_ratio, gap: taffy::Size { width: node.column_gap.into_length_percentage(context), height: node.row_gap.into_length_percentage(context), }, grid_auto_flow: node.grid_auto_flow.into(), grid_template_rows: node .grid_template_rows .iter() .map(|track| track.clone_into_repeated_taffy_track(context)) .collect::<Vec<_>>(), grid_template_columns: node .grid_template_columns .iter() .map(|track| track.clone_into_repeated_taffy_track(context)) .collect::<Vec<_>>(), grid_auto_rows: node .grid_auto_rows .iter() .map(|track| track.into_taffy_track(context)) .collect::<Vec<_>>(), grid_auto_columns: node .grid_auto_columns .iter() .map(|track| track.into_taffy_track(context)) .collect::<Vec<_>>(), grid_row: node.grid_row.into(), grid_column: node.grid_column.into(), ..Default::default() } } impl From<AlignItems> for Option<taffy::style::AlignItems> { fn from(value: AlignItems) -> Self { match value { AlignItems::Default => None, AlignItems::Start => taffy::style::AlignItems::Start.into(), AlignItems::End => taffy::style::AlignItems::End.into(), AlignItems::FlexStart => taffy::style::AlignItems::FlexStart.into(), AlignItems::FlexEnd => taffy::style::AlignItems::FlexEnd.into(), AlignItems::Center => taffy::style::AlignItems::Center.into(), AlignItems::Baseline => taffy::style::AlignItems::Baseline.into(), AlignItems::Stretch => taffy::style::AlignItems::Stretch.into(), } } } impl From<JustifyItems> for Option<taffy::style::JustifyItems> { fn from(value: JustifyItems) -> Self { match value { JustifyItems::Default => None, JustifyItems::Start => taffy::style::JustifyItems::Start.into(), JustifyItems::End => taffy::style::JustifyItems::End.into(), JustifyItems::Center => taffy::style::JustifyItems::Center.into(), JustifyItems::Baseline => taffy::style::JustifyItems::Baseline.into(), JustifyItems::Stretch => taffy::style::JustifyItems::Stretch.into(), } } } impl From<AlignSelf> for Option<taffy::style::AlignSelf> { fn from(value: AlignSelf) -> Self { match value { AlignSelf::Auto => None, AlignSelf::Start => taffy::style::AlignSelf::Start.into(), AlignSelf::End => taffy::style::AlignSelf::End.into(), AlignSelf::FlexStart => taffy::style::AlignSelf::FlexStart.into(), AlignSelf::FlexEnd => taffy::style::AlignSelf::FlexEnd.into(), AlignSelf::Center => taffy::style::AlignSelf::Center.into(), AlignSelf::Baseline => taffy::style::AlignSelf::Baseline.into(), AlignSelf::Stretch => taffy::style::AlignSelf::Stretch.into(), } } } impl From<JustifySelf> for Option<taffy::style::JustifySelf> { fn from(value: JustifySelf) -> Self { match value { JustifySelf::Auto => None, JustifySelf::Start => taffy::style::JustifySelf::Start.into(), JustifySelf::End => taffy::style::JustifySelf::End.into(), JustifySelf::Center => taffy::style::JustifySelf::Center.into(), JustifySelf::Baseline => taffy::style::JustifySelf::Baseline.into(), JustifySelf::Stretch => taffy::style::JustifySelf::Stretch.into(), } } } impl From<AlignContent> for Option<taffy::style::AlignContent> { fn from(value: AlignContent) -> Self { match value { AlignContent::Default => None, AlignContent::Start => taffy::style::AlignContent::Start.into(), AlignContent::End => taffy::style::AlignContent::End.into(), AlignContent::FlexStart => taffy::style::AlignContent::FlexStart.into(), AlignContent::FlexEnd => taffy::style::AlignContent::FlexEnd.into(), AlignContent::Center => taffy::style::AlignContent::Center.into(), AlignContent::Stretch => taffy::style::AlignContent::Stretch.into(), AlignContent::SpaceBetween => taffy::style::AlignContent::SpaceBetween.into(), AlignContent::SpaceAround => taffy::style::AlignContent::SpaceAround.into(), AlignContent::SpaceEvenly => taffy::style::AlignContent::SpaceEvenly.into(), } } } impl From<JustifyContent> for Option<taffy::style::JustifyContent> { fn from(value: JustifyContent) -> Self { match value { JustifyContent::Default => None, JustifyContent::Start => taffy::style::JustifyContent::Start.into(), JustifyContent::End => taffy::style::JustifyContent::End.into(), JustifyContent::FlexStart => taffy::style::JustifyContent::FlexStart.into(), JustifyContent::FlexEnd => taffy::style::JustifyContent::FlexEnd.into(), JustifyContent::Center => taffy::style::JustifyContent::Center.into(), JustifyContent::Stretch => taffy::style::JustifyContent::Stretch.into(), JustifyContent::SpaceBetween => taffy::style::JustifyContent::SpaceBetween.into(), JustifyContent::SpaceAround => taffy::style::JustifyContent::SpaceAround.into(), JustifyContent::SpaceEvenly => taffy::style::JustifyContent::SpaceEvenly.into(), } } } impl From<Display> for taffy::style::Display { fn from(value: Display) -> Self { match value { Display::Flex => taffy::style::Display::Flex, Display::Grid => taffy::style::Display::Grid, Display::Block => taffy::style::Display::Block, Display::None => taffy::style::Display::None, } } } impl From<BoxSizing> for taffy::style::BoxSizing { fn from(value: BoxSizing) -> Self { match value { BoxSizing::BorderBox => taffy::style::BoxSizing::BorderBox, BoxSizing::ContentBox => taffy::style::BoxSizing::ContentBox, } } } impl From<OverflowAxis> for taffy::style::Overflow { fn from(value: OverflowAxis) -> Self { match value { OverflowAxis::Visible => taffy::style::Overflow::Visible, OverflowAxis::Clip => taffy::style::Overflow::Clip, OverflowAxis::Hidden => taffy::style::Overflow::Hidden, OverflowAxis::Scroll => taffy::style::Overflow::Scroll, } } } impl From<FlexDirection> for taffy::style::FlexDirection { fn from(value: FlexDirection) -> Self { match value { FlexDirection::Row => taffy::style::FlexDirection::Row, FlexDirection::Column => taffy::style::FlexDirection::Column, FlexDirection::RowReverse => taffy::style::FlexDirection::RowReverse, FlexDirection::ColumnReverse => taffy::style::FlexDirection::ColumnReverse, } } } impl From<PositionType> for taffy::style::Position { fn from(value: PositionType) -> Self { match value { PositionType::Relative => taffy::style::Position::Relative, PositionType::Absolute => taffy::style::Position::Absolute, } } } impl From<FlexWrap> for taffy::style::FlexWrap { fn from(value: FlexWrap) -> Self { match value { FlexWrap::NoWrap => taffy::style::FlexWrap::NoWrap, FlexWrap::Wrap => taffy::style::FlexWrap::Wrap, FlexWrap::WrapReverse => taffy::style::FlexWrap::WrapReverse, } } } impl From<GridAutoFlow> for taffy::style::GridAutoFlow { fn from(value: GridAutoFlow) -> Self { match value { GridAutoFlow::Row => taffy::style::GridAutoFlow::Row, GridAutoFlow::RowDense => taffy::style::GridAutoFlow::RowDense, GridAutoFlow::Column => taffy::style::GridAutoFlow::Column, GridAutoFlow::ColumnDense => taffy::style::GridAutoFlow::ColumnDense, } } } impl From<GridPlacement> for taffy::geometry::Line<taffy::style::GridPlacement<String>> { fn from(value: GridPlacement) -> Self { let span = value.get_span().unwrap_or(1); match (value.get_start(), value.get_end()) { (Some(start), Some(end)) => taffy::geometry::Line { start: style_helpers::line(start), end: style_helpers::line(end), }, (Some(start), None) => taffy::geometry::Line { start: style_helpers::line(start), end: style_helpers::span(span), }, (None, Some(end)) => taffy::geometry::Line { start: style_helpers::span(span), end: style_helpers::line(end), }, (None, None) => style_helpers::span(span), } } } impl MinTrackSizingFunction { fn into_taffy(self, context: &LayoutContext) -> taffy::style::MinTrackSizingFunction { match self { MinTrackSizingFunction::Px(val) => Val::Px(val).into_length_percentage(context).into(), MinTrackSizingFunction::Percent(val) => { Val::Percent(val).into_length_percentage(context).into() } MinTrackSizingFunction::Auto => taffy::style::MinTrackSizingFunction::auto(), MinTrackSizingFunction::MinContent => { taffy::style::MinTrackSizingFunction::min_content() } MinTrackSizingFunction::MaxContent => { taffy::style::MinTrackSizingFunction::max_content() } MinTrackSizingFunction::VMin(val) => { Val::VMin(val).into_length_percentage(context).into() } MinTrackSizingFunction::VMax(val) => { Val::VMax(val).into_length_percentage(context).into() } MinTrackSizingFunction::Vh(val) => Val::Vh(val).into_length_percentage(context).into(), MinTrackSizingFunction::Vw(val) => Val::Vw(val).into_length_percentage(context).into(), } } } impl MaxTrackSizingFunction { fn into_taffy(self, context: &LayoutContext) -> taffy::style::MaxTrackSizingFunction { match self { MaxTrackSizingFunction::Px(val) => Val::Px(val).into_length_percentage(context).into(), MaxTrackSizingFunction::Percent(val) => { Val::Percent(val).into_length_percentage(context).into() } MaxTrackSizingFunction::Auto => taffy::style::MaxTrackSizingFunction::auto(), MaxTrackSizingFunction::MinContent => { taffy::style::MaxTrackSizingFunction::min_content() } MaxTrackSizingFunction::MaxContent => { taffy::style::MaxTrackSizingFunction::max_content() } MaxTrackSizingFunction::FitContentPx(val) => { taffy::style::MaxTrackSizingFunction::fit_content_px( Val::Px(val) .into_length_percentage(context) .into_raw() .value(), ) } MaxTrackSizingFunction::FitContentPercent(val) => { taffy::style::MaxTrackSizingFunction::fit_content_percent( Val::Percent(val) .into_length_percentage(context) .into_raw() .value(), ) } MaxTrackSizingFunction::Fraction(fraction) => { taffy::style::MaxTrackSizingFunction::fr(fraction) } MaxTrackSizingFunction::VMin(val) => { Val::VMin(val).into_length_percentage(context).into() } MaxTrackSizingFunction::VMax(val) => { Val::VMax(val).into_length_percentage(context).into() } MaxTrackSizingFunction::Vh(val) => Val::Vh(val).into_length_percentage(context).into(), MaxTrackSizingFunction::Vw(val) => Val::Vw(val).into_length_percentage(context).into(), } } } impl GridTrack { fn into_taffy_track(self, context: &LayoutContext) -> taffy::style::TrackSizingFunction { let min = self.min_sizing_function.into_taffy(context); let max = self.max_sizing_function.into_taffy(context); style_helpers::minmax(min, max) } } impl RepeatedGridTrack { fn clone_into_repeated_taffy_track( &self, context: &LayoutContext, ) -> taffy::style::GridTemplateComponent<String> { if self.tracks.len() == 1 && self.repetition == GridTrackRepetition::Count(1) { let min = self.tracks[0].min_sizing_function.into_taffy(context); let max = self.tracks[0].max_sizing_function.into_taffy(context); let taffy_track = style_helpers::minmax(min, max); taffy::GridTemplateComponent::Single(taffy_track) } else { let taffy_tracks: Vec<_> = self .tracks .iter() .map(|track| { let min = track.min_sizing_function.into_taffy(context); let max = track.max_sizing_function.into_taffy(context); style_helpers::minmax(min, max) }) .collect(); match self.repetition { GridTrackRepetition::Count(count) => style_helpers::repeat(count, taffy_tracks), GridTrackRepetition::AutoFit => { style_helpers::repeat(taffy::style::RepetitionCount::AutoFit, taffy_tracks) } GridTrackRepetition::AutoFill => { style_helpers::repeat(taffy::style::RepetitionCount::AutoFill, taffy_tracks) } } } } } #[cfg(test)] mod tests { use bevy_math::Vec2; use crate::BorderRadius; use super::*; #[test] fn test_convert_from() { use sh::TaffyZero; use taffy::style_helpers as sh; let node = Node { display: Display::Flex, box_sizing: BoxSizing::ContentBox, position_type: PositionType::Absolute, left: Val::ZERO, right: Val::Percent(50.), top: Val::Px(12.), bottom: Val::Auto, flex_direction: FlexDirection::ColumnReverse, flex_wrap: FlexWrap::WrapReverse, align_items: AlignItems::Baseline, align_self: AlignSelf::Start, align_content: AlignContent::SpaceAround, justify_items: JustifyItems::Default, justify_self: JustifySelf::Center, justify_content: JustifyContent::SpaceEvenly, margin: UiRect { left: Val::ZERO, right: Val::Px(10.), top: Val::Percent(15.), bottom: Val::Auto, }, padding: UiRect { left: Val::Percent(13.), right: Val::Px(21.), top: Val::Auto, bottom: Val::ZERO, }, border: UiRect { left: Val::Px(14.), right: Val::ZERO, top: Val::Auto, bottom: Val::Percent(31.), }, border_radius: BorderRadius::DEFAULT, flex_grow: 1., flex_shrink: 0., flex_basis: Val::ZERO, width: Val::ZERO, height: Val::Auto, min_width: Val::ZERO, min_height: Val::ZERO, max_width: Val::Auto, max_height: Val::ZERO, aspect_ratio: None, overflow: crate::Overflow::clip(), overflow_clip_margin: crate::OverflowClipMargin::default(), scrollbar_width: 7., column_gap: Val::ZERO, row_gap: Val::ZERO, grid_auto_flow: GridAutoFlow::ColumnDense, grid_template_rows: vec![ GridTrack::px(10.0), GridTrack::percent(50.0), GridTrack::fr(1.0), ], grid_template_columns: RepeatedGridTrack::px(5, 10.0), grid_auto_rows: vec![ GridTrack::fit_content_px(10.0), GridTrack::fit_content_percent(25.0), GridTrack::flex(2.0), ], grid_auto_columns: vec![ GridTrack::auto(), GridTrack::min_content(), GridTrack::max_content(), ], grid_column: GridPlacement::start(4), grid_row: GridPlacement::span(3), }; let viewport_values = LayoutContext::new(1.0, Vec2::new(800., 600.)); let taffy_style = from_node(&node, &viewport_values, false); assert_eq!(taffy_style.display, taffy::style::Display::Flex); assert_eq!(taffy_style.box_sizing, taffy::style::BoxSizing::ContentBox); assert_eq!(taffy_style.position, taffy::style::Position::Absolute); assert_eq!( taffy_style.inset.left, taffy::style::LengthPercentageAuto::ZERO ); assert_eq!( taffy_style.inset.right, taffy::style::LengthPercentageAuto::percent(0.5) ); assert_eq!( taffy_style.inset.top, taffy::style::LengthPercentageAuto::length(12.) ); assert_eq!( taffy_style.inset.bottom, taffy::style::LengthPercentageAuto::auto() ); assert_eq!( taffy_style.flex_direction, taffy::style::FlexDirection::ColumnReverse ); assert_eq!(taffy_style.flex_wrap, taffy::style::FlexWrap::WrapReverse); assert_eq!( taffy_style.align_items, Some(taffy::style::AlignItems::Baseline) ); assert_eq!(taffy_style.align_self, Some(taffy::style::AlignSelf::Start)); assert_eq!( taffy_style.align_content, Some(taffy::style::AlignContent::SpaceAround) ); assert_eq!( taffy_style.justify_content, Some(taffy::style::JustifyContent::SpaceEvenly) ); assert_eq!(taffy_style.justify_items, None); assert_eq!( taffy_style.justify_self, Some(taffy::style::JustifySelf::Center) ); assert_eq!( taffy_style.margin.left, taffy::style::LengthPercentageAuto::ZERO ); assert_eq!( taffy_style.margin.right, taffy::style::LengthPercentageAuto::length(10.) ); assert_eq!( taffy_style.margin.top, taffy::style::LengthPercentageAuto::percent(0.15) ); assert_eq!( taffy_style.margin.bottom, taffy::style::LengthPercentageAuto::auto() ); assert_eq!( taffy_style.padding.left, taffy::style::LengthPercentage::percent(0.13) ); assert_eq!( taffy_style.padding.right, taffy::style::LengthPercentage::length(21.) ); assert_eq!( taffy_style.padding.top, taffy::style::LengthPercentage::ZERO ); assert_eq!( taffy_style.padding.bottom, taffy::style::LengthPercentage::ZERO ); assert_eq!( taffy_style.border.left, taffy::style::LengthPercentage::length(14.) ); assert_eq!( taffy_style.border.right, taffy::style::LengthPercentage::ZERO ); assert_eq!(taffy_style.border.top, taffy::style::LengthPercentage::ZERO); assert_eq!( taffy_style.border.bottom, taffy::style::LengthPercentage::percent(0.31) ); assert_eq!(taffy_style.flex_grow, 1.); assert_eq!(taffy_style.flex_shrink, 0.); assert_eq!(taffy_style.flex_basis, taffy::style::Dimension::ZERO); assert_eq!(taffy_style.size.width, taffy::style::Dimension::ZERO); assert_eq!(taffy_style.size.height, taffy::style::Dimension::auto()); assert_eq!(taffy_style.min_size.width, taffy::style::Dimension::ZERO); assert_eq!(taffy_style.min_size.height, taffy::style::Dimension::ZERO); assert_eq!(taffy_style.max_size.width, taffy::style::Dimension::auto()); assert_eq!(taffy_style.max_size.height, taffy::style::Dimension::ZERO); assert_eq!(taffy_style.aspect_ratio, None); assert_eq!(taffy_style.scrollbar_width, 7.); assert_eq!(taffy_style.gap.width, taffy::style::LengthPercentage::ZERO); assert_eq!(taffy_style.gap.height, taffy::style::LengthPercentage::ZERO); assert_eq!( taffy_style.grid_auto_flow, taffy::style::GridAutoFlow::ColumnDense ); assert_eq!( taffy_style.grid_template_rows, vec![sh::length(10.0), sh::percent(0.5), sh::fr(1.0)] ); assert_eq!( taffy_style.grid_template_columns, vec![sh::repeat(5, vec![sh::length(10.0)])] ); assert_eq!( taffy_style.grid_auto_rows, vec![ sh::fit_content(taffy::style::LengthPercentage::length(10.0)), sh::fit_content(taffy::style::LengthPercentage::percent(0.25)), sh::minmax(sh::length(0.0), sh::fr(2.0)), ] ); assert_eq!( taffy_style.grid_auto_columns, vec![sh::auto(), sh::min_content(), sh::max_content()] ); assert_eq!( taffy_style.grid_column, taffy::geometry::Line { start: sh::line(4), end: sh::span(1) } ); assert_eq!(taffy_style.grid_row, sh::span(3)); } #[test] fn test_into_length_percentage() { use taffy::style::LengthPercentage; let context = LayoutContext::new(2.0, Vec2::new(800., 600.)); let cases = [ (Val::Auto, LengthPercentage::length(0.)), (Val::Percent(1.), LengthPercentage::percent(0.01)), (Val::Px(1.), LengthPercentage::length(2.)), (Val::Vw(1.), LengthPercentage::length(8.)), (Val::Vh(1.), LengthPercentage::length(6.)), (Val::VMin(2.), LengthPercentage::length(12.)), (Val::VMax(2.), LengthPercentage::length(16.)), ]; for (val, length) in cases { assert!({ let lhs = val.into_length_percentage(&context).into_raw().value(); let rhs = length.into_raw().value(); (lhs - rhs).abs() < 0.0001 }); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/layout/debug.rs
crates/bevy_ui/src/layout/debug.rs
use core::fmt::Write; use taffy::{NodeId, TraversePartialTree}; use bevy_ecs::prelude::Entity; use bevy_platform::collections::HashMap; use crate::layout::ui_surface::UiSurface; /// Prints a debug representation of the computed layout of the UI layout tree for each window. pub fn print_ui_layout_tree(ui_surface: &UiSurface) { let taffy_to_entity: HashMap<NodeId, Entity> = ui_surface .entity_to_taffy .iter() .map(|(entity, node)| (node.id, *entity)) .collect(); for (&entity, &viewport_node) in &ui_surface.root_entity_to_viewport_node { let mut out = String::new(); print_node( ui_surface, &taffy_to_entity, entity, viewport_node, false, String::new(), &mut out, ); tracing::info!("Layout tree for camera entity: {entity}\n{out}"); } } /// Recursively navigates the layout tree printing each node's information. fn print_node( ui_surface: &UiSurface, taffy_to_entity: &HashMap<NodeId, Entity>, entity: Entity, node: NodeId, has_sibling: bool, lines_string: String, acc: &mut String, ) { let tree = &ui_surface.taffy; let layout = tree.layout(node).unwrap(); let style = tree.style(node).unwrap(); let num_children = tree.child_count(node); let display_variant = match (num_children, style.display) { (_, taffy::style::Display::None) => "NONE", (0, _) => "LEAF", (_, taffy::style::Display::Flex) => "FLEX", (_, taffy::style::Display::Grid) => "GRID", (_, taffy::style::Display::Block) => "BLOCK", }; let fork_string = if has_sibling { "├── " } else { "└── " }; writeln!( acc, "{lines}{fork} {display} [x: {x:<4} y: {y:<4} width: {width:<4} height: {height:<4}] ({entity}) {measured}", lines = lines_string, fork = fork_string, display = display_variant, x = layout.location.x, y = layout.location.y, width = layout.size.width, height = layout.size.height, measured = if tree.get_node_context(node).is_some() { "measured" } else { "" } ).ok(); let bar = if has_sibling { "│ " } else { " " }; let new_string = lines_string + bar; // Recurse into children for (index, child_node) in tree.children(node).unwrap().iter().enumerate() { let has_sibling = index < num_children - 1; let child_entity = taffy_to_entity.get(child_node).unwrap(); print_node( ui_surface, taffy_to_entity, *child_entity, *child_node, has_sibling, new_string.clone(), acc, ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/layout/ui_surface.rs
crates/bevy_ui/src/layout/ui_surface.rs
use core::fmt; use core::ops::{Deref, DerefMut}; use bevy_platform::collections::hash_map::Entry; use taffy::TaffyTree; use bevy_ecs::{ entity::{Entity, EntityHashMap}, prelude::Resource, }; use bevy_math::{UVec2, Vec2}; use bevy_utils::default; use crate::{layout::convert, LayoutContext, LayoutError, Measure, MeasureArgs, Node, NodeMeasure}; use bevy_text::CosmicFontSystem; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct LayoutNode { // Implicit "viewport" node if this `LayoutNode` corresponds to a root UI node entity pub(super) viewport_id: Option<taffy::NodeId>, // The id of the node in the taffy tree pub(super) id: taffy::NodeId, } impl From<taffy::NodeId> for LayoutNode { fn from(value: taffy::NodeId) -> Self { LayoutNode { viewport_id: None, id: value, } } } pub(crate) struct UiTree<T>(TaffyTree<T>); #[expect(unsafe_code, reason = "TaffyTree is safe as long as calc is not used")] /// SAFETY: Taffy Tree becomes thread unsafe when you use the calc feature, which we do not implement unsafe impl Send for UiTree<NodeMeasure> {} #[expect(unsafe_code, reason = "TaffyTree is safe as long as calc is not used")] /// SAFETY: Taffy Tree becomes thread unsafe when you use the calc feature, which we do not implement unsafe impl Sync for UiTree<NodeMeasure> {} impl<T> Deref for UiTree<T> { type Target = TaffyTree<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> DerefMut for UiTree<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[derive(Resource)] pub struct UiSurface { pub root_entity_to_viewport_node: EntityHashMap<taffy::NodeId>, pub(super) entity_to_taffy: EntityHashMap<LayoutNode>, pub(super) taffy: UiTree<NodeMeasure>, taffy_children_scratch: Vec<taffy::NodeId>, } fn _assert_send_sync_ui_surface_impl_safe() { fn _assert_send_sync<T: Send + Sync>() {} _assert_send_sync::<EntityHashMap<taffy::NodeId>>(); _assert_send_sync::<UiTree<NodeMeasure>>(); _assert_send_sync::<UiSurface>(); } impl fmt::Debug for UiSurface { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("UiSurface") .field("entity_to_taffy", &self.entity_to_taffy) .field("taffy_children_scratch", &self.taffy_children_scratch) .finish() } } impl Default for UiSurface { fn default() -> Self { let taffy: UiTree<NodeMeasure> = UiTree(TaffyTree::new()); Self { root_entity_to_viewport_node: Default::default(), entity_to_taffy: Default::default(), taffy, taffy_children_scratch: Vec::new(), } } } impl UiSurface { /// Retrieves the Taffy node associated with the given UI node entity and updates its style. /// If no associated Taffy node exists a new Taffy node is inserted into the Taffy layout. pub fn upsert_node( &mut self, layout_context: &LayoutContext, entity: Entity, node: &Node, mut new_node_context: Option<NodeMeasure>, ) { let taffy = &mut self.taffy; match self.entity_to_taffy.entry(entity) { Entry::Occupied(entry) => { let taffy_node = *entry.get(); let has_measure = if new_node_context.is_some() { taffy .set_node_context(taffy_node.id, new_node_context) .unwrap(); true } else { taffy.get_node_context(taffy_node.id).is_some() }; taffy .set_style( taffy_node.id, convert::from_node(node, layout_context, has_measure), ) .unwrap(); } Entry::Vacant(entry) => { let taffy_node = if let Some(measure) = new_node_context.take() { taffy.new_leaf_with_context( convert::from_node(node, layout_context, true), measure, ) } else { taffy.new_leaf(convert::from_node(node, layout_context, false)) }; entry.insert(taffy_node.unwrap().into()); } } } /// Update the `MeasureFunc` of the taffy node corresponding to the given [`Entity`] if the node exists. pub fn update_node_context(&mut self, entity: Entity, context: NodeMeasure) -> Option<()> { let taffy_node = self.entity_to_taffy.get(&entity)?; self.taffy .set_node_context(taffy_node.id, Some(context)) .ok() } /// Update the children of the taffy node corresponding to the given [`Entity`]. pub fn update_children(&mut self, entity: Entity, children: impl Iterator<Item = Entity>) { self.taffy_children_scratch.clear(); for child in children { if let Some(taffy_node) = self.entity_to_taffy.get_mut(&child) { self.taffy_children_scratch.push(taffy_node.id); if let Some(viewport_id) = taffy_node.viewport_id.take() { self.taffy.remove(viewport_id).ok(); } } } let taffy_node = self.entity_to_taffy.get(&entity).unwrap(); self.taffy .set_children(taffy_node.id, &self.taffy_children_scratch) .unwrap(); } /// Removes children from the entity's taffy node if it exists. Does nothing otherwise. pub fn try_remove_children(&mut self, entity: Entity) { if let Some(taffy_node) = self.entity_to_taffy.get(&entity) { self.taffy.set_children(taffy_node.id, &[]).unwrap(); } } /// Removes the measure from the entity's taffy node if it exists. Does nothing otherwise. pub fn try_remove_node_context(&mut self, entity: Entity) { if let Some(taffy_node) = self.entity_to_taffy.get(&entity) { self.taffy.set_node_context(taffy_node.id, None).unwrap(); } } /// Gets or inserts an implicit taffy viewport node corresponding to the given UI root entity pub fn get_or_insert_taffy_viewport_node(&mut self, ui_root_entity: Entity) -> taffy::NodeId { *self .root_entity_to_viewport_node .entry(ui_root_entity) .or_insert_with(|| { let root_node = self.entity_to_taffy.get_mut(&ui_root_entity).unwrap(); let implicit_root = self .taffy .new_leaf(taffy::style::Style { display: taffy::style::Display::Grid, // Note: Taffy percentages are floats ranging from 0.0 to 1.0. // So this is setting width:100% and height:100% size: taffy::geometry::Size { width: taffy::style_helpers::percent(1.0), height: taffy::style_helpers::percent(1.0), }, align_items: Some(taffy::style::AlignItems::Start), justify_items: Some(taffy::style::JustifyItems::Start), ..default() }) .unwrap(); self.taffy.add_child(implicit_root, root_node.id).unwrap(); root_node.viewport_id = Some(implicit_root); implicit_root }) } /// Compute the layout for the given implicit taffy viewport node pub fn compute_layout<'a>( &mut self, ui_root_entity: Entity, render_target_resolution: UVec2, buffer_query: &'a mut bevy_ecs::prelude::Query<&mut bevy_text::ComputedTextBlock>, font_system: &'a mut CosmicFontSystem, ) { let implicit_viewport_node = self.get_or_insert_taffy_viewport_node(ui_root_entity); let available_space = taffy::geometry::Size { width: taffy::style::AvailableSpace::Definite(render_target_resolution.x as f32), height: taffy::style::AvailableSpace::Definite(render_target_resolution.y as f32), }; self.taffy .compute_layout_with_measure( implicit_viewport_node, available_space, |known_dimensions: taffy::Size<Option<f32>>, available_space: taffy::Size<taffy::AvailableSpace>, _node_id: taffy::NodeId, context: Option<&mut NodeMeasure>, style: &taffy::Style| -> taffy::Size<f32> { context .map(|ctx| { let buffer = get_text_buffer( crate::widget::TextMeasure::needs_buffer( known_dimensions.height, available_space.width, ), ctx, buffer_query, ); let size = ctx.measure( MeasureArgs { width: known_dimensions.width, height: known_dimensions.height, available_width: available_space.width, available_height: available_space.height, font_system, buffer, }, style, ); taffy::Size { width: size.x, height: size.y, } }) .unwrap_or(taffy::Size::ZERO) }, ) .unwrap(); } /// Removes each entity from the internal map and then removes their associated nodes from taffy pub fn remove_entities(&mut self, entities: impl IntoIterator<Item = Entity>) { for entity in entities { if let Some(node) = self.entity_to_taffy.remove(&entity) { self.taffy.remove(node.id).unwrap(); if let Some(viewport_node) = node.viewport_id { self.taffy.remove(viewport_node).ok(); } } } } /// 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 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, use_rounding: bool, ) -> Result<(taffy::Layout, Vec2), LayoutError> { let Some(taffy_node) = self.entity_to_taffy.get(&entity) else { return Err(LayoutError::InvalidHierarchy); }; if use_rounding { self.taffy.enable_rounding(); } else { self.taffy.disable_rounding(); } let out = match self.taffy.layout(taffy_node.id).cloned() { Ok(layout) => { self.taffy.disable_rounding(); let taffy_size = self.taffy.layout(taffy_node.id).unwrap().size; let unrounded_size = Vec2::new(taffy_size.width, taffy_size.height); Ok((layout, unrounded_size)) } Err(taffy_error) => Err(LayoutError::TaffyError(taffy_error)), }; self.taffy.enable_rounding(); out } } pub fn get_text_buffer<'a>( needs_buffer: bool, ctx: &mut NodeMeasure, query: &'a mut bevy_ecs::prelude::Query<&mut bevy_text::ComputedTextBlock>, ) -> Option<&'a mut bevy_text::ComputedTextBlock> { // We avoid a query lookup whenever the buffer is not required. if !needs_buffer { return None; } let NodeMeasure::Text(crate::widget::TextMeasure { info }) = ctx else { return None; }; let Ok(computed) = query.get_mut(info.entity) else { return None; }; Some(computed.into_inner()) } #[cfg(test)] mod tests { use super::*; use crate::{ContentSize, FixedMeasure}; use bevy_math::Vec2; use taffy::TraversePartialTree; #[test] fn test_initialization() { let ui_surface = UiSurface::default(); assert!(ui_surface.entity_to_taffy.is_empty()); assert_eq!(ui_surface.taffy.total_node_count(), 0); } #[test] fn test_upsert() { let mut ui_surface = UiSurface::default(); let root_node_entity = Entity::from_raw_u32(1).unwrap(); let node = Node::default(); // standard upsert ui_surface.upsert_node(&LayoutContext::TEST_CONTEXT, root_node_entity, &node, None); // should be inserted into taffy assert_eq!(ui_surface.taffy.total_node_count(), 1); assert!(ui_surface.entity_to_taffy.contains_key(&root_node_entity)); // test duplicate insert 1 ui_surface.upsert_node(&LayoutContext::TEST_CONTEXT, root_node_entity, &node, None); // node count should not have increased assert_eq!(ui_surface.taffy.total_node_count(), 1); // assign root node to camera ui_surface.get_or_insert_taffy_viewport_node(root_node_entity); // each root node will create 2 taffy nodes assert_eq!(ui_surface.taffy.total_node_count(), 2); // test duplicate insert 2 ui_surface.upsert_node(&LayoutContext::TEST_CONTEXT, root_node_entity, &node, None); // node count should not have increased assert_eq!(ui_surface.taffy.total_node_count(), 2); } #[test] fn test_remove_entities() { let mut ui_surface = UiSurface::default(); let root_node_entity = Entity::from_raw_u32(1).unwrap(); let node = Node::default(); ui_surface.upsert_node(&LayoutContext::TEST_CONTEXT, root_node_entity, &node, None); ui_surface.get_or_insert_taffy_viewport_node(root_node_entity); assert!(ui_surface.entity_to_taffy.contains_key(&root_node_entity)); ui_surface.remove_entities([root_node_entity]); assert!(!ui_surface.entity_to_taffy.contains_key(&root_node_entity)); } #[test] fn test_try_update_measure() { let mut ui_surface = UiSurface::default(); let root_node_entity = Entity::from_raw_u32(1).unwrap(); let node = Node::default(); ui_surface.upsert_node(&LayoutContext::TEST_CONTEXT, root_node_entity, &node, None); let mut content_size = ContentSize::default(); content_size.set(NodeMeasure::Fixed(FixedMeasure { size: Vec2::ONE })); let measure_func = content_size.measure.take().unwrap(); assert!(ui_surface .update_node_context(root_node_entity, measure_func) .is_some()); } #[test] fn test_update_children() { let mut ui_surface = UiSurface::default(); let root_node_entity = Entity::from_raw_u32(1).unwrap(); let child_entity = Entity::from_raw_u32(2).unwrap(); let node = Node::default(); ui_surface.upsert_node(&LayoutContext::TEST_CONTEXT, root_node_entity, &node, None); ui_surface.upsert_node(&LayoutContext::TEST_CONTEXT, child_entity, &node, None); ui_surface.update_children(root_node_entity, vec![child_entity].into_iter()); let parent_node = *ui_surface.entity_to_taffy.get(&root_node_entity).unwrap(); let child_node = *ui_surface.entity_to_taffy.get(&child_entity).unwrap(); assert_eq!(ui_surface.taffy.parent(child_node.id), Some(parent_node.id)); } #[expect( unreachable_code, reason = "Certain pieces of code tested here cause the test to fail if made reachable; see #16362 for progress on fixing this" )] #[test] fn test_set_camera_children() { let mut ui_surface = UiSurface::default(); let root_node_entity = Entity::from_raw_u32(1).unwrap(); let child_entity = Entity::from_raw_u32(2).unwrap(); let node = Node::default(); ui_surface.upsert_node(&LayoutContext::TEST_CONTEXT, root_node_entity, &node, None); ui_surface.upsert_node(&LayoutContext::TEST_CONTEXT, child_entity, &node, None); let root_taffy_node = *ui_surface.entity_to_taffy.get(&root_node_entity).unwrap(); let child_taffy = *ui_surface.entity_to_taffy.get(&child_entity).unwrap(); // set up the relationship manually ui_surface .taffy .add_child(root_taffy_node.id, child_taffy.id) .unwrap(); ui_surface.get_or_insert_taffy_viewport_node(root_node_entity); assert_eq!( ui_surface.taffy.parent(child_taffy.id), Some(root_taffy_node.id) ); let root_taffy_children = ui_surface.taffy.children(root_taffy_node.id).unwrap(); assert!( root_taffy_children.contains(&child_taffy.id), "root node is not a parent of child node" ); assert_eq!( ui_surface.taffy.child_count(root_taffy_node.id), 1, "expected root node child count to be 1" ); // clear camera's root nodes ui_surface.get_or_insert_taffy_viewport_node(root_node_entity); return; // TODO: can't pass the test if we continue - not implemented (remove allow(unreachable_code)) let root_taffy_children = ui_surface.taffy.children(root_taffy_node.id).unwrap(); assert!( root_taffy_children.contains(&child_taffy.id), "root node is not a parent of child node" ); assert_eq!( ui_surface.taffy.child_count(root_taffy_node.id), 1, "expected root node child count to be 1" ); // re-associate root node with viewport node ui_surface.get_or_insert_taffy_viewport_node(root_node_entity); let child_taffy = ui_surface.entity_to_taffy.get(&child_entity).unwrap(); let root_taffy_children = ui_surface.taffy.children(root_taffy_node.id).unwrap(); assert!( root_taffy_children.contains(&child_taffy.id), "root node is not a parent of child node" ); assert_eq!( ui_surface.taffy.child_count(root_taffy_node.id), 1, "expected root node child count to be 1" ); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/layout/mod.rs
crates/bevy_ui/src/layout/mod.rs
use crate::{ experimental::{UiChildren, UiRootNodes}, ui_transform::{UiGlobalTransform, UiTransform}, ComputedNode, ComputedUiRenderTargetInfo, ContentSize, Display, IgnoreScroll, LayoutConfig, Node, Outline, OverflowAxis, ScrollPosition, }; use bevy_ecs::{ change_detection::{DetectChanges, DetectChangesMut}, entity::Entity, hierarchy::Children, lifecycle::RemovedComponents, query::Added, system::{Query, ResMut}, world::Ref, }; use bevy_math::{Affine2, Vec2}; use bevy_sprite::BorderRect; use thiserror::Error; use ui_surface::UiSurface; use bevy_text::ComputedTextBlock; use bevy_text::CosmicFontSystem; mod convert; pub mod debug; pub mod ui_surface; pub struct LayoutContext { pub scale_factor: f32, pub physical_size: Vec2, } impl LayoutContext { pub const DEFAULT: Self = Self { scale_factor: 1.0, physical_size: Vec2::ZERO, }; /// Create a new [`LayoutContext`] from the window's physical size and scale factor #[inline] const fn new(scale_factor: f32, physical_size: Vec2) -> Self { Self { scale_factor, physical_size, } } } #[cfg(test)] impl LayoutContext { pub const TEST_CONTEXT: Self = Self { scale_factor: 1.0, physical_size: Vec2::new(1000.0, 1000.0), }; } impl Default for LayoutContext { fn default() -> Self { Self::DEFAULT } } #[derive(Debug, Error)] pub enum LayoutError { #[error("Invalid hierarchy")] InvalidHierarchy, #[error("Taffy error: {0}")] TaffyError(taffy::tree::TaffyError), } /// Updates the UI's layout tree, computes the new layout geometry and then updates the sizes and transforms of all the UI nodes. pub fn ui_layout_system( mut ui_surface: ResMut<UiSurface>, ui_root_node_query: UiRootNodes, ui_children: UiChildren, mut node_query: Query<( Entity, Ref<Node>, Option<&mut ContentSize>, Ref<ComputedUiRenderTargetInfo>, )>, added_node_query: Query<(), Added<Node>>, mut node_update_query: Query<( &mut ComputedNode, &UiTransform, &mut UiGlobalTransform, &Node, Option<&LayoutConfig>, Option<&Outline>, Option<&ScrollPosition>, Option<&IgnoreScroll>, )>, mut buffer_query: Query<&mut ComputedTextBlock>, mut font_system: ResMut<CosmicFontSystem>, mut removed_children: RemovedComponents<Children>, mut removed_content_sizes: RemovedComponents<ContentSize>, mut removed_nodes: RemovedComponents<Node>, ) { // When a `ContentSize` component is removed from an entity, we need to remove the measure from the corresponding taffy node. for entity in removed_content_sizes.read() { ui_surface.try_remove_node_context(entity); } // Sync Node and ContentSize to Taffy for all nodes node_query .iter_mut() .for_each(|(entity, node, content_size, computed_target)| { if computed_target.is_changed() || node.is_changed() || content_size .as_ref() .is_some_and(|c| c.is_changed() || c.measure.is_some()) { let layout_context = LayoutContext::new( computed_target.scale_factor, computed_target.physical_size.as_vec2(), ); let measure = content_size.and_then(|mut c| c.measure.take()); ui_surface.upsert_node(&layout_context, entity, &node, measure); } }); // update and remove children for entity in removed_children.read() { ui_surface.try_remove_children(entity); } // clean up removed nodes after syncing children to avoid potential panic (invalid SlotMap key used) ui_surface.remove_entities( removed_nodes .read() .filter(|entity| !node_query.contains(*entity)), ); for ui_root_entity in ui_root_node_query.iter() { fn update_children_recursively( ui_surface: &mut UiSurface, ui_children: &UiChildren, added_node_query: &Query<(), Added<Node>>, entity: Entity, ) { if ui_surface.entity_to_taffy.contains_key(&entity) && (added_node_query.contains(entity) || ui_children.is_changed(entity) || ui_children .iter_ui_children(entity) .any(|child| added_node_query.contains(child))) { ui_surface.update_children(entity, ui_children.iter_ui_children(entity)); } for child in ui_children.iter_ui_children(entity) { update_children_recursively(ui_surface, ui_children, added_node_query, child); } } update_children_recursively( &mut ui_surface, &ui_children, &added_node_query, ui_root_entity, ); let (_, _, _, computed_target) = node_query.get(ui_root_entity).unwrap(); ui_surface.compute_layout( ui_root_entity, computed_target.physical_size, &mut buffer_query, &mut font_system, ); update_uinode_geometry_recursive( ui_root_entity, &mut ui_surface, true, computed_target.physical_size().as_vec2(), Affine2::IDENTITY, &mut node_update_query, &ui_children, computed_target.scale_factor.recip(), Vec2::ZERO, Vec2::ZERO, ); } // Returns the combined bounding box of the node and any of its overflowing children. fn update_uinode_geometry_recursive( entity: Entity, ui_surface: &mut UiSurface, inherited_use_rounding: bool, target_size: Vec2, mut inherited_transform: Affine2, node_update_query: &mut Query<( &mut ComputedNode, &UiTransform, &mut UiGlobalTransform, &Node, Option<&LayoutConfig>, Option<&Outline>, Option<&ScrollPosition>, Option<&IgnoreScroll>, )>, ui_children: &UiChildren, inverse_target_scale_factor: f32, parent_size: Vec2, parent_scroll_position: Vec2, ) { if let Ok(( mut node, transform, mut global_transform, style, maybe_layout_config, maybe_outline, maybe_scroll_position, maybe_scroll_sticky, )) = node_update_query.get_mut(entity) { let use_rounding = maybe_layout_config .map(|layout_config| layout_config.use_rounding) .unwrap_or(inherited_use_rounding); let Ok((layout, unrounded_size)) = ui_surface.get_layout(entity, use_rounding) else { return; }; let layout_size = Vec2::new(layout.size.width, layout.size.height); // Taffy layout position of the top-left corner of the node, relative to its parent. let layout_location = Vec2::new(layout.location.x, layout.location.y); // If IgnoreScroll is set, parent scroll position is ignored along the specified axes. let effective_parent_scroll = maybe_scroll_sticky .map(|scroll_sticky| parent_scroll_position * Vec2::from(!scroll_sticky.0)) .unwrap_or(parent_scroll_position); // The position of the center of the node relative to its top-left corner. let local_center = layout_location - effective_parent_scroll + 0.5 * (layout_size - parent_size); // only trigger change detection when the new values are different if node.size != layout_size || node.unrounded_size != unrounded_size || node.inverse_scale_factor != inverse_target_scale_factor { node.size = layout_size; node.unrounded_size = unrounded_size; node.inverse_scale_factor = inverse_target_scale_factor; } let content_size = Vec2::new(layout.content_size.width, layout.content_size.height); node.bypass_change_detection().content_size = content_size; let taffy_rect_to_border_rect = |rect: taffy::Rect<f32>| BorderRect { min_inset: Vec2::new(rect.left, rect.top), max_inset: Vec2::new(rect.right, rect.bottom), }; node.bypass_change_detection().border = taffy_rect_to_border_rect(layout.border); node.bypass_change_detection().padding = taffy_rect_to_border_rect(layout.padding); // Compute the node's new global transform let mut local_transform = transform.compute_affine( inverse_target_scale_factor.recip(), layout_size, target_size, ); local_transform.translation += local_center; inherited_transform *= local_transform; if inherited_transform != **global_transform { *global_transform = inherited_transform.into(); } // We don't trigger change detection for changes to border radius node.bypass_change_detection().border_radius = style.border_radius.resolve( inverse_target_scale_factor.recip(), node.size, target_size, ); if let Some(outline) = maybe_outline { // don't trigger change detection when only outlines are changed let node = node.bypass_change_detection(); node.outline_width = if style.display != Display::None { outline .width .resolve( inverse_target_scale_factor.recip(), node.size().x, target_size, ) .unwrap_or(0.) .max(0.) } else { 0. }; node.outline_offset = outline .offset .resolve( inverse_target_scale_factor.recip(), node.size().x, target_size, ) .unwrap_or(0.) .max(0.); } node.bypass_change_detection().scrollbar_size = Vec2::new(layout.scrollbar_size.width, layout.scrollbar_size.height); let scroll_position: Vec2 = maybe_scroll_position .map(|scroll_pos| { Vec2::new( if style.overflow.x == OverflowAxis::Scroll { scroll_pos.x * inverse_target_scale_factor.recip() } else { 0.0 }, if style.overflow.y == OverflowAxis::Scroll { scroll_pos.y * inverse_target_scale_factor.recip() } else { 0.0 }, ) }) .unwrap_or_default(); let max_possible_offset = (content_size - layout_size + node.scrollbar_size).max(Vec2::ZERO); let clamped_scroll_position = scroll_position.clamp(Vec2::ZERO, max_possible_offset); let physical_scroll_position = clamped_scroll_position.floor(); node.bypass_change_detection().scroll_position = physical_scroll_position; for child_uinode in ui_children.iter_ui_children(entity) { update_uinode_geometry_recursive( child_uinode, ui_surface, use_rounding, target_size, inherited_transform, node_update_query, ui_children, inverse_target_scale_factor, layout_size, physical_scroll_position, ); } } } } #[cfg(test)] mod tests { use crate::{ layout::ui_surface::UiSurface, prelude::*, ui_layout_system, update::propagate_ui_target_cameras, ContentSize, LayoutContext, }; use bevy_app::{App, HierarchyPropagatePlugin, PostUpdate, PropagateSet}; use bevy_camera::{Camera, Camera2d, ComputedCameraValues, RenderTargetInfo, Viewport}; use bevy_ecs::{prelude::*, system::RunSystemOnce}; use bevy_math::{Rect, UVec2, Vec2}; use bevy_platform::collections::HashMap; use bevy_transform::systems::mark_dirty_trees; use bevy_transform::systems::{propagate_parent_transforms, sync_simple_transforms}; use bevy_utils::prelude::default; use taffy::TraversePartialTree; // these window dimensions are easy to convert to and from percentage values const TARGET_WIDTH: u32 = 1000; const TARGET_HEIGHT: u32 = 100; fn setup_ui_test_app() -> App { let mut app = App::new(); app.add_plugins(HierarchyPropagatePlugin::<ComputedUiTargetCamera>::new( PostUpdate, )); app.add_plugins(HierarchyPropagatePlugin::<ComputedUiRenderTargetInfo>::new( PostUpdate, )); app.init_resource::<UiScale>(); app.init_resource::<UiSurface>(); app.init_resource::<bevy_text::TextPipeline>(); app.init_resource::<bevy_text::CosmicFontSystem>(); app.init_resource::<bevy_text::SwashCache>(); app.init_resource::<bevy_transform::StaticTransformOptimizations>(); app.add_systems( PostUpdate, ( ApplyDeferred, propagate_ui_target_cameras, ui_layout_system, mark_dirty_trees, sync_simple_transforms, propagate_parent_transforms, ) .chain(), ); app.configure_sets( PostUpdate, PropagateSet::<ComputedUiTargetCamera>::default() .after(propagate_ui_target_cameras) .before(ui_layout_system), ); app.configure_sets( PostUpdate, PropagateSet::<ComputedUiRenderTargetInfo>::default() .after(propagate_ui_target_cameras) .before(ui_layout_system), ); let world = app.world_mut(); // spawn a camera with a dummy render target world.spawn(( Camera2d, Camera { computed: ComputedCameraValues { target_info: Some(RenderTargetInfo { physical_size: UVec2::new(TARGET_WIDTH, TARGET_HEIGHT), scale_factor: 1., }), ..Default::default() }, viewport: Some(Viewport { physical_size: UVec2::new(TARGET_WIDTH, TARGET_HEIGHT), ..default() }), ..Default::default() }, )); app } #[test] fn ui_nodes_with_percent_100_dimensions_should_fill_their_parent() { let mut app = setup_ui_test_app(); let world = app.world_mut(); // spawn a root entity with width and height set to fill 100% of its parent let ui_root = world .spawn(Node { width: Val::Percent(100.), height: Val::Percent(100.), ..default() }) .id(); let ui_child = world .spawn(Node { width: Val::Percent(100.), height: Val::Percent(100.), ..default() }) .id(); world.entity_mut(ui_root).add_child(ui_child); app.update(); let mut ui_surface = app.world_mut().resource_mut::<UiSurface>(); for ui_entity in [ui_root, ui_child] { let layout = ui_surface.get_layout(ui_entity, true).unwrap().0; assert_eq!(layout.size.width, TARGET_WIDTH as f32); assert_eq!(layout.size.height, TARGET_HEIGHT as f32); } } #[test] fn ui_surface_tracks_ui_entities() { let mut app = setup_ui_test_app(); let world = app.world_mut(); // no UI entities in world, none in UiSurface let ui_surface = world.resource::<UiSurface>(); assert!(ui_surface.entity_to_taffy.is_empty()); let ui_entity = world.spawn(Node::default()).id(); app.update(); let world = app.world_mut(); let ui_surface = world.resource::<UiSurface>(); assert!(ui_surface.entity_to_taffy.contains_key(&ui_entity)); assert_eq!(ui_surface.entity_to_taffy.len(), 1); world.despawn(ui_entity); app.update(); let world = app.world_mut(); let ui_surface = world.resource::<UiSurface>(); assert!(!ui_surface.entity_to_taffy.contains_key(&ui_entity)); assert!(ui_surface.entity_to_taffy.is_empty()); } #[test] #[should_panic] fn despawning_a_ui_entity_should_remove_its_corresponding_ui_node() { let mut app = setup_ui_test_app(); let world = app.world_mut(); let ui_entity = world.spawn(Node::default()).id(); // `ui_layout_system` will insert a ui node into the internal layout tree corresponding to `ui_entity` app.update(); let world = app.world_mut(); // retrieve the ui node corresponding to `ui_entity` from ui surface let ui_surface = world.resource::<UiSurface>(); let ui_node = ui_surface.entity_to_taffy[&ui_entity]; world.despawn(ui_entity); // `ui_layout_system` will receive a `RemovedComponents<Node>` event for `ui_entity` // and remove `ui_entity` from `ui_node` from the internal layout tree app.update(); let world = app.world_mut(); let ui_surface = world.resource::<UiSurface>(); // `ui_node` is removed, attempting to retrieve a style for `ui_node` panics let _ = ui_surface.taffy.style(ui_node.id); } #[test] fn changes_to_children_of_a_ui_entity_change_its_corresponding_ui_nodes_children() { let mut app = setup_ui_test_app(); let world = app.world_mut(); let ui_parent_entity = world.spawn(Node::default()).id(); // `ui_layout_system` will insert a ui node into the internal layout tree corresponding to `ui_entity` app.update(); let world = app.world_mut(); let ui_surface = world.resource::<UiSurface>(); let ui_parent_node = ui_surface.entity_to_taffy[&ui_parent_entity]; // `ui_parent_node` shouldn't have any children yet assert_eq!(ui_surface.taffy.child_count(ui_parent_node.id), 0); let mut ui_child_entities = (0..10) .map(|_| { let child = world.spawn(Node::default()).id(); world.entity_mut(ui_parent_entity).add_child(child); child }) .collect::<Vec<_>>(); app.update(); let world = app.world_mut(); // `ui_parent_node` should have children now let ui_surface = world.resource::<UiSurface>(); assert_eq!( ui_surface.entity_to_taffy.len(), 1 + ui_child_entities.len() ); assert_eq!( ui_surface.taffy.child_count(ui_parent_node.id), ui_child_entities.len() ); let child_node_map = <HashMap<_, _>>::from_iter( ui_child_entities .iter() .map(|child_entity| (*child_entity, ui_surface.entity_to_taffy[child_entity])), ); // the children should have a corresponding ui node and that ui node's parent should be `ui_parent_node` for node in child_node_map.values() { assert_eq!(ui_surface.taffy.parent(node.id), Some(ui_parent_node.id)); } // delete every second child let mut deleted_children = vec![]; for i in (0..ui_child_entities.len()).rev().step_by(2) { let child = ui_child_entities.remove(i); world.despawn(child); deleted_children.push(child); } app.update(); let world = app.world_mut(); let ui_surface = world.resource::<UiSurface>(); assert_eq!( ui_surface.entity_to_taffy.len(), 1 + ui_child_entities.len() ); assert_eq!( ui_surface.taffy.child_count(ui_parent_node.id), ui_child_entities.len() ); // the remaining children should still have nodes in the layout tree for child_entity in &ui_child_entities { let child_node = child_node_map[child_entity]; assert_eq!(ui_surface.entity_to_taffy[child_entity], child_node); assert_eq!( ui_surface.taffy.parent(child_node.id), Some(ui_parent_node.id) ); assert!(ui_surface .taffy .children(ui_parent_node.id) .unwrap() .contains(&child_node.id)); } // the nodes of the deleted children should have been removed from the layout tree for deleted_child_entity in &deleted_children { assert!(!ui_surface .entity_to_taffy .contains_key(deleted_child_entity)); let deleted_child_node = child_node_map[deleted_child_entity]; assert!(!ui_surface .taffy .children(ui_parent_node.id) .unwrap() .contains(&deleted_child_node.id)); } // despawn the parent entity and its descendants world.entity_mut(ui_parent_entity).despawn(); app.update(); let world = app.world_mut(); // all nodes should have been deleted let ui_surface = world.resource::<UiSurface>(); assert!(ui_surface.entity_to_taffy.is_empty()); } /// bugfix test, see [#16288](https://github.com/bevyengine/bevy/pull/16288) #[test] fn node_removal_and_reinsert_should_work() { let mut app = setup_ui_test_app(); app.update(); let world = app.world_mut(); // no UI entities in world, none in UiSurface let ui_surface = world.resource::<UiSurface>(); assert!(ui_surface.entity_to_taffy.is_empty()); let ui_entity = world.spawn(Node::default()).id(); // `ui_layout_system` should map `ui_entity` to a ui node in `UiSurface::entity_to_taffy` app.update(); let world = app.world_mut(); let ui_surface = world.resource::<UiSurface>(); assert!(ui_surface.entity_to_taffy.contains_key(&ui_entity)); assert_eq!(ui_surface.entity_to_taffy.len(), 1); // remove and re-insert Node to trigger removal code in `ui_layout_system` world.entity_mut(ui_entity).remove::<Node>(); world.entity_mut(ui_entity).insert(Node::default()); // `ui_layout_system` should still have `ui_entity` app.update(); let world = app.world_mut(); let ui_surface = world.resource::<UiSurface>(); assert!(ui_surface.entity_to_taffy.contains_key(&ui_entity)); assert_eq!(ui_surface.entity_to_taffy.len(), 1); } #[test] fn node_addition_should_sync_children() { let mut app = setup_ui_test_app(); let world = app.world_mut(); // spawn an invalid UI root node let root_node = world.spawn(()).with_child(Node::default()).id(); app.update(); let world = app.world_mut(); // fix the invalid root node by inserting a Node world.entity_mut(root_node).insert(Node::default()); app.update(); let world = app.world_mut(); let ui_surface = world.resource_mut::<UiSurface>(); let taffy_root = ui_surface.entity_to_taffy[&root_node]; // There should be one child of the root node after fixing it assert_eq!(ui_surface.taffy.child_count(taffy_root.id), 1); } #[test] fn node_addition_should_sync_parent_and_children() { let mut app = setup_ui_test_app(); let world = app.world_mut(); let d = world.spawn(Node::default()).id(); let c = world.spawn(()).add_child(d).id(); let b = world.spawn(Node::default()).id(); let a = world.spawn(Node::default()).add_children(&[b, c]).id(); app.update(); let world = app.world_mut(); // fix the invalid middle node by inserting a Node world.entity_mut(c).insert(Node::default()); app.update(); let world = app.world_mut(); let ui_surface = world.resource::<UiSurface>(); for (entity, n) in [(a, 2), (b, 0), (c, 1), (d, 0)] { let taffy_id = ui_surface.entity_to_taffy[&entity].id; assert_eq!(ui_surface.taffy.child_count(taffy_id), n); } } /// regression test for >=0.13.1 root node layouts /// ensure root nodes act like they are absolutely positioned /// without explicitly declaring it. #[test] fn ui_root_node_should_act_like_position_absolute() { let mut app = setup_ui_test_app(); let world = app.world_mut(); let mut size = 150.; world.spawn(Node { // test should pass without explicitly requiring position_type to be set to Absolute // position_type: PositionType::Absolute, width: Val::Px(size), height: Val::Px(size), ..default() }); size -= 50.; world.spawn(Node { // position_type: PositionType::Absolute, width: Val::Px(size), height: Val::Px(size), ..default() }); size -= 50.; world.spawn(Node { // position_type: PositionType::Absolute, width: Val::Px(size), height: Val::Px(size), ..default() }); app.update(); let world = app.world_mut(); let overlap_check = world .query_filtered::<(Entity, &ComputedNode, &UiGlobalTransform), Without<ChildOf>>() .iter(world) .fold( Option::<(Rect, bool)>::None, |option_rect, (entity, node, transform)| { let current_rect = Rect::from_center_size(transform.translation, node.size()); assert!( current_rect.height().abs() + current_rect.width().abs() > 0., "root ui node {entity} doesn't have a logical size" ); assert_ne!( *transform, UiGlobalTransform::default(), "root ui node {entity} transform is not populated" ); let Some((rect, is_overlapping)) = option_rect else { return Some((current_rect, false)); }; if rect.contains(current_rect.center()) { Some((current_rect, true)) } else { Some((current_rect, is_overlapping)) } }, ); let Some((_rect, is_overlapping)) = overlap_check else { unreachable!("test not setup properly"); }; assert!(is_overlapping, "root ui nodes are expected to behave like they have absolute position and be independent from each other"); } #[test] fn ui_node_should_properly_update_when_changing_target_camera() { #[derive(Component)] struct MovingUiNode; fn update_camera_viewports(mut cameras: Query<&mut Camera>) { let camera_count = cameras.iter().len(); for (camera_index, mut camera) in cameras.iter_mut().enumerate() { let target_size = camera.physical_target_size().unwrap(); let viewport_width = target_size.x / camera_count as u32; let physical_position = UVec2::new(viewport_width * camera_index as u32, 0); let physical_size = UVec2::new(target_size.x / camera_count as u32, target_size.y); camera.viewport = Some(Viewport { physical_position, physical_size, ..default() }); } } fn move_ui_node( In(pos): In<Vec2>, mut commands: Commands, cameras: Query<(Entity, &Camera)>, moving_ui_query: Query<Entity, With<MovingUiNode>>, ) { let (target_camera_entity, _) = cameras .iter() .find(|(_, camera)| { let Some(logical_viewport_rect) = camera.logical_viewport_rect() else { panic!("missing logical viewport") }; // make sure cursor is in viewport and that viewport has at least 1px of size logical_viewport_rect.contains(pos) && logical_viewport_rect.max.cmpge(Vec2::splat(0.)).any() }) .expect("cursor position outside of camera viewport"); for moving_ui_entity in moving_ui_query.iter() { commands .entity(moving_ui_entity) .insert(UiTargetCamera(target_camera_entity)) .insert(Node { position_type: PositionType::Absolute, top: Val::Px(pos.y), left: Val::Px(pos.x), ..default() }); } } fn do_move_and_test(app: &mut App, new_pos: Vec2, expected_camera_entity: &Entity) { let world = app.world_mut(); world.run_system_once_with(move_ui_node, new_pos).unwrap(); app.update(); let world = app.world_mut(); let (ui_node_entity, UiTargetCamera(target_camera_entity)) = world .query_filtered::<(Entity, &UiTargetCamera), With<MovingUiNode>>() .single(world) .expect("missing MovingUiNode"); assert_eq!(expected_camera_entity, target_camera_entity); let mut ui_surface = world.resource_mut::<UiSurface>(); let layout = ui_surface .get_layout(ui_node_entity, true) .expect("failed to get layout") .0; // negative test for #12255 assert_eq!(Vec2::new(layout.location.x, layout.location.y), new_pos); } fn get_taffy_node_count(world: &World) -> usize { world.resource::<UiSurface>().taffy.total_node_count() } let mut app = setup_ui_test_app(); let world = app.world_mut(); world.spawn(( Camera2d, Camera { order: 1, computed: ComputedCameraValues { target_info: Some(RenderTargetInfo { physical_size: UVec2::new(TARGET_WIDTH, TARGET_HEIGHT), scale_factor: 1., }), ..default() }, viewport: Some(Viewport { physical_size: UVec2::new(TARGET_WIDTH, TARGET_HEIGHT), ..default() }), ..default() }, )); world.spawn(( Node { position_type: PositionType::Absolute, top: Val::Px(0.), left: Val::Px(0.), ..default() }, MovingUiNode, )); app.update(); let world = app.world_mut(); let pos_inc = Vec2::splat(1.); let total_cameras = world.query::<&Camera>().iter(world).len(); // add total cameras - 1 (the assumed default) to get an idea for how many nodes we should expect let expected_max_taffy_node_count = get_taffy_node_count(world) + total_cameras - 1; world.run_system_once(update_camera_viewports).unwrap(); app.update(); let world = app.world_mut(); let viewport_rects = world
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/experimental/ghost_hierarchy.rs
crates/bevy_ui/src/experimental/ghost_hierarchy.rs
//! This module contains [`GhostNode`] and utilities to flatten the UI hierarchy, traversing past ghost nodes. #[cfg(feature = "ghost_nodes")] use crate::ui_node::ComputedUiTargetCamera; use crate::Node; #[cfg(feature = "ghost_nodes")] use bevy_camera::visibility::Visibility; use bevy_ecs::{prelude::*, system::SystemParam}; #[cfg(feature = "ghost_nodes")] use bevy_reflect::prelude::*; #[cfg(feature = "ghost_nodes")] use bevy_transform::prelude::Transform; #[cfg(feature = "ghost_nodes")] use smallvec::SmallVec; /// Marker component for entities that should be ignored within UI hierarchies. /// /// The UI systems will traverse past these and treat their first non-ghost descendants as direct children of their first non-ghost ancestor. /// /// Any components necessary for transform and visibility propagation will be added automatically. #[cfg(feature = "ghost_nodes")] #[derive(Component, Debug, Copy, Clone, Reflect)] #[cfg_attr(feature = "ghost_nodes", derive(Default))] #[reflect(Component, Debug, Clone)] #[require(Visibility, Transform, ComputedUiTargetCamera)] pub struct GhostNode; #[cfg(feature = "ghost_nodes")] /// System param that allows iteration of all UI root nodes. /// /// A UI root node is either a [`Node`] without a [`ChildOf`], or with only [`GhostNode`] ancestors. #[derive(SystemParam)] pub struct UiRootNodes<'w, 's> { root_node_query: Query<'w, 's, Entity, (With<Node>, Without<ChildOf>)>, root_ghost_node_query: Query<'w, 's, Entity, (With<GhostNode>, Without<ChildOf>)>, all_nodes_query: Query<'w, 's, Entity, With<Node>>, ui_children: UiChildren<'w, 's>, } #[cfg(not(feature = "ghost_nodes"))] pub type UiRootNodes<'w, 's> = Query<'w, 's, Entity, (With<Node>, Without<ChildOf>)>; #[cfg(feature = "ghost_nodes")] impl<'w, 's> UiRootNodes<'w, 's> { pub fn iter(&'s self) -> impl Iterator<Item = Entity> + 's { self.root_node_query .iter() .chain(self.root_ghost_node_query.iter().flat_map(|root_ghost| { self.all_nodes_query .iter_many(self.ui_children.iter_ui_children(root_ghost)) })) } } #[cfg(feature = "ghost_nodes")] /// System param that gives access to UI children utilities, skipping over [`GhostNode`]. #[derive(SystemParam)] pub struct UiChildren<'w, 's> { ui_children_query: Query< 'w, 's, (Option<&'static Children>, Has<GhostNode>), Or<(With<Node>, With<GhostNode>)>, >, changed_children_query: Query<'w, 's, Entity, Changed<Children>>, children_query: Query<'w, 's, &'static Children>, ghost_nodes_query: Query<'w, 's, Entity, With<GhostNode>>, parents_query: Query<'w, 's, &'static ChildOf>, } #[cfg(not(feature = "ghost_nodes"))] /// System param that gives access to UI children utilities. #[derive(SystemParam)] pub struct UiChildren<'w, 's> { ui_children_query: Query<'w, 's, Option<&'static Children>, With<Node>>, changed_children_query: Query<'w, 's, Entity, Changed<Children>>, parents_query: Query<'w, 's, &'static ChildOf>, } #[cfg(feature = "ghost_nodes")] impl<'w, 's> UiChildren<'w, 's> { /// Iterates the children of `entity`, skipping over [`GhostNode`]. /// /// Traverses the hierarchy depth-first to ensure child order. /// /// # Performance /// /// This iterator allocates if the `entity` node has more than 8 children (including ghost nodes). pub fn iter_ui_children(&'s self, entity: Entity) -> UiChildrenIter<'w, 's> { UiChildrenIter { stack: self .ui_children_query .get(entity) .map_or(SmallVec::new(), |(children, _)| { children.into_iter().flatten().rev().copied().collect() }), query: &self.ui_children_query, } } /// Returns the UI parent of the provided entity, skipping over [`GhostNode`]. pub fn get_parent(&'s self, entity: Entity) -> Option<Entity> { self.parents_query .iter_ancestors(entity) .find(|entity| !self.ghost_nodes_query.contains(*entity)) } /// Iterates the [`GhostNode`]s between this entity and its UI children. pub fn iter_ghost_nodes(&'s self, entity: Entity) -> Box<dyn Iterator<Item = Entity> + 's> { Box::new( self.children_query .get(entity) .into_iter() .flat_map(|children| { self.ghost_nodes_query .iter_many(children) .flat_map(|entity| { core::iter::once(entity).chain(self.iter_ghost_nodes(entity)) }) }), ) } /// Given an entity in the UI hierarchy, check if its set of children has changed, e.g if children has been added/removed or if the order has changed. pub fn is_changed(&'s self, entity: Entity) -> bool { self.changed_children_query.contains(entity) || self .iter_ghost_nodes(entity) .any(|entity| self.changed_children_query.contains(entity)) } /// Returns `true` if the given entity is either a [`Node`] or a [`GhostNode`]. pub fn is_ui_node(&'s self, entity: Entity) -> bool { self.ui_children_query.contains(entity) } } #[cfg(not(feature = "ghost_nodes"))] impl<'w, 's> UiChildren<'w, 's> { /// Iterates the children of `entity`. pub fn iter_ui_children(&'s self, entity: Entity) -> impl Iterator<Item = Entity> + 's { self.ui_children_query .get(entity) .ok() .flatten() .map(|children| children.as_ref()) .unwrap_or(&[]) .iter() .copied() } /// Returns the UI parent of the provided entity. pub fn get_parent(&'s self, entity: Entity) -> Option<Entity> { self.parents_query.get(entity).ok().map(ChildOf::parent) } /// Given an entity in the UI hierarchy, check if its set of children has changed, e.g if children has been added/removed or if the order has changed. pub fn is_changed(&'s self, entity: Entity) -> bool { self.changed_children_query.contains(entity) } /// Returns `true` if the given entity is either a [`Node`] or a [`GhostNode`]. pub fn is_ui_node(&'s self, entity: Entity) -> bool { self.ui_children_query.contains(entity) } } #[cfg(feature = "ghost_nodes")] pub struct UiChildrenIter<'w, 's> { stack: SmallVec<[Entity; 8]>, query: &'s Query< 'w, 's, (Option<&'static Children>, Has<GhostNode>), Or<(With<Node>, With<GhostNode>)>, >, } #[cfg(feature = "ghost_nodes")] impl<'w, 's> Iterator for UiChildrenIter<'w, 's> { type Item = Entity; fn next(&mut self) -> Option<Self::Item> { loop { let entity = self.stack.pop()?; if let Ok((children, has_ghost_node)) = self.query.get(entity) { if !has_ghost_node { return Some(entity); } if let Some(children) = children { self.stack.extend(children.iter().rev()); } } } } } #[cfg(all(test, feature = "ghost_nodes"))] mod tests { use bevy_ecs::{ prelude::Component, system::{Query, SystemState}, world::World, }; use super::{GhostNode, Node, UiChildren, UiRootNodes}; #[derive(Component, PartialEq, Debug)] struct A(usize); #[test] fn iterate_ui_root_nodes() { let world = &mut World::new(); // Normal root world .spawn((A(1), Node::default())) .with_children(|parent| { parent.spawn((A(2), Node::default())); parent .spawn((A(3), GhostNode)) .with_child((A(4), Node::default())); }); // Ghost root world.spawn((A(5), GhostNode)).with_children(|parent| { parent.spawn((A(6), Node::default())); parent .spawn((A(7), GhostNode)) .with_child((A(8), Node::default())) .with_child(A(9)); }); let mut system_state = SystemState::<(UiRootNodes, Query<&A>)>::new(world); let (ui_root_nodes, a_query) = system_state.get(world); let result: Vec<_> = a_query.iter_many(ui_root_nodes.iter()).collect(); assert_eq!([&A(1), &A(6), &A(8)], result.as_slice()); } #[test] fn iterate_ui_children() { let world = &mut World::new(); let n1 = world.spawn((A(1), Node::default())).id(); let n2 = world.spawn((A(2), GhostNode)).id(); let n3 = world.spawn((A(3), GhostNode)).id(); let n4 = world.spawn((A(4), Node::default())).id(); let n5 = world.spawn((A(5), Node::default())).id(); let n6 = world.spawn((A(6), GhostNode)).id(); let n7 = world.spawn((A(7), GhostNode)).id(); let n8 = world.spawn((A(8), Node::default())).id(); let n9 = world.spawn((A(9), GhostNode)).id(); let n10 = world.spawn((A(10), Node::default())).id(); let no_ui = world.spawn_empty().id(); world.entity_mut(n1).add_children(&[n2, n3, n4, n6]); world.entity_mut(n2).add_children(&[n5]); world.entity_mut(n6).add_children(&[n7, no_ui, n9]); world.entity_mut(n7).add_children(&[n8]); world.entity_mut(n9).add_children(&[n10]); let mut system_state = SystemState::<(UiChildren, Query<&A>)>::new(world); let (ui_children, a_query) = system_state.get(world); let result: Vec<_> = a_query .iter_many(ui_children.iter_ui_children(n1)) .collect(); assert_eq!([&A(5), &A(4), &A(8), &A(10)], result.as_slice()); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/experimental/mod.rs
crates/bevy_ui/src/experimental/mod.rs
//! Experimental features are not yet stable and may change or be removed in the future. //! //! These features are not recommended for production use, but are available to ease experimentation //! within Bevy's ecosystem. Please let us know how you are using these features and what you would //! like to see improved! //! //! These may be feature-flagged: check the `Cargo.toml` for `bevy_ui` to see what options //! are available. //! //! # Warning //! //! Be careful when using these features, especially in concert with third-party crates, //! as they may not be fully supported, functional or stable. mod ghost_hierarchy; pub use ghost_hierarchy::*;
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/widget/button.rs
crates/bevy_ui/src/widget/button.rs
use crate::{FocusPolicy, Interaction, Node}; use bevy_ecs::{component::Component, reflect::ReflectComponent}; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; /// Marker struct for buttons #[derive(Component, Debug, Default, Clone, Copy, PartialEq, Eq, Reflect)] #[reflect(Component, Default, Debug, PartialEq, Clone)] #[require(Node, FocusPolicy::Block, Interaction)] pub struct Button;
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/widget/viewport.rs
crates/bevy_ui/src/widget/viewport.rs
#[cfg(feature = "bevy_picking")] use crate::UiGlobalTransform; use crate::{ComputedNode, Node}; use bevy_asset::Assets; #[cfg(feature = "bevy_picking")] use bevy_camera::Camera; use bevy_camera::RenderTarget; use bevy_ecs::{ component::Component, entity::Entity, query::{Changed, Or}, reflect::ReflectComponent, system::{Query, ResMut}, }; #[cfg(feature = "bevy_picking")] use bevy_ecs::{ message::MessageReader, system::{Commands, Res}, }; use bevy_image::{Image, ToExtents}; use bevy_math::UVec2; #[cfg(feature = "bevy_picking")] use bevy_picking::{ events::PointerState, hover::HoverMap, pointer::{Location, PointerId, PointerInput, PointerLocation}, }; use bevy_reflect::Reflect; /// Component used to render a [`RenderTarget`] to a node. /// /// # See Also /// /// [`update_viewport_render_target_size`] #[derive(Component, Debug, Clone, Copy, Reflect)] #[reflect(Component, Debug)] #[require(Node)] #[cfg_attr( feature = "bevy_picking", require(PointerId::Custom(uuid::Uuid::new_v4())) )] pub struct ViewportNode { /// The entity representing the [`Camera`] associated with this viewport. /// /// Note that removing the [`ViewportNode`] component will not despawn this entity. pub camera: Entity, } impl ViewportNode { /// Creates a new [`ViewportNode`] with a given `camera`. #[inline] pub const fn new(camera: Entity) -> Self { Self { camera } } } #[cfg(feature = "bevy_picking")] /// Handles viewport picking logic. /// /// Viewport entities that are being hovered or dragged will have all pointer inputs sent to them. pub fn viewport_picking( mut commands: Commands, mut viewport_query: Query<( Entity, &ViewportNode, &PointerId, &mut PointerLocation, &ComputedNode, &UiGlobalTransform, )>, camera_query: Query<(&Camera, &RenderTarget)>, hover_map: Res<HoverMap>, pointer_state: Res<PointerState>, mut pointer_inputs: MessageReader<PointerInput>, ) { use bevy_camera::NormalizedRenderTarget; use bevy_math::Rect; use bevy_platform::collections::HashMap; // Handle hovered entities. let mut viewport_picks: HashMap<Entity, PointerId> = hover_map .iter() .flat_map(|(hover_pointer_id, hits)| { hits.iter() .filter(|(entity, _)| viewport_query.contains(**entity)) .map(|(entity, _)| (*entity, *hover_pointer_id)) }) .collect(); // Handle dragged entities, which need to be considered for dragging in and out of viewports. for ((pointer_id, _), pointer_state) in pointer_state.pointer_buttons.iter() { for &target in pointer_state .dragging .keys() .filter(|&entity| viewport_query.contains(*entity)) { viewport_picks.insert(target, *pointer_id); } } for ( viewport_entity, &viewport, &viewport_pointer_id, mut viewport_pointer_location, computed_node, global_transform, ) in &mut viewport_query { let Some(pick_pointer_id) = viewport_picks.get(&viewport_entity) else { // Lift the viewport pointer if it's not being used. viewport_pointer_location.location = None; continue; }; let Ok((camera, render_target)) = camera_query.get(viewport.camera) else { continue; }; let Some(cam_viewport_size) = camera.logical_viewport_size() else { continue; }; // Create a `Rect` in *physical* coordinates centered at the node's GlobalTransform let node_rect = Rect::from_center_size(global_transform.translation.trunc(), computed_node.size()); // Location::position uses *logical* coordinates let top_left = node_rect.min * computed_node.inverse_scale_factor(); let logical_size = computed_node.size() * computed_node.inverse_scale_factor(); let Some(target) = render_target.as_image() else { continue; }; for input in pointer_inputs .read() .filter(|input| &input.pointer_id == pick_pointer_id) { let local_position = (input.location.position - top_left) / logical_size; let position = local_position * cam_viewport_size; let location = Location { position, target: NormalizedRenderTarget::Image(target.clone().into()), }; viewport_pointer_location.location = Some(location.clone()); commands.write_message(PointerInput { location, pointer_id: viewport_pointer_id, action: input.action, }); } } } /// Updates the size of the associated render target for viewports when the node size changes. pub fn update_viewport_render_target_size( viewport_query: Query< (&ViewportNode, &ComputedNode), Or<(Changed<ComputedNode>, Changed<ViewportNode>)>, >, camera_query: Query<&RenderTarget>, mut images: ResMut<Assets<Image>>, ) { for (viewport, computed_node) in &viewport_query { let render_target = camera_query.get(viewport.camera).unwrap(); let size = computed_node.size(); let Some(image_handle) = render_target.as_image() else { continue; }; let size = size.as_uvec2().max(UVec2::ONE).to_extents(); images.get_mut(image_handle).unwrap().resize(size); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ui/src/widget/image.rs
crates/bevy_ui/src/widget/image.rs
use crate::{ComputedUiRenderTargetInfo, ContentSize, Measure, MeasureArgs, Node, NodeMeasure}; use bevy_asset::{AsAssetId, AssetId, Assets, Handle}; use bevy_color::Color; use bevy_ecs::prelude::*; use bevy_image::{prelude::*, TRANSPARENT_IMAGE_HANDLE}; use bevy_math::{Rect, UVec2, Vec2}; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_sprite::TextureSlicer; use taffy::{MaybeMath, MaybeResolve}; /// A UI Node that renders an image. #[derive(Component, Clone, Debug, Reflect)] #[reflect(Component, Default, Debug, Clone)] #[require(Node, ImageNodeSize, ContentSize)] pub struct ImageNode { /// The tint color used to draw the image. /// /// This is multiplied by the color of each pixel in the image. /// The field value defaults to solid white, which will pass the image through unmodified. pub color: Color, /// Handle to the texture. /// /// This defaults to a [`TRANSPARENT_IMAGE_HANDLE`], which points to a fully transparent 1x1 texture. pub image: Handle<Image>, /// The (optional) texture atlas used to render the image. pub texture_atlas: Option<TextureAtlas>, /// Whether the image should be flipped along its x-axis. pub flip_x: bool, /// Whether the image should be flipped along its y-axis. pub flip_y: bool, /// An optional rectangle representing the region of the image to render, instead of rendering /// the full image. This is an easy one-off alternative to using a [`TextureAtlas`]. /// /// When used with a [`TextureAtlas`], the rect /// is offset by the atlas's minimal (top-left) corner position. pub rect: Option<Rect>, /// Controls how the image is altered to fit within the layout and how the layout algorithm determines the space to allocate for the image. pub image_mode: NodeImageMode, } impl Default for ImageNode { /// A transparent 1x1 image with a solid white tint. /// /// # Warning /// /// This will be invisible by default. /// To set this to a visible image, you need to set the `texture` field to a valid image handle, /// or use [`Handle<Image>`]'s default 1x1 solid white texture (as is done in [`ImageNode::solid_color`]). fn default() -> Self { ImageNode { // This should be white because the tint is multiplied with the image, // so if you set an actual image with default tint you'd want its original colors color: Color::WHITE, texture_atlas: None, // This texture needs to be transparent by default, to avoid covering the background color image: TRANSPARENT_IMAGE_HANDLE, flip_x: false, flip_y: false, rect: None, image_mode: NodeImageMode::Auto, } } } impl ImageNode { /// Create a new [`ImageNode`] with the given texture. pub fn new(texture: Handle<Image>) -> Self { Self { image: texture, color: Color::WHITE, ..Default::default() } } /// Create a solid color [`ImageNode`]. /// /// This is primarily useful for debugging / mocking the extents of your image. pub fn solid_color(color: Color) -> Self { Self { image: Handle::default(), color, flip_x: false, flip_y: false, texture_atlas: None, rect: None, image_mode: NodeImageMode::Auto, } } /// Create a [`ImageNode`] from an image, with an associated texture atlas pub fn from_atlas_image(image: Handle<Image>, atlas: TextureAtlas) -> Self { Self { image, texture_atlas: Some(atlas), ..Default::default() } } /// Set the color tint #[must_use] pub const fn with_color(mut self, color: Color) -> Self { self.color = color; self } /// Flip the image along its x-axis #[must_use] pub const fn with_flip_x(mut self) -> Self { self.flip_x = true; self } /// Flip the image along its y-axis #[must_use] pub const fn with_flip_y(mut self) -> Self { self.flip_y = true; self } #[must_use] pub const fn with_rect(mut self, rect: Rect) -> Self { self.rect = Some(rect); self } #[must_use] pub const fn with_mode(mut self, mode: NodeImageMode) -> Self { self.image_mode = mode; self } } impl From<Handle<Image>> for ImageNode { fn from(texture: Handle<Image>) -> Self { Self::new(texture) } } impl AsAssetId for ImageNode { type Asset = Image; fn as_asset_id(&self) -> AssetId<Self::Asset> { self.image.id() } } /// Controls how the image is altered to fit within the layout and how the layout algorithm determines the space in the layout for the image #[derive(Default, Debug, Clone, PartialEq, Reflect)] #[reflect(Clone, Default, PartialEq)] pub enum NodeImageMode { /// The image will be sized automatically by taking the size of the source image and applying any layout constraints. #[default] Auto, /// The image will be resized to match the size of the node. The image's original size and aspect ratio will be ignored. Stretch, /// The texture will be cut in 9 slices, keeping the texture in proportions on resize Sliced(TextureSlicer), /// The texture will be repeated if stretched beyond `stretched_value` Tiled { /// Should the image repeat horizontally tile_x: bool, /// Should the image repeat vertically tile_y: bool, /// The texture will repeat when the ratio between the *drawing dimensions* of texture and the /// *original texture size* are above this value. stretch_value: f32, }, } impl NodeImageMode { /// Returns true if this mode uses slices internally ([`NodeImageMode::Sliced`] or [`NodeImageMode::Tiled`]) #[inline] pub const fn uses_slices(&self) -> bool { matches!( self, NodeImageMode::Sliced(..) | NodeImageMode::Tiled { .. } ) } } /// The size of the image's texture /// /// This component is updated automatically by [`update_image_content_size_system`] #[derive(Component, Debug, Copy, Clone, Default, Reflect)] #[reflect(Component, Default, Debug, Clone)] pub struct ImageNodeSize { /// The size of the image's texture /// /// This field is updated automatically by [`update_image_content_size_system`] size: UVec2, } impl ImageNodeSize { /// The size of the image's texture #[inline] pub const fn size(&self) -> UVec2 { self.size } } #[derive(Clone)] /// Used to calculate the size of UI image nodes pub struct ImageMeasure { /// The size of the image's texture pub size: Vec2, } // NOOP function used to call into taffy API fn resolve_calc(_calc_ptr: *const (), _parent_size: f32) -> f32 { 0.0 } impl Measure for ImageMeasure { fn measure(&mut self, measure_args: MeasureArgs, style: &taffy::Style) -> Vec2 { let MeasureArgs { width, height, available_width, available_height, .. } = measure_args; // Convert available width/height into an option let parent_width = available_width.into_option(); let parent_height = available_height.into_option(); // Resolve styles let s_aspect_ratio = style.aspect_ratio; let s_width = style.size.width.maybe_resolve(parent_width, resolve_calc); let s_min_width = style .min_size .width .maybe_resolve(parent_width, resolve_calc); let s_max_width = style .max_size .width .maybe_resolve(parent_width, resolve_calc); let s_height = style.size.height.maybe_resolve(parent_height, resolve_calc); let s_min_height = style .min_size .height .maybe_resolve(parent_height, resolve_calc); let s_max_height = style .max_size .height .maybe_resolve(parent_height, resolve_calc); // Determine width and height from styles and known_sizes (if a size is available // from any of these sources) let width = width.or(s_width .or(s_min_width) .maybe_clamp(s_min_width, s_max_width)); let height = height.or(s_height .or(s_min_height) .maybe_clamp(s_min_height, s_max_height)); // Use aspect_ratio from style, fall back to inherent aspect ratio let aspect_ratio = s_aspect_ratio.unwrap_or_else(|| self.size.x / self.size.y); // Apply aspect ratio // If only one of width or height was determined at this point, then the other is set beyond this point using the aspect ratio. let taffy_size = taffy::Size { width, height }.maybe_apply_aspect_ratio(Some(aspect_ratio)); // Use computed sizes or fall back to image's inherent size Vec2 { x: taffy_size .width .unwrap_or(self.size.x) .maybe_clamp(s_min_width, s_max_width), y: taffy_size .height .unwrap_or(self.size.y) .maybe_clamp(s_min_height, s_max_height), } } } type UpdateImageFilter = (With<Node>, Without<crate::prelude::Text>); /// Updates content size of the node based on the image provided pub fn update_image_content_size_system( textures: Res<Assets<Image>>, atlases: Res<Assets<TextureAtlasLayout>>, mut query: Query< ( &mut ContentSize, Ref<ImageNode>, &mut ImageNodeSize, Ref<ComputedUiRenderTargetInfo>, ), UpdateImageFilter, >, ) { for (mut content_size, image, mut image_size, computed_target) in &mut query { if !matches!(image.image_mode, NodeImageMode::Auto) || image.image.id() == TRANSPARENT_IMAGE_HANDLE.id() { if image.is_changed() { // Mutably derefs, marking the `ContentSize` as changed ensuring `ui_layout_system` will remove the node's measure func if present. content_size.measure = None; } continue; } if let Some(size) = image .rect .map(|rect| rect.size().as_uvec2()) .or_else(|| match &image.texture_atlas { Some(atlas) => atlas.texture_rect(&atlases).map(|t| t.size()), None => textures.get(&image.image).map(Image::size), }) { // Update only if size or scale factor has changed to avoid needless layout calculations if size != image_size.size || computed_target.is_changed() || content_size.is_added() { image_size.size = size; content_size.set(NodeMeasure::Image(ImageMeasure { // multiply the image size by the scale factor to get the physical size size: size.as_vec2() * computed_target.scale_factor(), })); } } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false