Remove Size and UiRect generics (#5404)

# Objective

- Migrate changes from #3503.

## Solution

- Change `Size<T>` and `UiRect<T>` to `Size` and `UiRect` using `Val`.
- Implement `Sub`, `SubAssign`, `Mul`, `MulAssign`, `Div` and `DivAssign` for `Val`.
- Update tests for `Size`.

---

## Changelog

### Changed

- The generic `T` of `Size` and `UiRect` got removed and instead they both now always use `Val`.

## Migration Guide

- The generic `T` of `Size` and `UiRect` got removed and instead they both now always use `Val`. If you used a `Size<f32>` consider replacing it with a `Vec2` which is way more powerful.


Co-authored-by: KDecay <KDecayMusic@protonmail.com>
This commit is contained in:
KDecay 2022-08-01 16:27:16 +00:00
parent 6752c9c59b
commit bf085ee1d2
6 changed files with 166 additions and 111 deletions

View File

@ -5,7 +5,7 @@ use crate::{
pub fn from_rect( pub fn from_rect(
scale_factor: f64, scale_factor: f64,
rect: UiRect<Val>, rect: UiRect,
) -> taffy::geometry::Rect<taffy::style::Dimension> { ) -> taffy::geometry::Rect<taffy::style::Dimension> {
taffy::geometry::Rect { taffy::geometry::Rect {
start: from_val(scale_factor, rect.left), start: from_val(scale_factor, rect.left),
@ -16,16 +16,16 @@ pub fn from_rect(
} }
} }
pub fn from_f32_size(scale_factor: f64, size: Size<f32>) -> taffy::geometry::Size<f32> { pub fn from_f32_size(scale_factor: f64, size: Size) -> taffy::geometry::Size<f32> {
taffy::geometry::Size { taffy::geometry::Size {
width: (scale_factor * size.width as f64) as f32, width: val_to_f32(scale_factor, size.width),
height: (scale_factor * size.height as f64) as f32, height: val_to_f32(scale_factor, size.height),
} }
} }
pub fn from_val_size( pub fn from_val_size(
scale_factor: f64, scale_factor: f64,
size: Size<Val>, size: Size,
) -> taffy::geometry::Size<taffy::style::Dimension> { ) -> taffy::geometry::Size<taffy::style::Dimension> {
taffy::geometry::Size { taffy::geometry::Size {
width: from_val(scale_factor, size.width), width: from_val(scale_factor, size.width),
@ -60,6 +60,15 @@ pub fn from_style(scale_factor: f64, value: &Style) -> taffy::style::Style {
} }
} }
/// Converts a [`Val`] to a [`f32`] while respecting the scale factor.
pub fn val_to_f32(scale_factor: f64, val: Val) -> f32 {
match val {
Val::Undefined | Val::Auto => 0.0,
Val::Px(value) => (scale_factor * value as f64) as f32,
Val::Percent(value) => value / 100.0,
}
}
pub fn from_val(scale_factor: f64, val: Val) -> taffy::style::Dimension { pub fn from_val(scale_factor: f64, val: Val) -> taffy::style::Dimension {
match val { match val {
Val::Auto => taffy::style::Dimension::Auto, Val::Auto => taffy::style::Dimension::Auto,

View File

@ -1,3 +1,4 @@
use crate::Val;
use bevy_math::Vec2; use bevy_math::Vec2;
use bevy_reflect::Reflect; use bevy_reflect::Reflect;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
@ -119,20 +120,20 @@ use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
/// bottom: Val::Px(40.0), /// bottom: Val::Px(40.0),
/// }; /// };
/// ``` /// ```
#[derive(Copy, Clone, PartialEq, Debug, Reflect)] #[derive(Copy, Clone, PartialEq, Debug, Default, Reflect)]
#[reflect(PartialEq)] #[reflect(PartialEq)]
pub struct UiRect<T: Reflect + PartialEq> { pub struct UiRect {
/// The value corresponding to the left side of the UI rect. /// The value corresponding to the left side of the UI rect.
pub left: T, pub left: Val,
/// The value corresponding to the right side of the UI rect. /// The value corresponding to the right side of the UI rect.
pub right: T, pub right: Val,
/// The value corresponding to the top side of the UI rect. /// The value corresponding to the top side of the UI rect.
pub top: T, pub top: Val,
/// The value corresponding to the bottom side of the UI rect. /// The value corresponding to the bottom side of the UI rect.
pub bottom: T, pub bottom: Val,
} }
impl<T: Reflect + PartialEq> UiRect<T> { impl UiRect {
/// Creates a new [`UiRect`] from the values specified. /// Creates a new [`UiRect`] from the values specified.
/// ///
/// # Example /// # Example
@ -152,7 +153,7 @@ impl<T: Reflect + PartialEq> UiRect<T> {
/// assert_eq!(ui_rect.top, Val::Px(30.0)); /// assert_eq!(ui_rect.top, Val::Px(30.0));
/// assert_eq!(ui_rect.bottom, Val::Px(40.0)); /// assert_eq!(ui_rect.bottom, Val::Px(40.0));
/// ``` /// ```
pub fn new(left: T, right: T, top: T, bottom: T) -> Self { pub fn new(left: Val, right: Val, top: Val, bottom: Val) -> Self {
UiRect { UiRect {
left, left,
right, right,
@ -175,43 +176,29 @@ impl<T: Reflect + PartialEq> UiRect<T> {
/// assert_eq!(ui_rect.top, Val::Px(10.0)); /// assert_eq!(ui_rect.top, Val::Px(10.0));
/// assert_eq!(ui_rect.bottom, Val::Px(10.0)); /// assert_eq!(ui_rect.bottom, Val::Px(10.0));
/// ``` /// ```
pub fn all(value: T) -> Self pub fn all(value: Val) -> Self {
where
T: Clone,
{
UiRect { UiRect {
left: value.clone(), left: value,
right: value.clone(), right: value,
top: value.clone(), top: value,
bottom: value, bottom: value,
} }
} }
} }
impl<T: Default + Reflect + PartialEq> Default for UiRect<T> {
fn default() -> Self {
Self {
left: Default::default(),
right: Default::default(),
top: Default::default(),
bottom: Default::default(),
}
}
}
/// A 2-dimensional area defined by a width and height. /// A 2-dimensional area defined by a width and height.
/// ///
/// It is commonly used to define the size of a text or UI element. /// It is commonly used to define the size of a text or UI element.
#[derive(Copy, Clone, PartialEq, Debug, Reflect)] #[derive(Copy, Clone, PartialEq, Debug, Default, Reflect)]
#[reflect(PartialEq)] #[reflect(PartialEq)]
pub struct Size<T: Reflect + PartialEq = f32> { pub struct Size {
/// The width of the 2-dimensional area. /// The width of the 2-dimensional area.
pub width: T, pub width: Val,
/// The height of the 2-dimensional area. /// The height of the 2-dimensional area.
pub height: T, pub height: Val,
} }
impl<T: Reflect + PartialEq> Size<T> { impl Size {
/// Creates a new [`Size`] from a width and a height. /// Creates a new [`Size`] from a width and a height.
/// ///
/// # Example /// # Example
@ -224,25 +211,13 @@ impl<T: Reflect + PartialEq> Size<T> {
/// assert_eq!(size.width, Val::Px(100.0)); /// assert_eq!(size.width, Val::Px(100.0));
/// assert_eq!(size.height, Val::Px(200.0)); /// assert_eq!(size.height, Val::Px(200.0));
/// ``` /// ```
pub fn new(width: T, height: T) -> Self { pub fn new(width: Val, height: Val) -> Self {
Size { width, height } Size { width, height }
} }
} }
impl<T: Default + Reflect + PartialEq> Default for Size<T> { impl Add<Vec2> for Size {
fn default() -> Self { type Output = Size;
Self {
width: Default::default(),
height: Default::default(),
}
}
}
impl<T: Reflect + PartialEq> Add<Vec2> for Size<T>
where
T: Add<f32, Output = T>,
{
type Output = Size<T>;
fn add(self, rhs: Vec2) -> Self::Output { fn add(self, rhs: Vec2) -> Self::Output {
Self { Self {
@ -252,21 +227,15 @@ where
} }
} }
impl<T: Reflect + PartialEq> AddAssign<Vec2> for Size<T> impl AddAssign<Vec2> for Size {
where
T: AddAssign<f32>,
{
fn add_assign(&mut self, rhs: Vec2) { fn add_assign(&mut self, rhs: Vec2) {
self.width += rhs.x; self.width += rhs.x;
self.height += rhs.y; self.height += rhs.y;
} }
} }
impl<T: Reflect + PartialEq> Sub<Vec2> for Size<T> impl Sub<Vec2> for Size {
where type Output = Size;
T: Sub<f32, Output = T>,
{
type Output = Size<T>;
fn sub(self, rhs: Vec2) -> Self::Output { fn sub(self, rhs: Vec2) -> Self::Output {
Self { Self {
@ -276,21 +245,15 @@ where
} }
} }
impl<T: Reflect + PartialEq> SubAssign<Vec2> for Size<T> impl SubAssign<Vec2> for Size {
where
T: SubAssign<f32>,
{
fn sub_assign(&mut self, rhs: Vec2) { fn sub_assign(&mut self, rhs: Vec2) {
self.width -= rhs.x; self.width -= rhs.x;
self.height -= rhs.y; self.height -= rhs.y;
} }
} }
impl<T: Reflect + PartialEq> Mul<f32> for Size<T> impl Mul<f32> for Size {
where type Output = Size;
T: Mul<f32, Output = T>,
{
type Output = Size<T>;
fn mul(self, rhs: f32) -> Self::Output { fn mul(self, rhs: f32) -> Self::Output {
Self::Output { Self::Output {
@ -300,21 +263,15 @@ where
} }
} }
impl<T: Reflect + PartialEq> MulAssign<f32> for Size<T> impl MulAssign<f32> for Size {
where
T: MulAssign<f32>,
{
fn mul_assign(&mut self, rhs: f32) { fn mul_assign(&mut self, rhs: f32) {
self.width *= rhs; self.width *= rhs;
self.height *= rhs; self.height *= rhs;
} }
} }
impl<T: Reflect + PartialEq> Div<f32> for Size<T> impl Div<f32> for Size {
where type Output = Size;
T: Div<f32, Output = T>,
{
type Output = Size<T>;
fn div(self, rhs: f32) -> Self::Output { fn div(self, rhs: f32) -> Self::Output {
Self::Output { Self::Output {
@ -324,10 +281,7 @@ where
} }
} }
impl<T: Reflect + PartialEq> DivAssign<f32> for Size<T> impl DivAssign<f32> for Size {
where
T: DivAssign<f32>,
{
fn div_assign(&mut self, rhs: f32) { fn div_assign(&mut self, rhs: f32) {
self.width /= rhs; self.width /= rhs;
self.height /= rhs; self.height /= rhs;
@ -339,22 +293,50 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn size_ops() { fn test_size_add() {
assert_eq!( assert_eq!(
Size::new(10., 10.) + Vec2::new(10., 10.), Size::new(Val::Px(10.), Val::Px(10.)) + Vec2::new(10., 10.),
Size::new(20., 20.) Size::new(Val::Px(20.), Val::Px(20.))
); );
assert_eq!(
Size::new(20., 20.) - Vec2::new(10., 10.),
Size::new(10., 10.)
);
assert_eq!(Size::new(10., 10.) * 2., Size::new(20., 20.));
assert_eq!(Size::new(20., 20.) / 2., Size::new(10., 10.));
let mut size = Size::new(10., 10.);
let mut size = Size::new(Val::Px(10.), Val::Px(10.));
size += Vec2::new(10., 10.); size += Vec2::new(10., 10.);
assert_eq!(size, Size::new(Val::Px(20.), Val::Px(20.)));
}
assert_eq!(size, Size::new(20., 20.)); #[test]
fn test_size_sub() {
assert_eq!(
Size::new(Val::Px(20.), Val::Px(20.)) - Vec2::new(10., 10.),
Size::new(Val::Px(10.), Val::Px(10.))
);
let mut size = Size::new(Val::Px(20.), Val::Px(20.));
size -= Vec2::new(10., 10.);
assert_eq!(size, Size::new(Val::Px(10.), Val::Px(10.)));
}
#[test]
fn test_size_mul() {
assert_eq!(
Size::new(Val::Px(10.), Val::Px(10.)) * 2.,
Size::new(Val::Px(20.), Val::Px(20.))
);
let mut size = Size::new(Val::Px(10.), Val::Px(10.));
size *= 2.;
assert_eq!(size, Size::new(Val::Px(20.), Val::Px(20.)));
}
#[test]
fn test_size_div() {
assert_eq!(
Size::new(Val::Px(20.), Val::Px(20.)) / 2.,
Size::new(Val::Px(10.), Val::Px(10.))
);
let mut size = Size::new(Val::Px(20.), Val::Px(20.));
size /= 2.;
assert_eq!(size, Size::new(Val::Px(10.), Val::Px(10.)));
} }
} }

View File

@ -67,9 +67,8 @@ impl Plugin for UiPlugin {
.register_type::<Option<f32>>() .register_type::<Option<f32>>()
.register_type::<Overflow>() .register_type::<Overflow>()
.register_type::<PositionType>() .register_type::<PositionType>()
.register_type::<Size<f32>>() .register_type::<Size>()
.register_type::<Size<Val>>() .register_type::<UiRect>()
.register_type::<UiRect<Val>>()
.register_type::<Style>() .register_type::<Style>()
.register_type::<UiColor>() .register_type::<UiColor>()
.register_type::<UiImage>() .register_type::<UiImage>()

View File

@ -9,7 +9,7 @@ use bevy_render::{
texture::{Image, DEFAULT_IMAGE_HANDLE}, texture::{Image, DEFAULT_IMAGE_HANDLE},
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::ops::{Add, AddAssign}; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
/// Describes the size of a UI node /// Describes the size of a UI node
#[derive(Component, Debug, Clone, Default, Reflect)] #[derive(Component, Debug, Clone, Default, Reflect)]
@ -56,6 +56,72 @@ impl AddAssign<f32> for Val {
} }
} }
impl Sub<f32> for Val {
type Output = Val;
fn sub(self, rhs: f32) -> Self::Output {
match self {
Val::Undefined => Val::Undefined,
Val::Auto => Val::Auto,
Val::Px(value) => Val::Px(value - rhs),
Val::Percent(value) => Val::Percent(value - rhs),
}
}
}
impl SubAssign<f32> for Val {
fn sub_assign(&mut self, rhs: f32) {
match self {
Val::Undefined | Val::Auto => {}
Val::Px(value) | Val::Percent(value) => *value -= rhs,
}
}
}
impl Mul<f32> for Val {
type Output = Val;
fn mul(self, rhs: f32) -> Self::Output {
match self {
Val::Undefined => Val::Undefined,
Val::Auto => Val::Auto,
Val::Px(value) => Val::Px(value * rhs),
Val::Percent(value) => Val::Percent(value * rhs),
}
}
}
impl MulAssign<f32> for Val {
fn mul_assign(&mut self, rhs: f32) {
match self {
Val::Undefined | Val::Auto => {}
Val::Px(value) | Val::Percent(value) => *value *= rhs,
}
}
}
impl Div<f32> for Val {
type Output = Val;
fn div(self, rhs: f32) -> Self::Output {
match self {
Val::Undefined => Val::Undefined,
Val::Auto => Val::Auto,
Val::Px(value) => Val::Px(value / rhs),
Val::Percent(value) => Val::Percent(value / rhs),
}
}
}
impl DivAssign<f32> for Val {
fn div_assign(&mut self, rhs: f32) {
match self {
Val::Undefined | Val::Auto => {}
Val::Px(value) | Val::Percent(value) => *value /= rhs,
}
}
}
/// Describes the style of a UI node /// Describes the style of a UI node
/// ///
/// It uses the [Flexbox](https://cssreference.io/flexbox/) system. /// It uses the [Flexbox](https://cssreference.io/flexbox/) system.
@ -87,13 +153,13 @@ pub struct Style {
/// How items align according to the main axis /// How items align according to the main axis
pub justify_content: JustifyContent, pub justify_content: JustifyContent,
/// The position of the node as described by its Rect /// The position of the node as described by its Rect
pub position: UiRect<Val>, pub position: UiRect,
/// The margin of the node /// The margin of the node
pub margin: UiRect<Val>, pub margin: UiRect,
/// The padding of the node /// The padding of the node
pub padding: UiRect<Val>, pub padding: UiRect,
/// The border of the node /// The border of the node
pub border: UiRect<Val>, pub border: UiRect,
/// Defines how much a flexbox item should grow if there's space available /// Defines how much a flexbox item should grow if there's space available
pub flex_grow: f32, pub flex_grow: f32,
/// How to shrink if there's not enough space available /// How to shrink if there's not enough space available
@ -101,11 +167,11 @@ pub struct Style {
/// The initial size of the item /// The initial size of the item
pub flex_basis: Val, pub flex_basis: Val,
/// The size of the flexbox /// The size of the flexbox
pub size: Size<Val>, pub size: Size,
/// The minimum size of the flexbox /// The minimum size of the flexbox
pub min_size: Size<Val>, pub min_size: Size,
/// The maximum size of the flexbox /// The maximum size of the flexbox
pub max_size: Size<Val>, pub max_size: Size,
/// The aspect ratio of the flexbox /// The aspect ratio of the flexbox
pub aspect_ratio: Option<f32>, pub aspect_ratio: Option<f32>,
/// How to handle overflow /// How to handle overflow

View File

@ -1,5 +1,4 @@
use crate::Size; use crate::{CalculatedSize, Size, UiImage, Val};
use crate::{CalculatedSize, UiImage};
use bevy_asset::Assets; use bevy_asset::Assets;
use bevy_ecs::{ use bevy_ecs::{
component::Component, component::Component,
@ -28,8 +27,8 @@ pub fn image_node_system(
for (mut calculated_size, image) in &mut query { for (mut calculated_size, image) in &mut query {
if let Some(texture) = textures.get(image) { if let Some(texture) = textures.get(image) {
let size = Size { let size = Size {
width: texture.texture_descriptor.size.width as f32, width: Val::Px(texture.texture_descriptor.size.width as f32),
height: texture.texture_descriptor.size.height as f32, height: Val::Px(texture.texture_descriptor.size.height as f32),
}; };
// Update only if size has changed to avoid needless layout calculations // Update only if size has changed to avoid needless layout calculations
if size != calculated_size.size { if size != calculated_size.size {

View File

@ -118,8 +118,8 @@ pub fn text_system(
"Failed to get glyphs from the pipeline that have just been computed", "Failed to get glyphs from the pipeline that have just been computed",
); );
calculated_size.size = Size { calculated_size.size = Size {
width: scale_value(text_layout_info.size.x, inv_scale_factor), width: Val::Px(scale_value(text_layout_info.size.x, inv_scale_factor)),
height: scale_value(text_layout_info.size.y, inv_scale_factor), height: Val::Px(scale_value(text_layout_info.size.y, inv_scale_factor)),
}; };
} }
} }