Compare commits

...
26 changed files with 1474 additions and 262 deletions

No files matched your search

@@ -2,6 +2,8 @@
mod fill_v1;
mod passthrough_from_read_attribute_gradient_form_node;
mod passthrough_from_footprint_value;
mod passthrough_from_upload_texture_node;
mod renames;
mod stroke_v1;
mod vary_colors_from_assign_colors;
@@ -0,0 +1,37 @@
use migration_core::{Inputs, migration};
/// 'Footprint Value' is gone with the footprint input of 'Rasterize', whose migration takes over the inputs of one feeding it. One read
/// elsewhere passes on its empty primary input instead, since nothing else takes a footprint.
#[migration("math_nodes::FootprintValueNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
pub fn passthrough_from_footprint_value(inputs: &mut Inputs) {
inputs.truncate(1);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PassthroughFromFootprintValue, &contract());
check_undo(&PassthroughFromFootprintValue, &contract());
}
#[test]
fn keeps_the_primary_input_and_drops_the_transform_and_resolution() {
let (primary, transform, resolution) = (literal(()), literal(1.), literal(2.));
let mut fixture = Fixture::new(&PassthroughFromFootprintValue);
let footprint_value = fixture.add(decl!("math_nodes::FootprintValueNode"@1), vec![primary.clone(), transform, resolution]);
let migrated = fixture.migrate(&PassthroughFromFootprintValue).unwrap();
assert_eq!(fixture.declaration_of(&migrated, footprint_value), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
assert_eq!(fixture.inputs(&migrated, footprint_value), [primary]);
}
}
@@ -0,0 +1,48 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
PaintMapping(PaintMapping),
}
#[derive(Serialize, Deserialize)]
enum PaintMapping {
Plane,
}
/// 'Stroke' gained Paint Mapping after its dash offset, set to Plane to keep placing the paint in the canvas as it was.
#[migration("graphene_core::vector::StrokeNode"@1 => @2)]
pub fn stroke_v1(inputs: &mut Inputs) {
inputs.push(literal(Tagged::PaintMapping(PaintMapping::Plane)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(9, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&StrokeV1, &contract());
check_undo(&StrokeV1, &contract());
}
#[test]
fn keeps_the_inputs_and_appends_the_plane_paint_mapping() {
let inputs: Vec<_> = (0..9).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&StrokeV1);
let stroke = fixture.add(decl!("graphene_core::vector::StrokeNode"@1), inputs.clone());
let migrated = fixture.migrate(&StrokeV1).unwrap();
assert_eq!(fixture.declaration_of(&migrated, stroke), Some(decl!("graphene_core::vector::StrokeNode"@2)));
assert_eq!(fixture.inputs(&migrated, stroke), [inputs, vec![literal(Tagged::PaintMapping(PaintMapping::Plane))]].concat());
}
}
@@ -1,3 +1,4 @@
//! Migrations of the nodes in `graphene_std`.
mod rasterize_v1;
mod renames;
@@ -0,0 +1,276 @@
use migration_core::{Declaration, Graph, InputConnector, Inputs, MigrationError, NewNode, Node, NodeInput, OutputConnector, Upstream, decl, encode, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
const FOOTPRINT: u32 = 1;
const RASTERIZE: Declaration = decl!("graphene_std::platform_application_io::RasterizeNode"@1);
/// Matched at any version, since naming one would order this migration after the one turning 'Footprint Value' into it, which must come after.
const PASSTHROUGH: &str = "graphene_core::ops::PassthroughNode";
/// The default area, a square 1000 px across centered at (500, 500), and its resolution of one pixel per px.
const DEFAULT_TRANSFORM: [f64; 6] = [1000., 0., 0., 1000., 500., 500.];
const DEFAULT_RESOLUTION: [f64; 2] = [1000., 1000.];
/// A translation by half a unit, which moves a unit square anchored at its corner to one centered on the origin.
const CORNER_TO_CENTER: [f64; 6] = [1., 0., 0., 1., 0.5, 0.5];
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
DVec2([f64; 2]),
DAffine2([f64; 6]),
Footprint(Footprint),
}
/// Frozen mirror of the removed `Footprint` value, leaving out the render quality 'Rasterize' ignored.
#[derive(Serialize, Deserialize)]
struct Footprint {
transform: [f64; 6],
resolution: [u32; 2],
}
/// 'Rasterize' takes its footprint's area as a transform placing a unit square centered on its origin, rather than anchored at its corner,
/// then its resolution. A 'Footprint Value' node feeding it, directly or through reroutes, hands over its own inputs and goes once nothing
/// else reads it. Any other wire can't be read before it runs, so it leaves the defaults, shown in the graph.
#[migration("graphene_std::platform_application_io::RasterizeNode"@1 => @2)]
pub fn rasterize_v1(node: &Node, graph: &Graph, inputs: &mut Inputs, upstream: &mut Upstream) -> Result<(), MigrationError> {
let Some(footprint) = node.inputs().get(FOOTPRINT as usize) else {
return Err(MigrationError::invariant("Rasterize has a Footprint input"));
};
let footprint = through_reroutes(*graph, &footprint.input);
let (transform, resolution) = match footprint {
NodeInput::Value { exposed, .. } => match literal_of::<Tagged>(footprint) {
Some(Tagged::Footprint(footprint)) => (
value(Tagged::DAffine2(centered(footprint.transform)), *exposed),
value(Tagged::DVec2(footprint.resolution.map(f64::from)), *exposed),
),
_ => defaults(*exposed),
},
NodeInput::Node { id, index: 0 } if graph.declaration(*id) == Some(decl!("math_nodes::FootprintValueNode"@1)) => {
let parameters = graph.node(*id).map(|footprint_value| footprint_value.inputs()).and_then(|slots| Some((slots.get(1)?, slots.get(2)?)));
let Some((transform, resolution)) = parameters else {
return Err(MigrationError::invariant("Footprint Value has Transform and Resolution inputs"));
};
// Each Rasterize node it feeds takes over its inputs, so it's only needed by whatever else reads it
let readers = graph.consumers(OutputConnector { node: *id, output: 0 });
let only_feeds_rasterize = readers
.iter()
.all(|reader| matches!(reader, InputConnector::Node { node, input: FOOTPRINT } if graph.declaration(*node) == Some(RASTERIZE)));
if only_feeds_rasterize {
upstream.remove_node(*id);
}
let multiply = decl!("math_nodes::MultiplyNode"@1);
(centered_transform_input(&transform.input, multiply, upstream), resolution.input.clone())
}
_ => defaults(true),
};
inputs.set(FOOTPRINT, transform);
inputs.insert(FOOTPRINT + 1, resolution);
Ok(())
}
/// Where `input` reads from past any 'Passthrough' nodes rerouting it, which pass their content along unchanged.
fn through_reroutes<'a>(graph: Graph<'a>, mut input: &'a NodeInput) -> &'a NodeInput {
let mut visited = HashSet::new();
// A cycle of reroutes leads nowhere else, so revisiting one ends the walk
while let NodeInput::Node { id, index: 0 } = input
&& visited.insert(*id)
&& graph.declaration(*id).is_some_and(|declaration| declaration.identifier == PASSTHROUGH)
&& let Some(content) = graph.node(*id).and_then(|node| node.inputs().first())
{
input = &content.input;
}
input
}
/// The area transform from a 'Footprint Value' node's transform input, through a `multiply` node centering its unit square if it's wired.
fn centered_transform_input(transform: &NodeInput, multiply: Declaration, upstream: &mut Upstream) -> NodeInput {
match transform {
NodeInput::Value { exposed, .. } => match literal_of::<Tagged>(transform) {
Some(Tagged::DAffine2(transform)) => value(Tagged::DAffine2(centered(transform)), *exposed),
_ => value(Tagged::DAffine2(DEFAULT_TRANSFORM), *exposed),
},
wire => {
let multiply = upstream.add_node(NewNode {
declaration: multiply,
inputs: vec![wire.clone(), literal(Tagged::DAffine2(CORNER_TO_CENTER))],
});
NodeInput::Node { id: multiply, index: 0 }
}
}
}
/// The transform placing a unit square centered on its origin over the one `transform` places anchored at its corner, which is `transform`
/// followed by a translation of half a unit, computed in the order a `DAffine2` product computes it.
fn centered([x_axis_x, x_axis_y, y_axis_x, y_axis_y, translation_x, translation_y]: [f64; 6]) -> [f64; 6] {
[
x_axis_x,
x_axis_y,
y_axis_x,
y_axis_y,
x_axis_x * 0.5 + y_axis_x * 0.5 + translation_x,
x_axis_y * 0.5 + y_axis_y * 0.5 + translation_y,
]
}
fn defaults(exposed: bool) -> (NodeInput, NodeInput) {
(value(Tagged::DAffine2(DEFAULT_TRANSFORM), exposed), value(Tagged::DVec2(DEFAULT_RESOLUTION), exposed))
}
fn value(value: Tagged, exposed: bool) -> NodeInput {
NodeInput::Value { value: encode(&value), exposed }
}
#[cfg(test)]
mod tests {
use super::*;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const FOOTPRINT_VALUE: Declaration = decl!("math_nodes::FootprintValueNode"@1);
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| match slot {
1 => literal(Tagged::Footprint(Footprint {
transform: [random.below(10) as f64, 0., 0., random.below(10) as f64, random.below(10) as f64, random.below(10) as f64],
resolution: [random.below(10) as u32, random.below(10) as u32],
})),
_ => literal(random.below(10) as f64),
})
}
/// Rasterize's inputs with `footprint` between its artwork and its executor.
fn rasterize_inputs(footprint: NodeInput) -> Vec<NodeInput> {
vec![literal(0.), footprint, NodeInput::Scope("wgpu-executor".into())]
}
/// Rasterize's migrated inputs with `transform` and `resolution` between its artwork and its executor.
fn migrated_inputs(transform: NodeInput, resolution: NodeInput) -> Vec<NodeInput> {
vec![literal(0.), transform, resolution, NodeInput::Scope("wgpu-executor".into())]
}
fn footprint_value_inputs(transform: NodeInput, resolution: NodeInput) -> Vec<NodeInput> {
vec![literal(()), transform, resolution]
}
#[test]
fn rewrites_history() {
check_commutation(&RasterizeV1, &contract());
check_undo(&RasterizeV1, &contract());
}
#[test]
fn a_footprint_becomes_the_transform_centered_on_its_area_and_its_resolution() {
// The 64 by 32 pixel footprint over the 500 by 250 px rectangle from (-20, 40)
let footprint = Footprint {
transform: [500., 0., 0., 250., -20., 40.],
resolution: [64, 32],
};
let mut fixture = Fixture::new(&RasterizeV1);
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(literal(Tagged::Footprint(footprint))));
let migrated = fixture.migrate(&RasterizeV1).unwrap();
let expected = migrated_inputs(literal(Tagged::DAffine2([500., 0., 0., 250., 230., 165.])), literal(Tagged::DVec2([64., 32.])));
assert_eq!(fixture.declaration_of(&migrated, rasterize), Some(decl!("graphene_std::platform_application_io::RasterizeNode"@2)));
assert_eq!(fixture.inputs(&migrated, rasterize), expected);
}
#[test]
fn the_default_footprint_becomes_the_default_area_and_resolution() {
let footprint = Footprint {
transform: [1000., 0., 0., 1000., 0., 0.],
resolution: [1000, 1000],
};
let mut fixture = Fixture::new(&RasterizeV1);
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(literal(Tagged::Footprint(footprint))));
let migrated = fixture.migrate(&RasterizeV1).unwrap();
let (transform, resolution) = defaults(false);
assert_eq!(fixture.inputs(&migrated, rasterize), migrated_inputs(transform, resolution));
}
#[test]
fn a_footprint_value_node_hands_over_its_inputs_and_goes() {
let transform = literal(Tagged::DAffine2([300., 0., 0., 200., 10., 20.]));
let mut fixture = Fixture::new(&RasterizeV1);
let resolution_source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
let resolution = NodeInput::Node { id: resolution_source, index: 0 };
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(transform, resolution.clone()));
let first = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
let second = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
let migrated = fixture.migrate(&RasterizeV1).unwrap();
let expected = migrated_inputs(literal(Tagged::DAffine2([300., 0., 0., 200., 160., 120.])), resolution);
assert_eq!(fixture.inputs(&migrated, first), expected);
assert_eq!(fixture.inputs(&migrated, second), expected);
assert_eq!(fixture.declaration_of(&migrated, footprint_value), None, "nothing else reads the Footprint Value node");
}
#[test]
fn a_footprint_value_node_hands_over_its_inputs_through_reroutes() {
let transform = literal(Tagged::DAffine2([300., 0., 0., 200., 10., 20.]));
let resolution = literal(Tagged::DVec2([30., 20.]));
let mut fixture = Fixture::new(&RasterizeV1);
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(transform, resolution.clone()));
let first_reroute = fixture.add(decl!("graphene_core::ops::PassthroughNode"@1), vec![NodeInput::Node { id: footprint_value, index: 0 }]);
let second_reroute = fixture.add(decl!("graphene_core::ops::PassthroughNode"@2), vec![NodeInput::Node { id: first_reroute, index: 0 }]);
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: second_reroute, index: 0 }));
let migrated = fixture.migrate(&RasterizeV1).unwrap();
let expected = migrated_inputs(literal(Tagged::DAffine2([300., 0., 0., 200., 160., 120.])), resolution);
assert_eq!(fixture.inputs(&migrated, rasterize), expected);
assert_eq!(
fixture.declaration_of(&migrated, footprint_value),
Some(FOOTPRINT_VALUE),
"the reroute still reads the Footprint Value node"
);
}
#[test]
fn a_wired_footprint_value_transform_reaches_the_area_through_a_multiply_node() {
let mut fixture = Fixture::new(&RasterizeV1);
let transform_source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
let wire = NodeInput::Node { id: transform_source, index: 0 };
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(wire.clone(), literal(Tagged::DVec2([30., 20.]))));
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
let migrated = fixture.migrate(&RasterizeV1).unwrap();
let inputs = fixture.inputs(&migrated, rasterize);
let NodeInput::Node { id: multiply, index: 0 } = inputs[1] else {
panic!("the area should be wired from a Multiply node");
};
assert_eq!(inputs, migrated_inputs(NodeInput::Node { id: multiply, index: 0 }, literal(Tagged::DVec2([30., 20.]))));
assert_eq!(fixture.declaration_of(&migrated, multiply), Some(decl!("math_nodes::MultiplyNode"@1)));
assert_eq!(fixture.inputs(&migrated, multiply), [wire, literal(Tagged::DAffine2(CORNER_TO_CENTER))]);
}
#[test]
fn a_footprint_value_node_read_elsewhere_stays() {
let mut fixture = Fixture::new(&RasterizeV1);
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(literal(Tagged::DAffine2(CORNER_TO_CENTER)), literal(Tagged::DVec2([1., 1.]))));
fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
fixture.export(NodeInput::Node { id: footprint_value, index: 0 });
let migrated = fixture.migrate(&RasterizeV1).unwrap();
assert_eq!(fixture.declaration_of(&migrated, footprint_value), Some(FOOTPRINT_VALUE));
}
#[test]
fn any_other_wire_leaves_the_defaults_shown_in_the_graph() {
let mut fixture = Fixture::new(&RasterizeV1);
let source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: source, index: 0 }));
let migrated = fixture.migrate(&RasterizeV1).unwrap();
let (transform, resolution) = defaults(true);
assert_eq!(fixture.inputs(&migrated, rasterize), migrated_inputs(transform, resolution));
}
}
@@ -31,8 +31,8 @@ use graphene_std::vector::misc::{
WeldMethod,
};
use graphene_std::vector::style::{
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap,
StrokeJoin,
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, PaintMapping, StrokeAlign,
StrokeCap, StrokeJoin,
};
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
use graphene_std::{
@@ -419,6 +419,7 @@ macro_rules! inspectable_types {
List<StrokeJoin>,
List<StrokeAlign>,
List<StrokeCap>,
List<PaintMapping>,
List<WeldMethod>,
List<UnweldMethod>,
List<ExtrudeJoiningAlgorithm>,
@@ -480,6 +481,7 @@ macro_rules! inspectable_types {
Item<StrokeJoin>,
Item<StrokeAlign>,
Item<StrokeCap>,
Item<PaintMapping>,
Item<WeldMethod>,
Item<UnweldMethod>,
Item<ExtrudeJoiningAlgorithm>,
@@ -1295,6 +1297,7 @@ impl_table_item_layout_for_choice_enum!(
StrokeJoin,
StrokeAlign,
StrokeCap,
PaintMapping,
WeldMethod,
UnweldMethod,
ExtrudeJoiningAlgorithm,
@@ -1491,6 +1494,7 @@ macro_rules! known_item_types {
StrokeJoin,
StrokeAlign,
StrokeCap,
PaintMapping,
WeldMethod,
UnweldMethod,
ExtrudeJoiningAlgorithm,
@@ -14,7 +14,7 @@ use graph_craft::document::{NodeId, NodeInput};
use graph_craft::list;
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{Gradient, GradientForm, GradientSettings, GradientSpace, GradientSpread, GradientStop, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::style::{Gradient, GradientForm, GradientSettings, GradientSpace, GradientSpread, GradientStop, PaintMapping, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::{Artboard, Color};
#[derive(ExtractField)]
@@ -991,6 +991,7 @@ fn apply_usvg_stroke(stroke: &usvg::Stroke, modify_inputs: &mut ModifyInputsCont
},
join_miter_limit: stroke.miterlimit().get() as f64,
align: StrokeAlign::Center,
paint_mapping: PaintMapping::Plane,
transform,
},
)
@@ -904,6 +904,8 @@ impl<'a> ModifyInputsContext<'a> {
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.dash_offset), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintMappingInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintMapping(stroke.paint_mapping), false), true);
}
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
@@ -1684,19 +1684,18 @@ mod test {
#[test]
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
use glam::{DAffine2, UVec2};
use glam::DAffine2;
use graph_craft::document::value::TaggedValue;
use graphene_std::platform_application_io::rasterize;
let definition = super::resolve_proto_node_definition(&rasterize::IDENTIFIER).expect("Rasterize should have a definition");
let footprint = definition.node_template.input(rasterize::FootprintInput).and_then(|input| input.as_value());
let transform = definition.node_template.input(rasterize::TransformInput).and_then(|input| input.as_value());
let resolution = definition.node_template.input(rasterize::ResolutionInput).and_then(|input| input.as_value());
let expected = Footprint {
transform: DAffine2::from_scale(DVec2::splat(1000.)),
resolution: UVec2::splat(1000),
..Default::default()
};
assert_eq!(footprint, Some(&TaggedValue::Footprint(expected)));
// The square from (0, 0) to (1000, 1000)
let expected_transform = DAffine2::from_scale_angle_translation(DVec2::splat(1000.), 0., DVec2::splat(500.));
assert_eq!(transform, Some(&TaggedValue::DAffine2(expected_transform)));
assert_eq!(resolution, Some(&TaggedValue::DVec2(DVec2::splat(1000.))));
}
// The executor input the compiler fills in has no type yet, which mustn't rule out every implementation
@@ -31,14 +31,14 @@ use graphene_std::raster_types::{CPU, GPU, Image, Raster};
use graphene_std::text::{Font, TextAlign};
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
use graphene_std::transform::{ReferencePoint, ScaleType, Transform};
use graphene_std::vector::misc::BooleanOperation;
use graphene_std::vector::misc::{
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
};
use graphene_std::vector::style::{
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign,
StrokeCap, StrokeJoin, build_transform_with_y_preservation,
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, PaintMapping,
StrokeAlign, StrokeCap, StrokeJoin, build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
@@ -421,7 +421,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
// ============
Some(x) if id_is::<Font>(x) => font_widget(default_info),
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info),
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(),
@@ -460,6 +459,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<PaintMapping>(x) => enum_choice::<PaintMapping>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).inspector_row(),
@@ -677,142 +677,6 @@ pub fn image_data_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<Wi
widgets
}
pub fn footprint_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
let mut location_widgets = start_widgets(&parameter_widgets_info);
location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
let mut scale_widgets = vec![TextLabel::new("").widget_instance()];
add_blank_assist(&mut scale_widgets);
scale_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
let mut resolution_widgets = vec![TextLabel::new("").widget_instance()];
add_blank_assist(&mut resolution_widgets);
resolution_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
let Some(document_node) = document_node else { return LayoutGroup::default() };
let Some(input) = document_node.inputs.get(index) else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return Vec::new().into();
};
if let Some(&TaggedValue::Footprint(footprint)) = input.as_non_exposed_value() {
let top_left = footprint.transform.transform_point2(DVec2::ZERO);
let bounds = footprint.scale();
let oversample = footprint.resolution.as_dvec2() / bounds;
location_widgets.extend_from_slice(&[
NumberInput::new(Some(top_left.x))
.label("X")
.unit(" px")
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| {
let (offset, scale) = {
let diff = DVec2::new(top_left.x - x.value.unwrap_or_default(), 0.);
(top_left - diff, bounds)
};
let footprint = Footprint {
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
resolution: (oversample * scale).as_uvec2(),
..footprint
};
TaggedValue::Footprint(footprint)
}))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(top_left.y))
.label("Y")
.unit(" px")
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| {
let (offset, scale) = {
let diff = DVec2::new(0., top_left.y - x.value.unwrap_or_default());
(top_left - diff, bounds)
};
let footprint = Footprint {
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
resolution: (oversample * scale).as_uvec2(),
..footprint
};
TaggedValue::Footprint(footprint)
}))
.on_commit(commit_value)
.widget_instance(),
]);
scale_widgets.extend_from_slice(&[
NumberInput::new(Some(bounds.x))
.label("W")
.unit(" px")
.on_update(update_value_at_index(
move |x: &NumberInput| {
let (offset, scale) = (top_left, DVec2::new(x.value.unwrap_or_default(), bounds.y));
let footprint = Footprint {
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
resolution: (oversample * scale).as_uvec2(),
..footprint
};
TaggedValue::Footprint(footprint)
},
node_id,
index,
))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(bounds.y))
.label("H")
.unit(" px")
.on_update(update_value_at_index(
move |x: &NumberInput| {
let (offset, scale) = (top_left, DVec2::new(bounds.x, x.value.unwrap_or_default()));
let footprint = Footprint {
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
resolution: (oversample * scale).as_uvec2(),
..footprint
};
TaggedValue::Footprint(footprint)
},
node_id,
index,
))
.on_commit(commit_value)
.widget_instance(),
]);
resolution_widgets.push(
NumberInput::new(Some((footprint.resolution.as_dvec2() / bounds).x * 100.))
.label("Resolution")
.mode_range()
.min(0.)
.range_min(Some(1.))
.range_max(Some(100.))
.unit("%")
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| {
let resolution = (bounds * x.value.unwrap_or(100.) / 100.).as_uvec2().max((1, 1).into()).min((4000, 4000).into());
let footprint = Footprint { resolution, ..footprint };
TaggedValue::Footprint(footprint)
}))
.on_commit(commit_value)
.widget_instance(),
);
}
let widgets = [LayoutGroup::row(location_widgets), LayoutGroup::row(scale_widgets), LayoutGroup::row(resolution_widgets)];
let (last, rest) = widgets.split_last().expect("Footprint widget should return multiple rows");
*extra_widgets = rest.to_vec();
last.clone()
}
/// The X, Y, rotation, W, and H of a transform input. W and H show as a multiplier, or with the parameter's `size_unit` (like " px") where it declares one, for a transform scaling a shape of unit size.
pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit: Option<&str>, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
@@ -3996,6 +3860,9 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput, true, context), TextInput::default().centered(true));
let number_input = disabled_number_input;
let dash_offset = number_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput, true, context), number_input);
let paint_mapping = enum_choice::<PaintMapping>()
.for_socket(ParameterWidgetsInfo::new(node_id, PaintMappingInput, true, context))
.inspector_row();
vec![
color,
@@ -4006,6 +3873,7 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
LayoutGroup::row(miter_limit),
LayoutGroup::row(dash_lengths),
LayoutGroup::row(dash_offset),
paint_mapping,
]
}
@@ -6,7 +6,7 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions:
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, NodeTemplateImplementation, OutputConnector};
use crate::messages::prelude::DocumentMessageHandler;
use glam::{DVec2, IVec2};
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
use graph_craft::document::DocumentNode;
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
@@ -297,10 +297,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::math_nodes::floor::IDENTIFIER,
aliases: &["graphene_math_nodes::FloorNode", "graphene_core::ops::FloorNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
aliases: &["math_nodes::SpreadMethodNode"],
@@ -1827,6 +1823,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
for (node_id, node, network_path) in &nodes {
migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open);
}
remove_footprint_value_nodes(document);
create_layer_stacks(document);
follow_segments_turned_on_load(document);
@@ -2185,6 +2182,100 @@ fn read_noise_through_gamma_correction(document: &mut DocumentMessageHandler, no
Some(())
}
/// Whether a node is a removed 'Footprint Value' node, under any identifier it had.
fn is_footprint_value(node: &DocumentNode) -> bool {
matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().ends_with("::FootprintValueNode"))
}
/// Sets an upgraded Rasterize node's area transform and resolution from the footprint it took, stored or from a 'Footprint Value' node (even
/// through reroutes) whose inputs it takes over. Any other wire can't be read before it runs, so it leaves the defaults, shown in the graph.
fn set_rasterize_area_from_footprint(document: &mut DocumentMessageHandler, node_id: &NodeId, network_path: &[NodeId], footprint: &NodeInput) -> Option<()> {
use graphene_std::math_nodes::multiply;
// A footprint's transform placed a unit square anchored at its corner, where the area's is centered on its origin
let corner_to_center = DAffine2::from_translation(DVec2::splat(0.5));
let (transform_connector, resolution_connector) = (InputConnector::node_at_index(*node_id, 1), InputConnector::node_at_index(*node_id, 2));
// Reroutes pass the footprint along unchanged, and a cycle of them leads nowhere else
let mut footprint = footprint.clone();
let mut visited = HashSet::new();
while let NodeInput::Node { node_id: source, output_index: 0 } = footprint
&& visited.insert(source)
&& let Some(reroute) = document.network_interface.document_node(&source, network_path)
&& matches!(&reroute.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::ops::passthrough::IDENTIFIER)
&& let Some(content) = reroute.inputs.first()
{
footprint = content.clone();
}
match &footprint {
// A stored footprint loads as its transform's six numbers then its resolution's two
NodeInput::Value { tagged_value, exposed } => {
let TaggedValue::Numbers(numbers) = &**tagged_value else { return None };
let &[x_axis_x, x_axis_y, y_axis_x, y_axis_y, translation_x, translation_y, width, height] = numbers.as_slice() else {
return None;
};
let transform = DAffine2::from_cols_array(&[x_axis_x, x_axis_y, y_axis_x, y_axis_y, translation_x, translation_y]) * corner_to_center;
let resolution = DVec2::new(width, height);
document
.network_interface
.set_input(&transform_connector, NodeInput::value(TaggedValue::DAffine2(transform), *exposed), network_path);
document
.network_interface
.set_input(&resolution_connector, NodeInput::value(TaggedValue::DVec2(resolution), *exposed), network_path);
}
NodeInput::Node { node_id: source, output_index: 0 } if document.network_interface.document_node(source, network_path).is_some_and(is_footprint_value) => {
let footprint_value = document.network_interface.document_node(source, network_path)?;
let (transform, resolution) = (footprint_value.inputs.get(1)?.clone(), footprint_value.inputs.get(2)?.clone());
document.network_interface.set_input(&resolution_connector, resolution, network_path);
match transform {
NodeInput::Value { tagged_value, exposed } => {
let &TaggedValue::DAffine2(transform) = &*tagged_value else { return None };
let transform = NodeInput::value(TaggedValue::DAffine2(transform * corner_to_center), exposed);
document.network_interface.set_input(&transform_connector, transform, network_path);
}
// A wired transform goes through a Multiply node moving its unit square's anchor to the center
wire => {
document.network_interface.set_input(&transform_connector, wire, network_path);
let multiply_id = NodeId::new();
document
.network_interface
.insert_node(multiply_id, resolve_proto_node_type(multiply::IDENTIFIER)?.default_node_template(), network_path);
let multiplicand = NodeInput::value(TaggedValue::DAffine2(corner_to_center), false);
document.network_interface.set_input(&InputConnector::node_at_index(multiply_id, 1), multiplicand, network_path);
document.network_interface.insert_node_before_input(&multiply_id, &transform_connector, network_path);
}
}
}
_ => {
for connector in [transform_connector, resolution_connector] {
let default = document.network_interface.input_from_connector(&connector, network_path)?.as_value()?.clone();
document.network_interface.set_input(&connector, NodeInput::value(default, true), network_path);
}
}
}
Some(())
}
/// Deletes every 'Footprint Value' node once the Rasterize nodes it fed have taken over its inputs, disconnecting whatever else it fed.
fn remove_footprint_value_nodes(document: &mut DocumentMessageHandler) {
let footprint_value_nodes: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter(|(_, node, _)| is_footprint_value(node))
.map(|(node_id, _, path)| (*node_id, path))
.collect();
for (node_id, network_path) in footprint_value_nodes {
document.network_interface.delete_nodes(vec![node_id], false, &network_path);
}
}
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
let NodeInput::Value { tagged_value, exposed } = input else { return None };
@@ -2770,9 +2861,14 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 9;
}
// The modern Stroke also has 10 inputs, so the Paint Order era is told apart by its paint order at 7 or its dash offset at 9,
// either of which may be wired, where the modern shape holds its dash pattern and paint mapping
let value_at = |index: usize| node.inputs.get(index).and_then(|input| input.as_value());
let is_paint_order_stroke = inputs_count == 10 && (matches!(value_at(7), Some(TaggedValue::PaintOrder(_))) || matches!(value_at(9), Some(TaggedValue::Number(_))));
// The Stroke node's "Paint Order" input was retired in favor of the relative order of the Fill and Stroke
// nodes in the chain, so the stored value becomes a topology rewrite that reorders the two nodes.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 10 {
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && is_paint_order_stroke {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
@@ -3165,6 +3261,16 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 2;
}
// Rasterize, like the wrapper network collapsed into it above, took a footprint where it now takes an area transform and a resolution
if reference == DefinitionIdentifier::ProtoNode(graphene_std::platform_application_io::rasterize::IDENTIFIER) && matches!(inputs_count, 2 | 3) {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), node.inputs[0].clone(), network_path);
set_rasterize_area_from_footprint(document, node_id, network_path, &node.inputs[1]);
inputs_count = 4;
}
// The removed "Brightness/Contrast Classic" node had no Use Classic input, so its three inputs become the unified node with the toggle on
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::brightness_contrast::IDENTIFIER) && inputs_count == 3 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -4697,6 +4803,7 @@ mod tests {
.find(|node_id| document.network_interface.reference(node_id, &[]).as_ref() == Some(&stroke_reference))
.expect("a fresh shape should have a Stroke node in its chain");
let mut inputs = document.network_interface.document_node(&stroke_node_id, &[]).unwrap().inputs.clone();
inputs.truncate(graphene_std::vector::stroke::PaintMappingInput::INDEX);
inputs.insert(7, NodeInput::value(TaggedValue::PaintOrder(PaintOrder::StrokeBelow), false));
let mut legacy_stroke = NodeTemplate { inputs, ..Default::default() };
legacy_stroke.normalize_input_metadata();
@@ -4718,6 +4825,50 @@ mod tests {
assert_eq!(chain_layout(&opened, layer), expected, "the migration should leave the layer's chain intact");
}
// The modern Stroke also has 10 inputs, which must not be mistaken for the retired "Paint Order" layout
#[tokio::test]
async fn opening_a_ten_input_stroke_keeps_its_inputs_and_paint_order() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::messages::tool::common_functionality::graph_modification_utils::get_stroke_paint_order;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::vector::stroke::{DashPatternInput, PaintMappingInput};
use graphene_std::vector::style::PaintMapping;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
let document = editor.active_document_mut();
let layer = document.metadata().all_layers().next().unwrap().to_node();
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
let stroke_node_id = document
.network_interface
.layer_chain_nodes(layer, &[])
.into_iter()
.find(|node_id| document.network_interface.reference(node_id, &[]).as_ref() == Some(&stroke_reference))
.expect("a fresh shape should have a Stroke node in its chain");
// A dashed stroke mapped along its path, whose dash pattern and paint mapping sit where the retired layout kept its paint order and dash offset
let dashed_along_path = [
(DashPatternInput::INDEX, TaggedValue::DashPattern(vec![4., 2.])),
(PaintMappingInput::INDEX, TaggedValue::PaintMapping(PaintMapping::Path)),
];
for (index, value) in dashed_along_path {
document
.network_interface
.set_input(&InputConnector::node_at_index(stroke_node_id, index), NodeInput::value(value, false), &[]);
}
let inputs = document.network_interface.document_node(&stroke_node_id, &[]).unwrap().inputs.clone();
assert_eq!(inputs.len(), 10, "the modern Stroke should have 10 inputs");
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
let reopened = opened.network_interface.document_node(&stroke_node_id, &[]).expect("the Stroke node should still exist");
assert_eq!(reopened.inputs, inputs, "the Stroke node should keep its inputs");
assert_eq!(get_stroke_paint_order(LayerNodeIdentifier::new_unchecked(layer), &opened.network_interface), PaintOrder::StrokeAbove);
}
#[tokio::test]
async fn opening_a_canvas_rasterize_network_upgrades_it_to_the_vello_node() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkTemplate;
@@ -4732,11 +4883,8 @@ mod tests {
let node_id = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 0).await;
let document = editor.active_document_mut();
let footprint = Footprint {
resolution: glam::UVec2::new(64, 32),
..Default::default()
};
let footprint_input = NodeInput::value(TaggedValue::Footprint(footprint), false);
// A footprint can't be written any more, so a placeholder value stands in for it until the document is serialized
let placeholder = NodeInput::value(TaggedValue::String("footprint placeholder".into()), false);
// Save the node as the network that drew into a browser canvas, which took only the artwork and footprint
let canvas_network = NodeNetworkTemplate {
@@ -4754,27 +4902,111 @@ mod tests {
..Default::default()
};
let mut legacy = NodeTemplate {
inputs: vec![NodeInput::type_default(list!(graphic_types::Graphic), true), footprint_input.clone()],
inputs: vec![NodeInput::type_default(list!(graphic_types::Graphic), true), placeholder],
implementation: NodeTemplateImplementation::Network(canvas_network),
..Default::default()
};
document.network_interface.replace_implementation(&node_id, &[], &mut legacy);
document.network_interface.replace_inputs(&node_id, &[], &mut legacy);
document.network_interface.set_reference(&node_id, &[], Some("Rasterize".into()));
// A 64 by 32 pixel footprint over the 500 by 250 px rectangle from (-20, 40)
let placeholder = r#"{"String":"footprint placeholder"}"#;
let footprint = r#"{"Footprint":{"transform":[500.0,0.0,0.0,250.0,-20.0,40.0],"resolution":[64,32],"quality":"Full"}}"#;
let serialized = document.serialize_document();
assert!(serialized.contains(placeholder), "the placeholder should be serialized as expected");
let serialized = serialized.replace(placeholder, footprint);
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
let interface = &opened.network_interface;
assert_eq!(interface.reference(&node_id, &[]), Some(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER)));
// The area's unit square is centered on its origin, so its translation is the rectangle's center
let area = DAffine2::from_scale_angle_translation(DVec2::new(500., 250.), 0., DVec2::new(230., 165.));
let input = |index| interface.input_from_connector(&InputConnector::node_at_index(node_id, index), &[]).cloned();
assert_eq!(input(1), Some(NodeInput::value(TaggedValue::DAffine2(area), false)), "the footprint should cover the same area");
assert_eq!(
interface.input_from_connector(&InputConnector::node_at_index(node_id, 1), &[]),
Some(&footprint_input),
"the footprint should carry over"
input(2),
Some(NodeInput::value(TaggedValue::DVec2(DVec2::new(64., 32.)), false)),
"the footprint should keep its resolution"
);
let definition_inputs = resolve_proto_node_type(rasterize::IDENTIFIER).expect("Rasterize should have a definition").node_template.inputs.len();
assert_eq!(interface.number_of_inputs(&node_id, &[]), definition_inputs, "the node should gain the inputs the compiler fills in");
}
#[tokio::test]
async fn opening_footprint_value_nodes_folds_them_into_the_rasterize_nodes_they_fed() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::platform_application_io::rasterize;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let literal_rasterize = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 0).await;
let wired_rasterize = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 10).await;
let transform_source = editor
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), -20, 10)
.await;
let reroute = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), -5, 10).await;
let document = editor.active_document_mut();
let footprint_transform = DAffine2::from_scale_angle_translation(DVec2::new(300., 200.), 0., DVec2::new(10., 20.));
let footprint_value = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("math_nodes::FootprintValueNode")),
inputs: vec![
NodeInput::value(TaggedValue::None, false),
NodeInput::value(TaggedValue::DAffine2(footprint_transform), false),
NodeInput::value(TaggedValue::DVec2(DVec2::new(30., 20.)), false),
],
..Default::default()
};
let (literal_footprint, wired_footprint) = (NodeId(1), NodeId(2));
document.network_interface.insert_node(literal_footprint, footprint_value.clone(), &[]);
document.network_interface.insert_node(wired_footprint, footprint_value, &[]);
document
.network_interface
.set_input(&InputConnector::node_at_index(wired_footprint, 1), NodeInput::node(transform_source, 0), &[]);
document
.network_interface
.set_input(&InputConnector::node_at_index(reroute, 0), NodeInput::node(wired_footprint, 0), &[]);
// Each Rasterize node as saved before its area and resolution, taking the artwork, the footprint, and the executor
let definition = resolve_proto_node_type(rasterize::IDENTIFIER).expect("Rasterize should have a definition");
let executor = definition.node_template.inputs.last().cloned().expect("Rasterize should take the executor");
for (rasterize_node, footprint_node) in [(literal_rasterize, literal_footprint), (wired_rasterize, reroute)] {
let mut old_inputs = NodeTemplate {
inputs: vec![NodeInput::type_default(list!(graphic_types::Graphic), true), NodeInput::node(footprint_node, 0), executor.clone()],
..Default::default()
};
document.network_interface.replace_inputs(&rasterize_node, &[], &mut old_inputs);
}
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
let interface = &opened.network_interface;
let input = |node, index| interface.input_from_connector(&InputConnector::node_at_index(node, index), &[]).cloned();
assert!(interface.document_node(&literal_footprint, &[]).is_none(), "the Footprint Value node should be removed");
assert!(interface.document_node(&wired_footprint, &[]).is_none(), "the Footprint Value node should be removed");
let corner_to_center = DAffine2::from_translation(DVec2::splat(0.5));
let resolution = Some(NodeInput::value(TaggedValue::DVec2(DVec2::new(30., 20.)), false));
assert_eq!(
input(literal_rasterize, 1),
Some(NodeInput::value(TaggedValue::DAffine2(footprint_transform * corner_to_center), false))
);
assert_eq!(input(literal_rasterize, 2), resolution);
// The wired transform reaches the area through a Multiply node centering its unit square
let Some(NodeInput::Node { node_id: multiply, output_index: 0 }) = input(wired_rasterize, 1) else {
panic!("the wired transform should reach the area through a node");
};
assert_eq!(input(multiply, 0), Some(NodeInput::node(transform_source, 0)));
assert_eq!(input(multiply, 1), Some(NodeInput::value(TaggedValue::DAffine2(corner_to_center), false)));
assert_eq!(input(wired_rasterize, 2), resolution);
}
#[tokio::test]
async fn opening_a_document_with_the_removed_extract_node_turns_it_into_a_passthrough() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
@@ -7,7 +7,7 @@ use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::utility_types::DocumentToolData;
use graphene_std::Color;
use graphene_std::color::SRGBA8;
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::style::{FillChoice, PaintMapping, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
/// Color selector widgets seen in [`LayoutTarget::ToolOptions`] bar.
pub struct ToolColorOptions {
@@ -242,6 +242,7 @@ impl DrawingToolState {
join_miter_limit: self.miter_limit.unwrap_or(defaults.miter_limit),
dash_lengths: self.dash_lengths.clone().unwrap_or_else(|| defaults.dash_lengths.clone()),
dash_offset: self.dash_offset.unwrap_or(defaults.dash_offset),
paint_mapping: PaintMapping::default(),
transform: glam::DAffine2::IDENTITY,
};
responses.add(GraphOperationMessage::StrokeSet { layer, color: Some(color), stroke });
-2
View File
@@ -191,7 +191,6 @@ import NodeFlattenGradient from "/../branding/assets/16x16-nodes/node-flatten-gr
import NodeFlattenRaster from "/../branding/assets/16x16-nodes/node-flatten-raster.svg";
import NodeFlattenVector from "/../branding/assets/16x16-nodes/node-flatten-vector.svg";
import NodeFloor from "/../branding/assets/16x16-nodes/node-floor.svg";
import NodeFootprintValue from "/../branding/assets/16x16-nodes/node-footprint-value.svg";
import NodeFormatJson from "/../branding/assets/16x16-nodes/node-format-json.svg";
import NodeFormatNumber from "/../branding/assets/16x16-nodes/node-format-number.svg";
import NodeGammaCorrection from "/../branding/assets/16x16-nodes/node-gamma-correction.svg";
@@ -485,7 +484,6 @@ export const ICON_16X16_NODES = {
NodeFlattenRaster: { svg: NodeFlattenRaster, size: 16 },
NodeFlattenVector: { svg: NodeFlattenVector, size: 16 },
NodeFloor: { svg: NodeFloor, size: 16 },
NodeFootprintValue: { svg: NodeFootprintValue, size: 16 },
NodeFormatJson: { svg: NodeFormatJson, size: 16 },
NodeFormatNumber: { svg: NodeFormatNumber, size: 16 },
NodeGammaCorrection: { svg: NodeGammaCorrection, size: 16 },
+28 -29
View File
@@ -5,7 +5,6 @@ use brush_nodes::{BrushCache, Stroke};
use core_types::color::SRGBA8;
use core_types::list::{Item, List, NodeIdPath};
use core_types::transfer_curve::TransferCurve;
use core_types::transform::Footprint;
use core_types::{CacheHash, Color, ContextModification, MemoHash, Node, Poll, RuntimeHandle, SourceId, Type, TypeDescriptor};
pub use dyn_any::StaticType;
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
@@ -75,7 +74,7 @@ macro_rules! tagged_value {
TypeDefault(Type),
/// Stored compactly as a `Vec<f64>`, materializes as `List<f64>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
#[serde(deserialize_with = "core_types::misc::migrate_to_numbers")] // TODO: Eventually remove this document upgrade code
#[serde(alias = "F64Array", alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4")]
#[serde(alias = "F64Array", alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4", alias = "Footprint")]
Numbers(Vec<f64>),
/// Stored compactly as a `Vec<f64>` of dash lengths, materializes as an `Item<DashPattern>` at runtime via `to_dynany`/`to_any`.
DashPattern(Vec<f64>),
@@ -514,7 +513,6 @@ tagged_value! {
#[serde(alias = "ColorTable", alias = "OptionalColor", alias = "ColorNotInTable")]
Color(Color),
Font(Font),
Footprint(Footprint),
VectorModification(Box<VectorModification>),
ImageData(Image<Color>),
Resource(ResourceId),
@@ -576,6 +574,7 @@ tagged_value! {
#[serde(alias = "LineJoin")]
StrokeJoin(vector::style::StrokeJoin),
StrokeAlign(vector::style::StrokeAlign),
PaintMapping(vector::style::PaintMapping),
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
GradientForm(vector::style::GradientForm),
GradientModel(vector::style::GradientModel),
@@ -706,17 +705,6 @@ impl TaggedValue {
Some(DAffine2::from_scale_angle_translation(DVec2::new(width, height), 0., DVec2::new(x, y)))
}
// The Inspector's X, Y, W, H, rendered at 100% resolution
fn to_footprint(input: &str) -> Option<Footprint> {
let transform = to_daffine2(input)?;
Some(Footprint {
transform,
resolution: transform.matrix2.diagonal().as_uvec2(),
..Default::default()
})
}
fn to_stroke_align(input: &str) -> Option<vector::style::StrokeAlign> {
let mut choices = input.split("::");
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
@@ -792,7 +780,6 @@ impl TaggedValue {
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
() if ty == TypeId::of::<Footprint>() => to_footprint(string).map(TaggedValue::Footprint)?,
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
() if ty == TypeId::of::<core_types::blending::BlendMode>() => to_blend_mode(string).map(TaggedValue::BlendMode)?,
() if ty == TypeId::of::<vector::style::GradientSpread>() => to_gradient_spread(string).map(TaggedValue::GradientSpread)?,
@@ -1148,20 +1135,6 @@ mod number_default_parsing {
assert_eq!(TaggedValue::from_primitive_string("- 1., 2.", &item!(DVec2)), Some(TaggedValue::DVec2(DVec2::new(-1., 2.))));
}
#[test]
fn footprint_defaults_parse_as_x_y_width_height() {
let expected = Footprint {
transform: DAffine2::from_scale_angle_translation(DVec2::new(10_000., 500.), 0., DVec2::new(-50., 20.)),
resolution: glam::UVec2::new(10_000, 500),
..Default::default()
};
assert_eq!(
TaggedValue::from_primitive_string("- 50., 20., 10_000., 500.", &item!(Footprint)),
Some(TaggedValue::Footprint(expected))
);
assert_eq!(TaggedValue::from_primitive_string("1., 2., 3.", &item!(Footprint)), None);
}
#[test]
fn transform_defaults_parse_as_x_y_width_height() {
let expected = DAffine2::from_scale_angle_translation(DVec2::new(500., 400.), 0., DVec2::new(250., -20.));
@@ -1303,3 +1276,29 @@ mod retired_numeric_variants {
assert_ne!(load(serde_json::json!({ "F32": 2.2 })), TaggedValue::Number(2.2_f32 as f64));
}
}
// TODO: Eventually remove this document upgrade code
#[cfg(test)]
mod retired_footprint_variant {
use super::*;
#[test]
fn a_footprint_reads_as_its_transform_then_its_resolution() {
let payload = serde_json::json!({ "Footprint": { "transform": [500., 0., 0., 250., -20., 40.], "resolution": [64, 32], "quality": "Full" } });
let expected = TaggedValue::Numbers(vec![500., 0., 0., 250., -20., 40., 64., 32.]);
let legacy = deserialize_tagged_value_with_legacy_migration(payload.clone()).expect("The footprint payload should deserialize");
assert_eq!(*legacy.into_inner(), expected);
let stored: TaggedValue = serde_json::from_value(payload).expect("The footprint payload should deserialize");
assert_eq!(stored, expected);
}
#[test]
fn a_null_in_a_footprint_transform_reads_as_zero() {
let payload = serde_json::json!({ "Footprint": { "transform": [1., 0., 0., 1., null, 0.], "resolution": [64, 32], "quality": "Full" } });
let loaded: TaggedValue = serde_json::from_value(payload).expect("The footprint payload should deserialize");
assert_eq!(loaded, TaggedValue::Numbers(vec![1., 0., 0., 1., 0., 0., 64., 32.]));
}
}
@@ -21,12 +21,14 @@ use graphene_std::render_node::RenderIntermediate;
use graphene_std::text::{Font, TextAlign};
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType};
use graphene_std::transform::{ReferencePoint, ScaleType};
use graphene_std::vector::misc::{
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
WeldMethod,
};
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::style::{
DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSpace, GradientSpread, PaintMapping, StrokeAlign, StrokeCap, StrokeJoin,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
@@ -87,7 +89,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<String>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<f64>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DAffine2>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Footprint>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DVec2>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<bool>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BlendMode>]),
@@ -269,6 +270,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
StrokeJoin,
StrokeAlign,
StrokeCap,
PaintMapping,
GradientForm,
GradientModel,
GradientSpread,
@@ -347,7 +349,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
DAffine2,
bool,
NodeIdPath,
Footprint,
Artboard,
));
node_types.extend(ranked_value_types!(rank_adapter_nodes));
@@ -107,6 +107,8 @@ pub const ATTR_JOIN: &str = "join";
pub const ATTR_JOIN_MITER_LIMIT: &str = "join_miter_limit";
/// Stroke coverage's `StrokeAlign` (implicit default `Center`), on the `Item<Cover>` inside a `Coverage`.
pub const ATTR_ALIGN: &str = "align";
/// Stroke coverage's `PaintMapping` (implicit default `Plane`), on the `Item<Cover>` inside a `Coverage`.
pub const ATTR_PAINT_MAPPING: &str = "paint_mapping";
/// Brush stroke item's `Color` its strokes are painted with.
pub const ATTR_COLOR: &str = "color";
/// Brush stroke item's tip diameter in document-space units (`f64`).
@@ -116,11 +116,18 @@ pub fn migrate_to_numbers<'de, D: serde::Deserializer<'de>>(deserializer: D) ->
enum NumbersFormat {
Array(Vec<f64>),
List(LegacyTable<f64>),
/// The removed `Footprint` value, stored only by 'Rasterize', for its upgrade to split back into its transform's six numbers then its resolution's two.
Footprint {
transform: [Option<f64>; 6],
resolution: [f64; 2],
},
}
Ok(match NumbersFormat::deserialize(deserializer)? {
NumbersFormat::Array(values) => values,
NumbersFormat::List(list) => list.element,
// A `null` saved in place of a NaN or infinite number loads as 0, like elsewhere
NumbersFormat::Footprint { transform, resolution } => transform.into_iter().map(Option::unwrap_or_default).chain(resolution).collect(),
})
}
@@ -5,7 +5,9 @@
use crate::effects::{rebased_stamped_transform, stamped_transform};
use crate::graphic::Graphic;
use core_types::graphene_hash::CacheHash;
use core_types::list::{ATTR_ALIGN, ATTR_APPEARANCE, ATTR_CAP, ATTR_DASH_OFFSET, ATTR_DASH_PATTERN, ATTR_JOIN, ATTR_JOIN_MITER_LIMIT, ATTR_PAINT, ATTR_TRANSFORM, ATTR_WEIGHT, Item, List};
use core_types::list::{
ATTR_ALIGN, ATTR_APPEARANCE, ATTR_CAP, ATTR_DASH_OFFSET, ATTR_DASH_PATTERN, ATTR_JOIN, ATTR_JOIN_MITER_LIMIT, ATTR_PAINT, ATTR_PAINT_MAPPING, ATTR_TRANSFORM, ATTR_WEIGHT, Item, List,
};
use glam::DAffine2;
use vector_types::vector::style::{DashPattern, Stroke};
@@ -82,6 +84,9 @@ impl Coverage {
if stroke.align != defaults.align {
item.set_attribute(ATTR_ALIGN, stroke.align);
}
if stroke.paint_mapping != defaults.paint_mapping {
item.set_attribute(ATTR_PAINT_MAPPING, stroke.paint_mapping);
}
Self(item)
}
@@ -105,6 +110,7 @@ impl Coverage {
ATTR_JOIN => stroke.join = value.downcast_ref().copied().unwrap_or(stroke.join),
ATTR_JOIN_MITER_LIMIT => stroke.join_miter_limit = value.downcast_ref().copied().unwrap_or(stroke.join_miter_limit),
ATTR_ALIGN => stroke.align = value.downcast_ref().copied().unwrap_or(stroke.align),
ATTR_PAINT_MAPPING => stroke.paint_mapping = value.downcast_ref().copied().unwrap_or(stroke.paint_mapping),
_ => {}
}
}
@@ -305,7 +311,7 @@ mod tests {
use super::*;
use core_types::Color;
use glam::{DAffine2, DVec2};
use vector_types::vector::style::{StrokeAlign, StrokeCap, StrokeJoin};
use vector_types::vector::style::{PaintMapping, StrokeAlign, StrokeCap, StrokeJoin};
fn solid_paint(color: Color) -> Graphic {
Graphic::ColorList(List::new_from_element(color))
@@ -327,6 +333,7 @@ mod tests {
join: StrokeJoin::Bevel,
join_miter_limit: 7.,
align: StrokeAlign::Inside,
paint_mapping: PaintMapping::Path,
transform: DAffine2::IDENTITY,
};
@@ -341,6 +348,7 @@ mod tests {
assert_eq!(extracted.join, StrokeJoin::Bevel);
assert_eq!(extracted.join_miter_limit, 7.);
assert_eq!(extracted.align, StrokeAlign::Inside);
assert_eq!(extracted.paint_mapping, PaintMapping::Path);
}
#[test]
@@ -404,6 +412,14 @@ mod tests {
let keys: Vec<_> = coverage.0.attributes().keys().collect();
assert_eq!(keys, vec![ATTR_WEIGHT], "only the non-default weight should be stamped");
assert_eq!(coverage.stroke_params().weight, 2.);
let coverage = Coverage::new_stroke(&Stroke {
paint_mapping: PaintMapping::Path,
..Stroke::default()
});
let keys: Vec<_> = coverage.0.attributes().keys().collect();
assert_eq!(keys, vec![ATTR_PAINT_MAPPING], "only the non-default paint mapping should be stamped");
assert_eq!(coverage.stroke_params().paint_mapping, PaintMapping::Path);
}
#[test]
@@ -8,6 +8,7 @@ mod geometry;
mod geometry_cache;
pub mod misc;
mod path;
mod path_chart;
pub mod reference_point;
pub mod style;
mod vector_attributes;
@@ -21,6 +22,7 @@ pub use flatten::{WorkingVector, vector_from_legacy_parts};
pub use geometry::VectorGeometry;
pub use geometry_cache::{GeometryCache, PlacedContours, SetVectorPaths, set_paths_at};
pub use path::*;
pub use path_chart::PathChart;
pub use reference_point::*;
pub use vector_attributes::*;
pub use vector_modification::*;
@@ -0,0 +1,677 @@
//! The chart a paint mapped along a stroke's paths reads its position from: arc length along each contour, and offset across the stroke's width.
use super::misc::{dvec2_to_point, point_to_dvec2};
use super::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use glam::DVec2;
use kurbo::{BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, QuadBez, Shape};
use std::ops::Range;
/// Accuracy of each path segment's arc length, the same kurbo measures dashes with, so the chart's dashes line up with the drawn ones.
const ARC_LENGTH_ACCURACY: f64 = 1e-6;
/// Maps points around a stroke to `(u, v)` coordinates. `u` runs from 0 to 1 along the arc length of each contour from its start point,
/// extending past open ends through their caps. `v` runs from 0 on the stroke's left edge to 1 on its right edge, relative to the contour's direction.
///
/// The path is flattened into straight pieces, and each piece is charted on its own, as a GPU pass reading the same pieces would chart it.
#[derive(Clone, Debug)]
pub struct PathChart {
pieces: Vec<ChartPiece>,
contours: Vec<ChartContour>,
/// The stroke's weight, across which `v` spans 0 to 1.
width: f64,
/// How far a cap reaches along the path past the end of an open contour or a dash.
cap_reach: f64,
/// -1 where the stroke space mirrors the path's own space, so the right side stays the path's own right side.
side_sign: f64,
}
/// One straight piece of a flattened contour.
#[derive(Clone, Copy, Debug)]
struct ChartPiece {
start: DVec2,
end: DVec2,
/// Arc length along the contour where the piece starts.
arc_start: f64,
/// Arc length the piece spans, scaled so a curve's pieces add up to the curve's exact arc length.
arc_span: f64,
contour: usize,
/// Whether the piece begins an open contour, so the chart extends backward past its start through the cap.
extends_backward: bool,
/// Whether the piece ends an open contour, so the chart extends forward past its end through the cap.
extends_forward: bool,
/// The corner where the piece meets the next piece of its contour.
join: Option<ChartJoin>,
}
#[derive(Clone, Copy, Debug)]
struct ChartJoin {
/// Unit direction of the next piece.
next_direction: DVec2,
/// Whether the corner's outer wedge is measured by distance from the corner, rather than from the two pieces' lines like a miter.
round: bool,
}
#[derive(Clone, Debug)]
struct ChartContour {
start: DVec2,
length: f64,
closed: bool,
/// Offset toward the right side where `v` is 0.
band_start: f64,
pieces: Range<usize>,
/// The sorted arc length intervals the stroke draws, or `None` when it draws all of a closed contour.
drawn: Option<Vec<(f64, f64)>>,
}
/// A contour flattened into straight pieces, before the chart's rules are attached to them.
struct FlatContour {
start: DVec2,
closed: bool,
pieces: Vec<FlatPiece>,
}
struct FlatPiece {
start: DVec2,
end: DVec2,
arc_span: f64,
/// Whether the piece ends one of the path's segments, rather than ending inside a flattened curve.
ends_segment: bool,
}
impl PathChart {
/// Charts `path`, which lies in the stroke's space as placed by `stroke.transform`, flattening its curves to within `tolerance`.
pub fn new(path: &BezPath, stroke: &Stroke, tolerance: f64) -> Self {
let side_sign = if stroke.transform.matrix2.determinant() < 0. { -1. } else { 1. };
let flat_contours = flatten_contours(path, tolerance.max(1e-9));
// Like the renderer, alignment only applies when every contour is closed, and then draws the stroke at twice its weight with one side masked away
let aligned = stroke.align != StrokeAlign::Center && flat_contours.iter().all(|contour| contour.closed);
let width = stroke.weight;
let drawn_half_width = if aligned { width } else { width / 2. };
let cap_reach = if stroke.cap == StrokeCap::Butt { 0. } else { drawn_half_width };
let dash_lengths: Vec<f64> = stroke.dash_lengths.iter().map(|length| length.max(0.)).collect();
let mut chart = Self {
pieces: Vec::new(),
contours: Vec::with_capacity(flat_contours.len()),
width,
cap_reach,
side_sign,
};
for (contour_index, flat_contour) in flat_contours.iter().enumerate() {
let first_piece = chart.pieces.len();
let piece_count = flat_contour.pieces.len();
// Lay the pieces end to end along the contour's arc length
let mut arc_start = 0.;
for (index, piece) in flat_contour.pieces.iter().enumerate() {
let is_last = index + 1 == piece_count;
let next = if is_last && flat_contour.closed {
flat_contour.pieces.first()
} else {
flat_contour.pieces.get(index + 1)
};
let join = next.map(|next| ChartJoin {
next_direction: (next.end - next.start).normalize(),
round: !piece.ends_segment || stroke.join == StrokeJoin::Round,
});
chart.pieces.push(ChartPiece {
start: piece.start,
end: piece.end,
arc_start,
arc_span: piece.arc_span,
contour: contour_index,
extends_backward: index == 0 && !flat_contour.closed,
extends_forward: is_last && !flat_contour.closed,
join,
});
arc_start += piece.arc_span;
}
let length = arc_start;
// The band covers the stroke's width about the contour, or for an aligned stroke, the side the fill keeps
let band_start = match stroke.align {
_ if !aligned => -width / 2.,
StrokeAlign::Inside if right_side_is_filled(path, flat_contour, side_sign) => 0.,
StrokeAlign::Outside if !right_side_is_filled(path, flat_contour, side_sign) => 0.,
_ => -width,
};
let drawn = match dash_intervals(&dash_lengths, stroke.dash_offset, length) {
Some(intervals) => Some(intervals),
None if flat_contour.closed => None,
None => Some(vec![(0., length)]),
};
chart.contours.push(ChartContour {
start: flat_contour.start,
length,
closed: flat_contour.closed,
band_start,
pieces: first_piece..chart.pieces.len(),
drawn,
});
}
chart
}
/// The `(u, v)` coordinates of `point`, given in stroke space, from the latest piece in path order that draws over it, or else from the nearest piece,
/// for points such as antialiased fringes that no piece draws over. `None` when there is no stroke to chart. O(pieces).
pub fn chart_at(&self, point: DVec2) -> Option<(f64, f64)> {
if self.width <= 0. || !self.width.is_finite() {
return None;
}
let mut charted = None;
for piece in &self.pieces {
let contour = &self.contours[piece.contour];
if let Some(coordinates) = self.body_coordinates(piece, contour, point) {
charted = Some(coordinates);
}
if let Some(coordinates) = self.join_coordinates(piece, contour, point) {
charted = Some(coordinates);
}
}
charted.or_else(|| self.nearest_coordinates(point))
}
/// The point in stroke space at `u` (clamped to 0 to 1) along the contour at the given index.
pub fn point_at(&self, contour: usize, u: f64) -> Option<DVec2> {
let contour = self.contours.get(contour)?;
let pieces = &self.pieces[contour.pieces.clone()];
if pieces.is_empty() {
return Some(contour.start);
}
let arc = u.clamp(0., 1.) * contour.length;
let index = pieces.partition_point(|piece| piece.arc_start + piece.arc_span < arc).min(pieces.len() - 1);
let piece = &pieces[index];
let along = ((arc - piece.arc_start) / piece.arc_span).clamp(0., 1.);
Some(piece.start.lerp(piece.end, along))
}
/// The body of the stroke around the piece, extended past an open contour's ends through its caps.
fn body_coordinates(&self, piece: &ChartPiece, contour: &ChartContour, point: DVec2) -> Option<(f64, f64)> {
let chord = piece.end - piece.start;
let offset = point - piece.start;
let along = offset.dot(chord) / chord.length_squared();
if (along < 0. && !piece.extends_backward) || (along > 1. && !piece.extends_forward) {
return None;
}
let across = offset.dot(self.right_normal(chord.normalize()));
let arc = piece.arc_start + along * piece.arc_span;
if !self.in_band(contour, across) || !contour.draws(arc, self.cap_reach) {
return None;
}
Some(self.coordinates(contour, arc, across))
}
/// The wedge on the outer side of the corner at the piece's end, between where its body ends and the next piece's body begins.
/// The whole wedge takes the corner's arc length, so colors fan around it.
fn join_coordinates(&self, piece: &ChartPiece, contour: &ChartContour, point: DVec2) -> Option<(f64, f64)> {
let join = piece.join?;
let incoming = (piece.end - piece.start).normalize();
let outgoing = join.next_direction;
let offset = point - piece.end;
if offset.dot(incoming) <= 0. || offset.dot(outgoing) >= 0. {
return None;
}
// The outer side is opposite the turn, except at a full reversal, where both sides are outer
let across_incoming = offset.dot(self.right_normal(incoming));
let across_outgoing = offset.dot(self.right_normal(outgoing));
let turn = outgoing.dot(self.right_normal(incoming));
let outer_side = if turn != 0. {
-turn.signum()
} else if across_incoming < 0. {
-1.
} else {
1.
};
// A miter measures the larger distance from the two pieces' lines, which stays within the band all the way to its tip
let distance = if join.round {
offset.length()
} else {
(outer_side * across_incoming).max(outer_side * across_outgoing)
};
let across = outer_side * distance;
let arc = piece.arc_start + piece.arc_span;
if !self.in_band(contour, across) || !contour.draws(arc, self.cap_reach) {
return None;
}
Some(self.coordinates(contour, arc, across))
}
/// The coordinates from the nearest point on any piece, measured across that piece's line. O(pieces).
fn nearest_coordinates(&self, point: DVec2) -> Option<(f64, f64)> {
let mut nearest: Option<(f64, &ChartPiece, f64)> = None;
for piece in &self.pieces {
let chord = piece.end - piece.start;
let along = ((point - piece.start).dot(chord) / chord.length_squared()).clamp(0., 1.);
let distance_squared = point.distance_squared(piece.start + chord * along);
// Ties go to the later piece, as overlaps do
if nearest.is_none_or(|(nearest_distance_squared, ..)| distance_squared <= nearest_distance_squared) {
nearest = Some((distance_squared, piece, along));
}
}
let (_, piece, along) = nearest?;
let contour = &self.contours[piece.contour];
let across = (point - piece.start).dot(self.right_normal((piece.end - piece.start).normalize()));
Some(self.coordinates(contour, piece.arc_start + along * piece.arc_span, across))
}
fn coordinates(&self, contour: &ChartContour, arc: f64, across: f64) -> (f64, f64) {
(arc / contour.length, (across - contour.band_start) / self.width)
}
fn in_band(&self, contour: &ChartContour, across: f64) -> bool {
(contour.band_start..=contour.band_start + self.width).contains(&across)
}
/// The unit normal toward the right side of a piece running in `direction`.
fn right_normal(&self, direction: DVec2) -> DVec2 {
self.side_sign * direction.perp()
}
}
impl ChartContour {
/// Whether the stroke draws at `arc` along the contour, counting caps that reach `cap_reach` past the ends of what it draws.
fn draws(&self, arc: f64, cap_reach: f64) -> bool {
let Some(intervals) = &self.drawn else { return true };
// The last interval starting within reach reaches the furthest, since the intervals are sorted and disjoint
let draws_at = |arc: f64| {
let count = intervals.partition_point(|&(start, _)| start <= arc + cap_reach);
count > 0 && intervals[count - 1].1 + cap_reach >= arc
};
// A closed contour's dashes continue across its start point
draws_at(arc) || (self.closed && (draws_at(arc - self.length) || draws_at(arc + self.length)))
}
}
/// Splits the path into its contours, each flattened into straight pieces whose arc lengths add up to each segment's exact arc length.
fn flatten_contours(path: &BezPath, tolerance: f64) -> Vec<FlatContour> {
let mut contours: Vec<FlatContour> = Vec::new();
let mut last_point = DVec2::ZERO;
for element in path.elements() {
let end = match *element {
PathEl::MoveTo(point) => {
last_point = point_to_dvec2(point);
contours.push(FlatContour {
start: last_point,
closed: false,
pieces: Vec::new(),
});
continue;
}
PathEl::ClosePath => {
let Some(contour) = contours.last_mut() else { continue };
if !contour.closed {
push_segment(contour, PathSeg::Line(Line::new(dvec2_to_point(last_point), dvec2_to_point(contour.start))), tolerance);
contour.closed = true;
last_point = contour.start;
}
continue;
}
PathEl::LineTo(p1) => p1,
PathEl::QuadTo(_, p2) => p2,
PathEl::CurveTo(_, _, p3) => p3,
};
// Drawing after a contour closes, without moving first, begins another contour where the closed one started
if contours.last().is_none_or(|contour| contour.closed) {
contours.push(FlatContour {
start: last_point,
closed: false,
pieces: Vec::new(),
});
}
let Some(contour) = contours.last_mut() else { continue };
let p0 = dvec2_to_point(last_point);
let segment = match *element {
PathEl::QuadTo(p1, p2) => PathSeg::Quad(QuadBez::new(p0, p1, p2)),
PathEl::CurveTo(p1, p2, p3) => PathSeg::Cubic(CubicBez::new(p0, p1, p2, p3)),
_ => PathSeg::Line(Line::new(p0, end)),
};
push_segment(contour, segment, tolerance);
last_point = point_to_dvec2(end);
}
contours
}
/// Appends a path segment's flattened pieces, scaling their chord lengths to add up to its arc length so `u` reaches exactly 1 at the contour's end.
/// Segments of no length are skipped, as the stroker skips them.
fn push_segment(contour: &mut FlatContour, segment: PathSeg, tolerance: f64) {
let arc_length = segment.arclen(ARC_LENGTH_ACCURACY);
if arc_length <= 0. || !arc_length.is_finite() {
return;
}
let mut points = Vec::new();
kurbo::flatten([PathEl::MoveTo(segment.start()), segment.as_path_el()], tolerance, |element| {
if let PathEl::MoveTo(point) | PathEl::LineTo(point) = element {
points.push(point_to_dvec2(point));
}
});
let chord_length: f64 = points.windows(2).map(|pair| pair[0].distance(pair[1])).sum();
if chord_length <= 0. || !chord_length.is_finite() {
return;
}
let scale = arc_length / chord_length;
let first_new_piece = contour.pieces.len();
for pair in points.windows(2) {
let length = pair[0].distance(pair[1]);
if length > 0. {
contour.pieces.push(FlatPiece {
start: pair[0],
end: pair[1],
arc_span: length * scale,
ends_segment: false,
});
}
}
if contour.pieces.len() > first_new_piece
&& let Some(last) = contour.pieces.last_mut()
{
last.ends_segment = true;
}
}
/// Whether the fill (nonzero) lies on the contour's right side, probed just beside the middle of its longest piece.
fn right_side_is_filled(path: &BezPath, contour: &FlatContour, side_sign: f64) -> bool {
let Some(piece) = contour.pieces.iter().max_by(|a, b| a.start.distance_squared(a.end).total_cmp(&b.start.distance_squared(b.end))) else {
return false;
};
let chord = piece.end - piece.start;
let right = side_sign * chord.normalize().perp();
let probe = piece.start.lerp(piece.end, 0.5) + right * chord.length() * 1e-4;
path.winding(dvec2_to_point(probe)) != 0
}
/// The arc length intervals kurbo draws as dashes along a contour of the given `length`, with the pattern restarting at its start,
/// or `None` when the pattern draws a solid line.
fn dash_intervals(lengths: &[f64], offset: f64, length: f64) -> Option<Vec<(f64, f64)>> {
// An odd-length pattern repeats with the dash and gap roles swapped, so its phase comes back around after two repetitions
let pattern_length: f64 = lengths.iter().sum();
let period = if lengths.len() % 2 == 1 { 2. * pattern_length } else { pattern_length };
let phase = offset.rem_euclid(period);
if lengths.is_empty() || period <= 0. || !phase.is_finite() || !length.is_finite() {
return None;
}
// Find where the offset lands in the pattern
let mut index = 0;
let mut remaining = lengths[0] - phase;
let mut drawing = true;
while remaining < 0. {
index = (index + 1) % lengths.len();
remaining += lengths[index];
drawing = !drawing;
}
// Walk the pattern along the contour, alternating between dashes and gaps
let mut intervals = Vec::new();
let mut position = 0.;
loop {
let end = position + remaining;
if drawing {
intervals.push((position, end.min(length)));
}
if end >= length {
break;
}
position = end;
index = (index + 1) % lengths.len();
remaining = lengths[index];
drawing = !drawing;
}
Some(intervals)
}
#[cfg(test)]
mod tests {
use super::*;
use glam::DAffine2;
const TOLERANCE: f64 = 0.01;
fn polyline(points: &[(f64, f64)], closed: bool) -> BezPath {
let mut path = BezPath::new();
for (index, &(x, y)) in points.iter().enumerate() {
if index == 0 {
path.move_to((x, y));
} else {
path.line_to((x, y));
}
}
if closed {
path.close_path();
}
path
}
#[track_caller]
fn assert_chart(chart: &PathChart, point: (f64, f64), expected: (f64, f64)) {
let Some((u, v)) = chart.chart_at(DVec2::new(point.0, point.1)) else {
panic!("{point:?} should be charted");
};
assert!(
(u - expected.0).abs() < 1e-9 && (v - expected.1).abs() < 1e-9,
"{point:?} charted at {:?}, expected {expected:?}",
(u, v)
);
}
#[test]
fn a_straight_line_runs_u_along_it_and_v_from_its_left_edge_to_its_right() {
let chart = PathChart::new(&polyline(&[(0., 0.), (100., 0.)], false), &Stroke::new(10.), TOLERANCE);
// Heading along +X with +Y down, the right side is +Y
assert_chart(&chart, (25., -5.), (0.25, 0.));
assert_chart(&chart, (50., 0.), (0.5, 0.5));
assert_chart(&chart, (75., 5.), (0.75, 1.));
assert_chart(&chart, (100., 2.5), (1., 0.75));
}
#[test]
fn closed_contours_each_span_zero_to_one_from_their_start_points() {
let mut path = polyline(&[(0., 0.), (10., 0.), (10., 10.), (0., 10.)], true);
path.extend(polyline(&[(120., 0.), (120., 10.), (110., 10.), (110., 0.)], true));
let chart = PathChart::new(&path, &Stroke::new(2.), TOLERANCE);
assert_chart(&chart, (5., 0.), (5. / 40., 0.5));
assert_chart(&chart, (0., 5.), (35. / 40., 0.5));
assert_chart(&chart, (120., 5.), (5. / 40., 0.5));
assert_chart(&chart, (115., 0.), (35. / 40., 0.5));
assert_eq!(chart.point_at(0, 0.5), Some(DVec2::new(10., 10.)));
assert_eq!(chart.point_at(1, 0.), Some(DVec2::new(120., 0.)));
assert_eq!(chart.point_at(1, 0.25), Some(DVec2::new(120., 10.)));
}
#[test]
fn a_round_joins_wedge_keeps_the_arc_length_of_its_corner() {
let stroke = Stroke {
join: StrokeJoin::Round,
..Stroke::new(20.)
};
let chart = PathChart::new(&polyline(&[(0., 0.), (100., 0.), (100., 100.)], false), &stroke, TOLERANCE);
// Turning right at the corner, its wedge lies on the left, where `v` falls from 0.5 at the corner to 0 at the round edge
for (x, y) in [(105., -5.), (107., -2.), (101., -9.), (100.5, -0.5)] {
let distance = DVec2::new(x - 100., y).length();
assert_chart(&chart, (x, y), (0.5, 0.5 - distance / 20.));
}
}
#[test]
fn a_miters_tip_keeps_v_within_zero_to_one() {
let stroke = Stroke {
join_miter_limit: 100.,
..Stroke::new(10.)
};
let points = [(0., 0.), (100., 0.), (0., 50.)];
let chart = PathChart::new(&polyline(&points, false), &stroke, TOLERANCE);
let corner = DVec2::new(100., 0.);
let incoming = DVec2::X;
let outgoing = (DVec2::new(0., 50.) - corner).normalize();
let corner_u = 100. / (100. + DVec2::new(100., 50.).length());
// The sharp right turn's miter points along the bisector of the two left normals, reaching the stroke's left edge at its tip
let left_normals = [-incoming.perp(), -outgoing.perp()];
let bisector = (left_normals[0] + left_normals[1]).normalize();
let tip_distance = 5. / bisector.dot(left_normals[0]);
for fraction in [0.1, 0.5, 0.9, 0.999] {
let point = corner + bisector * tip_distance * fraction;
assert_chart(&chart, (point.x, point.y), (corner_u, 0.5 * (1. - fraction)));
}
}
#[test]
fn caps_extend_u_below_zero_and_above_one_linearly() {
let path = polyline(&[(0., 0.), (100., 0.)], false);
for cap in [StrokeCap::Square, StrokeCap::Round] {
let chart = PathChart::new(&path, &Stroke { cap, ..Stroke::new(10.) }, TOLERANCE);
assert_chart(&chart, (-3., 1.), (-0.03, 0.6));
assert_chart(&chart, (104., -2.), (1.04, 0.3));
}
// Past a butt cap, nothing draws, so the fringe takes the nearest point on the path
let chart = PathChart::new(
&path,
&Stroke {
cap: StrokeCap::Butt,
..Stroke::new(10.)
},
TOLERANCE,
);
assert_chart(&chart, (-3., 1.), (0., 0.6));
}
#[test]
fn dashes_chart_like_the_solid_stroke_and_a_gap_never_wins_over_a_dash() {
let line = polyline(&[(0., 0.), (100., 0.)], false);
let dashed = Stroke {
dash_lengths: vec![10., 10.],
..Stroke::new(4.)
};
let solid_chart = PathChart::new(&line, &Stroke::new(4.), TOLERANCE);
let dashed_chart = PathChart::new(&line, &dashed, TOLERANCE);
for x in [5., 15., 25., 92.] {
let point = DVec2::new(x, 1.);
assert_eq!(dashed_chart.chart_at(point), solid_chart.chart_at(point), "the dashed stroke should chart like the solid one at {x}");
}
// Each vertical line crosses the horizontal one 45 or 55 units along itself, where its own dash pattern draws or skips
let crossing_u = |crossing_x: f64, vertical_start_y: f64| {
let mut path = line.clone();
path.extend(polyline(&[(crossing_x, vertical_start_y), (crossing_x, vertical_start_y + 100.)], false));
let chart = PathChart::new(&path, &dashed, TOLERANCE);
chart.chart_at(DVec2::new(crossing_x, 0.)).map(|(u, _)| u)
};
// The later line's gap leaves the earlier line's dash showing
assert_eq!(crossing_u(5., -55.), Some(0.05));
// The later line's dash covers the earlier line's gap
assert_eq!(crossing_u(15., -45.), Some(0.45));
// Where both draw, the later line is on top
assert_eq!(crossing_u(25., -45.), Some(0.45));
}
#[test]
fn a_figure_eights_later_pass_wins_with_the_fold_on_its_bands_edge() {
let chart = PathChart::new(&polyline(&[(0., 0.), (100., 100.), (100., 0.), (0., 100.)], true), &Stroke::new(10.), TOLERANCE);
let diagonal = 100. * 2_f64.sqrt();
let length = 2. * diagonal + 200.;
// The crossing belongs to the second diagonal, which comes later
let Some((u, _)) = chart.chart_at(DVec2::new(50., 50.)) else {
panic!("the crossing should be charted")
};
assert!((u - (diagonal + 100. + diagonal / 2.) / length).abs() < 1e-9);
// Along the first diagonal, the fold lies at the edge of the second one's band, where x and y pass 50 + 5 / √2 ≈ 53.54
let Some((inside_u, _)) = chart.chart_at(DVec2::splat(53.4)) else {
panic!("the fold should be charted")
};
let Some((outside_u, _)) = chart.chart_at(DVec2::splat(53.7)) else {
panic!("past the fold should be charted")
};
assert!(inside_u > 0.5, "within the later band, the later pass should win");
assert!((outside_u - 53.7 * 2_f64.sqrt() / length).abs() < 1e-9, "past the later band, the earlier pass should show");
}
#[test]
fn a_curves_end_reaches_u_of_one() {
let mut path = BezPath::new();
path.move_to((0., 0.));
path.curve_to((30., 80.), (70., -80.), (100., 0.));
let chart = PathChart::new(&path, &Stroke::new(2.), TOLERANCE);
let Some((u, v)) = chart.chart_at(DVec2::new(100., 0.)) else {
panic!("the end should be charted")
};
assert!((u - 1.).abs() < 1e-9, "the end should chart at u = 1, not {u}");
assert!((v - 0.5).abs() < 1e-9);
let Some(end) = chart.point_at(0, 1.) else { panic!("the contour should exist") };
assert!(end.abs_diff_eq(DVec2::new(100., 0.), 1e-9));
}
#[test]
fn inside_and_outside_bands_lie_on_their_side_of_the_fill() {
let clockwise = polyline(&[(0., 0.), (100., 0.), (100., 100.), (0., 100.)], true);
let counterclockwise = polyline(&[(0., 0.), (0., 100.), (100., 100.), (100., 0.)], true);
let aligned = |align| Stroke { align, ..Stroke::new(10.) };
// Clockwise on screen, the right side is inside, so the inside band runs from the path (left edge) inward
let chart = PathChart::new(&clockwise, &aligned(StrokeAlign::Inside), TOLERANCE);
assert_chart(&chart, (50., 2.), (0.125, 0.2));
let chart = PathChart::new(&clockwise, &aligned(StrokeAlign::Outside), TOLERANCE);
assert_chart(&chart, (50., -2.), (0.125, 0.8));
// Counterclockwise, the right side is outside, so the inside band runs inward to the path (right edge)
let chart = PathChart::new(&counterclockwise, &aligned(StrokeAlign::Inside), TOLERANCE);
assert_chart(&chart, (2., 50.), (0.125, 0.8));
let chart = PathChart::new(&counterclockwise, &aligned(StrokeAlign::Outside), TOLERANCE);
assert_chart(&chart, (-2., 50.), (0.125, 0.2));
// An open path isn't aligned, so its band stays centered
let chart = PathChart::new(&polyline(&[(0., 0.), (100., 0.)], false), &aligned(StrokeAlign::Inside), TOLERANCE);
assert_chart(&chart, (50., 0.), (0.5, 0.5));
}
#[test]
fn a_mirrored_stroke_transform_flips_v() {
let mirrored = Stroke {
transform: DAffine2::from_scale(DVec2::new(1., -1.)),
..Stroke::new(10.)
};
let chart = PathChart::new(&polyline(&[(0., 0.), (100., 0.)], false), &mirrored, TOLERANCE);
assert_chart(&chart, (25., -5.), (0.25, 1.));
assert_chart(&chart, (75., 5.), (0.75, 0.));
}
}
@@ -138,6 +138,20 @@ impl StrokeAlign {
}
}
/// Where a stroke's paint is placed: in the plane, or along the stroke's paths.
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[widget(Radio)]
pub enum PaintMapping {
/// The paint is placed in the canvas as usual.
#[default]
Plane,
/// The paint follows the stroke, its Along direction running the length of each path and Across running from the left edge to the right.
Path,
}
// Backs the control bar's stroke popover radio and legacy document parsing: the relative order
// of the Fill and Stroke nodes in the chain is what actually determines the paint order
#[repr(C)]
@@ -220,6 +234,8 @@ pub struct Stroke {
pub join_miter_limit: f64,
#[cfg_attr(feature = "serde", serde(default))]
pub align: StrokeAlign,
#[cfg_attr(feature = "serde", serde(default))]
pub paint_mapping: PaintMapping,
#[cfg_attr(feature = "serde", serde(default = "daffine2_identity"))]
pub transform: DAffine2,
}
@@ -234,6 +250,7 @@ impl Stroke {
join: StrokeJoin::Miter,
join_miter_limit: 4.,
align: StrokeAlign::Center,
paint_mapping: PaintMapping::Plane,
transform: DAffine2::IDENTITY,
}
}
@@ -247,6 +264,7 @@ impl Stroke {
join: if time < 0.5 { self.join } else { other.join },
join_miter_limit: self.join_miter_limit + (other.join_miter_limit - self.join_miter_limit) * time,
align: if time < 0.5 { self.align } else { other.align },
paint_mapping: if time < 0.5 { self.paint_mapping } else { other.paint_mapping },
transform: {
// Decompose into scale/rotation/skew and interpolate each component separately.
// We do this instead of linear matrix interpolation because that passes through a zero matrix
@@ -351,6 +369,7 @@ impl Default for Stroke {
join: StrokeJoin::Miter,
join_miter_limit: 4.,
align: StrokeAlign::Center,
paint_mapping: PaintMapping::Plane,
transform: DAffine2::IDENTITY,
}
}
-3
View File
@@ -1,5 +1,4 @@
use core_types::list::{Item, List};
use core_types::transform::Footprint;
use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, Interrupt, OwnedContextImpl};
use glam::{DAffine2, DVec2};
use graphene_animation::AnimationCurve;
@@ -82,7 +81,6 @@ fn step_real_time<T>(
Context -> Item<f64>,
Context -> Item<String>,
Context -> Item<DAffine2>,
Context -> Item<Footprint>,
Context -> Item<DVec2>,
Context -> Item<Vector>,
Context -> Item<Graphic>,
@@ -130,7 +128,6 @@ fn step_animation_time<T>(
Context -> Item<f64>,
Context -> Item<String>,
Context -> Item<DAffine2>,
Context -> Item<Footprint>,
Context -> Item<DVec2>,
Context -> Item<Vector>,
Context -> Item<Graphic>,
@@ -1,7 +1,6 @@
use core::f64;
use core_types::context::{CloneVarArgs, Context, ContextModification, Ctx, ExtractAll};
use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath};
use core_types::transform::Footprint;
use core_types::{Color, Interrupt, OwnedContextImpl};
use glam::{DAffine2, DVec2};
use graphene_animation::AnimationCurve;
@@ -22,7 +21,6 @@ fn context_modification<T>(
Context -> Item<f64>,
Context -> Item<String>,
Context -> Item<DAffine2>,
Context -> Item<Footprint>,
Context -> Item<DVec2>,
Context -> Item<Vector>,
Context -> Item<Graphic>,
@@ -5,7 +5,7 @@ use core_types::math::bbox::Bbox;
use core_types::ops::ConvertAsync;
use core_types::transform::Footprint;
use core_types::{ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, NodeError};
use glam::{DAffine2, UVec2};
use glam::{DAffine2, DVec2, UVec2};
pub use graph_craft::application_io::resource::{Resource, ResourceHash, ResourceId};
pub use graph_craft::application_io::*;
pub use graph_craft::document::value::RenderOutputType;
@@ -229,31 +229,46 @@ fn svg_to_graphic(_: impl Ctx, #[name("SVG")] svg: Item<String>) -> Result<List<
svg_convert::convert(&svg, &svg_convert::Options::default())
}
/// Renders a view of the input graphics within an area defined by the *Footprint*, producing a raster image.
#[node_macro::node(category("Raster"), icon("NodeRasterize"), placeholder = pending_raster)]
/// Renders the input graphics within a rectangle into a raster image of a chosen resolution.
///
/// Raster effects work on any graphic without this, so it's only needed to bake graphics into pixels.
#[node_macro::node(category("Raster"), icon("NodeRasterize"), version(2), placeholder = pending_raster)]
async fn rasterize(
_: impl Ctx,
/// The graphics to render as an image.
data: List<Graphic>,
/// The area of the document to render, and the resolution to render it at.
#[default(0., 0., 1000., 1000.)]
footprint: Item<Footprint>,
/// Places the rectangle the image covers, measured from the origin of the content's local coordinate space. By default, it's a square 1000 px across centered at (500, 500).
#[unit(" px")]
#[default(500., 500., 1000., 1000.)]
transform: Item<DAffine2>,
/// The number of pixels across and down the image, spread over the rectangle whatever its size. By default, it's 1000 by 1000, one pixel per px of the default rectangle.
#[unit(" px")]
#[hard(1..)]
#[default(1000., 1000.)]
resolution: Item<DVec2>,
#[scope(wgpu_executor::IDENTIFIER)] executor: Item<::wgpu_executor::WgpuExecutor>,
) -> Result<List<Raster<CPU>>, NodeError> {
rasterize_with_vello(data, footprint.into_element(), executor.into_element()).await
rasterize_with_vello(data, *transform.element(), resolution.element().as_uvec2(), executor.into_element()).await
}
async fn rasterize_with_vello(data: List<Graphic>, footprint: Footprint, executor: ::wgpu_executor::WgpuExecutor) -> Result<List<Raster<CPU>>, NodeError> {
let resolution = footprint.resolution;
if footprint.transform.matrix2.determinant() == 0. || resolution.cmpeq(UVec2::ZERO).any() {
log::trace!("Invalid footprint received for rasterization");
/// Renders `data` within the rectangle `transform` places, a unit square centered on its origin, as an image of `resolution` pixels.
async fn rasterize_with_vello(data: List<Graphic>, transform: DAffine2, resolution: UVec2, executor: ::wgpu_executor::WgpuExecutor) -> Result<List<Raster<CPU>>, NodeError> {
if transform.matrix2.determinant() == 0. || resolution.cmpeq(UVec2::ZERO).any() {
log::trace!("Invalid area or resolution received for rasterization");
return Ok(List::new());
}
let aabb = Bbox::from_transform(footprint.transform).to_axis_aligned_bbox();
// An image fills the unit square from its corner rather than its center
let image_transform = transform * DAffine2::from_translation(DVec2::splat(-0.5));
let aabb = Bbox::from_transform(image_transform).to_axis_aligned_bbox();
let view = DAffine2::from_scale(resolution.as_dvec2() / aabb.size()) * DAffine2::from_translation(-aabb.start);
let render_params = RenderParams {
footprint,
footprint: Footprint {
transform: image_transform,
resolution,
..Default::default()
},
for_export: true,
..Default::default()
};
@@ -265,12 +280,12 @@ async fn rasterize_with_vello(data: List<Graphic>, footprint: Footprint, executo
// The input's layers stay reachable so the renderer can expose their click targets to the editor's tools
Ok(List::new_from_item(
Item::new_from_element(raster)
.with_attribute(ATTR_TRANSFORM, footprint.transform)
.with_attribute(ATTR_TRANSFORM, image_transform)
.with_attribute(ATTR_EDITOR_MERGED_LAYERS, data),
))
}
fn pending_raster(_data: &List<Graphic>, _footprint: &Item<Footprint>, _executor: &Item<::wgpu_executor::WgpuExecutor>) -> List<Raster<CPU>> {
fn pending_raster(_data: &List<Graphic>, _transform: &Item<DAffine2>, _resolution: &Item<DVec2>, _executor: &Item<::wgpu_executor::WgpuExecutor>) -> List<Raster<CPU>> {
List::new()
}
@@ -328,28 +343,53 @@ fn wgpu_executor(_: impl Ctx, #[scope(application_io::IDENTIFIER)] application_i
mod tests {
use super::*;
use core_types::Color;
use glam::DVec2;
/// A red rectangle covering x from 0 to 500 px and y from 0 to 1000 px.
fn left_half_red() -> List<Graphic> {
let red = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, Color::RED))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(500., 1000.)));
List::new_from_item(Item::new_from_element(Graphic::RasterCPU(Box::new(red))))
}
/// Asserts each pixel of the image's first row is red for the first `red_columns` columns and transparent after.
fn assert_first_row_red_up_to(image: &Image<Color>, red_columns: u32) {
for x in 0..image.width {
let expected_red = x < red_columns;
assert_eq!(
image.data[x as usize].a() > 0.5,
expected_red,
"pixel {x} should be {}",
if expected_red { "red" } else { "transparent" }
);
}
}
#[tokio::test]
async fn rasterize_renders_the_footprint_area_at_its_resolution() {
async fn rasterize_renders_its_area_at_its_resolution() {
let Some(executor) = ::wgpu_executor::WgpuExecutor::for_tests().await else { return };
let red = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, Color::RED))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(500., 1000.)));
let data = List::new_from_item(Item::new_from_element(Graphic::RasterCPU(Box::new(red))));
let footprint = Footprint {
transform: DAffine2::from_scale(DVec2::splat(1000.)),
resolution: UVec2::splat(4),
..Default::default()
};
let output = rasterize_with_vello(data, footprint, executor).await.expect("Rasterize should render");
let area = DAffine2::from_scale_angle_translation(DVec2::splat(1000.), 0., DVec2::splat(500.));
let output = rasterize_with_vello(left_half_red(), area, UVec2::splat(4), executor).await.expect("Rasterize should render");
let image = output.iter_element_values().next().expect("Rasterize should output one image").data();
assert_eq!((image.width, image.height), (4, 4));
for x in 0..4 {
let pixel = image.data[(4 + x) as usize];
let expected_red = x < 2;
assert_eq!(pixel.a() > 0.5, expected_red, "pixel {x} should be {}", if expected_red { "red" } else { "transparent" });
}
assert_first_row_red_up_to(image, 2);
}
// What 'Rasterize' version 1 output for a footprint, its migrated area transform and resolution reproduce
#[tokio::test]
async fn rasterize_renders_a_migrated_footprint_where_it_did() {
let Some(executor) = ::wgpu_executor::WgpuExecutor::for_tests().await else { return };
// Version 1 rendered the 4 by 2 pixel footprint over x from 250 to 750 px, its transform placing the image's corner-anchored unit square
let footprint_transform = DAffine2::from_scale_angle_translation(DVec2::new(500., 1000.), 0., DVec2::new(250., 0.));
let migrated_area = footprint_transform * DAffine2::from_translation(DVec2::splat(0.5));
let output = rasterize_with_vello(left_half_red(), migrated_area, UVec2::new(4, 2), executor).await.expect("Rasterize should render");
assert_eq!(output.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0), footprint_transform);
let image = output.element(0).expect("Rasterize should output one image").data();
assert_eq!((image.width, image.height), (4, 2));
assert_first_row_red_up_to(image, 2);
}
}
-19
View File
@@ -1,6 +1,5 @@
use core_types::context::{CloneVarArgs, ExtractAll};
use core_types::list::{Bundle, Item, List};
use core_types::transform::Footprint;
use core_types::{Color, Ctx, OwnedContextImpl, num_traits};
use core_types::{Context, Interrupt};
use glam::{DAffine2, DMat2, DVec2};
@@ -2082,24 +2081,6 @@ fn evaluate_gradient(
Item::new_from_element(color)
}
/// Constructs a footprint value which may be set to any transformation of a unit square describing a render area, and a render resolution at least 1x1 integer pixels.
#[node_macro::node(category("Value"), icon("NodeFootprintValue"))]
fn footprint_value(
_: impl Ctx,
_primary: (),
transform: Item<DAffine2>,
#[unit(" px")]
#[hard(1..)]
#[default(100., 100.)]
resolution: Item<DVec2>,
) -> Item<Footprint> {
Item::new_from_element(Footprint {
transform: *transform.element(),
resolution: resolution.element().as_uvec2(),
..Default::default()
})
}
/// Composes a vec2 from its X and Y components.
///
/// The inverse of this node is **Vec2 to Numbers**, which decomposes a vec2 back into its X and Y components.
+7 -3
View File
@@ -38,7 +38,7 @@ use vector_types::vector::misc::{
BezierHandles, CentroidType, ExtrudeJoiningAlgorithm, InterpolationDistribution, ManipulatorGroup, PointSpacingType, RowsOrColumns, Tangent, UnweldMethod, WeldMethod, dvec2_to_point,
handles_to_segment, is_linear, point_to_dvec2, segment_to_handles,
};
use vector_types::vector::style::{DashPattern, Gradient, GradientSettings, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use vector_types::vector::style::{DashPattern, Gradient, GradientSettings, PaintMapping, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use vector_types::vector::{
CurveType, IdCollisionSet, Path, PointId, SegmentId, WorkingVector, curve_type_at, edit_item_geometry, edit_item_points, handle_point, no_paths, paths_from_item_attributes,
paths_from_list_row_attributes, push_path, push_paths, reverse_path_flows, shared_paths_from_item_attributes, span_endpoints, spans,
@@ -507,7 +507,7 @@ where
}
/// Applies a stroke style to the vector content, giving an appearance to the area within the outline of the geometry.
#[node_macro::node(category("Vector: Style"), icon("NodeStroke"), path(graphene_core::vector), inspector("stroke_inspector"))]
#[node_macro::node(category("Vector: Style"), icon("NodeStroke"), path(graphene_core::vector), inspector("stroke_inspector"), version(2))]
fn stroke<V>(
_: impl Ctx,
/// The content with vector paths to apply the stroke style to.
@@ -536,18 +536,21 @@ fn stroke<V>(
/// The phase offset distance from the starting point of the dash pattern.
#[unit(" px")]
dash_offset: Item<f64>,
/// Where the paint is placed: in the canvas like a fill's, or along the stroke's paths.
paint_mapping: Item<PaintMapping>,
) -> Item<V>
where
Item<V>: VectorItemMut + Send,
{
let mut content = content;
let (weight, align, cap, join, miter_limit, dash_offset) = (
let (weight, align, cap, join, miter_limit, dash_offset, paint_mapping) = (
weight.into_element(),
align.into_element(),
cap.into_element(),
join.into_element(),
miter_limit.into_element(),
dash_offset.into_element(),
paint_mapping.into_element(),
);
let dash_lengths = dash_pattern.into_element().clamped_lengths();
@@ -559,6 +562,7 @@ where
join,
join_miter_limit: miter_limit,
align,
paint_mapping,
transform: DAffine2::IDENTITY,
};