Compare commits

...
22 changed files with 865 additions and 92 deletions

No files matched your search

@@ -1,3 +1,4 @@
//! Migrations of the nodes in `graphene_std`.
mod rasterize_v1;
mod renames;
@@ -0,0 +1,68 @@
use migration_core::{Inputs, MigrationError, NodeInput, migration};
use serde::Serialize;
const EXECUTOR: u32 = 2;
const EXECUTOR_SCOPE: &str = "graphene_std::platform_application_io::WgpuExecutorNode";
/// Frozen mirror of the `DocumentNodeMetadata` variant this migration uses.
#[derive(Serialize)]
enum Reflected {
DocumentNodePath,
}
/// Rasterize gained an input holding its own document node path. Nodes stored without the executor input get it first, so the path lands after it.
#[migration("graphene_std::platform_application_io::RasterizeNode"@1 => @2)]
pub fn rasterize_v1(inputs: &mut Inputs) -> Result<(), MigrationError> {
if inputs.len() < EXECUTOR as usize {
return Err(MigrationError::invariant("Rasterize has Data and Footprint inputs"));
}
if inputs.len() == EXECUTOR as usize {
inputs.push(NodeInput::Scope(EXECUTOR_SCOPE.into()));
}
inputs.push_reflection(Reflected::DocumentNodePath);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
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))
}
fn migrate(inputs: Vec<NodeInput>) -> Vec<NodeInput> {
let mut fixture = Fixture::new(&RasterizeV1);
let rasterize = fixture.add(decl!("graphene_std::platform_application_io::RasterizeNode"@1), inputs);
let migrated = fixture.migrate(&RasterizeV1).unwrap();
let own_path = &migrated.node_instances[&rasterize].inputs()[3];
assert_eq!(own_path.attributes.get_typed::<String>(REFLECTION_METADATA).as_deref(), Some("DocumentNodePath"));
fixture.inputs(&migrated, rasterize)
}
#[test]
fn rewrites_history() {
check_commutation(&RasterizeV1, &contract());
check_undo(&RasterizeV1, &contract());
}
#[test]
fn gives_the_node_its_path() {
let inputs = vec![literal(1.), literal(2.), NodeInput::Scope(EXECUTOR_SCOPE.into())];
assert_eq!(migrate(inputs.clone()), [inputs, vec![NodeInput::Reflection]].concat());
}
#[test]
fn a_node_stored_without_its_executor_gets_it_before_its_path() {
let inputs = vec![literal(1.), literal(2.)];
assert_eq!(migrate(inputs.clone()), [inputs, vec![NodeInput::Scope(EXECUTOR_SCOPE.into()), NodeInput::Reflection]].concat());
}
}
@@ -319,6 +319,9 @@ pub enum DocumentMessage {
UpdateTextFrames {
text_frames: HashMap<NodeId, DAffine2>,
},
UpdateFootprintAreas {
footprint_areas: HashMap<NodeId, DAffine2>,
},
UpdateClipTargets {
clip_targets: HashSet<NodeId>,
},
@@ -1914,6 +1914,9 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
.collect();
self.network_interface.update_text_frames(layer_text_frames);
}
DocumentMessage::UpdateFootprintAreas { footprint_areas } => {
self.network_interface.update_footprint_areas(footprint_areas);
}
DocumentMessage::UpdateClipTargets { clip_targets } => {
self.network_interface.update_clip_targets(clip_targets);
}
@@ -46,6 +46,8 @@ pub struct DocumentMetadata {
pub text_frames: HashMap<LayerNodeIdentifier, DAffine2>,
pub clip_targets: HashSet<NodeId>,
pub vector_modify: HashMap<NodeId, VectorGeometry>,
/// Per node with a footprint input, the unit square mapped onto its area in document space.
pub footprint_areas: HashMap<NodeId, DAffine2>,
/// Vector data keyed by layer ID, used as fallback when no Path node exists.
/// This provides accurate SegmentIds for layers without explicit Path nodes.
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>,
@@ -138,6 +138,7 @@ impl NodeNetworkInterface {
self.document_metadata.upstream_footprints.retain(|node, _| nodes.contains(node));
self.document_metadata.local_transforms.retain(|node, _| nodes.contains(node));
self.document_metadata.vector_modify.retain(|node, _| nodes.contains(node));
self.document_metadata.footprint_areas.retain(|node, _| nodes.contains(node));
self.document_metadata.click_targets.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
self.document_metadata.outlines.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
self.document_metadata.text_frames.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
@@ -189,6 +190,11 @@ impl NodeNetworkInterface {
self.document_metadata.vector_modify = new_vector_modify;
}
/// Update the cached document space areas of the nodes with a footprint input
pub fn update_footprint_areas(&mut self, new_footprint_areas: HashMap<NodeId, DAffine2>) {
self.document_metadata.footprint_areas = new_footprint_areas;
}
/// Update the layer vector data (for layers without Path nodes)
pub fn update_vector_data(&mut self, new_layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>) {
self.document_metadata.mark_changed();
@@ -0,0 +1,332 @@
use crate::messages::frontend::utility_types::MouseCursorIcon;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::transformation_cage::{BoundingBoxManager, SelectedEdges};
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::context::bake_footprint;
use graphene_std::platform_application_io::rasterize;
use graphene_std::renderer::Quad;
use graphene_std::transform::Footprint;
/// A transform cage that resizes and moves the area of the selected node with a footprint input.
#[derive(Clone, Debug, Default)]
pub struct FootprintCage {
target: Option<CageTarget>,
drag: Option<CageDrag>,
}
#[derive(Clone, Debug)]
struct CageTarget {
footprint_input: InputConnector,
area: Footprint,
/// Spans the area, with the unit square as its bounds.
bounding_box: BoundingBoxManager,
}
#[derive(Clone, Debug)]
struct CageDrag {
footprint_input: InputConnector,
original_area: Footprint,
unit_square_to_viewport: DAffine2,
kind: CageDragKind,
}
#[derive(Clone, Debug)]
enum CageDragKind {
Resize(SelectedEdges),
Move { grab: DVec2 },
}
impl FootprintCage {
/// Places the cage on the area of the selected node with a footprint input, or removes it if it is hidden or there is none.
pub fn refresh(&mut self, document: &DocumentMessageHandler, visible: bool) {
self.target = visible.then(|| Self::find_target(document)).flatten();
}
fn find_target(document: &DocumentMessageHandler) -> Option<CageTarget> {
let network_path = document.selection_network_path();
let network_interface = &document.network_interface;
let selected_nodes = network_interface.selected_nodes_in_nested_network(network_path)?;
let mut footprint_inputs = selected_nodes.selected_nodes().filter_map(|&node_id| footprint_input(node_id, network_interface, network_path));
let footprint_input = footprint_inputs.next()?;
if footprint_inputs.next().is_some() {
return None;
}
let node_id = footprint_input.node_id()?;
let input = network_interface.input_from_connector(&footprint_input, network_path)?;
let &TaggedValue::Footprint(area) = input.as_non_exposed_value()? else { return None };
let unit_square_to_document = *document.metadata().footprint_areas.get(&node_id)?;
let unit_square_to_viewport = document.metadata().document_to_viewport * unit_square_to_document;
if unit_square_to_viewport.matrix2.determinant() == 0. {
return None;
}
let bounding_box = BoundingBoxManager {
bounds: [DVec2::ZERO, DVec2::ONE],
transform: unit_square_to_viewport,
..Default::default()
};
Some(CageTarget { footprint_input, area, bounding_box })
}
pub fn overlays(&mut self, overlay_context: &mut OverlayContext) {
if let Some(target) = &mut self.target {
target.bounding_box.render_overlays(overlay_context, true);
}
}
/// The cursor for the part of the cage under the pointer, if any.
pub fn cursor(&self, input: &InputPreprocessorMessageHandler) -> Option<MouseCursorIcon> {
let target = self.target.as_ref()?;
let edge_cursor = target.bounding_box.get_cursor(input, false, false, None);
if edge_cursor != MouseCursorIcon::Default {
return Some(edge_cursor);
}
target.contains(input.mouse.position).then_some(MouseCursorIcon::Move)
}
/// Begins resizing or moving the area if the pointer is on the cage, returning whether it did.
pub fn begin_drag(&mut self, mouse: DVec2, responses: &mut VecDeque<Message>) -> bool {
let Some(target) = &self.target else { return false };
let bounding_box = &target.bounding_box;
let kind = if let Some((top, bottom, left, right)) = bounding_box.check_selected_edges(mouse) {
CageDragKind::Resize(SelectedEdges::new(top, bottom, left, right, bounding_box.bounds))
} else if target.contains(mouse) {
CageDragKind::Move {
grab: bounding_box.transform.inverse().transform_point2(mouse),
}
} else {
return false;
};
self.drag = Some(CageDrag {
footprint_input: target.footprint_input,
original_area: target.area,
unit_square_to_viewport: bounding_box.transform,
kind,
});
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Changed a Footprint".into() });
true
}
/// Moves or resizes the area to follow the pointer, keeping its pixel density.
pub fn update_drag(&mut self, mouse: DVec2, centered: bool, constrain: bool, responses: &mut VecDeque<Message>) {
let Some(drag) = &self.drag else { return };
let (position, size) = match &drag.kind {
CageDragKind::Resize(edges) => {
let center = drag.unit_square_to_viewport.transform_point2(DVec2::splat(0.5));
let (position, size) = edges.new_size(mouse, drag.unit_square_to_viewport, centered.then_some(center), constrain, None);
(position.min(position + size), size.abs())
}
CageDragKind::Move { grab } => {
let pointer = drag.unit_square_to_viewport.inverse().transform_point2(mouse);
(pointer - *grab, DVec2::ONE)
}
};
let original_area = drag.original_area;
let one_pixel = original_area.resolution.as_dvec2().recip();
let size = size.max(one_pixel);
let area = Footprint {
transform: original_area.transform * DAffine2::from_scale_angle_translation(size, 0., position),
resolution: (original_area.resolution.as_dvec2() * size).round().as_uvec2().max(UVec2::ONE),
..original_area
};
responses.add(NodeGraphMessage::SetInput {
input_connector: drag.footprint_input,
input: NodeInput::value(TaggedValue::Footprint(area), false),
});
responses.add(NodeGraphMessage::RunDocumentGraph);
}
/// Keeps the drag in place on the document while the viewport pans by `shift`.
pub fn pan(&mut self, shift: DVec2) {
if let Some(drag) = &mut self.drag {
drag.unit_square_to_viewport.translation += shift;
}
}
/// Finishes the drag, undoing its changes if it was aborted.
pub fn end_drag(&mut self, aborted: bool, responses: &mut VecDeque<Message>) {
if self.drag.take().is_none() {
return;
}
responses.add(if aborted { DocumentMessage::AbortTransaction } else { DocumentMessage::EndTransaction });
}
}
/// The input holding the footprint of a node that has one.
fn footprint_input(node_id: NodeId, network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> Option<InputConnector> {
let reference = network_interface.reference(&node_id, network_path)?;
if reference == DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER) {
Some(InputConnector::node(node_id, bake_footprint::FootprintInput))
} else if reference == DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER) {
Some(InputConnector::node(node_id, rasterize::FootprintInput))
} else {
None
}
}
impl CageTarget {
fn contains(&self, viewport_point: DVec2) -> bool {
(self.bounding_box.transform * Quad::from_box(self.bounding_box.bounds)).contains(viewport_point)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::test_prelude::*;
#[tokio::test]
async fn a_bake_footprint_node_in_a_layer_reports_where_its_area_lies() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 10., 10.).await;
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
let node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
let document = editor.active_document();
let input = document.network_interface.input_from_connector(&InputConnector::node(node_id, bake_footprint::FootprintInput), &[]);
let Some(&TaggedValue::Footprint(area)) = input.and_then(NodeInput::as_non_exposed_value) else {
panic!("the node should have a footprint value")
};
let metadata = document.metadata();
let baked_area = metadata.footprint_areas.get(&node_id).expect("the render should report where the node baked its area");
let layer_content_to_viewport = metadata.upstream_footprints.get(&layer.to_node()).expect("the render should report the layer's footprint").transform;
let expected = metadata.rendered_document_to_viewport.inverse() * layer_content_to_viewport * area.transform;
assert!(baked_area.abs_diff_eq(expected, 1e-9), "{baked_area:?} should be {expected:?}");
}
#[tokio::test]
async fn a_baked_area_moves_with_a_transform_applied_after_it() {
use graphene_std::transform_nodes::transform;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 10., 10.).await;
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
let bake_footprint_node = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
editor
.handle_message(NodeGraphMessage::MoveNodeToChainStart {
node_id: bake_footprint_node,
parent: layer,
})
.await;
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
let untransformed = *editor.active_document().metadata().footprint_areas.get(&bake_footprint_node).expect("the area should be reported");
let transform_node = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(transform::IDENTIFIER)).await;
editor
.handle_message(NodeGraphMessage::MoveNodeToChainStart {
node_id: transform_node,
parent: layer,
})
.await;
let translation = DVec2::new(100., 50.);
editor
.handle_message(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(transform_node, transform::TranslationInput),
input: NodeInput::value(TaggedValue::DVec2(translation), false),
})
.await;
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
let transformed = *editor
.active_document()
.metadata()
.footprint_areas
.get(&bake_footprint_node)
.expect("the area should still be reported");
let expected = DAffine2::from_translation(translation) * untransformed;
assert!(transformed.abs_diff_eq(expected, 1e-9), "{transformed:?} should be {expected:?}");
}
/// Drags the cage of a 'Bake Footprint' node in a layer between two points of its unit square, giving its area before and after.
async fn drag_cage(from: DVec2, to: DVec2) -> (Footprint, Footprint) {
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::tool::utility_types::ToolType;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 10., 10.).await;
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
let node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
let area = Footprint {
transform: DAffine2::from_scale(DVec2::splat(100.)),
resolution: UVec2::splat(200),
..Default::default()
};
let footprint_input = InputConnector::node(node_id, bake_footprint::FootprintInput);
editor
.handle_message(NodeGraphMessage::SetInput {
input_connector: footprint_input,
input: NodeInput::value(TaggedValue::Footprint(area), false),
})
.await;
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }).await;
let metadata = editor.active_document().metadata();
let unit_square_to_viewport = metadata.document_to_viewport * *metadata.footprint_areas.get(&node_id).expect("the area should be reported");
let (from, to) = (unit_square_to_viewport.transform_point2(from), unit_square_to_viewport.transform_point2(to));
editor.select_tool(ToolType::Select).await;
editor.handle_message(SelectToolMessage::Overlays { context: OverlayContext::default() }).await;
editor.move_mouse(from.x, from.y, ModifierKeys::empty(), MouseKeys::empty()).await;
editor.left_mousedown(from.x, from.y, ModifierKeys::empty()).await;
editor.move_mouse(to.x, to.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
editor.left_mouseup(to.x, to.y, ModifierKeys::empty()).await;
let input = editor.active_document().network_interface.input_from_connector(&footprint_input, &[]);
let Some(&TaggedValue::Footprint(dragged)) = input.and_then(NodeInput::as_non_exposed_value) else {
panic!("the node should have a footprint value")
};
(area, dragged)
}
#[tokio::test]
async fn dragging_the_right_edge_of_the_cage_widens_the_area_and_its_resolution() {
let (area, dragged) = drag_cage(DVec2::new(1., 0.5), DVec2::new(1.5, 0.5)).await;
let expected_transform = area.transform * DAffine2::from_scale(DVec2::new(1.5, 1.));
assert!(dragged.transform.abs_diff_eq(expected_transform, 1e-9), "{:?} should be {expected_transform:?}", dragged.transform);
assert_eq!(dragged.resolution, UVec2::new(300, 200));
}
#[tokio::test]
async fn dragging_the_right_edge_onto_the_left_one_keeps_one_pixel_of_width() {
let (area, dragged) = drag_cage(DVec2::new(1., 0.5), DVec2::new(0., 0.5)).await;
let one_pixel = 1. / area.resolution.x as f64;
let expected_transform = area.transform * DAffine2::from_scale(DVec2::new(one_pixel, 1.));
assert!(dragged.transform.abs_diff_eq(expected_transform, 1e-9), "{:?} should be {expected_transform:?}", dragged.transform);
assert_eq!(dragged.resolution, UVec2::new(1, 200));
}
}
@@ -1,2 +1,3 @@
pub mod footprint_cage;
pub mod gizmo_manager;
pub mod shape_gizmos;
@@ -15,6 +15,7 @@ use crate::messages::tool::common_functionality::color_selector::{
DrawingToolState, apply_fill_color_pick, apply_fill_enabled, apply_stroke_color_pick, apply_stroke_enabled, apply_working_colors, has_paintable_selection, swap_fill_and_stroke, sync_drawing_state,
};
use crate::messages::tool::common_functionality::compass_rose::{Axis, CompassRose};
use crate::messages::tool::common_functionality::gizmos::footprint_cage::FootprintCage;
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::common_functionality::measure;
use crate::messages::tool::common_functionality::pivot::{Pivot, PivotGizmo, PivotGizmoType, PivotToolSource, pin_pivot_widget, pivot_gizmo_type_widget, pivot_reference_point_widget};
@@ -505,6 +506,7 @@ enum SelectToolFsmState {
},
RotatingBounds,
DraggingPivot,
DraggingFootprintCage,
}
impl Default for SelectToolFsmState {
@@ -545,6 +547,7 @@ struct SelectToolData {
axis_align: bool,
non_duplicated_layers: Option<Vec<LayerNodeIdentifier>>,
bounding_box_manager: Option<BoundingBoxManager>,
footprint_cage: FootprintCage,
cursor: MouseCursorIcon,
pivot_gizmo: PivotGizmo,
/// The pivot as it was when a drag of it began, restored if the drag is aborted.
@@ -954,6 +957,9 @@ impl Fsm for SelectToolFsmState {
(_, SelectToolMessage::Overlays { context: mut overlay_context }) => {
crate::messages::tool::common_functionality::layer_origin_cross::draw_for_selected_layers(&mut overlay_context, document);
tool_data.footprint_cage.refresh(document, overlay_context.visibility_settings.transform_cage());
tool_data.footprint_cage.overlays(&mut overlay_context);
let selected_layers_count = document.network_interface.selected_nodes().selected_unlocked_layers(&document.network_interface).count();
let paintable_layers_selected = has_paintable_selection(document);
tool_data.selected_layers_changed = selected_layers_count != tool_data.selected_layers_count || paintable_layers_selected != tool_data.paintable_layers_selected;
@@ -1388,6 +1394,10 @@ impl Fsm for SelectToolFsmState {
tool_data.drag_current = input.mouse.position;
tool_data.selection_mode = None;
if tool_data.state_from_pivot_gizmo(input.mouse.position).is_none() && tool_data.footprint_cage.begin_drag(input.mouse.position, responses) {
return SelectToolFsmState::DraggingFootprintCage;
}
let mut selected: Vec<_> = document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface).collect();
let intersection_list = document.click_list(input, viewport).collect::<Vec<_>>();
let intersection = document.find_deepest(&intersection_list);
@@ -1620,6 +1630,18 @@ impl Fsm for SelectToolFsmState {
remove,
}
}
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::PointerMove { modifier_keys }) => {
let (centered, constrain) = (input.keyboard.key(modifier_keys.center), input.keyboard.key(modifier_keys.axis_align));
tool_data.footprint_cage.update_drag(input.mouse.position, centered, constrain, responses);
let messages = [
SelectToolMessage::PointerOutsideViewport { modifier_keys: modifier_keys.clone() }.into(),
SelectToolMessage::PointerMove { modifier_keys }.into(),
];
tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses);
SelectToolFsmState::DraggingFootprintCage
}
(SelectToolFsmState::ResizingBounds, SelectToolMessage::PointerMove { modifier_keys }) => {
if let Some(bounds) = &mut tool_data.bounding_box_manager {
resize_bounds(
@@ -1721,6 +1743,10 @@ impl Fsm for SelectToolFsmState {
.as_ref()
.map_or(MouseCursorIcon::Default, |bounds| bounds.get_cursor(input, true, dragging_bounds, Some(tool_data.skew_edge)));
if let Some(footprint_cage_cursor) = tool_data.footprint_cage.cursor(input) {
cursor = footprint_cage_cursor;
}
// Dragging the pivot overrules the other operations
if tool_data.state_from_pivot_gizmo(input.mouse.position).is_some() {
cursor = MouseCursorIcon::Move;
@@ -1772,6 +1798,14 @@ impl Fsm for SelectToolFsmState {
self
}
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::PointerOutsideViewport { .. }) => {
// Auto-panning
if let Some(shift) = tool_data.auto_panning.shift_viewport(input, viewport, responses) {
tool_data.footprint_cage.pan(shift);
}
self
}
(SelectToolFsmState::DraggingPivot, SelectToolMessage::PointerOutsideViewport { .. }) => {
// Auto-panning
let _ = tool_data.auto_panning.shift_viewport(input, viewport, responses);
@@ -1917,6 +1951,14 @@ impl Fsm for SelectToolFsmState {
let selection = tool_data.nested_selection_behavior;
SelectToolFsmState::Ready { selection }
}
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::DragStop { .. } | SelectToolMessage::Enter) => {
let drag_too_small = input.mouse.position.distance(tool_data.drag_start) < 10. * f64::EPSILON;
tool_data.footprint_cage.end_drag(drag_too_small, responses);
responses.add(OverlaysMessage::Draw);
let selection = tool_data.nested_selection_behavior;
SelectToolFsmState::Ready { selection }
}
(SelectToolFsmState::Drawing { selection_shape, .. }, SelectToolMessage::DragStop { remove_from_selection }) => {
let quad = tool_data.selection_quad();
@@ -2006,6 +2048,13 @@ impl Fsm for SelectToolFsmState {
let selection = tool_data.nested_selection_behavior;
SelectToolFsmState::Ready { selection }
}
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::Abort) => {
tool_data.footprint_cage.end_drag(true, responses);
responses.add(OverlaysMessage::Draw);
let selection = tool_data.nested_selection_behavior;
SelectToolFsmState::Ready { selection }
}
(SelectToolFsmState::Dragging { .. }, SelectToolMessage::Abort) => {
responses.add(DocumentMessage::AbortTransaction);
tool_data.axis_align = false;
@@ -2175,6 +2224,13 @@ impl Fsm for SelectToolFsmState {
]);
hint_data.send_layout(responses);
}
SelectToolFsmState::DraggingFootprintCage => {
let hint_data = HintData(vec![
HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]),
HintGroup(vec![HintInfo::keys([Key::Alt], "From Center"), HintInfo::keys([Key::Shift], "Preserve Aspect Ratio")]),
]);
hint_data.send_layout(responses);
}
SelectToolFsmState::RotatingBounds => {
let hint_data = HintData(vec![
HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]),
+13 -47
View File
@@ -1,5 +1,4 @@
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus};
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError;
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
@@ -11,20 +10,23 @@ use graph_craft::proto::{GraphErrorType, GraphErrors};
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::color::SRGBA8;
use graphene_std::list::{Item, List};
use graphene_std::list::List;
use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint;
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter};
use graphene_std::vector::{Vector, graphic_types, no_paths, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use std::any::Any;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender};
mod observations;
#[cfg(test)]
mod recompile_tests;
mod runtime;
pub use observations::ObservationKey;
use observations::{path_content_observations, path_contents};
pub use runtime::*;
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
@@ -43,18 +45,6 @@ pub struct ExecutionResponse {
observations: HashMap<ObservationKey, InspectResult>,
}
/// Names an observation so it can be changed or stopped without touching the others.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ObservationKey {
/// The node the Data panel inspects.
DataPanel,
/// The content of a 'Path' node, which is the geometry the Pen and Path tools edit.
PathContent(NodeId),
// TODO: Eventually remove this document upgrade code
/// The "Fill" node whose geometry a gradient migration measures.
FillMeasurement,
}
#[derive(Debug)]
pub enum ExecutionResult {
Pending,
@@ -642,6 +632,7 @@ impl NodeGraphExecutor {
document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
document.network_interface.update_outlines(HashMap::new());
document.network_interface.update_vector_modify(HashMap::new());
document.network_interface.update_footprint_areas(HashMap::new());
if let Some(message) = &message {
log::error!("Node graph evaluation failed:\n{message}");
}
@@ -718,6 +709,7 @@ impl NodeGraphExecutor {
document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
document.network_interface.update_outlines(HashMap::new());
document.network_interface.update_vector_modify(HashMap::new());
document.network_interface.update_footprint_areas(HashMap::new());
// The graph only shows errors tied to nodes, so the console gets the others
if node_graph_errors.is_empty() {
@@ -1065,6 +1057,7 @@ impl NodeGraphExecutor {
outlines,
group_layers,
text_frames,
footprint_areas,
clip_targets,
vector_data,
appearance_attributes,
@@ -1072,6 +1065,9 @@ impl NodeGraphExecutor {
backgrounds: _,
} = render_output.metadata;
let viewport_to_document = document_to_viewport.inverse();
let footprint_areas = footprint_areas.into_iter().map(|(node_id, area)| (node_id, viewport_to_document * area)).collect();
// Run these update state messages immediately
responses.add(DocumentMessage::UpdateUpstreamTransforms {
upstream_footprints,
@@ -1082,6 +1078,7 @@ impl NodeGraphExecutor {
responses.add(DocumentMessage::UpdateClickTargets { click_targets, group_layers });
responses.add(DocumentMessage::UpdateOutlines { outlines });
responses.add(DocumentMessage::UpdateTextFrames { text_frames });
responses.add(DocumentMessage::UpdateFootprintAreas { footprint_areas });
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
responses.add(DocumentMessage::UpdateVectorData { vector_data });
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
@@ -1230,37 +1227,6 @@ fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
}
}
fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
path_nodes.into_iter().filter_map(|node_path| {
let key = ObservationKey::PathContent(*node_path.last()?);
let observation = Observation {
node_path,
connector: ObservedConnector::Input(path::ContentInput::INDEX),
overrides: ContextOverrides::default(),
};
Some((key, observation))
})
}
/// The incoming geometry of each 'Path' node, read from its observed content.
fn path_contents(observations: &HashMap<ObservationKey, InspectResult>) -> HashMap<NodeId, VectorGeometry> {
observations
.iter()
.filter_map(|(key, result)| {
let ObservationKey::PathContent(path_node) = *key else { return None };
let value = result.data.as_ref()?;
let geometry = match value.downcast_ref::<List<Vector>>() {
Some(list) => VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()),
None => VectorGeometry::from_item(value.downcast_ref::<Item<Vector>>()?),
};
Some((path_node, geometry))
})
.collect()
}
// Re-export for usage by tests in other modules
#[cfg(test)]
pub use test::Instrumented;
@@ -0,0 +1,51 @@
use super::{InspectResult, Observation, ObservedConnector};
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use graph_craft::document::NodeId;
use graphene_std::list::{Item, List};
use graphene_std::vector::{Vector, VectorGeometry, path, paths_from_list_row_attributes};
use graphene_std::{ContextOverrides, NodeParameter};
use std::collections::HashMap;
/// Names an observation so it can be changed or stopped without touching the others.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ObservationKey {
/// The node the Data panel inspects.
DataPanel,
/// The content of a 'Path' node, which is the geometry the Pen and Path tools edit.
PathContent(NodeId),
// TODO: Eventually remove this document upgrade code
/// The "Fill" node whose geometry a gradient migration measures.
FillMeasurement,
}
pub(super) fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
path_nodes.into_iter().filter_map(|node_path| {
let key = ObservationKey::PathContent(*node_path.last()?);
let observation = Observation {
node_path,
connector: ObservedConnector::Input(path::ContentInput::INDEX),
overrides: ContextOverrides::default(),
};
Some((key, observation))
})
}
/// The incoming geometry of each 'Path' node, read from its observed content.
pub(super) fn path_contents(observations: &HashMap<ObservationKey, InspectResult>) -> HashMap<NodeId, VectorGeometry> {
observations
.iter()
.filter_map(|(key, result)| {
let ObservationKey::PathContent(path_node) = *key else { return None };
let value = result.data.as_ref()?;
let geometry = match value.downcast_ref::<List<Vector>>() {
Some(list) => VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()),
None => VectorGeometry::from_item(value.downcast_ref::<Item<Vector>>()?),
};
Some((path_node, geometry))
})
.collect()
}
+4 -4
View File
@@ -32,10 +32,10 @@ pub use glam_ext::FallibleVec2Operations;
pub use graphene_hash;
pub use graphene_hash::CacheHash;
pub use list::{
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD,
ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
ATTR_TYPE,
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_FOOTPRINT_AREAS, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS,
ATTR_EDITOR_TEXT_FRAME, ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE,
ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START,
ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
};
pub use memo::MemoHash;
pub use num_traits;
@@ -40,6 +40,9 @@ pub const ATTR_EDITOR_CLICK_TARGET: &str = "editor:click_target";
/// glyph origin so it survives `Index Elements` filtering. The Text tool reads this to position
/// its drag cage. Stored as an affine to allow non-axis-aligned frames in the future.
pub const ATTR_EDITOR_TEXT_FRAME: &str = "editor:text_frame";
/// `List<NodeIdPath>` of the nodes with a footprint input this item passed through.
/// Each row's transform maps the unit square onto that node's area in this item's local space.
pub const ATTR_EDITOR_FOOTPRINT_AREAS: &str = "editor:footprint_areas";
/// `u64` byte offset where a regex match begins ('Regex Find All', 'Regex Capture' text nodes).
pub const ATTR_START: &str = "start";
/// `u64` byte offset where a regex match ends ('Regex Find All', 'Regex Capture' text nodes).
+135 -25
View File
@@ -113,7 +113,36 @@ impl RuntimeInner {
}
}
pub struct Slots<T>(Arc<Mutex<HashMap<u64, Slot<T>>>>);
pub struct Slots<T>(Arc<Mutex<SlotTable<T>>>);
struct SlotTable<T> {
slots: HashMap<u64, Slot<T>>,
/// The number of started evaluations, which orders them.
started: u64,
/// The value of the latest started evaluation that has landed, with its order.
latest: Option<(u64, T)>,
}
impl<T: Clone> SlotTable<T> {
fn start(&mut self) -> u64 {
self.started += 1;
self.started
}
fn land(&mut self, key: u64, order: u64, state: Poll<T>) {
let superseded = self.latest.as_ref().is_some_and(|(latest_order, _)| *latest_order > order);
if !superseded && let Some(value) = state.clone().value() {
self.latest = Some((order, value));
}
self.slots.insert(key, Slot::Ready(state));
}
/// The value a pending evaluation returns, preferring the latest landed value if `keep_previous` is set.
fn stand_in(&self, placeholder: Option<T>, keep_previous: bool) -> Poll<T> {
let previous = if keep_previous { self.latest.as_ref().map(|(_, value)| value.clone()) } else { None };
previous.or(placeholder).map_or(Poll::Pending, Poll::Partial)
}
}
enum Slot<T> {
Ready(Poll<T>),
@@ -130,7 +159,11 @@ impl<T> Drop for Slot<T> {
impl<T> Default for Slots<T> {
fn default() -> Self {
Self(Arc::default())
Self(Arc::new(Mutex::new(SlotTable {
slots: HashMap::new(),
started: 0,
latest: None,
})))
}
}
@@ -147,42 +180,46 @@ impl<T> std::fmt::Debug for Slots<T> {
}
impl<T: Clone + WasmNotSend + 'static> Slots<T> {
pub fn resolve<F>(&self, key: u64, runtime: &dyn Runtime, source: SourceId, placeholder: Option<T>, future: impl FnOnce() -> F) -> Poll<T>
/// The landed state for `key`, or else starts its evaluation and returns its stand-in.
pub fn resolve<F>(&self, key: u64, runtime: &dyn Runtime, source: SourceId, placeholder: Option<T>, keep_previous: bool, future: impl FnOnce() -> F) -> Poll<T>
where
F: Future<Output = Poll<T>> + WasmNotSend + 'static,
{
match self.0.lock().unwrap_or_else(PoisonError::into_inner).get(&key) {
Some(Slot::Ready(landed)) => return landed.clone(),
Some(Slot::Pending(_)) => return placeholder.map_or(Poll::Pending, Poll::Partial),
None => {}
}
let order = {
let mut table = self.0.lock().unwrap_or_else(PoisonError::into_inner);
match table.slots.get(&key) {
Some(Slot::Ready(landed)) => return landed.clone(),
Some(Slot::Pending(_)) => return table.stand_in(placeholder, keep_previous),
None => table.start(),
}
};
// Fast path for futures that are ready immediately
// TODO(Timon): check if this would ever cause a problem; running a future on the graph executor thread might also be a bit wierd
let mut future = Box::pin(future());
if let std::task::Poll::Ready(state) = future.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
self.0.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state.clone()));
self.0.lock().unwrap_or_else(PoisonError::into_inner).land(key, order, state.clone());
return state;
}
let (handle, registration) = AbortHandle::new_pair();
let slots = Arc::downgrade(&self.0);
let table = Arc::downgrade(&self.0);
runtime.spawn(
source,
Box::pin(async move {
if let Ok(state) = Abortable::new(future, registration).await
&& let Some(slots) = slots.upgrade()
&& let Some(table) = table.upgrade()
{
slots.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state));
table.lock().unwrap_or_else(PoisonError::into_inner).land(key, order, state);
}
}),
);
let mut slots = self.0.lock().unwrap_or_else(PoisonError::into_inner);
match slots.get(&key) {
let mut table = self.0.lock().unwrap_or_else(PoisonError::into_inner);
match table.slots.get(&key) {
Some(Slot::Ready(landed)) => landed.clone(),
_ => {
slots.insert(key, Slot::Pending(handle));
placeholder.map_or(Poll::Pending, Poll::Partial)
table.slots.insert(key, Slot::Pending(handle));
table.stand_in(placeholder, keep_previous)
}
}
}
@@ -215,6 +252,13 @@ mod tests {
}
count
}
fn drain_newest_first(&self) {
let tasks = std::mem::take(&mut *self.0.lock().unwrap());
for mut task in tasks.into_iter().rev() {
while !poll_once(&mut task) {}
}
}
}
struct BlockingSpawner;
@@ -276,7 +320,7 @@ mod tests {
runtime.update_sources(&[SOURCE]);
let slots = Slots::default();
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, || async { Poll::Final(1u32) }), Poll::Final(1));
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, || async { Poll::Final(1u32) }), Poll::Final(1));
assert_eq!(spawner.drain(), 0);
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]);
@@ -297,11 +341,77 @@ mod tests {
Poll::Final(42u32)
};
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Partial(0));
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending);
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Partial(0));
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
assert_eq!(spawner.drain(), 1, "an in-flight slot is not spawned twice");
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Final(42));
assert_eq!(slots.resolve(2, &runtime, SOURCE, None, || async { Poll::Final(1u32) }), Poll::Final(1));
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Final(42));
assert_eq!(slots.resolve(2, &runtime, SOURCE, None, false, || async { Poll::Final(1u32) }), Poll::Final(1));
}
#[test]
fn a_slot_keeping_the_previous_value_serves_it_until_the_next_response_lands() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
runtime.update_sources(&[SOURCE]);
let slots = Slots::default();
let fetch = |value: u32| {
move || async move {
YieldOnce(false).await;
Poll::Final(value)
}
};
assert_eq!(
slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1)),
Poll::Partial(0),
"nothing landed yet, so the placeholder stands in"
);
spawner.drain();
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1)), Poll::Final(1));
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2)), Poll::Partial(1), "the previous value stands in");
spawner.drain();
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2)), Poll::Final(2));
}
#[test]
fn an_older_response_landing_late_does_not_replace_the_previous_value() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
runtime.update_sources(&[SOURCE]);
let slots = Slots::default();
let fetch = |value: u32| {
move || async move {
YieldOnce(false).await;
Poll::Final(value)
}
};
slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1));
slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2));
spawner.drain_newest_first();
assert_eq!(slots.resolve(3, &runtime, SOURCE, Some(0), true, fetch(3)), Poll::Partial(2));
}
#[test]
fn a_fallback_response_stands_in_as_the_previous_value() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
runtime.update_sources(&[SOURCE]);
let slots = Slots::default();
slots.resolve(1, &runtime, SOURCE, Some(0), true, || async {
YieldOnce(false).await;
Poll::fallback(1, "failed")
});
spawner.drain();
let fetch = || async {
YieldOnce(false).await;
Poll::Final(2)
};
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch), Poll::Partial(1));
}
#[test]
@@ -314,7 +424,7 @@ mod tests {
Poll::Final(42u32)
};
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Final(42));
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Final(42));
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1)]);
}
@@ -328,11 +438,11 @@ mod tests {
Poll::Final(42u32)
};
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending);
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
let clone = slots.clone();
drop(slots);
assert_eq!(spawner.drain(), 1);
assert_eq!(clone.resolve(1, &runtime, SOURCE, None, fetch), Poll::Final(42));
assert_eq!(clone.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Final(42));
}
#[test]
@@ -350,7 +460,7 @@ mod tests {
}
};
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending);
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
drop(slots);
assert_eq!(spawner.drain(), 1);
assert!(!finished.load(Ordering::Relaxed));
+66 -3
View File
@@ -17,9 +17,9 @@ use core_types::math::quad::Quad;
use core_types::transform::Footprint;
use core_types::uuid::{NodeId, generate_uuid};
use core_types::{
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
ATTR_EFFECTS, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_FORM, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY,
ATTR_OPACITY_FILL, ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_FOOTPRINT_AREAS, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS,
ATTR_EDITOR_TEXT_FRAME, ATTR_EFFECTS, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_FORM, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH,
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
};
use dyn_any::DynAny;
use glam::{DAffine2, DMat2, DVec2};
@@ -149,6 +149,58 @@ impl<'a, T> ItemRef<'a, T> {
fn layer(self) -> Option<NodeId> {
self.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH).and_then(|path| path.0.iter_element_values().next_back().copied())
}
/// Records the viewport placement of each footprint area this item carries. `footprint` belongs to the space the item is placed in.
fn collect_footprint_areas(self, metadata: &mut RenderMetadata, footprint: Footprint) {
let Some(footprint_areas) = self.attribute::<List<NodeIdPath>>(ATTR_EDITOR_FOOTPRINT_AREAS) else {
return;
};
let item_to_viewport = footprint.transform * self.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
for index in 0..footprint_areas.len() {
let Some(node_id) = footprint_areas.element(index).and_then(|node_path| node_path.0.iter_element_values().next_back().copied()) else {
continue;
};
let area: DAffine2 = footprint_areas.attribute_cloned_or_default(ATTR_TRANSFORM, index);
metadata.footprint_areas.entry(node_id).or_insert(item_to_viewport * area);
}
}
}
/// Records the footprint areas of each item in non-graphic content.
fn collect_leaf_footprint_areas(graphic: &Graphic, metadata: &mut RenderMetadata, footprint: Footprint) {
fn item<T>(item: &Item<T>, metadata: &mut RenderMetadata, footprint: Footprint) {
ItemRef::Item(item).collect_footprint_areas(metadata, footprint);
}
fn list<T>(list: &List<T>, metadata: &mut RenderMetadata, footprint: Footprint) {
for index in 0..list.len() {
ItemRef::ListItem(list, index).collect_footprint_areas(metadata, footprint);
}
}
match graphic {
// Graphic items record their areas when their content is visited
Graphic::Graphic(_) | Graphic::GraphicList(_) => {}
Graphic::None(content) => item(content, metadata, footprint),
Graphic::Vector(content) => item(content, metadata, footprint),
Graphic::RasterCPU(content) => item(content, metadata, footprint),
Graphic::RasterGPU(content) => item(content, metadata, footprint),
Graphic::Color(content) => item(content, metadata, footprint),
Graphic::Gradient(content) => item(content, metadata, footprint),
Graphic::Generator(content) => item(content, metadata, footprint),
Graphic::Text(content) => item(content, metadata, footprint),
Graphic::NoneList(content) => list(content, metadata, footprint),
Graphic::VectorList(content) => list(content, metadata, footprint),
Graphic::RasterCPUList(content) => list(content, metadata, footprint),
Graphic::RasterGPUList(content) => list(content, metadata, footprint),
Graphic::ColorList(content) => list(content, metadata, footprint),
Graphic::GradientList(content) => list(content, metadata, footprint),
Graphic::GeneratorList(content) => list(content, metadata, footprint),
Graphic::TextList(content) => list(content, metadata, footprint),
Graphic::StrokeList(content) => list(content, metadata, footprint),
}
}
/// Geometry derived from a vector item, extracted once per geometry when the item carries a geometry cache.
@@ -1570,6 +1622,8 @@ pub struct RenderMetadata {
/// Per-layer text frame from item 0's `editor:text_frame` attribute.
/// The Text tool composes this with `transform_to_viewport(layer)` to position its drag cage.
pub text_frames: HashMap<NodeId, DAffine2>,
/// Per node with a footprint input, the unit square mapped onto its area in viewport space, from the first item carrying it.
pub footprint_areas: HashMap<NodeId, DAffine2>,
pub clip_targets: HashSet<NodeId>,
/// Per-layer source geometry as the holder item, carrying the pool element and its paths attribute.
#[cfg_attr(feature = "serde", serde(skip))]
@@ -1587,6 +1641,9 @@ impl RenderMetadata {
for value in self.upstream_footprints.values_mut() {
value.transform = transform * value.transform;
}
for footprint_area in self.footprint_areas.values_mut() {
*footprint_area = transform * *footprint_area;
}
}
/// Merge another RenderMetadata into this one.
@@ -1601,6 +1658,7 @@ impl RenderMetadata {
outlines,
group_layers,
text_frames,
footprint_areas,
clip_targets,
vector_data,
appearance_attributes,
@@ -1614,6 +1672,7 @@ impl RenderMetadata {
outlines.extend(other.outlines.iter().map(|(k, v)| (*k, v.clone())));
group_layers.extend(other.group_layers.iter());
text_frames.extend(other.text_frames.iter());
footprint_areas.extend(other.footprint_areas.iter());
clip_targets.extend(other.clip_targets.iter());
vector_data.extend(other.vector_data.iter().map(|(id, data)| (*id, data.clone())));
appearance_attributes.extend(other.appearance_attributes.iter().map(|(id, data)| (*id, data.clone())));
@@ -1891,6 +1950,8 @@ fn collect_graphic_item_metadata(item: ItemRef<'_, Graphic>, metadata: &mut Rend
// This item's appearance (if any) cascades to descendants lacking their own
let child_appearance = Appearance::cascade(item.attribute::<Appearance>(ATTR_APPEARANCE), inherited_appearance);
item.collect_footprint_areas(metadata, footprint);
let mut footprint = footprint;
footprint.transform *= item_transform;
@@ -2041,6 +2102,8 @@ impl Render for Graphic {
}
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option<NodeId>, inherited_appearance: Option<&Appearance>) {
collect_leaf_footprint_areas(self, metadata, footprint);
if let Some(element_id) = element_id {
// The footprint always lands; the transform (and for vectors the source layer) comes from the first item when one exists
let first_item_inserts = |metadata: &mut RenderMetadata, transform: DAffine2| {
+2 -1
View File
@@ -601,6 +601,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
Some(path) => quote!(Some(#path(#(&#declared_field_names),*))),
None => quote!(None),
};
let keep_previous = attributes.flags.keep_previous;
let data_clones = data_field_names.iter().map(|name| quote!(let #name = self.#name.clone();));
let landed_call = landed(quote!(self::#fn_name(__context #(, &#data_field_names)* #(, #regular_field_names)*).await));
quote! {
@@ -632,7 +633,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
let __runtime = _runtime.element().clone();
let __context = __input.clone();
#(#data_clones)*
let __state = self.slots.resolve(__key, &__runtime, __source, __placeholder, move || async move { #landed_call });
let __state = self.slots.resolve(__key, &__runtime, __source, __placeholder, #keep_previous, move || async move { #landed_call });
__cell.merge(__state)
}
}
+8 -1
View File
@@ -52,6 +52,8 @@ pub(crate) struct NodeFlags {
pub(crate) skip_impl: bool,
/// Whether the node refuses placeholder data.
pub(crate) no_partial: bool,
/// Whether a pending evaluation returns the latest landed output instead of the placeholder.
pub(crate) keep_previous: bool,
/// Set on the `Destructure` derive's generated extractor nodes, which take the struct rather than an `Item` or `List`. Not parsed from source.
pub(crate) destructure_extractor: bool,
}
@@ -598,13 +600,18 @@ impl Parse for NodeFnAttributes {
// Example usage:
// #[node_macro::node(..., no_partial, ...)]
"no_partial" => set_flag(&mut flags.no_partial, meta, "no_partial")?,
// Makes a pending evaluation return the latest landed output instead of the placeholder
//
// Example usage:
// #[node_macro::node(..., keep_previous, ...)]
"keep_previous" => set_flag(&mut flags.keep_previous, meta, "keep_previous")?,
_ => {
return Err(Error::new_spanned(
meta,
indoc!(
r#"
Unsupported attribute in `node`.
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', 'no_partial', and 'version'.
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', 'no_partial', 'keep_previous', and 'version'.
Example usage:
#[node_macro::node(..., name("Test Node"), ...)]
"#
+3
View File
@@ -459,6 +459,9 @@ fn validate_async(parsed: &ParsedNodeFn) {
if parsed.attributes.placeholder.is_some() && !parsed.is_async {
emit_error!(parsed.fn_name.span(), "Only an async node can have a `placeholder`");
}
if parsed.attributes.flags.keep_previous && !parsed.is_async {
emit_error!(parsed.fn_name.span(), "Only an async node can have `keep_previous`");
}
}
/// The arguments that aren't parameters, which are `#[data]` state and the inputs the compiler fills in, go after the parameters.
+96 -5
View File
@@ -1,10 +1,11 @@
use core_types::list::Item;
use core_types::{Color, ExtractVarArgs};
use core_types::list::{Item, List, NodeIdPath};
use core_types::transform::Footprint;
use core_types::{ATTR_EDITOR_FOOTPRINT_AREAS, ATTR_TRANSFORM, CloneVarArgs, Color, Context, ExtractAll, ExtractVarArgs, InjectFootprint, Interrupt, OwnedContextImpl};
use core_types::{Ctx, ExtractIndex, ExtractPosition};
use glam::DVec2;
use glam::{DAffine2, DVec2};
use graphic_types::vector_types::Gradient;
use graphic_types::{Graphic, Vector};
use raster_types::{CPU, Raster};
use graphic_types::{Artboard, Generator, Graphic, Vector};
use raster_types::{CPU, GPU, Raster};
#[derive(Debug, thiserror::Error)]
pub enum ReadContextError {
@@ -96,6 +97,96 @@ fn read_index(
Ok(Item::new_from_element(at_loop_level(indices, *loop_level.element())? as f64))
}
/// Evaluates the content with a fixed footprint in place of the one requested by the renderer, so the result no longer depends on the view.
#[node_macro::node(category("Data: Context"))]
fn bake_footprint<T>(
ctx: impl Ctx + ExtractAll + CloneVarArgs + InjectFootprint,
#[implementations(
Context -> Item<bool>,
Context -> Item<i64>,
Context -> Item<f64>,
Context -> Item<String>,
Context -> Item<DAffine2>,
Context -> Item<Footprint>,
Context -> Item<DVec2>,
Context -> Item<Vector>,
Context -> Item<Graphic>,
Context -> Item<Raster<CPU>>,
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<Generator>,
Context -> Item<Artboard>,
Context -> List<String>,
Context -> List<f64>,
Context -> List<DVec2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Generator>,
Context -> List<Artboard>,
)]
value: impl Node<Context<'static>, Output = T>,
/// The area of the document and the resolution the content is evaluated at.
#[default(0., 0., 1000., 1000.)]
footprint: Item<Footprint>,
#[node_path] node_path: Item<NodeIdPath>,
) -> Result<T, Interrupt>
where
T: RecordFootprintArea,
{
let area = footprint.into_element();
let unit_square_to_pixels = DAffine2::from_scale(area.resolution.as_dvec2());
let footprint = Footprint {
transform: unit_square_to_pixels * area.transform.inverse(),
..area
};
let new_context = OwnedContextImpl::from(ctx).with_footprint(footprint);
let mut content = value.eval(Some(new_context.into()))?;
content.record_footprint_area(node_path.element(), area.transform);
Ok(content)
}
/// Content whose items can record the footprint areas they were evaluated in.
pub trait RecordFootprintArea {
/// Appends the area of the node at `node_path` to each item. `area` maps the unit square into the space the items are placed in.
fn record_footprint_area(&mut self, node_path: &NodeIdPath, area: DAffine2);
}
impl<T> RecordFootprintArea for Item<T> {
fn record_footprint_area(&mut self, node_path: &NodeIdPath, area: DAffine2) {
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM);
let Some(footprint_area) = footprint_area_row(node_path, item_transform, area) else { return };
self.attribute_mut_or_insert_default::<List<NodeIdPath>>(ATTR_EDITOR_FOOTPRINT_AREAS).push(footprint_area);
}
}
impl<T> RecordFootprintArea for List<T> {
fn record_footprint_area(&mut self, node_path: &NodeIdPath, area: DAffine2) {
for index in 0..self.len() {
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
let Some(footprint_area) = footprint_area_row(node_path, item_transform, area) else { continue };
self.with_attribute_mut_or_default::<List<NodeIdPath>, _, _>(ATTR_EDITOR_FOOTPRINT_AREAS, index, |footprint_areas| footprint_areas.push(footprint_area));
}
}
}
/// The row recording the area relative to the item, so it follows the transforms later applied to the item.
fn footprint_area_row(node_path: &NodeIdPath, item_transform: DAffine2, area: DAffine2) -> Option<Item<NodeIdPath>> {
if item_transform.matrix2.determinant() == 0. {
return None;
}
Some(Item::new_from_element(node_path.clone()).with_attribute(ATTR_TRANSFORM, item_transform.inverse() * area))
}
/// The value of the loop `level` loops out from the innermost one, given the loops' values from the innermost outwards.
fn at_loop_level<T>(levels: impl Iterator<Item = T>, level: i64) -> Result<T, ReadContextError> {
let levels: Vec<T> = levels.collect();
@@ -1,6 +1,6 @@
use core_types::Ctx;
use core_types::color::SRGBA8;
use core_types::list::{Item, List};
use core_types::list::{Item, List, NodeIdPath};
use core_types::math::bbox::Bbox;
use core_types::ops::ConvertAsync;
use core_types::transform::Footprint;
@@ -11,6 +11,7 @@ pub use graph_craft::application_io::*;
pub use graph_craft::document::value::RenderOutputType;
#[cfg(target_family = "wasm")]
pub use graphene_canvas_utils as canvas_utils;
use graphene_core::context::RecordFootprintArea;
use graphic_types::Graphic;
use graphic_types::raster_types::{CPU, Raster};
use graphic_types::raster_types::{Image, ImageError};
@@ -219,7 +220,7 @@ fn bytes_to_image(_: impl Ctx, data: Item<Resource>) -> Result<Item<Raster<CPU>>
}
/// 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)]
#[node_macro::node(category("Raster"), icon("NodeRasterize"), placeholder = pending_raster, keep_previous, version(2))]
async fn rasterize(
_: impl Ctx,
/// The graphics to render as an image.
@@ -228,8 +229,13 @@ async fn rasterize(
#[default(0., 0., 1000., 1000.)]
footprint: Item<Footprint>,
#[scope(wgpu_executor::IDENTIFIER)] executor: Item<::wgpu_executor::WgpuExecutor>,
#[node_path] node_path: Item<NodeIdPath>,
) -> Result<List<Raster<CPU>>, NodeError> {
rasterize_with_vello(data, footprint.into_element(), executor.into_element()).await
let footprint = footprint.into_element();
let mut raster = rasterize_with_vello(data, footprint, executor.into_element()).await?;
raster.record_footprint_area(node_path.element(), footprint.transform);
Ok(raster)
}
async fn rasterize_with_vello(data: List<Graphic>, footprint: Footprint, executor: ::wgpu_executor::WgpuExecutor) -> Result<List<Raster<CPU>>, NodeError> {
@@ -259,7 +265,7 @@ async fn rasterize_with_vello(data: List<Graphic>, footprint: Footprint, executo
))
}
fn pending_raster(_data: &List<Graphic>, _footprint: &Item<Footprint>, _executor: &Item<::wgpu_executor::WgpuExecutor>) -> List<Raster<CPU>> {
fn pending_raster(_data: &List<Graphic>, _footprint: &Item<Footprint>, _executor: &Item<::wgpu_executor::WgpuExecutor>, _node_path: &Item<NodeIdPath>) -> List<Raster<CPU>> {
List::new()
}
+1 -1
View File
@@ -150,7 +150,7 @@ fn centered_cell_window(first_cell: DVec2, last_cell: DVec2, max_count: f64) ->
}
/// Repeats the content on a grid that covers the visible viewport.
#[node_macro::node(category(""), icon("NodeRepeatArray"))]
#[node_macro::node(category("Graphic"), icon("NodeRepeatArray"))]
fn tile<T: Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx + ExtractFootprint + InjectFootprint,
#[implementations(
+1 -1
View File
@@ -38,7 +38,7 @@ const BROWSER_MAX_MEGABYTES: f64 = 1000.;
/// Traces an image into a stack of filled and stroked shapes, drawn bottom to top as an artist would layer them.
///
/// The trace runs in slices, one per evaluation, showing the shapes traced so far until it is done.
#[node_macro::node(category("Raster"), icon("NodeVectorize"), memoize)]
#[node_macro::node(category("Raster"), icon("NodeVectorize"), memoize, footprint_invariant)]
fn vectorize(
_: impl Ctx,
/// The image to trace.