From 51e2003fead89d99013622e696572a2dc66cb734 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Fri, 4 Dec 2026 02:17:10 -0800 Subject: [PATCH] Add Gradient tool gizmos for adjusting each end's contour curvature --- editor/src/consts.rs | 4 + .../graph_operation_message.rs | 5 + .../graph_operation_message_handler.rs | 5 + .../document/graph_operation/utility_types.rs | 59 +- .../document/overlays/utility_types.rs | 24 + .../common_functionality/gradient_gizmos.rs | 256 +++++++++ .../messages/tool/common_functionality/mod.rs | 1 + .../tool/tool_messages/gradient_tool.rs | 527 +++++++++++++++++- 8 files changed, 843 insertions(+), 38 deletions(-) create mode 100644 editor/src/messages/tool/common_functionality/gradient_gizmos.rs diff --git a/editor/src/consts.rs b/editor/src/consts.rs index 10259f30ec..37dfd2f485 100644 --- a/editor/src/consts.rs +++ b/editor/src/consts.rs @@ -152,6 +152,10 @@ pub const GRADIENT_MIDPOINT_DIAMOND_RADIUS: f64 = 4.; pub const GRADIENT_MIDPOINT_MIN: f64 = 0.01; pub const GRADIENT_MIDPOINT_MAX: f64 = 0.99; pub const GRADIENT_STOP_MIN_VIEWPORT_GAP: f64 = 10.; +// In viewport pixels from a contour's dashed rim, within which a press takes hold of it +pub const GRADIENT_CONTOUR_RIM_GRAB_DISTANCE: f64 = 5.; +// In viewport pixels, within which a dragged contour handle snaps onto making its contour a line or a point +pub const GRADIENT_CONTOUR_SNAP_DISTANCE: f64 = 4.; // PEN TOOL pub const CREATE_CURVE_THRESHOLD: f64 = 5.; diff --git a/editor/src/messages/portfolio/document/graph_operation/graph_operation_message.rs b/editor/src/messages/portfolio/document/graph_operation/graph_operation_message.rs index 95f606ae34..5b4d27ce5f 100644 --- a/editor/src/messages/portfolio/document/graph_operation/graph_operation_message.rs +++ b/editor/src/messages/portfolio/document/graph_operation/graph_operation_message.rs @@ -57,6 +57,11 @@ pub enum GraphOperationMessage { layer: LayerNodeIdentifier, gradient_form: GradientForm, }, + GradientCurvatureSet { + layer: LayerNodeIdentifier, + /// The start and end curvatures. + curvatures: [f64; 2], + }, GradientSpreadSet { layer: LayerNodeIdentifier, gradient_spread: GradientSpread, diff --git a/editor/src/messages/portfolio/document/graph_operation/graph_operation_message_handler.rs b/editor/src/messages/portfolio/document/graph_operation/graph_operation_message_handler.rs index f580b9f7d4..b29c0bad62 100644 --- a/editor/src/messages/portfolio/document/graph_operation/graph_operation_message_handler.rs +++ b/editor/src/messages/portfolio/document/graph_operation/graph_operation_message_handler.rs @@ -86,6 +86,11 @@ impl MessageHandler> for modify_inputs.gradient_form_set(gradient_form); } } + GraphOperationMessage::GradientCurvatureSet { layer, curvatures } => { + if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) { + modify_inputs.gradient_curvature_set(curvatures); + } + } GraphOperationMessage::GradientSpreadSet { layer, gradient_spread } => { if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) { modify_inputs.gradient_spread_set(gradient_spread); diff --git a/editor/src/messages/portfolio/document/graph_operation/utility_types.rs b/editor/src/messages/portfolio/document/graph_operation/utility_types.rs index 28daec1dfc..49fcd5ce50 100644 --- a/editor/src/messages/portfolio/document/graph_operation/utility_types.rs +++ b/editor/src/messages/portfolio/document/graph_operation/utility_types.rs @@ -6,7 +6,8 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector}; use crate::messages::prelude::*; use crate::messages::tool::common_functionality::graph_modification_utils::{ - ReplaceablePaintChain, fill_node_curvatures, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, gradient_curvature_values, replaceable_paint_chain, + ReplaceablePaintChain, fill_node_curvatures, get_fill_input_node_id, get_fill_node_id_with_direct_fill_input, get_upstream_gradient_value_node_id, gradient_chain_target_input, + gradient_curvature_values, replaceable_paint_chain, }; use glam::{DAffine2, DVec2, IVec2}; use graph_craft::application_io::resource::ResourceId; @@ -492,19 +493,8 @@ impl<'a> ModifyInputsContext<'a> { } // Only a chosen form sets the curvatures, leaving any the graph feeds or that already make it - let curvatures = self.network_interface.document_network().nodes.get(&fill_node_id).and_then(fill_node_curvatures); - if let Some(gradient_form) = gradient_form - && curvatures.is_some_and(|curvatures| GradientForm::from_curvatures(curvatures) != Some(gradient_form)) - { - use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput}; - - let [start_curvature, end_curvature] = gradient_form.curvatures(); - self.set_input_with_refresh( - InputConnector::node(fill_node_id, StartCurvatureInput), - NodeInput::value(TaggedValue::Number(start_curvature), false), - true, - ); - self.set_input_with_refresh(InputConnector::node(fill_node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end_curvature), false), true); + if let Some(gradient_form) = gradient_form { + self.write_fill_curvatures(fill_node_id, gradient_form.curvatures(), |current| GradientForm::from_curvatures(current) == Some(gradient_form)); } self.responses.add(NodeGraphMessage::RunDocumentGraph); @@ -513,6 +503,20 @@ impl<'a> ModifyInputsContext<'a> { } } + /// Write both curvatures to a Fill node's hidden curvature inputs unless the graph feeds them or its current ones are `already_written`, for the caller to then run the graph. + fn write_fill_curvatures(&mut self, fill_node_id: NodeId, curvatures: [f64; 2], already_written: impl Fn([f64; 2]) -> bool) { + use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput}; + + let current = self.network_interface.document_network().nodes.get(&fill_node_id).and_then(fill_node_curvatures); + if current.is_none_or(already_written) { + return; + } + + let [start, end] = curvatures; + self.set_input_with_refresh(InputConnector::node(fill_node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true); + self.set_input_with_refresh(InputConnector::node(fill_node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), true); + } + /// A freshly created Fill node lands at the chain start, downstream of any Stroke node, where it would /// paint over the stroke. This hops the stroke back downstream so it keeps painting above by default. fn restore_default_stroke_order(&mut self) { @@ -776,23 +780,42 @@ impl<'a> ModifyInputsContext<'a> { /// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs /// from the default (`Linear`). Curvatures fed from the graph (procedural authorship) or already making the form are left untouched. pub fn gradient_form_set(&mut self, gradient_form: GradientForm) { + self.write_gradient_curvatures(gradient_form.curvatures(), |current| GradientForm::from_curvatures(current) == Some(gradient_form)); + } + + /// Write both curvatures to the layer's gradient: a Fill node holding it, or else the last 'Gradient Curvature' node in its chain, inserting + /// one only when they differ from the default form's (`Linear`). Curvatures fed from the graph (procedural authorship) are left untouched. + pub fn gradient_curvature_set(&mut self, curvatures: [f64; 2]) { + if let Some(output_layer) = self.get_output_layer() + && let Some(fill_node_id) = get_fill_node_id_with_direct_fill_input(output_layer, self.network_interface) + { + self.write_fill_curvatures(fill_node_id, curvatures, |current| current == curvatures); + self.responses.add(NodeGraphMessage::RunDocumentGraph); + return; + } + + self.write_gradient_curvatures(curvatures, |current| current == curvatures); + } + + /// Write these curvatures to the last 'Gradient Curvature' node in the chain unless its current ones are `already_written`. + fn write_gradient_curvatures(&mut self, curvatures: [f64; 2], already_written: impl Fn([f64; 2]) -> bool) { use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput}; let Some(output_layer) = self.get_output_layer() else { return }; let target_input = gradient_chain_target_input(output_layer, self.network_interface); - let create_if_nonexistent = gradient_form != GradientForm::default(); + let create_if_nonexistent = curvatures != GradientForm::default().curvatures(); let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else { return; }; let Some(node) = self.network_interface.document_network().nodes.get(&node_id) else { return }; - let Some(curvatures) = gradient_curvature_values(node) else { return }; - if GradientForm::from_curvatures(curvatures) == Some(gradient_form) { + let Some(current) = gradient_curvature_values(node) else { return }; + if already_written(current) { return; } - let [start, end] = gradient_form.curvatures(); + let [start, end] = curvatures; self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true); self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false); } diff --git a/editor/src/messages/portfolio/document/overlays/utility_types.rs b/editor/src/messages/portfolio/document/overlays/utility_types.rs index 5bf3cb31e1..63feabe045 100644 --- a/editor/src/messages/portfolio/document/overlays/utility_types.rs +++ b/editor/src/messages/portfolio/document/overlays/utility_types.rs @@ -404,6 +404,12 @@ impl OverlayContext { self.record(move |overlays| overlays.dashed_polygon(&polygon, stroke_color.as_deref(), color_fill.as_deref(), dash_width, dash_gap_width, dash_offset)); } + /// Strokes the open path through these points, unlike [`Self::dashed_polygon`], which closes it. + pub fn dashed_polyline(&mut self, points: &[DVec2], color: Option<&str>, dash_width: Option, dash_gap_width: Option, dash_offset: Option) { + let (points, color) = (points.to_vec(), owned(color)); + self.record(move |overlays| overlays.dashed_polyline(&points, color.as_deref(), dash_width, dash_gap_width, dash_offset)); + } + pub fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option) { let color = owned(color); self.record(move |overlays| overlays.line(start, end, color.as_deref(), thickness)); @@ -785,6 +791,24 @@ impl OverlayContextInternal { self.stroke_in_view(&stroke, Self::parse_color(stroke_color), &path); } + fn dashed_polyline(&mut self, points: &[DVec2], color: Option<&str>, dash_width: Option, dash_gap_width: Option, dash_offset: Option) { + let mut points = points.iter().map(|&point| self.snap_to_physical_pixel_center(point)); + let Some(first) = points.next() else { return }; + + let mut path = BezPath::new(); + path.move_to(kurbo::Point::new(first.x, first.y)); + for point in points { + path.line_to(kurbo::Point::new(point.x, point.y)); + } + + let mut stroke = kurbo::Stroke::new(1.); + if let Some(dash_width) = dash_width { + stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap_width.unwrap_or(1.)]); + } + + self.stroke_in_view(&stroke, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), &path); + } + fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option) { self.dashed_line(start, end, color, thickness, None, None, None) } diff --git a/editor/src/messages/tool/common_functionality/gradient_gizmos.rs b/editor/src/messages/tool/common_functionality/gradient_gizmos.rs new file mode 100644 index 0000000000..bd2bd1e9e7 --- /dev/null +++ b/editor/src/messages/tool/common_functionality/gradient_gizmos.rs @@ -0,0 +1,256 @@ +//! Geometry of the Gradient tool's gizmos for each end's contour, in gradient space, where the gradient line runs from the start point +//! at the origin to the end point at (1, 0). Each contour passes through its endpoint with its center on the line, set by its curvature +//! curvature, as described in [`graphene_std::vector::gradient_standard`]. + +use glam::{DAffine2, DVec2}; +use graphene_std::vector::gradient_standard::{curvature_radius, radius_curvature}; +use std::f64::consts::{FRAC_PI_2, PI}; + +/// The farthest a drawn contour bows from its chords between the points it's drawn through, in viewport pixels. +const CONTOUR_SAG_TOLERANCE: f64 = 0.25; + +/// The most chords a contour is drawn with. +const CONTOUR_MAX_CHORDS: usize = 1024; + +/// One of the gradient line's two ends, each with its own contour. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GradientEnd { + Start, + End, +} + +impl GradientEnd { + /// Its index in a `[start, end]` pair of curvatures. + pub fn index(self) -> usize { + match self { + Self::Start => 0, + Self::End => 1, + } + } + + /// Its endpoint in gradient space. + pub fn endpoint(self) -> DVec2 { + match self { + Self::Start => DVec2::ZERO, + Self::End => DVec2::X, + } + } + + /// Which way along the gradient line points toward the other end, which a positive curvature bows this end's contour toward. + fn inward(self) -> f64 { + match self { + Self::Start => 1., + Self::End => -1., + } + } +} + +/// The center of this end's contour in gradient space for its `curvature`, or `None` for a line. +pub fn contour_center(end: GradientEnd, curvature: f64) -> Option { + let radius = curvature_radius(curvature); + radius.is_finite().then(|| end.endpoint() + DVec2::new(end.inward() * radius, 0.)) +} + +/// The curvature that centers this end's contour at `axis_position` along the gradient line, as dragging its center dot there does. +pub fn center_curvature(end: GradientEnd, axis_position: f64) -> f64 { + radius_curvature((axis_position - end.endpoint().x) * end.inward()) +} + +/// The curvature of this end's contour through `point`, the circle through it and the endpoint with its center on the gradient line, +/// which is the line across the gradient line where `point` lies across from the endpoint. `None` at the endpoint itself. +pub fn rim_curvature(end: GradientEnd, point: DVec2) -> Option { + let offset = point - end.endpoint(); + let distance_squared = offset.length_squared(); + + // The inverse of the radius `|offset|² / 2 offset.x`, which stays finite where the radius doesn't + (distance_squared > 0.).then(|| (2. * offset.x * end.inward() / distance_squared).atan() / FRAC_PI_2) +} + +/// The signed radius that resizes this end's contour (from its `curvature`) to bring the place on its rim nearest `grabbed` as near `pointer` as it gets, +/// both in the space `unit_to_viewport` maps to, and where that place lands there. `None` for a line or a point, which no resizing moves a place on. +pub fn rim_resized_toward(end: GradientEnd, curvature: f64, grabbed: DVec2, pointer: DVec2, unit_to_viewport: DAffine2) -> Option<(f64, DVec2)> { + let radius = curvature_radius(curvature); + if !radius.is_finite() || radius == 0. { + return None; + } + let inward = DVec2::new(end.inward(), 0.); + + // Each circle through the endpoint is the others scaled about it, so the place keeps its angle around them from the endpoint, measured at the center + let to_endpoint = -radius * inward; + let to_grabbed = unit_to_viewport.inverse().transform_point2(grabbed) - end.endpoint() - radius * inward; + let angle = to_endpoint.perp_dot(to_grabbed).atan2(to_endpoint.dot(to_grabbed)); + + // At that angle, the place lies the radius times this from the endpoint, a line the pointer projects onto + let direction = unit_to_viewport.transform_vector2(inward - DVec2::from_angle(angle).rotate(inward)); + let endpoint = unit_to_viewport.transform_point2(end.endpoint()); + let resized = (pointer - endpoint).dot(direction) / direction.length_squared(); + resized.is_finite().then(|| (resized, endpoint + resized * direction)) +} + +/// The smallest factor `transform` scales any length by, the least singular value of its linear part. +fn least_scale(transform: DAffine2) -> f64 { + let [x_axis, y_axis] = [transform.matrix2.x_axis, transform.matrix2.y_axis]; + let determinant = transform.matrix2.determinant().abs(); + + // Of the singular values `√(mean ± √(mean² - determinant²))`, the least is the determinant over the greatest, which avoids cancellation + let mean = (x_axis.length_squared() + y_axis.length_squared()) / 2.; + let greatest = (mean + (mean * mean - determinant * determinant).max(0.).sqrt()).sqrt(); + if greatest > 0. { determinant / greatest } else { 0. } +} + +/// Points through which this end's contour is drawn in the viewport, from `unit_to_viewport`, as far as `reach` viewport pixels from +/// its endpoint along it (or around the whole circle if that's shorter). Empty for a point, or where the transform collapses. +pub fn contour_polyline(end: GradientEnd, curvature: f64, unit_to_viewport: DAffine2, reach: f64) -> Vec { + let radius = curvature_radius(curvature); + let endpoint = end.endpoint(); + + let least_scale = least_scale(unit_to_viewport); + if radius == 0. || least_scale <= 0. { + return Vec::new(); + } + + // A line runs straight across the gradient line through the endpoint + if radius.is_infinite() { + let Some(direction) = unit_to_viewport.transform_vector2(DVec2::Y).try_normalize() else { + return Vec::new(); + }; + let viewport_endpoint = unit_to_viewport.transform_point2(endpoint); + return vec![viewport_endpoint - direction * reach, viewport_endpoint + direction * reach]; + } + + // Sweep from the endpoint both ways around the circle, by the angle reaching `reach` pixels at the least scale + let size = radius.abs(); + let sweep = (reach / (size * least_scale)).min(PI); + + // Uniform steps small enough that each chord stays within the sag tolerance, even at twice the longest axis's scale (which bounds the greatest) + let viewport_radius_bound = size * unit_to_viewport.matrix2.x_axis.length().max(unit_to_viewport.matrix2.y_axis.length()) * 2.; + let step = (8. * CONTOUR_SAG_TOLERANCE / viewport_radius_bound).sqrt(); + let chords_each_way = ((sweep / step).ceil() as usize).clamp(4, CONTOUR_MAX_CHORDS / 2); + let chords = 2 * chords_each_way; + + // Measured from the endpoint rather than the center, the points stay precise on huge circles + (0..=chords) + .map(|index| { + let angle = sweep * (2. * index as f64 / chords as f64 - 1.); + let half_sine = (angle / 2.).sin(); + let offset = DVec2::new(2. * end.inward() * radius * half_sine * half_sine, size * angle.sin()); + unit_to_viewport.transform_point2(endpoint + offset) + }) + .collect() +} + +/// The distance from `point` to the nearest place on the polyline through `points`, or `None` if it has none. +pub fn distance_to_polyline(points: &[DVec2], point: DVec2) -> Option { + if let [only] = points { + return Some(only.distance(point)); + } + + points + .windows(2) + .map(|pair| { + let (start, end) = (pair[0], pair[1]); + let along = (point - start).dot(end - start) / (end - start).length_squared(); + let nearest = if along.is_finite() { start.lerp(end, along.clamp(0., 1.)) } else { start }; + nearest.distance(point) + }) + .min_by(f64::total_cmp) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Curvatures through circles of each size and bend, both lines, and the points. + fn curvatures() -> impl Iterator { + (-20..=20).map(|step| step as f64 * 0.05) + } + + #[test] + fn a_rim_dragged_to_a_point_takes_the_curvature_of_the_circle_through_it() { + for end in [GradientEnd::Start, GradientEnd::End] { + for point in [DVec2::new(0.3, 0.4), DVec2::new(-0.7, 1.2), DVec2::new(2.5, -0.25), DVec2::new(0.5, 3.)] { + let curvature = rim_curvature(end, point).unwrap(); + + // The contour of that curvature passes through the point, centered on the gradient line + let center = contour_center(end, curvature).unwrap(); + assert!(center.y == 0.); + let radius = center.distance(end.endpoint()); + assert!((center.distance(point) - radius).abs() < 1e-9 * radius.max(1.), "{end:?} through {point}: curvature {curvature}"); + } + + // Straight across from the endpoint is the line, and either side of it bends toward that side + let across = end.endpoint() + DVec2::Y; + assert_eq!(rim_curvature(end, across), Some(0.)); + let inward = DVec2::new(end.inward() * 0.1, 0.); + assert!(rim_curvature(end, across + inward).unwrap() > 0.); + assert!(rim_curvature(end, across - inward).unwrap() < 0.); + + // The endpoint is on every contour, so it sets none + assert_eq!(rim_curvature(end, end.endpoint()), None); + } + } + + #[test] + fn a_rim_dragged_along_its_own_contour_keeps_its_curvature() { + for end in [GradientEnd::Start, GradientEnd::End] { + for curvature in curvatures().filter(|curvature| curvature.abs() != 1.) { + for point in contour_polyline(end, curvature, DAffine2::IDENTITY, 3.) { + // Every point but the endpoint sets the curvature back, as a line's points beside the endpoint do + if point.distance(end.endpoint()) < 1e-6 { + continue; + } + let found = rim_curvature(end, point).unwrap(); + assert!((found - curvature).abs() < 1e-9, "{end:?} curvature {curvature} at {point}: {found}"); + } + } + } + } + + #[test] + fn a_center_dragged_along_the_line_takes_the_curvature_centered_there() { + for end in [GradientEnd::Start, GradientEnd::End] { + for curvature in curvatures().filter(|&curvature| curvature != 0.) { + let center = contour_center(end, curvature).unwrap(); + let found = center_curvature(end, center.x); + + // A point is both -1 and 1, which the drag settles at -1 + let expected = if curvature.abs() == 1. { -1. } else { curvature }; + assert!((found - expected).abs() < 1e-9, "{end:?} curvature {curvature}: {found}"); + } + + // Toward the other end bows toward it, and onto the endpoint is a point + assert!(center_curvature(end, 0.5) > 0.); + assert!(center_curvature(end, end.endpoint().x - end.inward()) < 0.); + assert_eq!(center_curvature(end, end.endpoint().x), -1.); + } + + // The start contour centered at the end point, and the end contour at the start point, are each the circle of radius 1 between them + assert!((center_curvature(GradientEnd::Start, 1.) - 0.5).abs() < 1e-12); + assert!((center_curvature(GradientEnd::End, 0.) - 0.5).abs() < 1e-12); + } + + #[test] + fn contours_are_drawn_through_their_endpoints_out_to_their_reach() { + let unit_to_viewport = DAffine2::from_scale_angle_translation(DVec2::new(200., 100.), 0.3, DVec2::new(40., 60.)); + for end in [GradientEnd::Start, GradientEnd::End] { + let endpoint = unit_to_viewport.transform_point2(end.endpoint()); + + // A point draws nothing, and a line is one long chord through the endpoint + assert!(contour_polyline(end, 1., unit_to_viewport, 500.).is_empty()); + let line = contour_polyline(end, 0., unit_to_viewport, 500.); + assert_eq!(line.len(), 2); + assert!(distance_to_polyline(&line, endpoint).unwrap() < 1e-9); + + // A small circle is drawn whole, closing on itself, and a huge one only as far as its reach, nearly straight + let small = contour_polyline(end, 0.5, unit_to_viewport, 500.); + assert!(small.first().unwrap().distance(*small.last().unwrap()) < 1e-6); + let huge = contour_polyline(end, 1e-6, unit_to_viewport, 500.); + let farthest = huge.iter().map(|point| point.distance(endpoint)).fold(0., f64::max); + assert!((400. ..=1000.).contains(&farthest), "a huge circle should reach about 500 pixels, not {farthest}"); + + for polyline in [small, huge] { + assert!(distance_to_polyline(&polyline, endpoint).unwrap() < 1e-6); + } + } + } +} diff --git a/editor/src/messages/tool/common_functionality/mod.rs b/editor/src/messages/tool/common_functionality/mod.rs index 92c5379bcd..5072876839 100644 --- a/editor/src/messages/tool/common_functionality/mod.rs +++ b/editor/src/messages/tool/common_functionality/mod.rs @@ -3,6 +3,7 @@ pub mod color_selector; pub mod compass_rose; pub mod edit_target; pub mod gizmos; +pub mod gradient_gizmos; pub mod graph_modification_utils; pub mod layer_origin_cross; pub mod measure; diff --git a/editor/src/messages/tool/tool_messages/gradient_tool.rs b/editor/src/messages/tool/tool_messages/gradient_tool.rs index 647c0adafd..455ecb38cd 100644 --- a/editor/src/messages/tool/tool_messages/gradient_tool.rs +++ b/editor/src/messages/tool/tool_messages/gradient_tool.rs @@ -1,13 +1,14 @@ use super::tool_prelude::*; use crate::consts::{ - COLOR_OVERLAY_BLUE, DRAG_THRESHOLD, GRADIENT_MIDPOINT_DIAMOND_RADIUS, GRADIENT_MIDPOINT_MAX, GRADIENT_MIDPOINT_MIN, GRADIENT_STOP_MIN_VIEWPORT_GAP, MANIPULATOR_GROUP_MARKER_SIZE, - SEGMENT_INSERTION_DISTANCE, SEGMENT_OVERLAY_SIZE, SELECTION_THRESHOLD, + COLOR_OVERLAY_BLUE, COLOR_OVERLAY_MAGENTA, COLOR_OVERLAY_WHITE, DRAG_THRESHOLD, GRADIENT_CONTOUR_RIM_GRAB_DISTANCE, GRADIENT_CONTOUR_SNAP_DISTANCE, GRADIENT_MIDPOINT_DIAMOND_RADIUS, + GRADIENT_MIDPOINT_MAX, GRADIENT_MIDPOINT_MIN, GRADIENT_STOP_MIN_VIEWPORT_GAP, MANIPULATOR_GROUP_MARKER_SIZE, SEGMENT_INSERTION_DISTANCE, SEGMENT_OVERLAY_SIZE, SELECTION_THRESHOLD, }; use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; use crate::messages::portfolio::document::overlays::utility_types::{GizmoEmphasis, OverlayContext}; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, NodeNetworkInterface}; use crate::messages::tool::common_functionality::auto_panning::AutoPanning; +use crate::messages::tool::common_functionality::gradient_gizmos::{GradientEnd, center_curvature, contour_center, contour_polyline, distance_to_polyline, rim_curvature, rim_resized_toward}; use crate::messages::tool::common_functionality::graph_modification_utils::{ self, NodeGraphLayer, get_chain_source_gradient_settings, get_fill_node_id_with_direct_fill_input, get_gradient_stops, get_upstream_gradient_value_node_id, gradient_chain_target_input, paint_target_layer, replaceable_paint_chain, reverse_direction_tooltip_description, @@ -17,7 +18,8 @@ use glam::DMat2; use graph_craft::document::value::TaggedValue; use graphene_std::color::SRGBA8; use graphene_std::raster::color::Color; -use graphene_std::vector::style::{FillChoice, Gradient, GradientForm, GradientInterpolation, GradientRamp, GradientSettings, GradientStop, build_transform_with_y_preservation}; +use graphene_std::vector::gradient_standard::{curvature_radius, radius_curvature}; +use graphene_std::vector::style::{FillChoice, Gradient, GradientForm, GradientInterpolation, GradientRamp, GradientSettings, GradientStop, build_transform_with_y_preservation, wrapped_curvature}; #[derive(Default, ExtractField)] pub struct GradientTool { @@ -103,6 +105,7 @@ impl<'a> MessageHandler> for Grad |(_gradient, appearance)| { appearance.gradient_form = gradient_form; appearance.curvature_source = CurvatureSource::Form; + appearance.curvatures = gradient_form.curvatures(); }, ); responses.add(ToolMessage::UpdateHints); @@ -382,7 +385,7 @@ fn gradient_handle_positions(unit_to_viewport: DAffine2) -> (DVec2, DVec2) { (unit_to_viewport.transform_point2(DVec2::ZERO), unit_to_viewport.transform_point2(DVec2::X)) } -#[derive(Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq)] enum GradientSource { Direct, Chain, @@ -402,6 +405,7 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI GradientAppearance { gradient_form, curvature_source, + curvatures: drawn_curvatures(gradient.curvatures, gradient_form), settings: gradient.settings, transform: gradient.transform, }, @@ -421,12 +425,21 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI struct GradientAppearance { transform: DAffine2, gradient_form: GradientForm, - /// Where the chain's curvatures come from. Unless they make `gradient_form`, the tool draws the linear form's controls. + /// Where its curvatures come from. Unless they make `gradient_form`, the tool draws the linear form's controls. // TODO: Draw the stops and midpoints of custom curvatures where their contours cross the line, since the ramp can then span just part of it curvature_source: CurvatureSource, + /// The start and end curvatures it's drawn with, each wrapped into the range starting at -1. Those of its form when fed from the graph. + curvatures: [f64; 2], settings: GradientSettings, } +impl GradientAppearance { + /// Whether the tool may adjust its curvatures, which takes ones not fed from the graph. + fn has_editable_curvatures(&self) -> bool { + self.curvature_source != CurvatureSource::Graph + } +} + /// Where a gradient's curvatures come from, as told by its 'Gradient Curvature' node or the Fill node holding it. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] enum CurvatureSource { @@ -452,6 +465,11 @@ impl CurvatureSource { } } +/// The curvatures a gradient is drawn with: its `curvatures` each wrapped into the range starting at -1, or its form's where the graph feeds them. +fn drawn_curvatures(curvatures: Option<[f64; 2]>, gradient_form: GradientForm) -> [f64; 2] { + curvatures.map_or(gradient_form.curvatures(), |curvatures| curvatures.map(|curvature| wrapped_curvature(curvature, 0.))) +} + /// Resolve the gradient transform, form, and spread by walking the chain feeding the layer. fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> GradientAppearance { let target_input = gradient_chain_target_input(layer, network_interface); @@ -463,6 +481,7 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod let mut transforms_downstream_to_upstream: Vec = Vec::new(); let mut gradient_form: Option = None; let mut curvature_source = CurvatureSource::Form; + let mut curvatures: Option<[f64; 2]> = None; for node_id in network_interface .upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow) @@ -477,7 +496,8 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod if reference == transform_reference { transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs)); } else if reference == gradient_curvature_reference && gradient_form.is_none() { - let (form, source) = CurvatureSource::of(graph_modification_utils::gradient_curvature_values(document_node)); + curvatures = graph_modification_utils::gradient_curvature_values(document_node); + let (form, source) = CurvatureSource::of(curvatures); (gradient_form, curvature_source) = (Some(form), source); } } @@ -485,10 +505,12 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod // Iteration order [T_n, ..., T_1] is the matrix-product order, so the fold yields T_n * ... * T_1 let composed_transform = transforms_downstream_to_upstream.into_iter().fold(DAffine2::IDENTITY, |acc, matrix| acc * matrix); + let gradient_form = gradient_form.unwrap_or_default(); GradientAppearance { transform: composed_transform, - gradient_form: gradient_form.unwrap_or_default(), + gradient_form, curvature_source, + curvatures: drawn_curvatures(curvatures, gradient_form), settings: get_chain_source_gradient_settings(layer, network_interface).unwrap_or_default(), } } @@ -596,6 +618,164 @@ fn midpoint_ratio_at(gradient: &Gradient, index: usize, gradient_cyclic: bool, p Some((local / span).clamp(GRADIENT_MIDPOINT_MIN, GRADIENT_MIDPOINT_MAX)) } +/// The color each end's contour gizmos are drawn in. +fn contour_color(end: GradientEnd) -> &'static str { + match end { + GradientEnd::Start => COLOR_OVERLAY_BLUE, + GradientEnd::End => COLOR_OVERLAY_MAGENTA, + } +} + +/// How far from its endpoint a contour is drawn along its length, which reaches past the farthest corner of the viewport. +fn contour_reach(viewport: &ViewportMessageHandler, endpoint: DVec2) -> f64 { + let size = viewport.size().into_dvec2(); + endpoint.distance(size / 2.) + size.length() +} + +/// The center dot of this end's contour in the viewport, if it's a circle rather than a line or a point (whose center is its endpoint). +fn contour_center_dot(end: GradientEnd, curvature: f64, unit_to_viewport: DAffine2) -> Option { + let center = contour_center(end, curvature).filter(|¢er| center != end.endpoint())?; + Some(unit_to_viewport.transform_point2(center)) +} + +/// The distance from `mouse` to the nearest of the gradient's stops and endpoints within reach of a press, if any. +fn nearest_stop_distance(start: DVec2, end: DVec2, gradient: &Gradient, settings: GradientSettings, mouse: DVec2) -> Option { + let stops = (0..gradient.len()).map(|index| start.lerp(end, gradient.position(index, settings.cyclic))); + stops + .chain([start, end]) + .map(|position| position.distance(mouse)) + .filter(|&distance| distance < MANIPULATOR_GROUP_MARKER_SIZE * 2.) + .min_by(f64::total_cmp) +} + +/// Whether a press at `mouse` takes hold of something on the gradient line: a stop, an endpoint, a midpoint diamond, or the point a stop would be inserted. +fn line_takes_press(start: DVec2, end: DVec2, gradient: &Gradient, settings: GradientSettings, mouse: DVec2) -> bool { + let on_midpoint = midpoint_diamonds(gradient, settings, start.distance(end)) + .into_iter() + .any(|(_, position)| start.lerp(end, position).distance(mouse) < GRADIENT_MIDPOINT_DIAMOND_RADIUS); + + on_midpoint || nearest_stop_distance(start, end, gradient, settings, mouse).is_some() || calculate_insertion(start, end, gradient, settings, mouse).is_some() +} + +/// The contour handle a press at `mouse` takes hold of on a gradient with these curvatures: the nearest center dot within reach, or else the +/// nearest rim. None where the press `yields_to_line`, since everything on the gradient line takes precedence over the contours. +fn contour_handle_at(mouse: DVec2, unit_to_viewport: DAffine2, curvatures: [f64; 2], yields_to_line: bool, viewport: &ViewportMessageHandler) -> Option { + if yields_to_line { + return None; + } + let ends = [GradientEnd::Start, GradientEnd::End]; + + let nearest_center = ends + .into_iter() + .filter_map(|end| Some((end, contour_center_dot(end, curvatures[end.index()], unit_to_viewport)?.distance(mouse)))) + .filter(|&(_, distance)| distance < MANIPULATOR_GROUP_MARKER_SIZE * 2.) + .min_by(|(_, a), (_, b)| a.total_cmp(b)); + if let Some((end, _)) = nearest_center { + return Some(GradientDragTarget::ContourCenter(end)); + } + + ends.into_iter() + .filter_map(|end| { + let endpoint = unit_to_viewport.transform_point2(end.endpoint()); + let reach = contour_reach(viewport, endpoint).max(2. * endpoint.distance(mouse)); + let rim = contour_polyline(end, curvatures[end.index()], unit_to_viewport, reach); + Some((end, distance_to_polyline(&rim, mouse)?)) + }) + .filter(|&(_, distance)| distance < GRADIENT_CONTOUR_RIM_GRAB_DISTANCE) + .min_by(|(_, a), (_, b)| a.total_cmp(b)) + .map(|(end, _)| GradientDragTarget::ContourRim(end)) +} + +/// The curvature a drag of a contour's center dot or rim to `mouse`, pressed at `press` while its end had `initial_curvature`, gives its end, snapped onto +/// a line or a point within a few pixels of making one. A point keeps the sign of the curvatures it shrank from. +fn dragged_contour_curvature(target: GradientDragTarget, mouse: DVec2, press: DVec2, initial_curvature: f64, unit_to_viewport: DAffine2) -> Option { + let endpoint = |end: GradientEnd| unit_to_viewport.transform_point2(end.endpoint()); + let point_curvature = |curvature: f64| if curvature < 0. { -1. } else { 1. }; + + match target { + // The center slides to where the pointer projects onto the gradient line, shrinking the contour to a point on its endpoint + GradientDragTarget::ContourCenter(end) => { + let (start_point, end_point) = gradient_handle_positions(unit_to_viewport); + let axis_position = (mouse - start_point).dot(end_point - start_point) / start_point.distance_squared(end_point); + if !axis_position.is_finite() { + return None; + } + + let curvature = center_curvature(end, axis_position); + let snapped = start_point.lerp(end_point, axis_position).distance(endpoint(end)) < GRADIENT_CONTOUR_SNAP_DISTANCE; + Some(if snapped { point_curvature(curvature) } else { curvature }) + } + // The rim resizes about its endpoint to keep the place on it the press took hold of nearest the pointer, or passes through the pointer if it was flat + GradientDragTarget::ContourRim(end) => { + let (radius, place) = match rim_resized_toward(end, initial_curvature, press, mouse, unit_to_viewport) { + Some(resized) => resized, + None => (curvature_radius(rim_curvature(end, unit_to_viewport.inverse().transform_point2(mouse))?), mouse), + }; + + // That place reaching the endpoint makes a point there, and the pointer reaching the line across the gradient line through the endpoint, + // clear of the endpoint, flattens the contour into it + let offset = mouse - endpoint(end); + let across = unit_to_viewport.transform_vector2(DVec2::Y).try_normalize()?; + if place.distance(endpoint(end)) < GRADIENT_CONTOUR_SNAP_DISTANCE { + return Some(point_curvature(radius)); + } + if offset.perp_dot(across).abs() < GRADIENT_CONTOUR_SNAP_DISTANCE && offset.length() >= MANIPULATOR_GROUP_MARKER_SIZE * 2. { + return Some(0.); + } + + Some(radius_curvature(radius)) + } + _ => None, + } +} + +/// Zeroes the curvature of this end of the layer's gradient, making its contour a line, as one step in the history. +fn straighten_contour(layer: LayerNodeIdentifier, end: GradientEnd, document: &DocumentMessageHandler, responses: &mut VecDeque) { + let Some((_, appearance, _)) = resolve_gradient(layer, &document.network_interface) else { + return; + }; + if !appearance.has_editable_curvatures() || appearance.curvatures[end.index()] == 0. { + return; + } + + let mut curvatures = appearance.curvatures; + curvatures[end.index()] = 0.; + + responses.add(DocumentMessage::StartTransaction); + responses.add(GraphOperationMessage::GradientCurvatureSet { layer, curvatures }); + responses.add(DocumentMessage::EndTransaction); + responses.add(InspectorMessage::Refresh); +} + +/// Draws the dashed contour through each end of a gradient with these curvatures, and the center dot of each that's a circle, +/// emphasizing the hovered or dragged handle. +fn draw_contour_gizmos(overlay_context: &mut OverlayContext, unit_to_viewport: DAffine2, curvatures: [f64; 2], emphasized: Option<(GradientDragTarget, GizmoEmphasis)>) { + for end in [GradientEnd::Start, GradientEnd::End] { + let curvature = curvatures[end.index()]; + let color = contour_color(end); + let emphasis = |target: GradientDragTarget| match emphasized { + Some((emphasized_target, emphasis)) if emphasized_target == target => emphasis, + _ => GizmoEmphasis::Regular, + }; + + let endpoint = unit_to_viewport.transform_point2(end.endpoint()); + let rim = contour_polyline(end, curvature, unit_to_viewport, contour_reach(&overlay_context.viewport, endpoint)); + match emphasis(GradientDragTarget::ContourRim(end)) { + GizmoEmphasis::Regular => overlay_context.dashed_polyline(&rim, Some(color), Some(8.), Some(6.), None), + GizmoEmphasis::Hovered | GizmoEmphasis::Active => overlay_context.dashed_polyline(&rim, Some(color), None, None, None), + } + + if let Some(center) = contour_center_dot(end, curvature, unit_to_viewport) { + let (radius, stroke) = match emphasis(GradientDragTarget::ContourCenter(end)) { + GizmoEmphasis::Regular => (3., color), + GizmoEmphasis::Hovered => (4., color), + GizmoEmphasis::Active => (4., COLOR_OVERLAY_WHITE), + }; + overlay_context.circle(center, radius, Some(color), Some(stroke)); + } + } +} + #[derive(PartialEq, Eq, Clone, Copy, Debug, Default)] pub enum GradientDragTarget { Start, @@ -604,6 +784,20 @@ pub enum GradientDragTarget { Stop(usize), Midpoint(usize), New, + /// The center dot of an end's contour, sliding along the gradient line. + ContourCenter(GradientEnd), + /// The dashed rim of an end's contour, or its dashed line where it's flat. + ContourRim(GradientEnd), +} + +impl GradientDragTarget { + /// The end whose contour this curves, if it's a contour handle. + fn contour_end(self) -> Option { + match self { + Self::ContourCenter(end) | Self::ContourRim(end) => Some(end), + _ => None, + } + } } /// Contains information about the selected gradient handle @@ -618,6 +812,8 @@ struct SelectedGradient { initial_gradient: Gradient, /// Transform from unit [0, 1] line to the geometry's local gradient space, the snapshot from `GradientAppearance.transform`. initial_gradient_transform: DAffine2, + /// The snapshot of `GradientAppearance.curvatures`. + initial_curvatures: [f64; 2], is_gradient_chain: bool, } @@ -665,6 +861,7 @@ impl SelectedGradient { dragging: GradientDragTarget::End, initial_gradient: gradient, initial_gradient_transform: appearance.transform, + initial_curvatures: appearance.curvatures, is_gradient_chain: source == GradientSource::Chain, } } @@ -688,6 +885,9 @@ impl SelectedGradient { if self.dragging != GradientDragTarget::New { self.gradient = self.initial_gradient.clone(); self.appearance.transform = self.initial_gradient_transform; + if self.dragging.contour_end().is_some() { + self.set_curvatures(self.initial_curvatures); + } self.render_gradient(responses); } return; @@ -830,14 +1030,36 @@ impl SelectedGradient { self.gradient.set_midpoint(midpoint_index, midpoint_ratio); } } + GradientDragTarget::ContourCenter(end) | GradientDragTarget::ContourRim(end) => { + if let Some(curvature) = dragged_contour_curvature(self.dragging, mouse, press_unsnapped, self.initial_curvatures[end.index()], self.unit_to_viewport_transform()) { + let mut curvatures = self.appearance.curvatures; + curvatures[end.index()] = curvature; + self.set_curvatures(curvatures); + } + } } self.render_gradient(responses); } + /// Set the curvatures, along with the form they make, if either. + fn set_curvatures(&mut self, curvatures: [f64; 2]) { + let form = GradientForm::from_curvatures(curvatures); + + self.appearance.curvatures = curvatures; + self.appearance.gradient_form = form.unwrap_or_default(); + self.appearance.curvature_source = if form.is_some() { CurvatureSource::Form } else { CurvatureSource::Custom }; + } + /// Update the layer fill to the current gradient pub fn render_gradient(&mut self, responses: &mut VecDeque) { if let Some(layer) = self.layer { - if self.is_gradient_chain { + // Curving a contour changes nothing else + if self.dragging.contour_end().is_some() { + responses.add(GraphOperationMessage::GradientCurvatureSet { + layer, + curvatures: self.appearance.curvatures, + }); + } else if self.is_gradient_chain { // Only a new gradient takes its form from the tool, as the Properties panel may have adjusted an existing one after it was selected let write_form = self.dragging == GradientDragTarget::New; dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, write_form, responses); @@ -967,6 +1189,8 @@ struct GradientToolData { secondary_color: Color, color_picker_editing_color_stop: Option, color_picker_transaction_open: bool, + /// The layer and end of the contour handle the last press took hold of, which a double-click straightens. + contour_press: Option<(LayerNodeIdentifier, GradientEnd)>, } impl Fsm for GradientToolFsmState { @@ -1005,6 +1229,7 @@ impl Fsm for GradientToolFsmState { let dragging = selected .filter(|selected| selected.layer.is_some_and(|selected_layer| selected_layer == layer)) .map(|selected| selected.dragging); + let drawing = matches!(self, GradientToolFsmState::Drawing { .. }); let gradient = if matches!(self, GradientToolFsmState::Drawing { .. }) && dragging.is_some() @@ -1030,6 +1255,21 @@ impl Fsm for GradientToolFsmState { let first_at_start = !gradient.is_empty() && gradient.position(0, gradient_cyclic).abs() < f64::EPSILON * 1000.; let last_at_end = !gradient.is_empty() && (1. - gradient.position(gradient.len() - 1, gradient_cyclic)).abs() < f64::EPSILON * 1000.; + // The contour handles beneath everything else, emphasizing the one being dragged or else hovered + let mut hovered_contour = None; + if appearance.has_editable_curvatures() { + let emphasized = match dragging.filter(|target| target.contour_end().is_some()) { + Some(target) => Some((target, GizmoEmphasis::Active)), + None if !drawing => { + let yields_to_line = line_takes_press(start, end, gradient, settings, mouse); + hovered_contour = contour_handle_at(mouse, unit_to_viewport, appearance.curvatures, yields_to_line, &overlay_context.viewport); + hovered_contour.map(|target| (target, GizmoEmphasis::Hovered)) + } + None => None, + }; + draw_contour_gizmos(&mut overlay_context, unit_to_viewport, appearance.curvatures, emphasized); + } + overlay_context.line(start, end, None, None); // Determine which stop is selected (being dragged) and hovered (closest to mouse) @@ -1043,7 +1283,7 @@ impl Fsm for GradientToolFsmState { _ => None, }; let stop_tolerance = (MANIPULATOR_GROUP_MARKER_SIZE * 2.).powi(2); - let hovered_stop_id: Option = if !matches!(self, GradientToolFsmState::Drawing { .. }) { + let hovered_stop_id: Option = if !drawing && hovered_contour.is_none() { // Find the closest stop to the mouse (matching the click detection logic) let mut best: Option<(f64, StopId)> = None; let mut check = |dist_sq: f64, id: StopId| { @@ -1193,9 +1433,14 @@ impl Fsm for GradientToolFsmState { // Only reset if the mouse hasn't moved so we don't trigger from a click-then-click-and-drag being reported as a double-click. // Compared against the unsnapped press position so a snap point near the stop doesn't make a stationary mouse look moved. let drag_start_viewport = document.metadata().document_to_viewport.transform_point2(tool_data.drag_start_unsnapped); - if input.mouse.position.distance(drag_start_viewport) <= DRAG_THRESHOLD - && let Some(selected_gradient) = &mut tool_data.selected_gradient - { + let unmoved = input.mouse.position.distance(drag_start_viewport) <= DRAG_THRESHOLD; + + // A contour handle straightens its contour, as double-clicking its curvature's slider resets it + if unmoved && let Some((layer, end)) = tool_data.contour_press { + straighten_contour(layer, end, document, responses); + } + + if unmoved && let Some(selected_gradient) = &mut tool_data.selected_gradient { match selected_gradient.dragging { GradientDragTarget::Midpoint(index) => { selected_gradient.gradient.reset_midpoint(index); @@ -1282,7 +1527,7 @@ impl Fsm for GradientToolFsmState { return ready_default; } } - GradientDragTarget::New => { + GradientDragTarget::New | GradientDragTarget::ContourCenter(_) | GradientDragTarget::ContourRim(_) => { responses.add(DocumentMessage::AbortTransaction); return ready_default; } @@ -1378,7 +1623,7 @@ impl Fsm for GradientToolFsmState { // The press lands on whatever the pointer was shown snapping to, or takes hold of a handle right where it is let unsnapped = document_to_viewport.inverse().transform_point2(input.mouse.position); - let drag_start = match detect_hover_target(input.mouse.position, document) { + let drag_start = match detect_hover_target(input.mouse.position, document, viewport) { GradientHoverTarget::None | GradientHoverTarget::InsertionPoint => snap_session .shown_position() .unwrap_or_else(|| snap_press(snap_session, SnapView::new(document, *document_id, input)).0), @@ -1394,6 +1639,7 @@ impl Fsm for GradientToolFsmState { // The press selects whatever it lands on, so one landing on nothing leaves no stop selected tool_data.selected_gradient = None; + tool_data.contour_press = None; let mut drag_hint: Option = None; let mut transaction_started = false; @@ -1423,6 +1669,7 @@ impl Fsm for GradientToolFsmState { gradient: gradient.clone(), appearance, initial_gradient_transform: appearance.transform, + initial_curvatures: appearance.curvatures, dragging: GradientDragTarget::Midpoint(index), initial_gradient: gradient.clone(), is_gradient_chain, @@ -1433,6 +1680,19 @@ impl Fsm for GradientToolFsmState { } } + // Check for dragging a contour's center dot or rim, unless something on the gradient line takes the press + if drag_hint.is_none() && appearance.has_editable_curvatures() { + let yields_to_line = line_takes_press(start, end, &gradient, appearance.settings, mouse); + if let Some(target) = contour_handle_at(mouse, unit_to_viewport, appearance.curvatures, yields_to_line, viewport) { + drag_hint = Some(GradientDragHintState::Contour); + tool_data.contour_press = target.contour_end().map(|end| (layer, end)); + tool_data.selected_gradient = Some(SelectedGradient { + dragging: target, + ..SelectedGradient::new(gradient.clone(), appearance, source, layer, document) + }); + } + } + // Check for dragging the closest stop to the mouse pointer if drag_hint.is_none() { let mut best: Option<(f64, usize)> = None; @@ -1468,6 +1728,7 @@ impl Fsm for GradientToolFsmState { appearance, initial_gradient: gradient.clone(), initial_gradient_transform: appearance.transform, + initial_curvatures: appearance.curvatures, is_gradient_chain, }); } @@ -1486,6 +1747,7 @@ impl Fsm for GradientToolFsmState { appearance, initial_gradient: gradient.clone(), initial_gradient_transform: appearance.transform, + initial_curvatures: appearance.curvatures, is_gradient_chain, }) } @@ -1573,6 +1835,7 @@ impl Fsm for GradientToolFsmState { transform: DAffine2::IDENTITY, gradient_form: tool_options.gradient_form, curvature_source: CurvatureSource::Form, + curvatures: tool_options.gradient_form.curvatures(), settings: tool_options.settings, }, // A blank layer, or one holding only the other tool's paint, starts a whole-expanse gradient chain; a layer with content gets its Fill painted @@ -1680,12 +1943,13 @@ impl Fsm for GradientToolFsmState { responses.add(DocumentMessage::EndTransaction); } - // Clear the selection if we were dragging an endpoint of the gradient which isn't a stop + // Clear the selection if we were dragging an endpoint of the gradient which isn't a stop, or a contour handle if tool_data.selected_gradient.as_ref().is_some_and(|selected| match selected.dragging { GradientDragTarget::Start => selected.gradient.is_empty() || selected.gradient.position(0, selected.appearance.settings.cyclic).abs() >= f64::EPSILON * 1000., GradientDragTarget::End => { selected.gradient.is_empty() || (1. - selected.gradient.position(selected.gradient.len() - 1, selected.appearance.settings.cyclic)).abs() >= f64::EPSILON * 1000. } + GradientDragTarget::ContourCenter(_) | GradientDragTarget::ContourRim(_) => true, _ => false, }) { tool_data.selected_gradient = None; @@ -1699,7 +1963,7 @@ impl Fsm for GradientToolFsmState { } (GradientToolFsmState::Ready { .. }, GradientToolMessage::PointerMove { .. }) => { let mouse = input.mouse.position; - let hovering = detect_hover_target(mouse, document); + let hovering = detect_hover_target(mouse, document, viewport); let selected = compute_selected_target(tool_data); // Show where a press would land or insert a stop, unless it would take hold of a handle @@ -1779,6 +2043,14 @@ impl Fsm for GradientToolFsmState { groups.push(HintGroup(vec![HintInfo::mouse(MouseMotion::LmbDouble, "Reset Midpoint")])); } } + GradientHoverTarget::ContourCenter => { + groups.push(HintGroup(vec![HintInfo::mouse(MouseMotion::LmbDrag, "Slide Contour Center")])); + groups.push(HintGroup(vec![HintInfo::mouse(MouseMotion::LmbDouble, "Straighten Contour")])); + } + GradientHoverTarget::ContourRim => { + groups.push(HintGroup(vec![HintInfo::mouse(MouseMotion::LmbDrag, "Bend Contour")])); + groups.push(HintGroup(vec![HintInfo::mouse(MouseMotion::LmbDouble, "Straighten Contour")])); + } } // Delete/reset hint based on selection @@ -1821,7 +2093,10 @@ impl Fsm for GradientToolFsmState { _ => {} } - groups.push(snapping_hints()); + // Contour handles snap to making a line or a point rather than to the document + if drag_hint != &GradientDragHintState::Contour { + groups.push(snapping_hints()); + } HintData(groups) } @@ -1894,7 +2169,7 @@ fn dismiss_color_stop_color_picker(tool_data: &mut GradientToolData, responses: } } -fn detect_hover_target(mouse: DVec2, document: &DocumentMessageHandler) -> GradientHoverTarget { +fn detect_hover_target(mouse: DVec2, document: &DocumentMessageHandler, viewport: &ViewportMessageHandler) -> GradientHoverTarget { let stop_tolerance = (MANIPULATOR_GROUP_MARKER_SIZE * 2.).powi(2); let midpoint_tolerance = GRADIENT_MIDPOINT_DIAMOND_RADIUS.powi(2); @@ -1917,6 +2192,16 @@ fn detect_hover_target(mouse: DVec2, document: &DocumentMessageHandler) -> Gradi } } + // Check contour handles, unless something on the gradient line takes the press + if appearance.has_editable_curvatures() { + let yields_to_line = line_takes_press(start, end, &gradient, appearance.settings, mouse); + match contour_handle_at(mouse, unit_to_viewport, appearance.curvatures, yields_to_line, viewport) { + Some(GradientDragTarget::ContourCenter(_)) => return GradientHoverTarget::ContourCenter, + Some(GradientDragTarget::ContourRim(_)) => return GradientHoverTarget::ContourRim, + _ => {} + } + } + // Check stops for index in 0..gradient.len() { let position = gradient.position(index, appearance.settings.cyclic); @@ -1956,7 +2241,7 @@ fn compute_selected_target(tool_data: &GradientToolData) -> GradientSelectedTarg let resettable = i < selected_gradient.gradient.len() && midpoint_is_resettable(selected_gradient.gradient.midpoint(i)); GradientSelectedTarget::Midpoint { resettable } } - GradientDragTarget::New => GradientSelectedTarget::None, + GradientDragTarget::New | GradientDragTarget::ContourCenter(_) | GradientDragTarget::ContourRim(_) => GradientSelectedTarget::None, } } @@ -2131,6 +2416,8 @@ enum GradientHoverTarget { Midpoint { resettable: bool, }, + ContourCenter, + ContourRim, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] @@ -2153,6 +2440,7 @@ enum GradientDragHintState { Midpoint { resettable: bool, }, + Contour, } #[cfg(test)] @@ -3102,7 +3390,10 @@ mod test_gradient { let (gradient, _) = get_gradient_from_fill(&mut editor).await; assert!(!gradient.stops.has_position_attribute(), "the evenly spaced positions should be implicit"); - assert_eq!(detect_hover_target(DVec2::new(50., 50.), editor.active_document()), GradientHoverTarget::Stop); + assert_eq!( + detect_hover_target(DVec2::new(50., 50.), editor.active_document(), &ViewportMessageHandler::default()), + GradientHoverTarget::Stop + ); } #[tokio::test] @@ -3926,6 +4217,202 @@ mod test_gradient { ); } + /// The viewport position of a point in the gradient space of a layer's gradient, where its line runs from the origin to (1, 0). + fn gradient_point(editor: &EditorTestUtils, layer: LayerNodeIdentifier, point: DVec2) -> DVec2 { + let document = editor.active_document(); + let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the layer should have a gradient"); + (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(point) + } + + /// Presses at `from`, drags to `to`, and releases there, holding `modifier_keys` throughout. + async fn drag_between(editor: &mut EditorTestUtils, from: DVec2, to: DVec2, modifier_keys: ModifierKeys) { + editor.move_mouse(from.x, from.y, modifier_keys, MouseKeys::empty()).await; + editor.left_mousedown(from.x, from.y, modifier_keys).await; + editor.move_mouse(to.x, to.y, modifier_keys, MouseKeys::LEFT).await; + editor.left_mouseup(to.x, to.y, modifier_keys).await; + } + + /// The start and end curvatures a 'Gradient Curvature' node holds as values. + fn curvature_values(editor: &EditorTestUtils, curvature_node_id: NodeId) -> [f64; 2] { + let node = &editor.active_document().network_interface.document_network().nodes[&curvature_node_id]; + crate::messages::tool::common_functionality::graph_modification_utils::gradient_curvature_values(node).expect("the curvatures should be values") + } + + fn assert_curvatures(actual: [f64; 2], expected: [f64; 2], what: &str) { + let near = actual.iter().zip(expected).all(|(actual, expected)| (actual - expected).abs() < 1e-9); + assert!(near, "{what}: {actual:?} rather than {expected:?}"); + } + + #[tokio::test] + async fn dragging_a_flat_contour_bends_it_through_the_pointer_as_one_undoable_step() { + use graphene_std::vector::gradient_standard::radius_curvature; + + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await; + set_curvatures(&mut editor, curvature_node_id, GradientForm::Linear.curvatures()).await; + + // Pulling the end's line toward the start bends it into the circle through the pointer, centered a quarter of the line before the end + let rim = gradient_point(&editor, layer, DVec2::new(1., 0.25)); + let pointer = gradient_point(&editor, layer, DVec2::new(0.75, 0.25)); + drag_between(&mut editor, rim, pointer, ModifierKeys::empty()).await; + assert_curvatures(curvature_values(&editor, curvature_node_id), [0., radius_curvature(0.25)], "the bent end"); + + editor.handle_message(DocumentMessage::Undo).await; + assert_curvatures(curvature_values(&editor, curvature_node_id), [0., 0.], "undoing the drag"); + + // Escape mid-drag puts it back too + editor.move_mouse(rim.x, rim.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor.left_mousedown(rim.x, rim.y, ModifierKeys::empty()).await; + editor.move_mouse(pointer.x, pointer.y, ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.press(Key::Escape, ModifierKeys::empty()).await; + assert_curvatures(curvature_values(&editor, curvature_node_id), [0., 0.], "aborting the drag"); + } + + #[tokio::test] + async fn dragging_a_contour_center_slides_it_along_the_line_and_a_double_click_straightens_a_contour() { + use graphene_std::vector::gradient_standard::{curvature_radius, radius_curvature}; + + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await; + set_curvatures(&mut editor, curvature_node_id, [-0.6, 0.6]).await; + + // The start circle's center behind the start point, dragged off the line, lands where the pointer projects onto it, halfway along + let center = gradient_point(&editor, layer, DVec2::new(-curvature_radius(0.6), 0.)); + let pointer = gradient_point(&editor, layer, DVec2::new(0.5, 0.1)); + drag_between(&mut editor, center, pointer, ModifierKeys::empty()).await; + assert_curvatures(curvature_values(&editor, curvature_node_id), [radius_curvature(0.5), 0.6], "the slid start"); + + editor.handle_message(DocumentMessage::Undo).await; + assert_curvatures(curvature_values(&editor, curvature_node_id), [-0.6, 0.6], "undoing the slide"); + + // Double-clicking the end circle's rim flattens it to a line in one step + let end_radius = curvature_radius(0.6); + let rim = gradient_point(&editor, layer, DVec2::new(1. - end_radius, 0.) + DVec2::from_angle(std::f64::consts::TAU / 3.) * end_radius); + editor.move_mouse(rim.x, rim.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor.left_mousedown(rim.x, rim.y, ModifierKeys::empty()).await; + editor.left_mouseup(rim.x, rim.y, ModifierKeys::empty()).await; + editor.double_click(rim).await; + assert_curvatures(curvature_values(&editor, curvature_node_id), [-0.6, 0.], "the straightened end"); + + editor.handle_message(DocumentMessage::Undo).await; + assert_curvatures(curvature_values(&editor, curvature_node_id), [-0.6, 0.6], "undoing the straightening"); + } + + #[test] + fn a_dragged_rim_keeps_the_place_it_was_pressed_at_nearest_the_pointer() { + use crate::messages::tool::common_functionality::gradient_gizmos::GradientEnd; + use graphene_std::vector::gradient_standard::radius_curvature; + + // The radial form's end circle along a line from (10, 50) to (200, 50), pressed at its top + let unit_to_viewport = DAffine2::from_scale_angle_translation(DVec2::splat(190.), 0., DVec2::new(10., 50.)); + let drag = |target, pointer: DVec2| super::dragged_contour_curvature(target, pointer, unit_to_viewport.transform_point2(DVec2::Y), 0.5, unit_to_viewport); + let rim = super::GradientDragTarget::ContourRim(GradientEnd::End); + let end_point = unit_to_viewport.transform_point2(DVec2::X); + + // That place moves along the line from the end point through it as the circle resizes, so a pointer off that line projects onto it + let curvature = drag(rim, unit_to_viewport.transform_point2(DVec2::new(0., 0.5))).unwrap(); + assert!((curvature - radius_curvature(0.75)).abs() < 1e-9, "the radius should become 0.75, not that of curvature {curvature}"); + + // Brought onto the end point, it shrinks to a point on the side it came from + assert_eq!(drag(rim, end_point + DVec2::new(-1., 1.)), Some(1.)); + assert_eq!(drag(rim, end_point + DVec2::new(1., -1.)), Some(-1.)); + + // The line across the gradient line through the end point flattens it, but not near the end point itself + assert_eq!(drag(rim, end_point + DVec2::new(1., 40.)), Some(0.)); + assert!( + drag(rim, end_point + DVec2::new(0., 10.)).is_some_and(|curvature| curvature > 0.9), + "near the end point, it should nearly be a point" + ); + } + + #[test] + fn a_center_dragged_onto_its_endpoint_makes_a_point_on_the_side_it_came_from() { + use crate::messages::tool::common_functionality::gradient_gizmos::GradientEnd; + + let unit_to_viewport = DAffine2::from_scale_angle_translation(DVec2::splat(190.), 0., DVec2::new(10., 50.)); + let center = super::GradientDragTarget::ContourCenter(GradientEnd::End); + let end_point = unit_to_viewport.transform_point2(DVec2::X); + let drag = |pointer: DVec2| super::dragged_contour_curvature(center, pointer, unit_to_viewport.transform_point2(DVec2::ZERO), 0.5, unit_to_viewport); + + assert_eq!(drag(end_point - DVec2::new(2., 0.)), Some(1.)); + assert_eq!(drag(end_point + DVec2::new(2., 0.)), Some(-1.)); + } + + #[tokio::test] + async fn contour_handles_yield_to_everything_on_the_gradient_line() { + use graphene_std::vector::gradient_standard::{curvature_radius, radius_curvature}; + + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await; + let hovered = |editor: &EditorTestUtils, point: DVec2| detect_hover_target(gradient_point(editor, layer, point), editor.active_document(), &ViewportMessageHandler::default()); + + // The start circle's center dot, a few pixels from the start point, yields to it + set_curvatures(&mut editor, curvature_node_id, [radius_curvature(0.03), 0.]).await; + let hovered_center = hovered(&editor, DVec2::new(0.03, 0.)); + assert!( + matches!(hovered_center, GradientHoverTarget::Endpoint { .. }), + "the start point should be hovered, not {hovered_center:?}" + ); + + // The end circle's center dot between the stops yields to inserting a stop there, while its rim off the line can still be taken + set_curvatures(&mut editor, curvature_node_id, [0., 0.6]).await; + let (center, radius) = (1. - curvature_radius(0.6), curvature_radius(0.6)); + assert_eq!(hovered(&editor, DVec2::new(center, 0.)), GradientHoverTarget::InsertionPoint); + assert_eq!(hovered(&editor, DVec2::new(center, radius)), GradientHoverTarget::ContourRim); + } + + /// A rectangle with a linear gradient held by its Fill node, drawn by the Gradient tool, along with that Fill node. + async fn fill_gradient_layer(editor: &mut EditorTestUtils) -> (LayerNodeIdentifier, NodeId) { + editor.active_document_mut().snapping_state.snapping_enabled = false; + editor.drag_tool(ToolType::Rectangle, 0., 0., 300., 100., ModifierKeys::empty()).await; + editor.drag_tool(ToolType::Gradient, 10., 50., 200., 50., ModifierKeys::empty()).await; + + let layer = editor.active_document().metadata().all_layers().next().expect("the rectangle should be a layer"); + let fill_node_id = get_fill_node_id_with_direct_fill_input(layer, &editor.active_document().network_interface).expect("a Fill node should hold the gradient"); + (layer, fill_node_id) + } + + /// The start and end curvatures a Fill node holds in its hidden curvature inputs. + fn fill_curvatures(editor: &EditorTestUtils, fill_node_id: NodeId) -> [f64; 2] { + let node = &editor.active_document().network_interface.document_network().nodes[&fill_node_id]; + let curvature = |value: Option<&TaggedValue>| match value { + Some(&TaggedValue::Number(curvature)) => curvature, + _ => panic!("the Fill node's curvatures should be numbers, not {value:?}"), + }; + [ + curvature(node.input(fill::StartCurvatureInput).and_then(|input| input.as_value())), + curvature(node.input(fill::EndCurvatureInput).and_then(|input| input.as_value())), + ] + } + + #[tokio::test] + async fn curving_a_fill_gradients_contour_writes_its_fill_nodes_curvatures_which_moving_its_line_keeps() { + use graphene_std::vector::gradient_standard::radius_curvature; + + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (layer, fill_node_id) = fill_gradient_layer(&mut editor).await; + assert_curvatures(fill_curvatures(&editor, fill_node_id), GradientForm::Linear.curvatures(), "the new gradient"); + + // Pulling the end's line toward the start bends it, as on a gradient chain + let rim = gradient_point(&editor, layer, DVec2::new(1., 0.25)); + let pointer = gradient_point(&editor, layer, DVec2::new(0.75, 0.25)); + drag_between(&mut editor, rim, pointer, ModifierKeys::empty()).await; + assert_curvatures(fill_curvatures(&editor, fill_node_id), [0., radius_curvature(0.25)], "the bent end"); + + // Moving the start point rewrites the Fill node's gradient, keeping its curvatures + let start = gradient_point(&editor, layer, DVec2::ZERO); + drag_between(&mut editor, start, start + DVec2::new(0., 20.), ModifierKeys::empty()).await; + assert_curvatures(fill_curvatures(&editor, fill_node_id), [0., radius_curvature(0.25)], "moving the start"); + + editor.handle_message(DocumentMessage::Undo).await; + editor.handle_message(DocumentMessage::Undo).await; + assert_curvatures(fill_curvatures(&editor, fill_node_id), GradientForm::Linear.curvatures(), "undoing both"); + } + #[tokio::test] async fn drag_on_blank_layer_starts_gradient_chain() { use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;