mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Round half away from zero on every Number to Integer conversion instead of truncating (#4578)
* Add an I64 tagged value as the node graph's integer storage type, with a whole-number widget for it * Round half away from zero on every Number to Integer conversion instead of truncating
This commit is contained in:
1 parent
60bba681d3
commit
f5507c0959
4 files changed
+84
-35
No files matched your search
@@ -329,6 +329,7 @@ pub(crate) fn property_from_type(
|
||||
Some(x) if id_is::<f64>(x) || id_is::<f32>(x) => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY), false),
|
||||
Some(x) if id_is::<u32>(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::from(u32::MAX))).into(),
|
||||
Some(x) if id_is::<u64>(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
|
||||
Some(x) if id_is::<String>(x) => text_widget(default_info).into(),
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", "", None, false),
|
||||
@@ -1152,6 +1153,14 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]),
|
||||
Some(&TaggedValue::I64(x)) => widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
number_props
|
||||
.value(Some(x as f64))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::I64(x.value.unwrap().round() as i64)))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]),
|
||||
Some(&TaggedValue::DVec2(dvec2)) => widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
number_props
|
||||
|
||||
@@ -181,18 +181,23 @@
|
||||
text = displayText(sanitized, unit);
|
||||
}
|
||||
|
||||
// Rounds half away from zero, the graph's one Number to Integer rule, where `Math.round` would carry -1.5 up to -1
|
||||
function roundToInteger(value: number): number {
|
||||
return Math.sign(value) * Math.round(Math.abs(value));
|
||||
}
|
||||
|
||||
// Called internally to update the value indirectly by informing the parent component of the new value,
|
||||
// so it can update the prop for this component, finally yielding the value change.
|
||||
function updateValue(newValue: number | undefined): number | undefined {
|
||||
// Check if the new value is valid, otherwise we use the old value (rounded if it's an integer)
|
||||
const oldValue = value !== undefined && isInteger ? Math.round(value) : value;
|
||||
const oldValue = value !== undefined && isInteger ? roundToInteger(value) : value;
|
||||
let newValueValidated = newValue !== undefined ? newValue : oldValue;
|
||||
|
||||
if (newValueValidated !== undefined) {
|
||||
if (typeof min === "number" && !Number.isNaN(min)) newValueValidated = Math.max(newValueValidated, min);
|
||||
if (typeof max === "number" && !Number.isNaN(max)) newValueValidated = Math.min(newValueValidated, max);
|
||||
|
||||
if (isInteger) newValueValidated = Math.round(newValueValidated);
|
||||
if (isInteger) newValueValidated = roundToInteger(newValueValidated);
|
||||
|
||||
rangeSliderValue = newValueValidated;
|
||||
rangeSliderValueAsRendered = newValueValidated;
|
||||
@@ -529,7 +534,7 @@
|
||||
cumulativeDragDelta += dragDelta;
|
||||
|
||||
const combined = initialValue + cumulativeDragDelta;
|
||||
const combineSnapped = snapping || isInteger ? Math.round(combined) : combined;
|
||||
const combineSnapped = snapping || isInteger ? roundToInteger(combined) : combined;
|
||||
|
||||
const newValue = updateValue(combineSnapped);
|
||||
|
||||
@@ -577,7 +582,7 @@
|
||||
}
|
||||
|
||||
// Snap the slider value to the nearest integer if the Ctrl key is held, or the widget is set to integer mode.
|
||||
const snappedValue = ctrlKeyDown || isInteger ? Math.round(roundedValue) : roundedValue;
|
||||
const snappedValue = ctrlKeyDown || isInteger ? roundToInteger(roundedValue) : roundedValue;
|
||||
|
||||
// The first "input" event upon mousedown means we transition to a "Deciding" state, allowing us to wait for the
|
||||
// next event to determine if the user is dragging (to slide the slider) or releasing (to edit the numerical text field).
|
||||
|
||||
@@ -523,6 +523,7 @@ tagged_value! {
|
||||
F64(f64),
|
||||
U32(u32),
|
||||
U64(u64),
|
||||
I64(i64),
|
||||
Bool(bool),
|
||||
String(String),
|
||||
#[serde(alias = "IVec2", alias = "UVec2", alias = "Vec2")]
|
||||
@@ -605,6 +606,7 @@ impl TaggedValue {
|
||||
TaggedValue::String(x) => format!("\"{x}\""),
|
||||
TaggedValue::U32(x) => x.to_string() + "_u32",
|
||||
TaggedValue::U64(x) => x.to_string() + "_u64",
|
||||
TaggedValue::I64(x) => x.to_string() + "_i64",
|
||||
TaggedValue::F32(x) => x.to_string() + "_f32",
|
||||
TaggedValue::F64(x) => x.to_string() + "_f64",
|
||||
TaggedValue::Bool(x) => x.to_string(),
|
||||
@@ -705,6 +707,7 @@ impl TaggedValue {
|
||||
() if ty == TypeId::of::<f32>() => FromStr::from_str(string).map(TaggedValue::F32).ok()?,
|
||||
() if ty == TypeId::of::<u64>() => FromStr::from_str(string).map(TaggedValue::U64).ok()?,
|
||||
() if ty == TypeId::of::<u32>() => FromStr::from_str(string).map(TaggedValue::U32).ok()?,
|
||||
() if ty == TypeId::of::<i64>() => FromStr::from_str(string).map(TaggedValue::I64).ok()?,
|
||||
() if ty == TypeId::of::<DVec2>() => to_dvec2(string).map(TaggedValue::DVec2)?,
|
||||
() if ty == TypeId::of::<bool>() => FromStr::from_str(string).map(TaggedValue::Bool).ok()?,
|
||||
() if ty == TypeId::of::<Color>() => to_color(string).map(TaggedValue::Color)?,
|
||||
@@ -866,6 +869,7 @@ impl Display for TaggedValue {
|
||||
TaggedValue::String(x) => f.write_str(x),
|
||||
TaggedValue::U32(x) => f.write_fmt(format_args!("{x}")),
|
||||
TaggedValue::U64(x) => f.write_fmt(format_args!("{x}")),
|
||||
TaggedValue::I64(x) => f.write_fmt(format_args!("{x}")),
|
||||
TaggedValue::F32(x) => f.write_fmt(format_args!("{x}")),
|
||||
TaggedValue::F64(x) => f.write_fmt(format_args!("{x}")),
|
||||
TaggedValue::Bool(x) => f.write_fmt(format_args!("{x}")),
|
||||
|
||||
@@ -75,30 +75,37 @@ pub trait FromAnchorPosition {
|
||||
fn from_anchor_position(position: DVec2) -> Self;
|
||||
}
|
||||
|
||||
/// Implements the [`Convert`] trait for conversion between the cartesian product of Rust's primitive numeric types.
|
||||
/// Implements the [`Convert`] trait between Rust's primitive numeric types. A float narrowing to an integer rounds to the
|
||||
/// nearest whole number (half away from zero), the graph's one Number to Integer rule, so float noise like 5.999999 reaches
|
||||
/// an integer connector as 6 rather than truncating to 5. Every other pair is a plain `as` cast.
|
||||
macro_rules! impl_convert {
|
||||
($from:ty, $to:ty) => {
|
||||
($from:ty => $to:ty) => {
|
||||
impl Convert<$to, ()> for $from {
|
||||
async fn convert(self, _: Footprint, _: ()) -> $to {
|
||||
self as $to
|
||||
}
|
||||
}
|
||||
};
|
||||
($to:ty) => {
|
||||
impl_convert!(f32, $to);
|
||||
impl_convert!(f64, $to);
|
||||
impl_convert!(i8, $to);
|
||||
impl_convert!(u8, $to);
|
||||
impl_convert!(u16, $to);
|
||||
impl_convert!(i16, $to);
|
||||
impl_convert!(i32, $to);
|
||||
impl_convert!(u32, $to);
|
||||
impl_convert!(i64, $to);
|
||||
impl_convert!(u64, $to);
|
||||
impl_convert!(i128, $to);
|
||||
impl_convert!(u128, $to);
|
||||
impl_convert!(isize, $to);
|
||||
impl_convert!(usize, $to);
|
||||
($from:ty => round $to:ty) => {
|
||||
impl Convert<$to, ()> for $from {
|
||||
async fn convert(self, _: Footprint, _: ()) -> $to {
|
||||
self.round() as $to
|
||||
}
|
||||
}
|
||||
};
|
||||
(from_integers $to:ty) => {
|
||||
impl_convert!(i8 => $to);
|
||||
impl_convert!(u8 => $to);
|
||||
impl_convert!(u16 => $to);
|
||||
impl_convert!(i16 => $to);
|
||||
impl_convert!(i32 => $to);
|
||||
impl_convert!(u32 => $to);
|
||||
impl_convert!(i64 => $to);
|
||||
impl_convert!(u64 => $to);
|
||||
impl_convert!(i128 => $to);
|
||||
impl_convert!(u128 => $to);
|
||||
impl_convert!(isize => $to);
|
||||
impl_convert!(usize => $to);
|
||||
|
||||
impl Convert<DVec2, ()> for $to {
|
||||
async fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
||||
@@ -106,21 +113,31 @@ macro_rules! impl_convert {
|
||||
}
|
||||
}
|
||||
};
|
||||
(float $to:ty) => {
|
||||
impl_convert!(f32 => $to);
|
||||
impl_convert!(f64 => $to);
|
||||
impl_convert!(from_integers $to);
|
||||
};
|
||||
(integer $to:ty) => {
|
||||
impl_convert!(f32 => round $to);
|
||||
impl_convert!(f64 => round $to);
|
||||
impl_convert!(from_integers $to);
|
||||
};
|
||||
}
|
||||
impl_convert!(f32);
|
||||
impl_convert!(f64);
|
||||
impl_convert!(i8);
|
||||
impl_convert!(u8);
|
||||
impl_convert!(u16);
|
||||
impl_convert!(i16);
|
||||
impl_convert!(i32);
|
||||
impl_convert!(u32);
|
||||
impl_convert!(i64);
|
||||
impl_convert!(u64);
|
||||
impl_convert!(i128);
|
||||
impl_convert!(u128);
|
||||
impl_convert!(isize);
|
||||
impl_convert!(usize);
|
||||
impl_convert!(float f32);
|
||||
impl_convert!(float f64);
|
||||
impl_convert!(integer i8);
|
||||
impl_convert!(integer u8);
|
||||
impl_convert!(integer u16);
|
||||
impl_convert!(integer i16);
|
||||
impl_convert!(integer i32);
|
||||
impl_convert!(integer u32);
|
||||
impl_convert!(integer i64);
|
||||
impl_convert!(integer u64);
|
||||
impl_convert!(integer i128);
|
||||
impl_convert!(integer u128);
|
||||
impl_convert!(integer isize);
|
||||
impl_convert!(integer usize);
|
||||
|
||||
/// Implements the [`Convert`] trait from `bool` into each numeric type, embedding `false` and `true` as exactly 0 and 1.
|
||||
/// The reverse direction is deliberately absent: a number only becomes a truth value through an explicit comparison.
|
||||
@@ -136,3 +153,17 @@ macro_rules! impl_convert_from_bool {
|
||||
};
|
||||
}
|
||||
impl_convert_from_bool!(f32, f64, i8, u8, u16, i16, i32, u32, i64, u64, i128, u128, isize, usize);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_float_narrows_to_the_nearest_integer() {
|
||||
let footprint = Footprint::default();
|
||||
assert_eq!(Convert::<i64, ()>::convert(5.999_999_f64, footprint, ()).await, 6, "float noise rounds up to the whole number it meant");
|
||||
assert_eq!(Convert::<i64, ()>::convert(2.5_f64, footprint, ()).await, 3, "ties round away from zero");
|
||||
assert_eq!(Convert::<i64, ()>::convert(-1.5_f64, footprint, ()).await, -2);
|
||||
assert_eq!(Convert::<f64, ()>::convert(7_i64, footprint, ()).await, 7., "an integer widens exactly");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user