Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom MeasureFunc #7730

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 22 additions & 25 deletions crates/bevy_ui/src/flex/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,38 +97,35 @@ impl FlexSurface {
&mut self,
entity: Entity,
style: &Style,
calculated_size: CalculatedSize,
calculated_size: &CalculatedSize,
context: &LayoutContext,
) {
let taffy = &mut self.taffy;
let taffy_style = convert::from_style(context, style);
let scale_factor = context.scale_factor;
let m = calculated_size.measure.dyn_clone();
let measure = taffy::node::MeasureFunc::Boxed(Box::new(
move |constraints: Size<Option<f32>>, _available: Size<AvailableSpace>| {
let mut size = Size {
width: (scale_factor * calculated_size.size.x as f64) as f32,
height: (scale_factor * calculated_size.size.y as f64) as f32,
};
match (constraints.width, constraints.height) {
(None, None) => {}
(Some(width), None) => {
if calculated_size.preserve_aspect_ratio {
size.height = width * size.height / size.width;
move |constraints: Size<Option<f32>>, available_space: Size<AvailableSpace>| {
let size = m.measure(
constraints.width.map(|w| (w as f64 / scale_factor) as f32),
constraints.height.map(|h| (h as f64 / scale_factor) as f32),
match available_space.width {
AvailableSpace::Definite(w) => {
AvailableSpace::Definite((w as f64 / scale_factor) as f32)
}
size.width = width;
}
(None, Some(height)) => {
if calculated_size.preserve_aspect_ratio {
size.width = height * size.width / size.height;
s => s,
},
match available_space.height {
AvailableSpace::Definite(h) => {
AvailableSpace::Definite((h as f64 / scale_factor) as f32)
}
size.height = height;
}
(Some(width), Some(height)) => {
size.width = width;
size.height = height;
}
s => s,
},
);
taffy::geometry::Size {
width: (size.x as f64 * scale_factor) as f32,
height: (size.y as f64 * scale_factor) as f32,
}
size
},
));
if let Some(taffy_node) = self.entity_to_taffy.get(&entity) {
Expand Down Expand Up @@ -307,7 +304,7 @@ pub fn flex_node_system(
for (entity, style, calculated_size) in &query {
// TODO: remove node from old hierarchy if its root has changed
if let Some(calculated_size) = calculated_size {
flex_surface.upsert_leaf(entity, style, *calculated_size, viewport_values);
flex_surface.upsert_leaf(entity, style, calculated_size, viewport_values);
} else {
flex_surface.upsert_node(entity, style, viewport_values);
}
Expand All @@ -322,7 +319,7 @@ pub fn flex_node_system(
}

for (entity, style, calculated_size) in &changed_size_query {
flex_surface.upsert_leaf(entity, style, *calculated_size, &viewport_values);
flex_surface.upsert_leaf(entity, style, calculated_size, &viewport_values);
}

// clean up removed nodes
Expand Down
6 changes: 4 additions & 2 deletions crates/bevy_ui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ mod ui_node;
#[cfg(feature = "bevy_text")]
mod accessibility;
pub mod camera_config;
pub mod measurement;
pub mod node_bundles;
pub mod update;
pub mod widget;
Expand All @@ -24,14 +25,16 @@ use bevy_render::extract_component::ExtractComponentPlugin;
pub use flex::*;
pub use focus::*;
pub use geometry::*;
pub use measurement::*;
pub use render::*;
pub use ui_node::*;

#[doc(hidden)]
pub mod prelude {
#[doc(hidden)]
pub use crate::{
camera_config::*, geometry::*, node_bundles::*, ui_node::*, widget::*, Interaction, UiScale,
camera_config::*, geometry::*, measurement::*, node_bundles::*, ui_node::*, widget::*,
Interaction, UiScale,
};
}

Expand Down Expand Up @@ -85,7 +88,6 @@ impl Plugin for UiPlugin {
.register_type::<AlignContent>()
.register_type::<AlignItems>()
.register_type::<AlignSelf>()
.register_type::<CalculatedSize>()
.register_type::<Direction>()
.register_type::<Display>()
.register_type::<FlexDirection>()
Expand Down
104 changes: 104 additions & 0 deletions crates/bevy_ui/src/measurement.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
use bevy_ecs::prelude::Component;
use bevy_math::Vec2;
use std::fmt::Formatter;
pub use taffy::style::AvailableSpace;

/// The calculated size of the node
#[derive(Component)]
pub struct CalculatedSize {
pub size: Vec2,
/// The measure function used to calculate the size
pub measure: Box<dyn NodeMeasure>,
}

impl Clone for CalculatedSize {
fn clone(&self) -> Self {
Self {
size: self.size.clone(),
measure: self.measure.dyn_clone(),
}
}
}

impl Default for CalculatedSize {
fn default() -> Self {
Self {
size: Default::default(),
measure: Box::new(|w: Option<f32>, h: Option<f32>, _, _| {
Vec2::new(w.unwrap_or(0.), h.unwrap_or(0.))
}),
}
}
}

impl std::fmt::Debug for CalculatedSize {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CalculatedSize")
.field("size", &self.size)
.finish()
}
}

pub trait NodeMeasure: Send + Sync + 'static {
/// Calculate the size of the node given the constraints.
fn measure(
&self,
width: Option<f32>,
height: Option<f32>,
available_width: AvailableSpace,
available_height: AvailableSpace,
) -> Vec2;

/// Clone and box self.
fn dyn_clone(&self) -> Box<dyn NodeMeasure>;
}

#[derive(Clone)]
pub struct BasicMeasure {
/// Prefered size
pub size: Vec2,
}

impl NodeMeasure for BasicMeasure {
fn measure(
&self,
width: Option<f32>,
height: Option<f32>,
_: AvailableSpace,
_: AvailableSpace,
) -> Vec2 {
match (width, height) {
(Some(width), Some(height)) => Vec2::new(width, height),
(Some(width), None) => Vec2::new(width, self.size.y),
(None, Some(height)) => Vec2::new(self.size.x, height),
(None, None) => self.size,
}
}

fn dyn_clone(&self) -> Box<dyn NodeMeasure> {
Box::new(self.clone())
}
}

impl<F> NodeMeasure for F
where
F: Fn(Option<f32>, Option<f32>, AvailableSpace, AvailableSpace) -> Vec2
+ Send
+ Sync
+ 'static
+ Clone,
{
fn measure(
&self,
width: Option<f32>,
height: Option<f32>,
available_width: AvailableSpace,
available_height: AvailableSpace,
) -> Vec2 {
self(width, height, available_width, available_height)
}

fn dyn_clone(&self) -> Box<dyn NodeMeasure> {
Box::new(self.clone())
}
}
2 changes: 1 addition & 1 deletion crates/bevy_ui/src/node_bundles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ impl Default for NodeBundle {
}

/// A UI node that is an image
#[derive(Bundle, Clone, Debug, Default)]
#[derive(Bundle, Debug, Default)]
pub struct ImageBundle {
/// Describes the logical size of the node
pub node: Node,
Expand Down
23 changes: 0 additions & 23 deletions crates/bevy_ui/src/ui_node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -682,29 +682,6 @@ impl Default for FlexWrap {
}
}

/// The calculated size of the node
#[derive(Component, Copy, Clone, Debug, Reflect)]
#[reflect(Component)]
pub struct CalculatedSize {
/// The size of the node in logical pixels
pub size: Vec2,
/// Whether to attempt to preserve the aspect ratio when determining the layout for this item
pub preserve_aspect_ratio: bool,
}

impl CalculatedSize {
const DEFAULT: Self = Self {
size: Vec2::ZERO,
preserve_aspect_ratio: false,
};
}

impl Default for CalculatedSize {
fn default() -> Self {
Self::DEFAULT
}
}

/// The background color of the node
///
/// This serves as the "fill" color.
Expand Down
42 changes: 40 additions & 2 deletions crates/bevy_ui/src/widget/image.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{CalculatedSize, UiImage};
use crate::{CalculatedSize, NodeMeasure, UiImage};
use bevy_asset::Assets;
#[cfg(feature = "bevy_text")]
use bevy_ecs::query::Without;
Expand All @@ -7,6 +7,44 @@ use bevy_math::Vec2;
use bevy_render::texture::Image;
#[cfg(feature = "bevy_text")]
use bevy_text::Text;
use taffy::prelude::AvailableSpace;

#[derive(Clone)]
pub struct ImageMeasure {
size: Vec2,
}

impl NodeMeasure for ImageMeasure {
fn measure(
&self,
width: Option<f32>,
height: Option<f32>,
_: AvailableSpace,
_: AvailableSpace,
) -> Vec2 {
let mut size = self.size;
match (width, height) {
(None, None) => {}
(Some(width), None) => {
size.y = width * size.y / size.x;
size.x = width;
}
(None, Some(height)) => {
size.x = height * size.x / size.y;
size.y = height;
}
(Some(width), Some(height)) => {
size.x = width;
size.y = height;
}
}
size
}

fn dyn_clone(&self) -> Box<dyn NodeMeasure> {
Box::new(self.clone())
}
}

/// Updates calculated size of the node based on the image provided
pub fn update_image_calculated_size_system(
Expand All @@ -23,7 +61,7 @@ pub fn update_image_calculated_size_system(
// Update only if size has changed to avoid needless layout calculations
if size != calculated_size.size {
calculated_size.size = size;
calculated_size.preserve_aspect_ratio = true;
calculated_size.measure = Box::new(ImageMeasure { size });
}
}
}
Expand Down
12 changes: 7 additions & 5 deletions crates/bevy_ui/src/widget/text.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{CalculatedSize, Node, Style, UiScale, Val};
use crate::{BasicMeasure, CalculatedSize, Node, Style, UiScale, Val};
use bevy_asset::Assets;
use bevy_ecs::{
entity::Entity,
Expand Down Expand Up @@ -133,10 +133,12 @@ pub fn text_system(
panic!("Fatal error when processing text: {e}.");
}
Ok(info) => {
calculated_size.size = Vec2::new(
scale_value(info.size.x, inv_scale_factor),
scale_value(info.size.y, inv_scale_factor),
);
calculated_size.measure = Box::new(BasicMeasure {
size: Vec2::new(
scale_value(info.size.x, inv_scale_factor),
scale_value(info.size.y, inv_scale_factor),
),
});
match text_layout_info {
Some(mut t) => *t = info,
None => {
Expand Down