Make the data model use Item and List types universally, with nodes authored as rank-polymorphic kernels (#4335)

* Add rank polymorphism node audit classifying all 271 nodes

* Implement StaticType for Item<T>

* Generate Item and mapped List wire variants for nodes declaring an Item<T> primary input

* Migrate nine nodes to Item element-wise kernels, dissolving the blending trait boilerplate

* Document the Item kernel implementation and staging plan

* Route Item<Vector> through TaggedValue::TypeDefault

* Add executor integration tests covering the Item and List wire variants

* Collapse element-wise Item/List wire pairs to the List form for conversion insertion

* Migrate sixteen vector modifier nodes to Item element-wise kernels

* Migrate Sample Image, Extend Image to Bounds, and Dehaze to Item element-wise kernels

* Fix bevel_with_transform test to actually exercise the transform attribute

* Implement From<T> for Item<T>

* Register PromoteNode rank adapters wrapping bare values into Item wires

* Insert PromoteNode adapters for Item/List wire pair fields in the preprocessor

* Define a real promote node backing the PromoteNode registry identifiers

* Zip ranked Item connectors by frame slot in the mapped element-wise variant

* Register ItemToListNode singleton raise adapters

* Resolve Item wires against List connectors by inserting promotion adapters at construction

* Rank the Offset Points distance connector and prove mixed-rank resolution end-to-end

* Implement Clampable for Item and List wires with per-variant clamp bounds

* Rank the Round Corners radius connector, exercising hard bounds on a ranked wire

* Implement ApplyTransform for Item

* Add Item wire implementations to the Transform node, keeping rank-0 chains rank 0

* Detect element-wise nodes by lazy primary connectors declaring Output = Item

* Convert Transform to an Item kernel with ranked parameters, delivering the broadcast milestone

* Rename Apply Transform to Bake Transform, baking item transforms on Vector, DAffine2, and DVec2

* Promote bare wires onto Item connectors at resolution via WrapItemNode adapters

* Rank the numeric, vector, and boolean parameters across the migrated element-wise nodes

* Rank the enum, integer, and seed parameters, registering their rank adapters via a consolidated macro

* Amend the audit with the DashPattern value type resolution

* Migrate the string family to Item element-wise kernels

* Unwrap Item wires into bare legacy connectors at resolution via UnwrapItemNode adapters

* Shadow owned node parameters in bodies instead of mut in signatures

* Migrate the math family and string measure nodes to Item element-wise kernels

* Convert the comparison and clamp nodes to Item kernels, dropping unreachable &str rows

* Flat-map expander kernels returning List under the mapped variant's frame

* Migrate the expander nodes to Item kernels flat-mapping under the frame

* Remove the unused peel_list helper

* Rank the raster adjustment and blending kernels, recontextualizing shader nodes onto an Item stand-in

Migrate the 16 adjustment nodes, Mix, Color Overlay, and Gradient Map from whole-List kernels to rank-0 Item kernels, letting the macro derive the List-mapped (zip) variants. Move the Adjust and Blend per-element seams off List onto the element types (add the Raster<CPU> impls, drop the now-dead List impls).

Shader nodes keep their bodies verbatim: PerPixelAdjust re-emits the identical kernel against a transparent no_std Item stand-in, so every Item<T> connector and .element() call resolves to a zero-cost identity on the GPU while the uniform buffer stays bare repr(C). The macro peels Item off ranked uniform params, wraps the fetched texel and uniforms at the entry point, and unwraps the result. This drops the shader_node/Item incompatibility guard. Register rank adapters for the adjustment enums.

* Update the rank polymorphism roadmap for the landed shader-node and adjustments chunk

* Rename the GPU Item stand-in to ShaderItem, aliased as Item at its shader-node import sites

* Flip the vector shape generators to emit rank-0 Item<Vector>

The shape generators (Rectangle, Circle, Ellipse, Arc, Spiral, Polygon, Star, Arrow, Line, Grid, QR Code) each produced exactly one shape wrapped in a singleton List<Vector>. Emit Item<Vector> directly so they connect to the rank-0 content connector of the migrated Transform node. Downstream List consumers receive the value through the existing Item to List promotion.

Relax the element-wise validation so a `()` (generator) primary may return Item<T> without being element-wise. Adapt the Repeat on Points test, which still takes a List content connector, by raising the generator's Item output through a singleton wrapper node.

* Parse ranked Item<T> parameter defaults against the bare element type

A ranked `Item<T>` parameter's default value is a bare, unranked `T` (promoted to the wire at resolution), but the preprocessor was handed the wrapped `Item<T>` type and could not parse the literal, flooding the console with warnings and dropping the defaults. Key the field's default_type metadata off the peeled element type for concrete ranked parameters, leaving generic `Item<T>` primaries and skip_impl nodes untouched.

* Parse an element-wise primary's scalar default against the bare element type

An element-wise node's primary reports its default_type as the List wire form so an unconnected primary defaults to an empty list. But when the primary carries a scalar `#[default]` (such as Root's radicand), that literal must parse as a bare element, not a List. Key the primary's default_type off the bare element type when it has a Default value source, keeping the List form otherwise.

* Add the DashPattern value type for stroke dash sequences

Introduce a rank-0 DashPattern value type (a Vec<f64> of alternating dash and gap lengths) so a stroke's dash pattern is a single frameable value rather than a rank-1 List<f64>. Register it as an auto-generated TaggedValue variant, parse its default from a comma or space separated string, and register its rank adapters. Not yet wired into the Stroke node.

* Rank the Fill and Stroke nodes element-wise and give Stroke a DashPattern connector

Migrate Fill and Stroke to element-wise Item<V> primaries (over Vector and Graphic element types) via a new element-level VectorItemMut trait, so styling one shape yields one shape and rank is preserved instead of promoting the input to a singleton List and emitting a List. The macro derives the List-mapped variant for genuine collections.

Wire the Stroke dash sequence to the new rank-0 DashPattern value type, collapsing the old content x paint x dash cartesian and dropping the IntoF64Vec trait. Update the stroke properties dash widget, the drawing tool, and graph-operation plumbing to read and write DashPattern, and migrate legacy F64Array, F64, and String dash inputs on document open.

Assign Colors stays a whole-collection node: each element's gradient position depends on its index among all siblings, which the element frame does not expose, so it keeps its List primary and the VectorListIterMut trait.

* Register rank adapters for the ranked Stroke enum parameters

The element-wise Stroke node ranks its align, cap, and paint order parameters as Item<StrokeAlign>, Item<StrokeCap>, and Item<PaintOrder>, but those enums lacked promotion adapters, so a bare default enum value could not be promoted to its Item wire and no Stroke variant resolved ("No construct found for node"). Register their rank adapters alongside StrokeJoin.

* Display Item wires in the Data panel without a List's ID column

Add a TableItemLayout impl for Item<T> and recognize Item wire types when introspecting graph data. An Item holds a single element, so it renders as a one-row table of the element plus its attributes with no leading index column, and it labels as its element type T rather than a List's T[]. Add ItemAttributeValues::get_any for the attribute widget dispatch.

* Register MonitorNode for Item wire types so the Data panel introspects them directly

Graph introspection wraps the inspected output in a generic MonitorNode typed to the wire. Without Item<T> monitor registrations, an Item<Vector> output could only be monitored after an Item to List promotion, so the Data panel captured and displayed a List<Vector> despite the connector being Item<Vector>. Register monitors for the Item types the element-wise nodes emit, and add the matching Data panel downcast entries.

* Color and double Item/List wires and cleave layer-stack connectors in the node graph

* Route wire color and rank through hidden nodes and refresh them on type changes

* Rework the DashPattern connector conversions with element-wise promotion and an explicit reducer node

* Rank the remaining value, context, aggregation, and transform nodes onto Item<T> wires

* Back DashPattern with a List<f64> so the Data panel can introspect its lengths

* Carry a single Item<T> through varargs so the Read context nodes emit Item<T> not List<T>

* Relax rank validation for aggregation shapes, add element adapters, and match variants by fewest promotions

* Rank the remaining bare and unnecessarily-List connectors across the node catalog

* Add Graphic::None and the FillChoice paint value, making colors and gradients plain values

* Rename GradientStops to Gradient and the legacy Gradient/Fill structs to LegacyGradient/LegacyFill

* Restore generator frame-from-params ranking to the roadmap as a planned stage

* Rename the ranked-field adapter identifier from PromoteNode to FieldAdapterNode to reflect its full contract

* Unload only the wires whose displayed style changed when types update

* Peel wire rank in the editor's semantic type checks so rank-0 layers are recognized

* Restore the whole-List Transform variant so rank-1 content wires resolve again

* Register the Item wire forms for the Memoize and Context Modification infrastructure nodes

* Give every ranked connector a field adapter and add numeric cast variants for legacy wires

* Key a ranked param's type default off its Item wire form when no literal default exists

* Inherit the layer's content value when splicing a node into an empty chain

* Migrate stale List-form TypeDefault inputs to the definition's current default

* Generate the mapped wire variant only when the element-wise node has a frame source

* Let a bare wire feed a List connector via a wrap-raise adapter, costed as two rank steps

* Add a zip companion to the whole-List Transform so ranked List parameters pair per slot

* Add the Sum, Average, Minimum, Maximum, Any, and All list reducers

* Convert the measure family to element-wise Item kernels per the audit classification

* Prefer the bare element value over the Item type default so ranked params keep their widgets

* Rename GradientStopsUI to GradientUI

* Split Fill's optional transform into a _has_transform bool and a ranked _transform matrix

* Rename the migration-only OptionalDAffine2 TaggedValue to LegacyOptionalDAffine2

* Flow byte buffers as Item<Resource> instead of List<u8> across the byte nodes

* Macro-generate the list-content wire variant, retiring the hand-written Transform-zip, Area, and Centroid companions

* Let ()-primary generators take ranked params and frame over them via the mapped variant, ranking Circle's radius

* Rank the vector shape generators' params to Item, adding a rank-aware input grab to the introspection harness

* Rank the value, color, and text generator params to Item

* Rank the raster, web-request, and context-reader generator params to Item

* Fix the repeat and brush test wirings left behind by the param-ranking sweeps

* Delete the vestigial Some, Unwrap Option, and Size Of debug nodes

* Delete the Attach Attribute node, folding its role into Write Attribute

* Add the Filter and Sort list companion nodes

* Guard the removed-definition migration swap target with a test

* Add the Box Corners value type in place of the rectangle corner radius list

* Split Text to Vector's per-glyph mode into a Text to Vector Glyphs node

* Rank the Combine Channels node's channel connectors to Item

* Make Map Points an element-wise node

* Delete the deprecated Upload Texture node

* Update the implementation roadmap to reflect the landed stages

* Let monitor introspection read rank-0 wires, locking in the layer coercion promotion path

* Prefer the rank-0 default when disconnecting a rank-capable input

* Make Path Modify an element-wise node

* Wrap node paths in a NodeIdPath newtype so they flow as a single Item

* Give Item<Raster<CPU>> a default so an unconnected Brush background resolves

* Stop the Brush node from setting layer attributes its paint operation doesn't produce

* Present-gate Flatten Path's adopted layer path like its fill and stroke

* Gate carried layer attributes on static column presence, not runtime values

* Give the remaining graphic Item<T> types a default so unconnected primaries resolve

* Dispatch a ranked param's Properties widget from its rank-0 element type

* Make Extract Transform an element-wise node, restoring the Origins to Polyline body

* Rename Flatten Path to Combine Paths

* Stamp Legacy Layer Extend's adopted layer path as a readable NodeIdPath

* Drop the dead List<u8> and List<NodeId> wire rows

* Rank Flatten Graphic's Fully Flatten toggle to Item

* Update the implementation roadmap with the endgame scope

* Make Combine Paths a reducer that collapses the whole frame into one path

* Stop type-converter nodes from carrying the source's unrelated attributes

* Format the Origins to Polyline regression test

* Wrap the Brush node's trace in a BrushTrace newtype so it flows as one value

* Make Switch a framed element-wise select, bundling whole collections

* Widen and align element-type coverage across the list and graphic nodes

* Register the compiler's cache chain pair for every ranked enum and newtype wire

* Fix wire colors for Passthrough outputs, bundled lists, and bools, and widen list wires

* Represent List wire types structurally with Type::List, replacing name-parsed rank promotion

* Treat scope and data fields as environment, rank scope wires as Item, and feed the render boundary through a context vararg

* Delete the vestigial Clone debug node

* Reinstate Upload Texture as an element-wise node and fix the GPU variants' scope executor and rank adapters

* Rename Combine Paths back to Flatten Path, deferring that rename to its own PR

* Deduplicate the promotion adapter registrations into the field adapter macro

* Rank Write Attribute's value connector to Item<AttributeValueDyn>, retiring the UnwrapItem bridge

* Vertical wire styling

* Store the editor layer path attribute as a bare NodeIdPath, not an Item<NodeIdPath>

* Rank Context Modification's features connector to Item<ContextFeatures>, dropping the dead memoize row

* Rank Path Modify's modification parameter to Item<Box<VectorModification>>

* Rename the field adapter node family to input adapter

* Drop the dead bare scalar rows from Context Modification's implementations list

* Move the dynamic executor's test module into its own file

* Drop the registry's unreachable bare rows for Memoize, the cache chain, and ConvertNode

* Materialize stored TaggedValues as ranked Item wires at the source

* Remove the bare-wire promotion and adapter machinery made dead by ranked value materialization

* Plant the input adapter for List-only inputs, composing position conversion from standard rows

* Consolidate Into/Convert conversions into the input adapter umbrella and rename the rank adapter identifiers

* Fix grouped layers gaining a phantom None stack element from the FillChoice default hijacking every List<Graphic> disconnect

* Enforce ranked node inputs in the macro, rejecting bare wire declarations

* Remove the unit Context => () machinery rows, leaving () purely as the no-primary sentinel

* Add a --signatures rank-audit mode to node-docs for the ranked-wire migration

* Remove the node-docs --signatures rank-audit mode now that ranked wires are enforced

* Migrate legacy no-color values on the Black & White, Color Overlay, and Empty Image color inputs

* Rewrite the element-wise accessor wire type at the primary input, not raw index 0

* Register the cache chain for Resource wires, replacing the lone hand-written Monitor row

* Gate the remaining Raster<GPU> registry rows behind the gpu feature

* Let List<DVec2> wires erase to ListDyn for the attribute reader and element counter

* Rename Extract Element to Item at Index, Count Elements to List Length, and Omit Element to Remove at Index

* Store paint picks as plain color/gradient values, removing the FillChoice value type

* Code review restructuring

* Sort by the consumed sort_key attribute or natural element order, adding the Sort Key node

* Remove the new list-combinator and reducer nodes to defer them to a follow-up PR

* Parse Fill and Stroke color defaults through the paint wire's Graphic element

* Emit ranked implementation-row default types structurally so their element TypeIds survive to default-literal parsing

* Exempt the deliberate no-paint choice from the stale List-form TypeDefault migration

* Migrate the legacy 4-input Fill directly to the split has-transform shape

* Upgrade the demo artwork

* Fix the valid AI review findings: Item eq/hash contract, table-era no-paint migration, quantize List rows, and other smaller issues

* Remove the rank polymorphism working documents

* Hash Item attribute values directly instead of debug-formatting them, speeding up cached evaluation

* Replace the data panel's dead bare-wire downcast arms with full coverage of the ranked monitor row types

* Derive PartialEq for Item now that attributes participate in equality

* Extend the data panel's attribute dispatchers with the newly supported scalar and choice enum types

* Add List monitor rows for the framed numeric conversion outputs so inspecting them resolves, with matching data panel arms
This commit is contained in:
Keavon Chambers
2026-07-15 19:03:01 -07:00
committed by Timon
parent 296185b7fc
commit a708a54492
3257 changed files with 766343 additions and 1830 deletions

View File

@@ -121,6 +121,18 @@ impl OriginalLocation {
}
}
impl DocumentNode {
/// Normalizes this node's stored types (call argument, `Import` input types, `TypeDefault` value payloads, and any nested network) to their structural form.
/// Applied once at ingestion (document migration and clipboard paste) so no name-encoded ranked type enters a live document.
pub fn normalize_stored_types(&mut self) {
self.call_argument = self.call_argument.clone().normalize_rank();
for input in &mut self.inputs {
normalize_input_stored_type(input);
}
if let Some(network) = self.implementation.get_network_mut() {
network.normalize_stored_types();
}
}
/// Locate the input that is a [`NodeInput::Import`] at index `offset` and replace it with a [`NodeInput::Node`].
pub fn populate_first_network_input(&mut self, node_id: NodeId, output_index: usize, offset: usize, source: impl Iterator<Item = Source>, skip: usize) {
let (index, _) = self
@@ -239,10 +251,10 @@ impl NodeInput {
Self::Value { tagged_value, exposed }
}
/// Constructs a `NodeInput::Value` whose tagged value is `TaggedValue::TypeDefault(td)`, recording only the
/// Constructs a `NodeInput::Value` whose tagged value is `TaggedValue::TypeDefault(ty)`, recording only the
/// type so the runtime materializes its default rather than baking a placeholder value into the saved document.
pub fn type_default(td: core_types::TypeDescriptor, exposed: bool) -> Self {
Self::value(TaggedValue::TypeDefault(td), exposed)
pub fn type_default(ty: Type, exposed: bool) -> Self {
Self::value(TaggedValue::TypeDefault(ty.normalize_rank()), exposed)
}
pub const fn import(import_type: Type, import_index: usize) -> Self {
@@ -274,6 +286,7 @@ impl NodeInput {
match self {
NodeInput::Node { .. } => unreachable!("ty() called on NodeInput::Node"),
NodeInput::Value { tagged_value, .. } => tagged_value.ty(),
// Stored import types are normalized to their structural form once at document migration
NodeInput::Import { import_type, .. } => import_type.clone(),
NodeInput::Inline(_) => panic!("ty() called on NodeInput::Inline"),
NodeInput::Scope(_) => panic!("ty() called on NodeInput::Scope"),
@@ -727,7 +740,33 @@ impl ScopeChain<'_> {
}
/// Functions for compiling the network
/// Normalizes the ranked types an input can store: an `Import`'s type or a value's `TypeDefault` payload.
fn normalize_input_stored_type(input: &mut NodeInput) {
match input {
NodeInput::Import { import_type, .. } => *import_type = import_type.clone().normalize_rank(),
NodeInput::Value { tagged_value, .. } => {
if let TaggedValue::TypeDefault(ty) = &**tagged_value {
let normalized = ty.clone().normalize_rank();
if normalized != *ty {
*tagged_value = TaggedValue::TypeDefault(normalized).into();
}
}
}
_ => {}
}
}
impl NodeNetwork {
/// Normalizes every stored type in the network (exports and each node's types) to the structural form, recursively.
pub fn normalize_stored_types(&mut self) {
for export in &mut self.exports {
normalize_input_stored_type(export);
}
for node in self.nodes.values_mut() {
node.normalize_stored_types();
}
}
/// Replace all references in the graph of a node ID with a new node ID defined by the function `f`.
pub fn map_ids(&mut self, f: impl Fn(NodeId) -> NodeId + Copy) {
self.exports.iter_mut().for_each(|output| {

View File

@@ -16,8 +16,11 @@ use dyn_any::DynAny;
pub use dyn_any::StaticType;
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
use graphene_application_io::resource::ResourceHash;
use graphene_application_io::resource::ResourceId;
use graphic_types::raster_types::{CPU, Image, Raster};
use graphic_types::vector_types::vector::style::GradientStops;
use graphic_types::vector_types::vector::misc::BoxCorners;
use graphic_types::vector_types::vector::style::DashPattern;
use graphic_types::vector_types::vector::style::Gradient;
use graphic_types::vector_types::vector::{self, ReferencePoint};
use graphic_types::{Artboard, Graphic, Vector};
use rendering::RenderMetadata;
@@ -31,15 +34,38 @@ use vector::VectorModification;
pub struct TaggedValueTypeError;
/// List of types routed through [`TaggedValue::TypeDefault`] instead of another dedicated variant.
/// Item-cell element types routed through [`TaggedValue::TypeDefault`] instead of another dedicated variant, stored as the concrete `Item<T>` wire type.
/// Consumed by [`TaggedValue::from_type`] (which creates `TypeDefault` values) and [`TaggedValue::to_dynany`]/[`TaggedValue::to_any`] (which unwrap them into real default values).
macro_rules! for_each_type_default {
macro_rules! for_each_item_type_default {
($action:ident) => {
$action!(Vector);
$action!(f64);
$action!(Raster<CPU>);
$action!(Graphic);
$action!(Color);
$action!(Gradient);
$action!(Artboard);
$action!(String);
};
}
/// List element types routed through [`TaggedValue::TypeDefault`], stored as the structural [`Type::List`] form.
/// `List<f64>` is absent because it stores as `TaggedValue::F64Array`.
macro_rules! for_each_list_type_default {
($action:ident) => {
$action!(Graphic);
$action!(Artboard);
$action!(Raster<CPU>);
$action!(Vector);
$action!(String);
$action!(Color);
$action!(Gradient);
};
}
/// Unranked types routed through [`TaggedValue::TypeDefault`], stored as their concrete type.
macro_rules! for_each_bare_type_default {
($action:ident) => {
$action!(List<Graphic>);
$action!(List<Artboard>);
$action!(List<Raster<CPU>>);
$action!(List<Vector>);
$action!(List<String>);
$action!(DocumentNode);
$action!(Resource);
};
@@ -57,22 +83,24 @@ macro_rules! tagged_value {
// ===============
None,
/// Stores a type, from which its `Default::default()` value can be obtained, rather than storing an actual type's value.
/// Example: `TaggedValue::TypeDefault(descriptor!(String))` stores the type `String` but no specific string value.
TypeDefault(TypeDescriptor),
/// Example: `TaggedValue::TypeDefault(concrete!(String))` stores the type `String` but no specific string value.
/// (Old documents stored a bare `TypeDescriptor` payload, routed to this shape by `deserialize_tagged_value_with_legacy_migration`.)
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_f64_array")] // TODO: Eventually remove this migration document upgrade code
#[serde(alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4")]
F64Array(Vec<f64>),
/// Stored compactly as an `Option<Color>`, materializes as `List<Color>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
#[serde(deserialize_with = "core_types::misc::migrate_to_optional_color")] // TODO: Eventually remove this migration document upgrade code
/// A plain, always-present color. Aliases recover legacy on-disk shapes; a legacy `null` payload (the old "no color")
/// is routed to [`TaggedValue::no_paint`] by `deserialize_tagged_value_with_legacy_migration`.
#[serde(deserialize_with = "core_types::misc::migrate_to_color")] // TODO: Eventually remove this migration document upgrade code
#[serde(alias = "ColorTable", alias = "OptionalColor", alias = "ColorNotInTable")]
Color(Option<Color>),
/// Stored compactly as a `GradientStops`, materializes as a single-row `List<GradientStops>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
Color(Color),
/// Stored compactly as a `Gradient`, materializing as an `Item<Gradient>` at runtime. Aliases recover legacy on-disk shapes.
/// (Old documents that stored a full `Gradient` struct under this same `"Gradient"` tag are routed to `LegacyGradient` by `deserialize_tagged_value_with_legacy_migration`.)
#[serde(deserialize_with = "graphic_types::vector_types::gradient::migrate_to_gradient_stops")] // TODO: Eventually remove this migration document upgrade code
#[serde(deserialize_with = "graphic_types::vector_types::gradient::migrate_to_gradient")] // TODO: Eventually remove this migration document upgrade code
#[serde(alias = "GradientTable", alias = "GradientPositions", alias = "GradientStops")]
Gradient(GradientStops),
/// Stored compactly as a `Vec<BrushStroke>`, materializes as `List<BrushStroke>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
Gradient(Gradient),
/// Stored compactly as a `Vec<BrushStroke>`, materializes as the single-value `Item<BrushTrace>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
#[serde(deserialize_with = "brush_nodes::migrations::migrate_to_brush_strokes")] // TODO: Eventually remove this migration document upgrade code
#[serde(alias = "BrushStrokeTable")]
BrushStrokes(Vec<BrushStroke>),
@@ -85,10 +113,10 @@ macro_rules! tagged_value {
// =======================
#[serde(skip)]
RenderOutput(RenderOutput),
/// Path to the consumer of a `NodeInput::Reflection(DocumentNodePath)`. Materializes a `List<NodeId>` at runtime via `to_dynany`/`to_any` during graph flattening.
/// Path to the consumer of a `NodeInput::Reflection(DocumentNodePath)`. Materializes an `Item<NodeIdPath>` at runtime via `to_dynany`/`to_any` during graph flattening, matching the ranked connectors it feeds.
#[serde(skip)]
NodeIdPath(Vec<NodeId>),
/// The `DocumentNode` value carried by an `Extract` proto node, populated at flatten time by `resolve_extract_nodes`. The on-disk placeholder uses `TypeDefault(descriptor!(DocumentNode))`.
NodeIdPath(NodeIdPath),
/// The `DocumentNode` value carried by an `Extract` proto node, populated at flatten time by `resolve_extract_nodes`. The on-disk placeholder uses `TypeDefault(concrete!(DocumentNode))`.
#[serde(skip)]
DocumentNode(DocumentNode),
/// Carried by context nullification proto nodes constructed at proto node compilation time in `insert_context_nullification_nodes`.
@@ -121,7 +149,7 @@ macro_rules! tagged_value {
// =======================
// NON-SERIALIZED VARIANTS
// =======================
Self::NodeIdPath(path) => path.hash(state),
Self::NodeIdPath(path) => path.cache_hash(state),
Self::DocumentNode(node) => node.cache_hash(state),
Self::ContextModification(modification) => modification.cache_hash(state),
Self::RenderOutput(x) => x.cache_hash(state),
@@ -149,26 +177,19 @@ macro_rules! tagged_value {
if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Box::new(<$type_default>::default()); }
};
}
for_each_type_default!(check);
Self::from_type_or_none(&Type::Concrete(td)).to_dynany()
Self::from_type_or_none(&td).to_dynany()
}
Self::F64Array(values) => {
let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect();
Box::new(list)
}
Self::Color(color) => {
let list: List<Color> = color.into_iter().map(core_types::list::Item::new_from_element).collect();
Box::new(list)
}
Self::Gradient(stops) => Box::new(List::<GradientStops>::new_from_element(stops)),
Self::BrushStrokes(strokes) => {
let list: List<BrushStroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
Box::new(list)
}
Self::Color(color) => Box::new(Item::new_from_element(color)),
Self::Gradient(stops) => Box::new(Item::new_from_element(stops)),
Self::BrushStrokes(strokes) => Box::new(core_types::list::Item::new_from_element(BrushTrace::from(strokes))),
// =======================
// AUTO-GENERATED VARIANTS
// =======================
$( Self::$identifier(x) => Box::new(x), )*
$( Self::$identifier(x) => Box::new(Item::new_from_element(x)), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
@@ -177,7 +198,7 @@ macro_rules! tagged_value {
Self::DocumentNode(node) => Box::new(node),
Self::ContextModification(modification) => Box::new(modification),
Self::EditorApi(x) => Box::new(x),
Self::ResourceHash(x) => Box::new(x),
Self::ResourceHash(x) => Box::new(Item::new_from_element(x)),
}
}
@@ -196,26 +217,19 @@ macro_rules! tagged_value {
if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Arc::new(<$type_default>::default()); }
};
}
for_each_type_default!(check);
Self::from_type_or_none(&Type::Concrete(td)).to_any()
Self::from_type_or_none(&td).to_any()
}
Self::F64Array(values) => {
let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect();
Arc::new(list)
}
Self::Color(color) => {
let list: List<Color> = color.into_iter().map(core_types::list::Item::new_from_element).collect();
Arc::new(list)
}
Self::Gradient(stops) => Arc::new(List::<GradientStops>::new_from_element(stops)),
Self::BrushStrokes(strokes) => {
let list: List<BrushStroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
Arc::new(list)
}
Self::Color(color) => Arc::new(Item::new_from_element(color)),
Self::Gradient(stops) => Arc::new(Item::new_from_element(stops)),
Self::BrushStrokes(strokes) => Arc::new(core_types::list::Item::new_from_element(BrushTrace::from(strokes))),
// =======================
// AUTO-GENERATED VARIANTS
// =======================
$( Self::$identifier(x) => Arc::new(x), )*
$( Self::$identifier(x) => Arc::new(Item::new_from_element(x)), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
@@ -224,13 +238,13 @@ macro_rules! tagged_value {
Self::DocumentNode(node) => Arc::new(node),
Self::ContextModification(modification) => Arc::new(modification),
Self::EditorApi(x) => Arc::new(x),
Self::ResourceHash(x) => Arc::new(x),
Self::ResourceHash(x) => Arc::new(Item::new_from_element(x)),
}
}
/// Creates a core_types::Type::Concrete(TypeDescriptor { .. }) with the type of the value inside the tagged value
/// Creates the wire [`Type`] of the value inside the tagged value, with ranked types in their structural form.
pub fn ty(&self) -> Type {
match self {
let ty = match self {
// ===============
// MANUAL VARIANTS
// ===============
@@ -253,7 +267,7 @@ macro_rules! tagged_value {
// =======================
// AUTO-GENERATED VARIANTS
// =======================
$( Self::$identifier(_) => concrete!($ty), )*
$( Self::$identifier(_) => item!($ty), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
@@ -399,10 +413,11 @@ macro_rules! tagged_value {
// AUTO-GENERATED VARIANTS
// =======================
$( x if x == TypeId::of::<$ty>() => Ok(TaggedValue::$identifier(*downcast(input).unwrap())), )*
$( x if x == TypeId::of::<Item<$ty>>() => Ok(TaggedValue::$identifier(downcast::<Item<$ty>>(input).unwrap().into_element())), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
x if x == TypeId::of::<RenderOutput>() => Ok(TaggedValue::RenderOutput(*downcast(input).unwrap())),
x if x == TypeId::of::<Item<RenderOutput>>() => Ok(TaggedValue::RenderOutput(downcast::<Item<RenderOutput>>(input).unwrap().into_element())),
_ => Err(format!("Cannot convert {:?} to TaggedValue", DynAny::type_name(input.as_ref()))),
}
@@ -421,17 +436,18 @@ macro_rules! tagged_value {
// AUTO-GENERATED VARIANTS
// =======================
$( x if x == TypeId::of::<$ty>() => Ok(TaggedValue::$identifier(<$ty as Clone>::clone(input.downcast_ref().unwrap()))), )*
$( x if x == TypeId::of::<Item<$ty>>() => Ok(TaggedValue::$identifier(Item::<$ty>::clone(input.downcast_ref().unwrap()).into_element())), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
x if x == TypeId::of::<RenderOutput>() => Ok(TaggedValue::RenderOutput(RenderOutput::clone(input.downcast_ref().unwrap()))),
x if x == TypeId::of::<Item<RenderOutput>>() => Ok(TaggedValue::RenderOutput(Item::<RenderOutput>::clone(input.downcast_ref().unwrap()).into_element())),
_ => Err(format!("Cannot convert {:?} to TaggedValue", std::any::type_name_of_val(input))),
}
}
/// Returns a TaggedValue from the type, where that value is its type's `Default::default()`.
/// Dispatches by the type's name (the field that round-trips through serde) so it works for both
/// freshly constructed types and types deserialized from disk where the runtime `TypeId` is unavailable.
/// Dispatches by name for concrete types and structurally by element for ranked types, where the name
/// field is what round-trips through serde so it works even for types deserialized from disk.
pub fn from_type(input: &Type) -> Option<Self> {
match input {
Type::Generic(_) => None,
@@ -462,11 +478,34 @@ macro_rules! tagged_value {
if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Some(TaggedValue::TypeDefault(concrete_type.clone())); }
};
}
for_each_type_default!(check);
for_each_bare_type_default!(check_bare);
None
}
Type::Fn(_, output) => TaggedValue::from_type(output),
Type::Future(output) => TaggedValue::from_type(output),
// Element types with a dedicated variant use it directly (the variant's value is a rank-0 cell); the rest store the structural type
Type::Item(element) => TaggedValue::from_type(element).or_else(|| {
macro_rules! check {
($type_default:ty) => {
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
};
}
for_each_item_type_default!(check);
None
}),
// Structural lists match by element; `List<f64>` stays the dedicated `F64Array` variant
Type::List(element) => {
if **element == concrete!(f64) {
return Some(TaggedValue::F64Array(Vec::new()));
}
macro_rules! check {
($type_default:ty) => {
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
};
}
for_each_list_type_default!(check);
None
}
}
}
@@ -480,7 +519,7 @@ macro_rules! tagged_value {
// MANUAL VARIANTS
// ===============
Self::None => "()".to_string(),
Self::TypeDefault(td) => format!("TypeDefault({})", td.name),
Self::TypeDefault(td) => format!("TypeDefault({td})"),
Self::F64Array(values) => format!("F64Array({values:?})"),
Self::Color(color) => format!("Color({color:?})"),
Self::Gradient(stops) => format!("Gradient({stops:?})"),
@@ -538,19 +577,19 @@ tagged_value! {
DVec2(DVec2),
#[serde(alias = "Affine2")]
DAffine2(DAffine2),
OptionalDAffine2(Option<DAffine2>),
#[serde(alias = "FillGradient")]
LegacyGradient(graphic_types::migrations::legacy::Gradient),
Font(Font),
Footprint(Footprint),
VectorModification(Box<VectorModification>),
ImageData(Image<Color>),
Resource(graphene_application_io::resource::ResourceId),
Resource(ResourceId),
// Legacy
#[serde(alias = "OptionalDAffine2")]
LegacyOptionalDAffine2(Option<DAffine2>),
#[serde(alias = "FillGradient")]
LegacyGradient(graphic_types::migrations::legacy::LegacyGradient),
// ==========
// ENUM TYPES
// ==========
#[serde(alias = "Fill")]
LegacyFill(graphic_types::migrations::legacy::Fill),
BlendMode(core_types::blending::BlendMode),
LuminanceCalculation(raster_nodes::adjustments::LuminanceCalculation),
QRCodeErrorCorrectionLevel(vector_nodes::generator_nodes::QRCodeErrorCorrectionLevel),
@@ -580,6 +619,8 @@ tagged_value! {
StrokeJoin(vector::style::StrokeJoin),
StrokeAlign(vector::style::StrokeAlign),
PaintOrder(vector::style::PaintOrder),
DashPattern(vector::style::DashPattern),
BoxCorners(vector::misc::BoxCorners),
GradientType(vector::style::GradientType),
GradientSpreadMethod(vector::style::GradientSpreadMethod),
ReferencePoint(vector::ReferencePoint),
@@ -587,6 +628,9 @@ tagged_value! {
BooleanOperation(vector::misc::BooleanOperation),
TextAlign(text_nodes::TextAlign),
ScaleType(core_types::transform::ScaleType),
// Legacy
#[serde(alias = "Fill")]
LegacyFill(graphic_types::migrations::legacy::LegacyFill),
}
impl TaggedValue {
@@ -648,11 +692,11 @@ impl TaggedValue {
None
}
fn to_gradient(input: &str) -> Option<GradientStops> {
fn to_gradient(input: &str) -> Option<Gradient> {
// String syntax: (e.g. "000000ff, ff0000ff")
let stops = input.split(',').filter_map(|s| to_color(s.trim())).collect::<Vec<_>>();
if stops.len() == 1 {
Some(GradientStops::new(vec![
Some(Gradient::new(vec![
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -666,7 +710,7 @@ impl TaggedValue {
]))
} else if stops.len() >= 2 {
let step = 1. / (stops.len() - 1) as f64;
Some(GradientStops::new(stops.into_iter().enumerate().map(|(i, color)| GradientStop {
Some(Gradient::new(stops.into_iter().enumerate().map(|(i, color)| GradientStop {
position: i as f64 * step,
midpoint: 0.5,
color,
@@ -721,19 +765,21 @@ impl TaggedValue {
() if ty == TypeId::of::<u32>() => FromStr::from_str(string).map(TaggedValue::U32).ok()?,
() if ty == TypeId::of::<DVec2>() => to_dvec2(string).map(TaggedValue::DVec2)?,
() if ty == TypeId::of::<bool>() => FromStr::from_str(string).map(TaggedValue::Bool).ok()?,
// `Color` (not in a `List`) is still currently needed by `BlackAndWhiteNode` and `ColorOverlayNode` GPU `shader_node(PerPixelAdjust)` variants
() if ty == TypeId::of::<Color>() => to_color(string).map(|color| TaggedValue::Color(Some(color)))?,
() if ty == TypeId::of::<List<Color>>() => to_color(string).map(|color| TaggedValue::Color(Some(color)))?,
// The Fill and Stroke nodes' paint connectors default to `List<Graphic>`, their first registered implementation row
() if ty == TypeId::of::<List<Graphic>>() => to_color(string).map(|color| TaggedValue::Color(Some(color)))?,
() if ty == TypeId::of::<List<GradientStops>>() => to_gradient(string).map(TaggedValue::Gradient)?,
() if ty == TypeId::of::<Color>() => to_color(string).map(TaggedValue::Color)?,
// The Fill/Stroke paint wires carry `Graphic` or `Gradient` elements, so a paint default parses through the element recursion as a color or gradient literal
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(TaggedValue::Gradient)?,
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(DashPattern::from(string)),
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(BoxCorners::from(string)),
_ => return None,
};
Some(ty)
}
Type::Fn(_, output) => TaggedValue::from_primitive_string(string, output),
Type::Future(fut) => TaggedValue::from_primitive_string(string, fut),
Type::Item(element) => TaggedValue::from_primitive_string(string, element),
Type::List(element) => TaggedValue::from_primitive_string(string, element),
}
}
@@ -743,6 +789,16 @@ impl TaggedValue {
_ => panic!("Passed value is not of type u32"),
}
}
/// The stored form of a paint input's red-slash "no paint" choice: the `List<Graphic>` type default, materializing as an empty paint list.
pub fn no_paint() -> Self {
TaggedValue::TypeDefault(list!(Graphic))
}
/// Whether this is the `List<Graphic>` type default created by [`Self::no_paint`] (and by disconnecting a paint wire).
pub fn is_no_paint(&self) -> bool {
matches!(self, TaggedValue::TypeDefault(td) if *td == list!(Graphic))
}
}
/// Custom deserializer hooked onto `NodeInput::Value::tagged_value` that intercepts removed-variant tags before delegating to `TaggedValue`'s standard derive.
@@ -750,14 +806,16 @@ impl TaggedValue {
/// Routes legacy variant names into modern variants, in typed Rust. Each legacy name is also matched against the historical `#[serde(alias = "...")]` spellings the deleted variant accepted, so old-shape inner payloads are caught:
///
/// - `BrushCache` → `TaggedValue::None` (purely runtime cache; no payload to preserve)
/// - `Graphic` (or alias `GraphicGroup`/`Group`) → `TaggedValue::TypeDefault(descriptor!(List<Graphic>))`
/// - `Artboard` (or alias `ArtboardGroup`) → `TaggedValue::TypeDefault(descriptor!(List<Artboard>))`
/// - `Graphic` (or alias `GraphicGroup`/`Group`) → `TaggedValue::TypeDefault(list!(Graphic))`
/// - `Artboard` (or alias `ArtboardGroup`) → `TaggedValue::TypeDefault(list!(Artboard))`
/// - `Raster` (or alias `ImageFrame`/`RasterData`/`Image`):
/// - non-empty (the legacy `image` proto's input 1, where the inner `Raster<CPU>` serializes as the embedded `Image<Color>`) → `TaggedValue::ImageData(<inner Image<Color>>)`
/// - empty → `TaggedValue::TypeDefault(descriptor!(List<Raster<CPU>>))`
/// - empty → `TaggedValue::TypeDefault(list!(Raster<CPU>))`
/// - `Vector` (or alias `VectorData`):
/// - non-empty → `TaggedValue::VectorModification(<built from first element>)` (the document_migration's Path pass disambiguates this between SVG-import legacy and a discardable modern baked value via the input's `exposed` flag)
/// - empty → `TaggedValue::TypeDefault(descriptor!(List<Vector>))`
/// - empty → `TaggedValue::TypeDefault(list!(Vector))`
/// - `FillChoice` → `TaggedValue::Color` (solid), `TaggedValue::Gradient` (gradient), or `TaggedValue::no_paint()` (none)
/// - `TypeDefault` with the old bare-`TypeDescriptor` payload → the same variant wrapping a `Type` (name-encoded `List` normalized to structural)
///
/// All other tags (including ones with the modern shape) fall through to the standard derived `Deserialize` for `TaggedValue`.
// TODO: Eventually remove this migration document upgrade code
@@ -772,8 +830,8 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
{
match tag.as_str() {
"BrushCache" => return Ok(MemoHash::new(TaggedValue::None)),
"Graphic" | "GraphicGroup" | "Group" => return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Graphic>)))),
"Artboard" | "ArtboardGroup" => return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Artboard>)))),
"Graphic" | "GraphicGroup" | "Group" => return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Graphic)))),
"Artboard" | "ArtboardGroup" => return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Artboard)))),
"Raster" | "ImageFrame" | "RasterData" | "Image" => {
let first_element = content
.as_object()
@@ -784,7 +842,7 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
let image: Image<Color> = serde_json::from_value(image_value.clone()).map_err(serde::de::Error::custom)?;
return Ok(MemoHash::new(TaggedValue::ImageData(image)));
}
return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Raster<CPU>>))));
return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Raster<CPU>))));
}
"Vector" | "VectorData" => {
let vector = graphic_types::migrations::migrate_to_optional_vector(content.clone()).map_err(serde::de::Error::custom)?;
@@ -792,12 +850,42 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
let modification = Box::new(VectorModification::create_from_vector(&vector));
return Ok(MemoHash::new(TaggedValue::VectorModification(modification)));
}
return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Vector>))));
return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Vector))));
}
// The `Gradient` tag was reused: it used to carry a full `Gradient` struct (now `LegacyGradient`), and now carries an `Option<GradientStops>`.
// Disambiguate by payload shape: a Gradient struct has `start`/`end` keys; a `GradientStops` has none of those (it has `position`/`midpoint`/`color`).
// The `TypeDefault` payload used to be a bare `TypeDescriptor`; it now carries a `Type`
"TypeDefault" if content.as_object().is_some_and(|c| c.contains_key("name")) => {
let descriptor: TypeDescriptor = serde_json::from_value(content.clone()).map_err(serde::de::Error::custom)?;
return Ok(MemoHash::new(TaggedValue::TypeDefault(Type::Concrete(descriptor).normalize_rank())));
}
// The `Color` tag used to carry `Option<Color>`, where a `null` payload (or an empty legacy color table) was the red-slash "no paint" choice
"Color" | "ColorTable" | "OptionalColor" | "ColorNotInTable"
if content.is_null()
|| content
.as_object()
.and_then(|c| c.get("element").or_else(|| c.get("instance")).or_else(|| c.get("instances")))
.and_then(|e| e.as_array())
.is_some_and(|colors| colors.is_empty()) =>
{
return Ok(MemoHash::new(TaggedValue::no_paint()));
}
// The removed `FillChoice` variant decomposes into the plain paint values
"FillChoice" => {
if let Some(payload) = content.as_object() {
if let Some(solid) = payload.get("Solid") {
let color: Color = serde_json::from_value(solid.clone()).map_err(serde::de::Error::custom)?;
return Ok(MemoHash::new(TaggedValue::Color(color)));
}
if let Some(gradient) = payload.get("Gradient") {
let gradient: Gradient = serde_json::from_value(gradient.clone()).map_err(serde::de::Error::custom)?;
return Ok(MemoHash::new(TaggedValue::Gradient(gradient)));
}
}
return Ok(MemoHash::new(TaggedValue::no_paint()));
}
// The `Gradient` tag was reused: it used to carry a full `Gradient` struct (now `LegacyGradient`), and now carries an `Option<Gradient>`.
// Disambiguate by payload shape: a Gradient struct has `start`/`end` keys; a `Gradient` has none of those (it has `position`/`midpoint`/`color`).
"Gradient" if content.as_object().is_some_and(|c| c.contains_key("start") && c.contains_key("end")) => {
let gradient: graphic_types::migrations::legacy::Gradient = serde_json::from_value(content.clone()).map_err(serde::de::Error::custom)?;
let gradient: graphic_types::migrations::legacy::LegacyGradient = serde_json::from_value(content.clone()).map_err(serde::de::Error::custom)?;
return Ok(MemoHash::new(TaggedValue::LegacyGradient(gradient)));
}
_ => {}
@@ -883,18 +971,18 @@ impl CacheHash for RenderOutput {
#[cfg(test)]
mod typedefault_dispatch {
use super::*;
use core_types::descriptor;
use core_types::{concrete, item, list};
/// Round-trips every type listed in [`for_each_type_default`] through `TaggedValue::TypeDefault → to_dynany / to_any` and asserts the resulting concrete type matches the descriptor.
/// Round-trips every type in the type-default lists through `TaggedValue::TypeDefault → to_dynany / to_any` and asserts the resulting concrete type matches the stored type.
///
/// This guards against the only way to break the recursion invariant in the unwrap functions: someone hand-rolling a `TypeDefault`-yielding case in `from_type` (or the macro's expansion in one of the unwrap sites silently failing to match a name). If it fails, the message points at the specific type and the structural reason.
#[test]
fn typedefault_dispatch_terminates() {
macro_rules! check {
($type_default:ty) => {{
let descriptor = descriptor!($type_default);
($type_default:ty, $stored:expr) => {{
let ty: Type = $stored;
let expected_type_id = std::any::TypeId::of::<$type_default>();
let dyn_value = TaggedValue::TypeDefault(descriptor.clone()).to_dynany();
let dyn_value = TaggedValue::TypeDefault(ty.clone()).to_dynany();
assert_eq!(
DynAny::type_id(&*dyn_value),
expected_type_id,
@@ -902,7 +990,7 @@ mod typedefault_dispatch {
core_types::normalize_type_name(std::any::type_name::<$type_default>()),
);
let arc_value = TaggedValue::TypeDefault(descriptor).to_any();
let arc_value = TaggedValue::TypeDefault(ty).to_any();
assert_eq!(
(*arc_value).type_id(),
expected_type_id,
@@ -911,7 +999,58 @@ mod typedefault_dispatch {
);
}};
}
for_each_type_default!(check);
macro_rules! check_item {
($element:ty) => {
check!(Item<$element>, item!($element));
};
}
macro_rules! check_list {
($element:ty) => {
check!(List<$element>, list!($element));
};
}
macro_rules! check_bare {
($type_default:ty) => {
check!($type_default, concrete!($type_default));
};
}
for_each_item_type_default!(check_item);
for_each_list_type_default!(check_list);
for_each_bare_type_default!(check_bare);
}
}
#[cfg(test)]
mod paint_default_parsing {
use super::*;
use core_types::{item, list};
/// A Fill/Stroke paint wire carries `Graphic` elements, so its `Color::BLACK` default must parse through the
/// element recursion into a `Color` for a fresh Fill node's paint to resolve.
#[test]
fn paint_wire_parses_color_default_through_its_element() {
let black = Some(TaggedValue::Color(Color::BLACK));
assert_eq!(
TaggedValue::from_primitive_string("Color::BLACK", &list!(Graphic)),
black,
"a `List<Graphic>` paint wire should resolve its color default"
);
assert_eq!(
TaggedValue::from_primitive_string("Color::BLACK", &item!(Graphic)),
black,
"an `Item<Graphic>` paint wire should resolve its color default"
);
}
/// Table-era documents stored the red-slash "no paint" fill as an empty color table, which must keep
/// deserializing to [`TaggedValue::no_paint`] rather than collapsing to a transparent color.
#[test]
fn empty_legacy_color_table_deserializes_to_no_paint() {
for payload in [r#"{"ColorTable": {"instances": []}}"#, r#"{"ColorTable": {"element": []}}"#, r#"{"Color": null}"#] {
let mut deserializer = serde_json::Deserializer::from_str(payload);
let value = deserialize_tagged_value_with_legacy_migration(&mut deserializer).expect("The legacy payload should deserialize");
assert!(value.is_no_paint(), "The legacy payload `{payload}` should migrate to the no-paint choice");
}
}
}

View File

@@ -3,7 +3,7 @@ extern crate log;
#[macro_use]
extern crate core_types;
pub use core_types::{ProtoNodeIdentifier, Type, TypeDescriptor, concrete, descriptor, generic};
pub use core_types::{ProtoNodeIdentifier, Type, TypeDescriptor, concrete, descriptor, generic, item, list};
pub mod application_io;
pub mod document;

View File

@@ -839,6 +839,31 @@ pub struct TypingContext {
lookup: Cow<'static, Registry>,
inferred: HashMap<NodeId, NodeIOTypes>,
constructor: HashMap<NodeId, NodeConstructor>,
promotions: HashMap<NodeId, Vec<(usize, Promotion)>>,
}
/// A rank adapter which type resolution marks for insertion between a wire and a connector whose ranks differ,
/// carrying the element type the adapter is registered under.
#[derive(Debug, Clone, PartialEq)]
pub enum Promotion {
/// Raises an `Item<X>` wire onto a `List<X>` connector as a one-element list.
ItemToList(Type),
/// Bundles a whole `List<X>` wire into one opaque `Item<Bundle<X>>` cell.
Bundle(Type),
/// Unbundles an `Item<Bundle<X>>` wire back into the whole `List<X>`.
Unbundle(Type),
}
impl Promotion {
/// The registry identifier of the adapter node monomorphized for this promotion's element type.
pub fn adapter_identifier(&self) -> ProtoNodeIdentifier {
let (adapter_name, element) = match self {
Self::ItemToList(element) => ("graphene_core::ops::ItemToListNode", element),
Self::Bundle(element) => ("graphene_core::ops::BundleNode", element),
Self::Unbundle(element) => ("graphene_core::ops::UnbundleNode", element),
};
ProtoNodeIdentifier::with_owned_string(format!("{adapter_name}<{}>", element.identifier_name()))
}
}
impl TypingContext {
@@ -867,9 +892,20 @@ impl TypingContext {
pub fn remove_inference(&mut self, node_id: NodeId) -> Option<NodeIOTypes> {
self.constructor.remove(&node_id);
self.promotions.remove(&node_id);
self.inferred.remove(&node_id)
}
/// Returns the input positions of a node which type resolution marked for rank promotion, with each position's adapter.
pub fn promotions(&self, node_id: NodeId) -> Option<&Vec<(usize, Promotion)>> {
self.promotions.get(&node_id)
}
/// Looks up the sole constructor registered under an adapter identifier, such as an Item -> List promotion adapter.
pub fn adapter_constructor(&self, identifier: &ProtoNodeIdentifier) -> Option<NodeConstructor> {
self.lookup.get(identifier).and_then(|implementations| implementations.values().next().copied())
}
/// Returns the node constructor for a given node id.
pub fn constructor(&self, node_id: NodeId) -> Option<NodeConstructor> {
self.constructor.get(&node_id).copied()

View File

@@ -7,10 +7,11 @@ use graphene_std::application_io::RenderConfig;
fn subsequent_evaluations(c: &mut Criterion) {
let mut group = c.benchmark_group("Subsequent Evaluations");
let context = RenderConfig::default();
let context = RenderConfig::default().into_context();
bench_for_each_demo(&mut group, |name, g| {
let (executor, _) = setup_network(name);
g.bench_function(name, |b| b.iter(|| Executor::execute(&&executor, std::hint::black_box(context)).unwrap()));
let context = context.clone();
g.bench_function(name, |b| b.iter(|| Executor::execute(&&executor, std::hint::black_box(context.clone())).unwrap()));
});
group.finish();
}

View File

@@ -11,7 +11,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
let (executor, _) = setup_network(name);
// Warm up the cache by running once
let context = RenderConfig::default();
let context = RenderConfig::default().into_context();
let _ = Executor::execute(&&executor, context);
executor
@@ -20,7 +20,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
#[library_benchmark]
#[benches::with_setup(args = ["changing-seasons", "isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)]
pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor {
let context = RenderConfig::default();
let context = RenderConfig::default().into_context();
black_box(Executor::execute(&&executor, black_box(context)).unwrap());
// Return the executor so its teardown happens outside the measured section

View File

@@ -8,13 +8,14 @@ use interpreted_executor::dynamic_executor::DynamicExecutor;
fn run_once(c: &mut Criterion) {
let mut group = c.benchmark_group("Run Once");
let context = RenderConfig::default();
let context = RenderConfig::default().into_context();
bench_for_each_demo(&mut group, |name, g| {
let (_, network) = setup_network(name);
let context = context.clone();
g.bench_function(name, |b| {
b.iter_batched_ref(
|| DynamicExecutor::new(network.clone()).unwrap(),
|executor| Executor::execute(&&*executor, std::hint::black_box(context)).unwrap(),
|executor| Executor::execute(&&*executor, std::hint::black_box(context.clone())).unwrap(),
criterion::BatchSize::LargeInput,
)
});

View File

@@ -15,7 +15,7 @@ fn setup_run_once(name: &str) -> DynamicExecutor {
#[library_benchmark]
#[benches::with_setup(args = ["changing-seasons", "isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)]
pub fn run_once(executor: DynamicExecutor) -> (DynamicExecutor, core_types::gpoll::GPoll<graph_craft::document::value::TaggedValue>) {
let context = application_io::RenderConfig::default();
let context = application_io::RenderConfig::default().into_context();
let result = black_box(Executor::execute(&&executor, black_box(context)).unwrap());
// Return the executor and result so their teardown happens outside the measured section

View File

@@ -0,0 +1,624 @@
use super::*;
use core_types::Context;
use core_types::list::{Item, List};
use core_types::{item, list};
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::TaggedValue;
use graphene_std::vector::Vector;
#[test]
fn push_node_sync() {
let mut tree = BorrowTree::default();
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(2u32).into()), vec![]);
let context = TypingContext::default();
let future = tree.push_node(NodeId(0), val_1_protonode, &context);
futures::executor::block_on(future).unwrap();
let _node = tree.get(NodeId(0)).unwrap();
let result: Option<Item<u32>> = futures::executor::block_on(tree.eval(NodeId(0), ()));
assert_eq!(result.map(|item| *item.element()), Some(2_u32));
}
/// Builds a two-node network feeding the given value into Bounding Box, whose primary input registers both `Item<Vector>` and `List<Vector>` wire variants.
fn bounding_box_network(content: TaggedValue) -> ProtoNetwork {
let value_node = ProtoNode::value(ConstructionArgs::Value(content.into()), vec![NodeId(0)]);
let mut bounding_box_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
bounding_box_node.identifier = ProtoNodeIdentifier::new("core_types::vector::BoundingBoxNode");
ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), value_node), (NodeId(1), bounding_box_node)],
}
}
fn compile_bounding_box_network(content: TaggedValue) -> BorrowTree {
let network = bounding_box_network(content);
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("The network should resolve against exactly one registered wire variant");
futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The resolved variant's constructor should instantiate")
}
#[test]
fn item_wire_variant_resolves_and_executes() {
let tree = compile_bounding_box_network(TaggedValue::TypeDefault(item!(Vector)));
let context: Context = None;
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context.clone()));
assert!(result.is_some(), "The Item wire variant should downcast and execute end-to-end");
let wrong_type: Option<List<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert!(wrong_type.is_none(), "An Item wire should not downcast as a List");
}
#[test]
fn item_wire_promotes_to_list_connector() {
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(item!(f64)).into()), vec![NodeId(0)]);
// Box Corners takes a `List<f64>` primary, so feeding it an `Item<f64>` wire exercises the singleton raise
let mut box_corners_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
box_corners_node.identifier = graphene_std::vector::generator_nodes::box_corners::IDENTIFIER;
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), value_node), (NodeId(1), box_corners_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An Item wire should resolve a List connector via promotion");
assert!(typing_context.promotions(NodeId(1)).is_some(), "The typing pass should record the promotion");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The promotion adapter should instantiate");
let context: Context = None;
let result: Option<Item<graphene_std::vector::misc::BoxCorners>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert!(result.is_some(), "The promoted wire should execute end-to-end");
}
// The layer content path: a rank-0 content wire enters Wrap Graphic's `List` connector by singleton raise, and the
// wrapped `Item<Graphic>` raises again at Extend's `List` connector, so layers accept rank-0 chains without new machinery
#[test]
fn rank_0_content_promotes_through_the_layer_coercion_path() {
let content_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(item!(Vector)).into()), vec![NodeId(0)]);
let mut wrap_graphic_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
wrap_graphic_node.identifier = ProtoNodeIdentifier::new("graphic_nodes::graphic::WrapGraphicNode");
let base_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(list!(graphene_std::Graphic)).into()), vec![NodeId(2)]);
let mut extend_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(2), NodeId(1)]), vec![NodeId(3)]);
extend_node.identifier = ProtoNodeIdentifier::new("graphic_nodes::graphic::ExtendNode");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![(NodeId(0), content_node), (NodeId(1), wrap_graphic_node), (NodeId(2), base_node), (NodeId(3), extend_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A rank-0 content wire should resolve the layer coercion path via promotion");
assert!(typing_context.promotions(NodeId(1)).is_some(), "The rank-0 content should be raised at Wrap Graphic's List connector");
assert!(typing_context.promotions(NodeId(3)).is_some(), "The wrapped Item<Graphic> should be raised at Extend's List connector");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The promotion adapters should instantiate");
let context: Context = None;
let result: Option<List<graphene_std::Graphic>> = futures::executor::block_on(tree.eval(NodeId(3), context));
let stack = result.expect("The layer coercion path should execute end-to-end");
assert_eq!(stack.len(), 1, "The rank-0 content should contribute exactly one graphic to the stack");
}
/// Builds a network feeding the given content plus an f64 distance value into Offset Points, whose distance input is ranked `Item<f64>`.
fn offset_points_network(content: TaggedValue) -> ProtoNetwork {
let content_node = ProtoNode::value(ConstructionArgs::Value(content.into()), vec![NodeId(0)]);
let distance_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(10.).into()), vec![NodeId(1)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
let mut offset_points_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2)]), vec![NodeId(3)]);
offset_points_node.identifier = ProtoNodeIdentifier::new("core_types::vector::OffsetPointsNode");
ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![(NodeId(0), content_node), (NodeId(1), distance_node), (NodeId(2), input_adapter_node), (NodeId(3), offset_points_node)],
}
}
#[test]
fn mixed_rank_connectors_resolve_via_promotion() {
let network = offset_points_network(TaggedValue::TypeDefault(list!(Vector)));
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context
.update(&network)
.expect("A List primary with an Item parameter should resolve the mapped variant via promotion");
assert!(typing_context.promotions(NodeId(3)).is_some(), "The Item distance should be marked for promotion");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("Construction should wrap the promoted argument");
let context: Context = None;
let result: Option<List<Vector>> = futures::executor::block_on(tree.eval(NodeId(3), context));
assert!(result.is_some(), "The zipped mapped variant should execute end-to-end");
}
#[test]
fn all_item_connectors_resolve_without_promotion() {
let network = offset_points_network(TaggedValue::TypeDefault(item!(Vector)));
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("All-Item connectors should resolve the rank-0 variant exactly");
assert!(typing_context.promotions(NodeId(3)).is_none(), "No promotion should be needed at rank 0");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The rank-0 variant should instantiate");
let context: Context = None;
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(NodeId(3), context));
assert!(result.is_some(), "The rank-0 variant should execute and stay rank 0");
}
/// Builds a Transform network: content (node 0) plus four parameter values, each promoted onto Item wires as the preprocessor would.
fn transform_network(content: TaggedValue, rotation: TaggedValue) -> ProtoNetwork {
let mut nodes = vec![(NodeId(0), ProtoNode::value(ConstructionArgs::Value(content.into()), vec![NodeId(0)]))];
let parameters = [
(TaggedValue::DVec2(glam::DVec2::new(5., 0.)), "DVec2"),
(rotation, "f64"),
(TaggedValue::DVec2(glam::DVec2::ONE), "DVec2"),
(TaggedValue::DVec2(glam::DVec2::ZERO), "DVec2"),
];
let mut transform_inputs = vec![NodeId(0)];
let mut next_id = 1;
for (value, element) in parameters {
let value_id = NodeId(next_id);
let input_adapter_id = NodeId(next_id + 1);
next_id += 2;
nodes.push((value_id, ProtoNode::value(ConstructionArgs::Value(value.into()), vec![value_id])));
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![value_id]), vec![input_adapter_id]);
input_adapter_node.identifier = ProtoNodeIdentifier::with_owned_string(format!("input_adapter<{element}>"));
nodes.push((input_adapter_id, input_adapter_node));
transform_inputs.push(input_adapter_id);
}
let output = NodeId(next_id);
let mut transform_node = ProtoNode::value(ConstructionArgs::Nodes(transform_inputs), vec![output]);
transform_node.identifier = graphene_std::transform_nodes::transform::IDENTIFIER;
nodes.push((output, transform_node));
ProtoNetwork { inputs: vec![], output, nodes }
}
#[test]
fn transform_composes_onto_item_wire() {
use glam::{DAffine2, DVec2};
let network = transform_network(TaggedValue::TypeDefault(item!(Vector)), TaggedValue::F64(0.));
let output = network.output;
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("Transform should resolve its rank-0 variant");
assert!(typing_context.promotions(output).is_none(), "All-Item connectors should need no promotion");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("Transform's rank-0 variant should instantiate");
let context: Context = None;
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(output, context));
let item = result.expect("A rank-0 chain through Transform should stay rank 0");
let transform = item.attribute_cloned_or_default::<DAffine2>(core_types::ATTR_TRANSFORM);
assert_eq!(transform.translation, DVec2::new(5., 0.), "The translation should compose onto the item's transform attribute");
}
#[test]
fn transform_broadcasts_item_content_across_a_framed_parameter() {
use glam::DAffine2;
let network = transform_network(TaggedValue::TypeDefault(item!(Vector)), TaggedValue::F64Array(vec![0., 90.]));
let output = network.output;
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context
.update(&network)
.expect("A framed rotation should resolve the mapped variant via promotion of the other connectors");
assert!(typing_context.promotions(output).is_some(), "The Item-typed connectors should be raised into the frame");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The mapped variant should instantiate");
let context: Context = None;
let result: Option<List<Vector>> = futures::executor::block_on(tree.eval(output, context));
let list = result.expect("The broadcast should produce a List");
assert_eq!(list.len(), 2, "One output item per frame slot");
let first: DAffine2 = list.attribute_cloned_or_default(core_types::ATTR_TRANSFORM, 0);
let second: DAffine2 = list.attribute_cloned_or_default(core_types::ATTR_TRANSFORM, 1);
assert!((first.matrix2.col(0).y - 0.).abs() < 1e-10, "Slot 0 should be unrotated");
assert!((second.matrix2.col(0).y - 1.).abs() < 1e-10, "Slot 1 should be rotated 90 degrees");
}
#[test]
fn generator_frames_over_a_list_parameter() {
// A `()` generator (Circle) fed a `List<f64>` radius should frame into one circle per slot
let primary = ProtoNode::value(ConstructionArgs::Value(TaggedValue::None.into()), vec![NodeId(0)]);
let radii = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![10., 20., 30.]).into()), vec![NodeId(1)]);
let mut radius_adapter = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
radius_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
let mut circle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2)]), vec![NodeId(3)]);
circle_node.identifier = graphene_std::vector_nodes::circle::IDENTIFIER;
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![(NodeId(0), primary), (NodeId(1), radii), (NodeId(2), radius_adapter), (NodeId(3), circle_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A List<f64> radius should resolve Circle's mapped generator variant");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The mapped generator variant should instantiate");
let context: Context = None;
let result: Option<List<Vector>> = futures::executor::block_on(tree.eval(NodeId(3), context));
let list = result.expect("The generator frame should produce a List<Vector>");
assert_eq!(list.len(), 3, "One circle per radius slot");
}
/// Builds the compiler's cache chain (child, then Memoize, then Context Modification) around a value, as `insert_context_nullification_node` does.
fn nullification_chain_network(value: TaggedValue) -> ProtoNetwork {
let value_node = ProtoNode::value(ConstructionArgs::Value(value.into()), vec![NodeId(0)]);
let mut memoize_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
memoize_node.identifier = graphene_core::memo::memoize::IDENTIFIER;
let features_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::ContextFeatures(Default::default()).into()), vec![NodeId(2)]);
let mut nullification_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1), NodeId(2)]), vec![NodeId(3)]);
nullification_node.identifier = graphene_core::context_modification::context_modification::IDENTIFIER;
ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![(NodeId(0), value_node), (NodeId(1), memoize_node), (NodeId(2), features_node), (NodeId(3), nullification_node)],
}
}
#[test]
fn the_nullification_chain_resolves_for_ranked_enum_wires() {
use graphene_std::vector::style::StrokeAlign;
// The Item form, as a wrapped input adapter's output presents to the chain
let network = nullification_chain_network(TaggedValue::TypeDefault(item!(StrokeAlign)));
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An Item<StrokeAlign> wire should resolve through the compiler's cache chain");
// The List form, as a whole-list enum wire presents to the chain
let network = nullification_chain_network(TaggedValue::TypeDefault(list!(StrokeAlign)));
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A List<StrokeAlign> wire should resolve through the compiler's cache chain");
}
#[test]
fn value_wires_materialize_as_items_at_resolution() {
use glam::{DAffine2, DVec2};
let values = [
TaggedValue::DAffine2(DAffine2::IDENTITY),
TaggedValue::DVec2(DVec2::new(7., 0.)),
TaggedValue::F64(0.),
TaggedValue::DVec2(DVec2::ONE),
TaggedValue::DVec2(DVec2::ZERO),
];
let mut nodes: Vec<_> = values
.into_iter()
.enumerate()
.map(|(index, value)| (NodeId(index as u64), ProtoNode::value(ConstructionArgs::Value(value.into()), vec![NodeId(index as u64)])))
.collect();
let mut transform_node = ProtoNode::value(ConstructionArgs::Nodes((0..5).map(NodeId).collect()), vec![NodeId(5)]);
transform_node.identifier = graphene_std::transform_nodes::transform::IDENTIFIER;
nodes.push((NodeId(5), transform_node));
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(5),
nodes,
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("Value wires should materialize as Items and resolve the all-Item variant");
assert!(typing_context.promotions(NodeId(5)).is_none(), "Already-Item value wires should need no promotion");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The all-Item variant should instantiate");
let context: Context = None;
let result: Option<Item<DAffine2>> = futures::executor::block_on(tree.eval(NodeId(5), context));
let item = result.expect("A value matrix should flow through Transform as an Item");
let transform = item.attribute_cloned_or_default::<DAffine2>(core_types::ATTR_TRANSFORM);
assert_eq!(transform.translation, DVec2::new(7., 0.), "The translation should compose onto the gained transform attribute");
}
// A position's Item wire converts through the vector input adapter into a single-anchor path, which the ItemToList promotion can then raise at a List connector
#[test]
fn position_value_converts_through_the_vector_input_adapter() {
let position_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::DVec2(glam::DVec2::new(3., 4.)).into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<Vector>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), position_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An Item<DVec2> wire should resolve the adapter's element conversion row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The conversion constructor should instantiate");
let context: Context = None;
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert!(result.is_some(), "The position should arrive as an Item<Vector> single-anchor path");
}
// A `List` wire feeding a `ListDyn` connector erases its element type through the input adapter's `Into` row
#[test]
fn list_wire_erases_through_the_list_dyn_input_adapter() {
use core_types::list::ListDyn;
let list_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![1., 2., 3.]).into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<ListDyn>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), list_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A List<f64> wire should resolve the ListDyn erasure row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The erasure constructor should instantiate");
let context: Context = None;
let result: Option<ListDyn> = futures::executor::block_on(tree.eval(NodeId(1), context));
let erased = result.expect("The erased list should arrive as a ListDyn");
assert_eq!(erased.len(), 3, "The erased list should keep its row count");
}
#[test]
fn value_wire_passes_through_the_input_adapter_as_item() {
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(3.).into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), value_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An f64 value's Item wire should resolve the adapter's passthrough row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The passthrough constructor should instantiate");
let context: Context = None;
let result: Option<Item<f64>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert_eq!(result.map(|item| *item.element()), Some(3.), "The value should arrive as an Item");
}
// Path Modify's ranked modification parameter: a `Box<VectorModification>` value rides the `Item` wire through its input adapter,
// exercising the nested-generic identifier round-trip between the registered `stringify!` name and the preprocessor's simplified name
#[test]
fn modification_value_rides_the_item_wire_through_its_input_adapter() {
use graphene_std::vector::VectorModification;
let modification = TaggedValue::VectorModification(Default::default());
let value_node = ProtoNode::value(ConstructionArgs::Value(modification.into()), vec![NodeId(0)]);
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<Box<VectorModification>>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), value_node), (NodeId(1), input_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A modification value's Item wire should resolve the adapter's passthrough row");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The passthrough constructor should instantiate");
let context: Context = None;
let result: Option<Item<Box<VectorModification>>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert!(result.is_some(), "The modification should arrive as an Item");
}
// The Write Attribute value input: a value's Item wire boxes its element into a type-erased attribute value through the input adapter
#[test]
fn item_wire_boxes_into_the_attribute_value_connector() {
use graphene_std::list::AttributeValueDyn;
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(3.).into()), vec![NodeId(0)]);
let mut attribute_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
attribute_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<AttributeValueDyn>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), value_node), (NodeId(1), attribute_adapter_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("An Item<f64> wire should resolve the attribute value boxing row");
assert!(typing_context.promotions(NodeId(1)).is_none(), "The already-Item value wire should need no promotion");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The boxing constructor should instantiate");
let context: Context = None;
let result: Option<Item<AttributeValueDyn>> = futures::executor::block_on(tree.eval(NodeId(1), context));
let boxed = result.expect("The boxed attribute value should arrive as an Item");
assert_eq!(
boxed.element().0.as_any().downcast_ref::<f64>(),
Some(&3.),
"The stored value should be the bare element, not the whole Item"
);
}
#[test]
fn list_wire_variant_resolves_and_executes() {
let tree = compile_bounding_box_network(TaggedValue::TypeDefault(list!(Vector)));
let context: Context = None;
let result: Option<List<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context.clone()));
assert!(result.is_some(), "The mapped List wire variant should downcast and execute end-to-end");
let wrong_type: Option<Item<Vector>> = futures::executor::block_on(tree.eval(NodeId(1), context));
assert!(wrong_type.is_none(), "A List wire should not downcast as an Item");
}
#[test]
fn expander_flattens_under_the_frame() {
// A string value's Item wire feeds String Split's expander primary; its parameters ride Item wires through their input adapters
let string_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::String("a,b".into()).into()), vec![NodeId(0)]);
let delimiter_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(",".into()).into()), vec![NodeId(1)]);
let mut delimiter_input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
delimiter_input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<String>");
let escaping_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(false).into()), vec![NodeId(3)]);
let mut escaping_input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(3)]), vec![NodeId(4)]);
escaping_input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<bool>");
let output = NodeId(5);
let mut string_split_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(2), NodeId(4)]), vec![output]);
string_split_node.identifier = graphene_std::text_nodes::string_split::IDENTIFIER;
let network = ProtoNetwork {
inputs: vec![],
output,
nodes: vec![
(NodeId(0), string_node),
(NodeId(1), delimiter_node),
(NodeId(2), delimiter_input_adapter_node),
(NodeId(3), escaping_node),
(NodeId(4), escaping_input_adapter_node),
(output, string_split_node),
],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context
.update(&network)
.expect("All-Item connectors should resolve the expander's direct `Item -> List` variant");
assert!(typing_context.promotions(output).is_none(), "No promotion should be needed when every connector is already an Item");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The expander variant should instantiate");
let context: Context = None;
let result: Option<List<String>> = futures::executor::block_on(tree.eval(output, context));
let list = result.expect("An Item-wired expander should produce a List");
assert_eq!(list.len(), 2, "Splitting \"a,b\" on the comma should expand into two rows");
let substrings: Vec<_> = list.iter_element_values().map(|s| s.as_str()).collect();
assert_eq!(substrings, ["a", "b"], "The rows should hold the split substrings");
}
#[test]
fn whole_list_switches_as_one_bundle() {
// One bool selecting between two whole `List<f64>` stacks: each branch bundles into a rank-0 cell, and the result unbundles back to the flat stack
let condition_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(true).into()), vec![NodeId(0)]);
let if_true_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![1., 2., 3.]).into()), vec![NodeId(1)]);
let if_false_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![4., 5.]).into()), vec![NodeId(2)]);
let mut switch_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(1), NodeId(2)]), vec![NodeId(3)]);
switch_node.identifier = ProtoNodeIdentifier::new("math_nodes::SwitchNode");
let mut unbundle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(3)]), vec![NodeId(4)]);
unbundle_node.identifier = ProtoNodeIdentifier::new("graphene_core::ops::UnbundleNode<f64>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(4),
nodes: vec![
(NodeId(0), condition_node),
(NodeId(1), if_true_node),
(NodeId(2), if_false_node),
(NodeId(3), switch_node),
(NodeId(4), unbundle_node),
],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context
.update(&network)
.expect("A List<f64> branch should resolve the Item<Bundle<f64>> row via the bundle wrap");
let promotions = typing_context.promotions(NodeId(3)).expect("The condition wrap and both branch bundles should be recorded");
let branch_bundles = promotions
.iter()
.filter(|(index, adapter)| *index != 0 && matches!(adapter, graph_craft::proto::Promotion::Bundle(_)))
.count();
assert_eq!(branch_bundles, 2, "Both branches should bundle their whole list into one opaque cell");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The bundle, wrap, and unbundle adapters should instantiate");
let context: Context = None;
let result: Option<List<f64>> = futures::executor::block_on(tree.eval(NodeId(4), context));
let list = result.expect("The whole stack should round-trip through the bundle switch back to a flat List<f64>");
let values: Vec<f64> = list.iter_element_values().copied().collect();
assert_eq!(values, [1., 2., 3.], "The taken branch's whole list should come through unchanged");
}
#[test]
fn a_bundle_unbundles_into_a_list_connector() {
// A bundled wire (sourced here from a BundleNode, as a Switch branch produces one) feeding Extend's whole-`List` base connector
let stack_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(list!(graphene_std::Graphic)).into()), vec![NodeId(0)]);
let mut bundle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
bundle_node.identifier = ProtoNodeIdentifier::new("graphene_core::ops::BundleNode<Graphic>");
let new_layers_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(list!(graphene_std::Graphic)).into()), vec![NodeId(2)]);
let mut extend_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1), NodeId(2)]), vec![NodeId(3)]);
extend_node.identifier = ProtoNodeIdentifier::new("graphic_nodes::graphic::ExtendNode");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![(NodeId(0), stack_node), (NodeId(1), bundle_node), (NodeId(2), new_layers_node), (NodeId(3), extend_node)],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context.update(&network).expect("A bundled wire should feed Extend's List<Graphic> connector via the unbundle");
let promotions = typing_context.promotions(NodeId(3)).expect("Extend's bundled base should be marked for unbundling");
assert!(
promotions.iter().any(|(index, adapter)| *index == 0 && matches!(adapter, graph_craft::proto::Promotion::Unbundle(_))),
"The base connector should unbundle the whole list"
);
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The unbundle adapter should instantiate");
let context: Context = None;
let result: Option<List<graphene_std::Graphic>> = futures::executor::block_on(tree.eval(NodeId(3), context));
assert!(result.is_some(), "The unbundled stack should flow into Extend as a List<Graphic>");
}
#[test]
fn a_whole_list_of_scalars_switches_as_one_bundle() {
// A single bool selecting between two whole `List<f64>` values, covering a primitive element type and confirming the selected list survives intact
let condition_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(true).into()), vec![NodeId(0)]);
let if_true_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![1., 2.]).into()), vec![NodeId(1)]);
let if_false_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![3., 4., 5.]).into()), vec![NodeId(2)]);
let mut switch_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(1), NodeId(2)]), vec![NodeId(3)]);
switch_node.identifier = ProtoNodeIdentifier::new("math_nodes::SwitchNode");
let mut unbundle_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(3)]), vec![NodeId(4)]);
unbundle_node.identifier = ProtoNodeIdentifier::new("graphene_core::ops::UnbundleNode<f64>");
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(4),
nodes: vec![
(NodeId(0), condition_node),
(NodeId(1), if_true_node),
(NodeId(2), if_false_node),
(NodeId(3), switch_node),
(NodeId(4), unbundle_node),
],
};
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
typing_context
.update(&network)
.expect("A List<f64> branch should resolve the Item<Bundle<f64>> row via the bundle wrap");
let promotions = typing_context.promotions(NodeId(3)).expect("The condition wrap and both branch bundles should be recorded");
let branch_bundles = promotions
.iter()
.filter(|(index, adapter)| *index != 0 && matches!(adapter, graph_craft::proto::Promotion::Bundle(_)))
.count();
assert_eq!(branch_bundles, 2, "Both scalar-list branches should bundle into one opaque cell");
let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The bundle, wrap, and unbundle adapters should instantiate");
let context: Context = None;
let result: Option<List<f64>> = futures::executor::block_on(tree.eval(NodeId(4), context));
let list = result.expect("The whole scalar list should round-trip through the bundle switch");
assert_eq!(list.len(), 2, "The true branch's whole list should be selected and preserved intact");
}

View File

@@ -191,10 +191,12 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
// This might be caused by the stringify! macro
let mut new_name = id.as_str().replace('\n', " ");
// Remove struct generics for all nodes except for the IntoNode and ConvertNode
if !(new_name.contains("IntoNode") || new_name.contains("ConvertNode"))
&& let Some((path, _generics)) = new_name.split_once("<")
{
// Remove struct generics for all nodes except the adapter identifiers, whose element suffix distinguishes their rows
let element_suffixed_adapter = new_name.starts_with("input_adapter<")
|| new_name.starts_with("graphene_core::ops::ItemToListNode<")
|| new_name.starts_with("graphene_core::ops::BundleNode<")
|| new_name.starts_with("graphene_core::ops::UnbundleNode<");
if !element_suffixed_adapter && let Some((path, _generics)) = new_name.split_once("<") {
new_name = path.to_string();
}

View File

@@ -1,8 +1,8 @@
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
use graph_craft::generic;
use graph_craft::{concrete, item};
use graphene_std::Context;
use graphene_std::ContextFeatures;
use graphene_std::uuid::NodeId;
@@ -72,7 +72,7 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
call_argument: concrete!(Context),
inputs: vec![NodeInput::node(NodeId(4), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
// We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
// INDEX is never read; it forces a nullification and cache pair onto the `data` parameter's wire so the render cache keys on a stable context
context_features: graphene_std::ContextDependencies::new(
ContextFeatures::INDEX | ContextFeatures::VARARGS,
ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,

View File

@@ -16,7 +16,7 @@ wgpu = ["dep:raster-types", "raster-types/wgpu"]
# Local dependencies
dyn-any = { workspace = true }
core-types = { workspace = true }
graphene-hash = { workspace = true }
graphene-hash = { workspace = true, features = ["derive"] }
vector-types = { workspace = true }
text-nodes = { workspace = true }
graphene-resource = { workspace = true }

View File

@@ -1,6 +1,8 @@
use core_types::transform::Footprint;
use core_types::{Context, OwnedContextImpl};
use dyn_any::{DynAny, StaticType, StaticTypeSized};
use glam::DVec2;
use graphene_hash::CacheHash;
use std::fmt::Debug;
use std::hash::{Hash, Hasher};
use std::ptr::addr_of;
@@ -61,7 +63,7 @@ pub trait GetEditorPreferences {
fn max_render_region_area(&self) -> u32;
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, graphene_hash::CacheHash)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, CacheHash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ExportFormat {
#[default]
@@ -69,14 +71,14 @@ pub enum ExportFormat {
Raster,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, graphene_hash::CacheHash)]
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, CacheHash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TimingInformation {
pub time: f64,
pub animation_time: Duration,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, graphene_hash::CacheHash)]
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, CacheHash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RenderConfig {
pub viewport: Footprint,
@@ -90,6 +92,13 @@ pub struct RenderConfig {
pub for_eyedropper: bool,
}
impl RenderConfig {
/// Wraps this render configuration as the sole vararg of a fresh context, the call argument of a compiled network's boundary node.
pub fn into_context(self) -> Context<'static> {
OwnedContextImpl::default().with_vararg(Box::new(self)).into_context()
}
}
struct Logger;
impl NodeGraphUpdateSender for Logger {
@@ -136,7 +145,7 @@ impl<Io> Hash for EditorApi<Io> {
}
}
impl<Io> core_types::graphene_hash::CacheHash for EditorApi<Io> {
impl<Io> CacheHash for EditorApi<Io> {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
core::hash::Hash::hash(self, state);
}

View File

@@ -16,7 +16,7 @@ pub trait BoundingBox {
/// Returns the bounding box to use when sizing this value's thumbnail in the Layers panel.
///
/// Diverges from `bounding_box` for types where the rendering bounds wouldn't make a useful thumbnail frame.
/// For instance, `GradientStops` is `Infinite` for rendering but returns the line's AABB here, so a `List<Graphic>`
/// For instance, `Gradient` is `Infinite` for rendering but returns the line's AABB here, so a `List<Graphic>`
/// group of a gradient and a vector frames around the vector's geometry rather than infinity.
/// Types with no meaningful contribution (e.g., `Color`) return `Infinite` from both; the runtime substitutes a
/// small fallback rectangle at the end if no finite bounds remain after combining.

View File

@@ -61,6 +61,27 @@ impl Clampable for DVec2 {
}
}
// Implement for ranked wires (element-wise clamping across the frame)
use crate::list::{Item, List};
impl<T: Clampable> Clampable for Item<T> {
fn clamp_hard_min(self, min: f64) -> Self {
let (element, attributes) = self.into_parts();
Item::from_parts(element.clamp_hard_min(min), attributes)
}
fn clamp_hard_max(self, max: f64) -> Self {
let (element, attributes) = self.into_parts();
Item::from_parts(element.clamp_hard_max(max), attributes)
}
}
impl<T: Clampable> Clampable for List<T> {
fn clamp_hard_min(self, min: f64) -> Self {
self.into_iter().map(|item| item.clamp_hard_min(min)).collect()
}
fn clamp_hard_max(self, max: f64) -> Self {
self.into_iter().map(|item| item.clamp_hard_max(max)).collect()
}
}
#[cfg(feature = "serde")]
#[derive(serde::Deserialize)]
struct LegacyTable<T> {
@@ -69,7 +90,7 @@ struct LegacyTable<T> {
}
// TODO: Eventually remove this migration document upgrade code
pub fn migrate_to_optional_color<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<no_std_types::color::Color>, D::Error> {
pub fn migrate_to_color<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<no_std_types::color::Color, D::Error> {
use no_std_types::color::Color;
use serde::Deserialize;
@@ -81,8 +102,8 @@ pub fn migrate_to_optional_color<'de, D: serde::Deserializer<'de>>(deserializer:
}
Ok(match ColorFormat::deserialize(deserializer)? {
ColorFormat::OptionalColor(color) => color,
ColorFormat::List(list) => list.element.into_iter().next(),
ColorFormat::OptionalColor(color) => color.unwrap_or(Color::TRANSPARENT),
ColorFormat::List(list) => list.element.into_iter().next().unwrap_or(Color::TRANSPARENT),
})
}

View File

@@ -217,6 +217,23 @@ impl From<()> for Footprint {
}
}
/// Consumes an item's `transform` attribute by baking it into the underlying value itself.
pub trait BakeTransform {
fn bake_transform(&mut self, transform: &DAffine2);
}
impl BakeTransform for DAffine2 {
fn bake_transform(&mut self, transform: &DAffine2) {
*self = *transform * *self;
}
}
impl BakeTransform for DVec2 {
fn bake_transform(&mut self, transform: &DAffine2) {
*self = transform.transform_point2(*self);
}
}
pub trait ApplyTransform {
fn apply_transform(&mut self, modification: &DAffine2);
fn left_apply_transform(&mut self, modification: &DAffine2);

View File

@@ -57,6 +57,7 @@ impl_via_hash! {
bool, char,
u8, u16, u32, u64, u128, usize,
i8, i16, i32, i64, i128, isize,
core::time::Duration,
// glam integer vector types have Hash
glam::UVec2, glam::UVec3, glam::UVec4,
glam::IVec2, glam::IVec3, glam::IVec4,

View File

@@ -23,11 +23,11 @@ pub mod migrations {
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
use vector_types::vector::{PointDomain, RegionDomain, SegmentDomain, misc::HandleId, style::Stroke};
use vector_types::{GradientStops, Vector, vector};
use vector_types::{Gradient, Vector, vector};
#[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
pub struct Gradient {
pub stops: GradientStops,
pub struct LegacyGradient {
pub stops: Gradient,
pub gradient_type: vector::style::GradientType,
pub start: DVec2,
pub end: DVec2,
@@ -39,11 +39,11 @@ pub mod migrations {
pub transform: DAffine2,
}
impl Gradient {
impl LegacyGradient {
/// Converts a legacy bounding-box-relative gradient (`start`/`end` in [0,1]) into an absolute one in the geometry's local space.
/// `bounding_box` maps [0,1] onto the geometry's bounding box; `layer_transform` is the layer's own transform,
/// used to bake the elliptical adjustment that reproduces the legacy isotropic radial through a non-uniform layer.
pub fn to_absolute(&self, bounding_box: DAffine2, layer_transform: DAffine2) -> Gradient {
pub fn to_absolute(&self, bounding_box: DAffine2, layer_transform: DAffine2) -> LegacyGradient {
let start = bounding_box.transform_point2(self.start);
let end = bounding_box.transform_point2(self.end);
let direction = end - start;
@@ -66,7 +66,7 @@ pub mod migrations {
DAffine2::IDENTITY
};
Gradient {
LegacyGradient {
start,
end,
transform,
@@ -83,15 +83,15 @@ pub mod migrations {
}
#[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
pub enum Fill {
pub enum LegacyFill {
#[default]
None,
Solid(Color),
Gradient(Gradient),
Gradient(LegacyGradient),
}
/// The legacy `fill` field is intentionally omitted because vector payload migration only
/// recovers editable vector data. The fill/stroke paints are migrated from the the node inputs.
/// recovers editable vector data. The fill/stroke paints are migrated from the node inputs.
#[derive(serde::Deserialize)]
#[cfg_attr(test, derive(Default, serde::Serialize))]
pub(super) struct PathStyle {
@@ -165,7 +165,7 @@ pub mod migrations {
.unwrap()
.as_object_mut()
.unwrap()
.insert("fill".into(), serde_json::to_value(legacy::Fill::default()).unwrap());
.insert("fill".into(), serde_json::to_value(legacy::LegacyFill::default()).unwrap());
let migrated = migrate_to_optional_vector(value).unwrap().unwrap();
assert_eq!(migrated.stroke.unwrap().weight, 12.);

View File

@@ -4,6 +4,7 @@ pub mod blending;
pub mod choice_type;
pub mod color;
pub mod context;
pub mod list;
pub mod registry;
pub mod shaders;

View File

@@ -0,0 +1,41 @@
//! A zero-cost stand-in for `core_types::list::Item` used when node kernels are compiled for the GPU.
//!
//! Shader node kernels compile twice: under `std` against the real attribute-carrying `Item`, and under
//! `no_std` (SPIR-V) against this transparent wrapper, imported as `Item`. Only the element-access surface is
//! provided, since rust-gpu cannot allocate and attributes have no per-pixel meaning; attribute use fails the
//! shader build. It is named distinctly from `Item` so a search for the canonical type finds only that one.
/// A rank-0 wire value holding a single element, mirroring the element-access API of the real `Item`.
#[repr(transparent)]
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct ShaderItem<T> {
element: T,
}
impl<T> ShaderItem<T> {
/// Constructs an item with the given element.
pub fn new_from_element(element: T) -> Self {
Self { element }
}
/// Returns a shared reference to this item's element.
pub fn element(&self) -> &T {
&self.element
}
/// Returns a mutable reference to this item's element.
pub fn element_mut(&mut self) -> &mut T {
&mut self.element
}
/// Consumes this item and returns the owned element.
pub fn into_element(self) -> T {
self.element
}
}
impl<T> From<T> for ShaderItem<T> {
fn from(element: T) -> Self {
Self::new_from_element(element)
}
}

View File

@@ -11,7 +11,7 @@ use graphic_types::vector_types::gradient::GradientType;
use graphic_types::vector_types::markers::{GradientType as GradientTypeAttr, SpreadMethod};
use graphic_types::vector_types::vector::style::{PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use std::fmt::Write;
use vector_types::GradientStops;
use vector_types::Gradient;
use vector_types::gradient::GradientSpreadMethod;
#[derive(Copy, Clone, PartialEq)]
@@ -83,7 +83,7 @@ impl RenderExt for List<Color> {
}
}
impl RenderExt for List<GradientStops> {
impl RenderExt for List<Gradient> {
type Output = u64;
/// Adds the gradient def through mutating the first argument, returning the gradient ID.

View File

@@ -552,6 +552,7 @@ pub trait Render: BoundingBox + RenderComplexity {
impl Render for Graphic<'_> {
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
match self {
Graphic::None => (),
Graphic::Graphic(list) => list.render_svg(render, render_params),
Graphic::Vector(vector) => render_vector_svg(&Single(vector), render, render_params),
Graphic::RasterCPU(raster) => render_raster_cpu_svg(&Single(raster), render, render_params),
@@ -565,6 +566,7 @@ impl Render for Graphic<'_> {
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) {
match self {
Graphic::None => (),
Graphic::Graphic(list) => list.render_to_vello(scene, transform, context, render_params),
Graphic::Vector(vector) => render_vector_vello(&Single(vector), scene, transform, context, render_params),
Graphic::RasterCPU(raster) => render_raster_cpu_vello(&Single(raster), scene, transform, render_params),
@@ -590,6 +592,7 @@ impl Render for Graphic<'_> {
fn contains_artboard(&self) -> bool {
match self {
Graphic::None => false,
Graphic::Graphic(list) => list.contains_artboard(),
_ => false,
}
@@ -597,6 +600,7 @@ impl Render for Graphic<'_> {
fn new_ids_from_hash(&mut self, reference: Option<NodeId>) {
match self {
Graphic::None => (),
Graphic::Graphic(list) => list.new_ids_from_hash(reference),
Graphic::Vector(vector) => vector.vector_new_ids_from_hash(reference.map(|id| id.0).unwrap_or_default()),
_ => (),

View File

@@ -17,10 +17,10 @@ pub enum GradientType {
// TODO: Someday we could switch this to a Box[T] to avoid over-allocation
/// A list of colors (linear, unassociated alpha) associated with positions (in the range 0 to 1) along a gradient.
///
/// Not exposed via Tsify; use [`GradientStopsUI`] at the JS boundary.
/// Not exposed via Tsify; use [`GradientUI`] at the JS boundary.
#[derive(Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct GradientStops {
pub struct Gradient {
/// The position of this stop, a factor from 0-1 along the length of the full gradient.
pub position: Vec<f64>,
/// The midpoint to the right of this stop, a factor from 0-1 along the distance to the next stop. The final stop's midpoint is ignored.
@@ -29,18 +29,18 @@ pub struct GradientStops {
pub color: Vec<Color>,
}
/// JS-boundary version of [`GradientStops`] where stop colors are [`SRGBA8`] byte triples instead of linear-light [`Color`].
/// JS-boundary version of [`Gradient`] where stop colors are [`SRGBA8`] byte triples instead of linear-light [`Color`].
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[derive(Debug, Clone, PartialEq, Default, DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GradientStopsUI {
pub struct GradientUI {
pub position: Vec<f64>,
pub midpoint: Vec<f64>,
pub color: Vec<SRGBA8>,
}
impl From<&GradientStops> for GradientStopsUI {
fn from(s: &GradientStops) -> Self {
impl From<&Gradient> for GradientUI {
fn from(s: &Gradient) -> Self {
Self {
position: s.position.clone(),
midpoint: s.midpoint.clone(),
@@ -49,8 +49,8 @@ impl From<&GradientStops> for GradientStopsUI {
}
}
impl From<&GradientStopsUI> for GradientStops {
fn from(s: &GradientStopsUI) -> Self {
impl From<&GradientUI> for Gradient {
fn from(s: &GradientUI) -> Self {
Self {
position: s.position.clone(),
midpoint: s.midpoint.clone(),
@@ -59,7 +59,7 @@ impl From<&GradientStopsUI> for GradientStops {
}
}
impl GradientStopsUI {
impl GradientUI {
/// CSS `linear-gradient(...)` string. Stops are emitted as `#rrggbbaa` hex (already gamma-encoded bytes).
pub fn to_css_linear_gradient(&self) -> String {
if self.position.len() <= 1 {
@@ -67,7 +67,7 @@ impl GradientStopsUI {
return format!("linear-gradient(to right, #{hex} 0%, #{hex} 100%)");
}
// Sample via the midpoint-aware subdivision used for SVG/Vello stops so browser interpolation matches
let stops: GradientStops = self.into();
let stops: Gradient = self.into();
let pieces = stops
.interpolated_samples()
.into_iter()
@@ -83,7 +83,7 @@ impl GradientStopsUI {
}
// TODO: Eventually remove this migration document upgrade code
impl<'de> serde::Deserialize<'de> for GradientStops {
impl<'de> serde::Deserialize<'de> for Gradient {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(serde::Deserialize)]
struct NewFormat {
@@ -117,7 +117,7 @@ impl<'de> serde::Deserialize<'de> for GradientStops {
}
}
impl Default for GradientStops {
impl Default for Gradient {
fn default() -> Self {
Self {
position: vec![0., 1.],
@@ -127,7 +127,7 @@ impl Default for GradientStops {
}
}
impl RenderComplexity for GradientStops {
impl RenderComplexity for Gradient {
fn render_complexity(&self) -> usize {
1
}
@@ -158,7 +158,7 @@ pub struct GradientStop {
}
pub struct GradientStopsIter<'a> {
stops: &'a GradientStops,
stops: &'a Gradient,
index: usize,
}
@@ -187,7 +187,7 @@ impl<'a> Iterator for GradientStopsIter<'a> {
impl ExactSizeIterator for GradientStopsIter<'_> {}
impl<'a> IntoIterator for &'a GradientStops {
impl<'a> IntoIterator for &'a Gradient {
type Item = GradientStop;
type IntoIter = GradientStopsIter<'a>;
@@ -196,7 +196,7 @@ impl<'a> IntoIterator for &'a GradientStops {
}
}
impl IntoIterator for GradientStops {
impl IntoIterator for Gradient {
type Item = GradientStop;
type IntoIter = std::vec::IntoIter<GradientStop>;
@@ -211,7 +211,7 @@ impl IntoIterator for GradientStops {
}
}
impl GradientStops {
impl Gradient {
pub fn new(stops: impl IntoIterator<Item = GradientStop>) -> Self {
let mut position = Vec::new();
let mut midpoint = Vec::new();
@@ -465,7 +465,7 @@ impl GradientStops {
let color = a.color.lerp(&b.color, time as f32);
GradientStop { position, midpoint: 0.5, color }
});
GradientStops::new(stops)
Gradient::new(stops)
}
}
@@ -540,19 +540,19 @@ pub fn initial_gradient_transform_for_bounding_box(bounds: [DVec2; 2]) -> DAffin
}
// TODO: Eventually remove this migration document upgrade code
pub fn migrate_to_gradient_stops<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<GradientStops, D::Error> {
pub fn migrate_to_gradient<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Gradient, D::Error> {
use serde::Deserialize;
#[derive(serde::Deserialize)]
struct LegacyTable {
#[serde(alias = "instances", alias = "instance")]
element: Vec<GradientStops>,
element: Vec<Gradient>,
}
#[derive(serde::Deserialize)]
#[cfg_attr(feature = "serde", serde(untagged))]
enum GradientStopsFormat {
Stops(GradientStops),
Stops(Gradient),
List(LegacyTable),
}
@@ -562,7 +562,7 @@ pub fn migrate_to_gradient_stops<'de, D: serde::Deserializer<'de>>(deserializer:
})
}
impl core_types::bounds::BoundingBox for GradientStops {
impl core_types::bounds::BoundingBox for Gradient {
fn bounding_box(&self, _transform: DAffine2, _include_stroke: bool) -> core_types::bounds::RenderBoundingBox {
core_types::bounds::RenderBoundingBox::Infinite
}

View File

@@ -9,7 +9,7 @@ pub mod vector;
// Re-export commonly used types at the crate root
pub use core_types as gcore;
pub use gradient::{GradientSpreadMethod, GradientStop, GradientStops, GradientType};
pub use gradient::{Gradient, GradientSpreadMethod, GradientStop, GradientType};
pub use markers::{ATTR_EDITOR_CLICK_TARGET, ATTR_GRADIENT_TYPE, ATTR_SPREAD_METHOD};
pub use math::{QuadExt, RectExt};
pub use subpath::Subpath;

View File

@@ -47,7 +47,7 @@ impl MergeByDistanceExt for Vector {
// Collect points and segments to delete at the end to avoid invalidating indices
let mut points_to_delete = FxHashSet::default();
let mut segments_to_delete = FxHashSet::default();
for (mut collapse_set, average_pos) in collapse.into_iter().zip(average_position.into_iter()) {
for (mut collapse_set, average_pos) in collapse.into_iter().zip(average_position) {
// Remove any segments where both endpoints are in the collapse set
segments_to_delete.extend(self.segment_domain.iter().filter_map(|(id, start_offset, end_offset, _)| {
let start = self.point_domain.ids()[start_offset];

View File

@@ -2,6 +2,7 @@ use super::PointId;
use super::algorithms::offset_subpath::MAX_ABSOLUTE_DIFFERENCE;
use crate::subpath::{BezierHandles, ManipulatorGroup};
use crate::vector::{SegmentId, Vector};
use core_types::list::{Item, List};
use dyn_any::DynAny;
use glam::DVec2;
use kurbo::{BezPath, CubicBez, Line, ParamCurve, ParamCurveDeriv, PathSeg, Point, QuadBez};
@@ -49,6 +50,77 @@ pub enum RowsOrColumns {
Columns,
}
/// A box's four corner values, such as a rectangle's corner radii, expanded on read from any number of stored
/// values by the CSS `border-radius` shorthand rules.
///
/// Wraps a `List<f64>` so the Data panel can introspect its values, mirroring how `DashPattern` wraps its lengths,
/// while remaining a single rank-0 value on the wire.
#[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny)]
pub struct BoxCorners(pub List<f64>);
impl BoxCorners {
/// Expands the stored values to the four corners, clockwise from the top-left, by the CSS `border-radius` shorthand rules.
/// - `[]` → `[0, 0, 0, 0]`
/// - `[a]` → `[a, a, a, a]`
/// - `[a, b]` → `[a, b, a, b]`
/// - `[a, b, c]` → `[a, b, c, b]`
/// - `[a, b, c, d, …]` → `[a, b, c, d]`
pub fn to_corner_values(&self) -> [f64; 4] {
let values: Vec<f64> = self.0.iter_element_values().copied().collect();
match values.as_slice() {
[] => [0., 0., 0., 0.],
&[a] => [a, a, a, a],
&[a, b] => [a, b, a, b],
&[a, b, c] => [a, b, c, b],
&[a, b, c, d, ..] => [a, b, c, d],
}
}
}
// `List<f64>` is a runtime-only wire type, so serialize the corners as their bare values to keep documents stable
#[cfg(feature = "serde")]
impl serde::Serialize for BoxCorners {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_seq(self.0.iter_element_values())
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for BoxCorners {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(Self::from(<Vec<f64> as serde::Deserialize>::deserialize(deserializer)?))
}
}
impl From<f64> for BoxCorners {
fn from(value: f64) -> Self {
Self(List::new_from_element(value))
}
}
impl From<Vec<f64>> for BoxCorners {
fn from(values: Vec<f64>) -> Self {
Self(values.into_iter().map(Item::new_from_element).collect())
}
}
impl From<&str> for BoxCorners {
fn from(text: &str) -> Self {
Self::from(
text.split([',', ' '])
.filter(|piece| !piece.is_empty())
.filter_map(|piece| piece.parse::<f64>().ok())
.collect::<Vec<f64>>(),
)
}
}
impl From<String> for BoxCorners {
fn from(text: String) -> Self {
Self::from(text.as_str())
}
}
pub trait AsU64 {
fn as_u64(&self) -> u64;
}

View File

@@ -3,14 +3,16 @@
pub use crate::gradient::*;
use core_types::Color;
use core_types::color::SRGBA8;
use core_types::list::{Item, List};
use core_types::transform::Transform;
use dyn_any::DynAny;
use glam::DAffine2;
use std::f64::consts::{PI, TAU};
/// Describes an editable fill choice, storing color or gradient stops without gradient placement metadata.
/// The editor's in-memory paint picker state, storing color or gradient stops without gradient placement metadata.
/// Not stored in documents: paint inputs hold the picked value as a plain color, gradient, or no-paint type default.
///
/// Can be None, a solid [Color], or a linear/radial [GradientStops].
/// Can be None, a solid [Color], or a linear/radial [Gradient].
///
/// In the future we'll probably also add a pattern fill.
///
@@ -22,11 +24,11 @@ pub enum FillChoice {
#[default]
None,
Solid(Color),
Gradient(GradientStops),
Gradient(Gradient),
}
// TODO: Deprecate [`FillChoice`] and keep this, renamed, as the main widget-controlling type
/// JS-boundary version of [`FillChoice`] where the solid color is [`SRGBA8`] and the gradient is [`GradientStopsUI`].
/// JS-boundary version of [`FillChoice`] where the solid color is [`SRGBA8`] and the gradient is [`GradientUI`].
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[derive(Default, Debug, Clone, PartialEq, DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@@ -34,7 +36,7 @@ pub enum FillChoiceUI {
#[default]
None,
Solid(SRGBA8),
Gradient(GradientStopsUI),
Gradient(GradientUI),
}
impl From<&FillChoice> for FillChoiceUI {
@@ -42,7 +44,7 @@ impl From<&FillChoice> for FillChoiceUI {
match value {
FillChoice::None => Self::None,
FillChoice::Solid(color) => Self::Solid(SRGBA8::from(*color)),
FillChoice::Gradient(stops) => Self::Gradient(GradientStopsUI::from(stops)),
FillChoice::Gradient(stops) => Self::Gradient(GradientUI::from(stops)),
}
}
}
@@ -52,7 +54,7 @@ impl From<&FillChoiceUI> for FillChoice {
match value {
FillChoiceUI::None => Self::None,
FillChoiceUI::Solid(srgba) => Self::Solid(Color::from(*srgba)),
FillChoiceUI::Gradient(stops) => Self::Gradient(GradientStops::from(stops)),
FillChoiceUI::Gradient(stops) => Self::Gradient(Gradient::from(stops)),
}
}
}
@@ -63,7 +65,7 @@ impl FillChoiceUI {
Some(*c)
}
pub fn as_gradient(&self) -> Option<&GradientStopsUI> {
pub fn as_gradient(&self) -> Option<&GradientUI> {
let Self::Gradient(g) = self else { return None };
Some(g)
}
@@ -88,7 +90,7 @@ impl FillChoice {
Some(*color)
}
pub fn as_gradient(&self) -> Option<&GradientStops> {
pub fn as_gradient(&self) -> Option<&Gradient> {
let Self::Gradient(gradient) = self else { return None };
Some(gradient)
}
@@ -201,6 +203,65 @@ fn daffine2_identity() -> DAffine2 {
DAffine2::IDENTITY
}
/// A stroke's dash pattern: a sequence of lengths that alternate dash, gap, dash, gap, and so on. An odd-length
/// sequence repeats with the dash and gap roles swapped.
///
/// Wraps a `List<f64>` so the Data panel can introspect its lengths, mirroring how `Artboard` wraps a `List<Graphic>`,
/// while remaining a single rank-0 value on the wire.
#[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny)]
pub struct DashPattern(pub List<f64>);
impl DashPattern {
/// Returns the dash lengths with any negative values clamped to zero.
pub fn clamped_lengths(&self) -> Vec<f64> {
self.0.iter_element_values().map(|length| length.max(0.)).collect()
}
}
// `List<f64>` is a runtime-only wire type, so serialize the pattern as its bare lengths to keep documents stable
#[cfg(feature = "serde")]
impl serde::Serialize for DashPattern {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_seq(self.0.iter_element_values())
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for DashPattern {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(Self::from(<Vec<f64> as serde::Deserialize>::deserialize(deserializer)?))
}
}
impl From<f64> for DashPattern {
fn from(length: f64) -> Self {
Self(List::new_from_element(length))
}
}
impl From<Vec<f64>> for DashPattern {
fn from(lengths: Vec<f64>) -> Self {
Self(lengths.into_iter().map(Item::new_from_element).collect())
}
}
impl From<&str> for DashPattern {
fn from(text: &str) -> Self {
Self::from(
text.split([',', ' '])
.filter(|piece| !piece.is_empty())
.filter_map(|piece| piece.parse::<f64>().ok())
.collect::<Vec<f64>>(),
)
}
}
impl From<String> for DashPattern {
fn from(text: String) -> Self {
Self::from(text.as_str())
}
}
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny)]

View File

@@ -63,11 +63,19 @@ impl core_types::ops::FromAnchorPosition for Vector {
}
}
// Identity item conversion so `List<Vector>` satisfies the blanket `Convert<List<U>, ()> for List<T>`, letting its
// auto-inserted input wrapper be a `ConvertNode` (which also accepts a `DVec2` anchor position) rather than an `IntoNode`.
impl core_types::ops::ListConvert<Vector> for Vector {
fn convert_item(self) -> Vector {
self
// Lets a position wire feed a ranked vector connector through the input adapter's element conversion
impl From<DVec2> for Vector {
fn from(position: DVec2) -> Self {
<Self as core_types::ops::FromAnchorPosition>::from_anchor_position(position)
}
}
impl core_types::transform::BakeTransform for Vector {
fn bake_transform(&mut self, transform: &glam::DAffine2) {
for (_, point) in self.point_domain.positions_mut() {
*point = transform.transform_point2(*point);
}
self.segment_domain.transform(*transform);
}
}

View File

@@ -1,6 +1,5 @@
use crate::WgpuExecutorHandle;
use core_types::Color;
use core_types::Ctx;
use core_types::color::SRGBA8;
use core_types::list::{Item, List};
use core_types::ops::{Convert, ConvertAsync};
@@ -21,7 +20,7 @@ fn upload_to_texture(device: &wgpu::Device, queue: &wgpu::Queue, image: &Raster<
device.create_texture_with_data(
queue,
&TextureDescriptor {
label: Some("upload_texture node texture"),
label: Some("upload_to_texture staging texture"),
size: Extent3d {
width: image.width,
height: image.height,
@@ -250,15 +249,3 @@ impl ConvertAsync<Raster<CPU>, WgpuExecutorHandle> for Raster<GPU> {
Box::pin(async move { converter.convert(&device).await.expect("Failed to download texture data") })
}
}
/// Uploads an raster texture from the CPU to the GPU. This is now deprecated and the Convert node should be used in the future.
///
/// Accepts either individual raster data or a `List` of raster elements and converts it to the GPU format using the WgpuExecutor's device and queue.
#[node_macro::node(category(""))]
pub fn upload_texture<T: Convert<List<Raster<GPU>>, WgpuExecutorHandle>>(
_: impl Ctx,
#[implementations(List<Raster<CPU>>, List<Raster<GPU>>)] input: T,
executor: WgpuExecutorHandle,
) -> List<Raster<GPU>> {
input.convert(Footprint::DEFAULT, executor)
}

View File

@@ -25,15 +25,15 @@ fn opacity<T>(
/// Whether the *Opacity* property is enabled, multiplying the existing opacity by the chosen percentage.
#[widget(ParsedWidgetOverride::Hidden)]
#[default(true)]
has_opacity: bool,
has_opacity: Item<bool>,
/// How visible the content should be, including any content clipped to it.
/// Ranges from the default of 100% (fully opaque) to 0% (fully transparent).
#[widget(ParsedWidgetOverride::Custom = "optional_percentage")]
#[default(100.)]
opacity: Percentage,
opacity: Item<Percentage>,
/// Whether the *Fill* property is enabled, multiplying the existing fill by the chosen percentage.
#[widget(ParsedWidgetOverride::Hidden)]
has_fill: bool,
has_fill: Item<bool>,
/// How visible the content should be, independent of any content clipped to it.
/// Ranges from 0% (fully transparent) to the default of 100% (fully opaque).
#[widget(ParsedWidgetOverride::Custom = "optional_percentage")]

View File

@@ -458,6 +458,7 @@ pub fn blend_stamp_closure(foreground: BrushStampGenerator<Color>, mut backgroun
#[cfg(test)]
mod test {
use super::*;
use crate::brush_stroke::BrushStroke;
use core_types::transform::Transform;
use glam::DAffine2;

View File

@@ -1,6 +1,7 @@
use core_types::CacheHash;
use core_types::blending::BlendMode;
use core_types::color::Color;
use core_types::list::{Item, List};
use core_types::math::bbox::AxisAlignedBbox;
use dyn_any::DynAny;
use glam::DVec2;
@@ -57,6 +58,22 @@ pub struct BrushStroke {
pub trace: Vec<BrushInputSample>,
}
/// One Brush layer's full sequence of strokes, treated as a single rank-0 value rather than a frame of independent strokes.
#[derive(Default, Debug, Clone, PartialEq, CacheHash, DynAny)]
pub struct BrushTrace(pub List<BrushStroke>);
impl From<List<BrushStroke>> for BrushTrace {
fn from(strokes: List<BrushStroke>) -> Self {
Self(strokes)
}
}
impl From<Vec<BrushStroke>> for BrushTrace {
fn from(strokes: Vec<BrushStroke>) -> Self {
Self(strokes.into_iter().map(Item::new_from_element).collect())
}
}
impl BrushStroke {
pub fn bounding_box(&self) -> AxisAlignedBbox {
let radius = self.style.diameter / 2.;

View File

@@ -1,9 +1,9 @@
use core_types::gpoll::GPoll;
use core_types::list::List;
use core_types::list::{Item, List};
use core_types::transform::Footprint;
use core_types::{CacheHash, Color, Context, Ctx, DeriveCtx, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime};
use glam::{DAffine2, DVec2};
use graphic_types::vector_types::GradientStops;
use graphic_types::vector_types::Gradient;
use graphic_types::{Artboard, Graphic, Vector};
use raster_types::{CPU, GPU, Raster};
@@ -34,19 +34,22 @@ fn real_time(
ctx: impl Ctx + ExtractRealTime,
_primary: (),
/// The time and date component to be produced as a number.
component: RealTimeMode,
) -> f64 {
component: Item<RealTimeMode>,
) -> Item<f64> {
let component = component.into_element();
let real_time = ctx.try_real_time().unwrap_or_default();
// TODO: Implement proper conversion using and existing time implementation
match component {
let result = match component {
RealTimeMode::Utc => real_time,
RealTimeMode::Year => (real_time / DAY / 365.25).floor() + 1970., // TODO: Factor in a chosen timezone
RealTimeMode::Hour => (real_time / 1000. / 3600.).floor() % 24., // TODO: Factor in a chosen timezone
RealTimeMode::Minute => (real_time / 1000. / 60.).floor() % 60., // TODO: Factor in a chosen timezone
RealTimeMode::Second => (real_time / 1000.).floor() % 60.,
RealTimeMode::Millisecond => real_time % 1000.,
}
};
Item::new_from_element(result)
}
/// Produces the time, in seconds on the timeline, since the beginning of animation playback.
@@ -56,42 +59,50 @@ fn animation_time(
_primary: (),
#[default(1)]
#[unit("/sec")]
rate: f64,
) -> f64 {
ctx.try_animation_time().unwrap_or_default() * rate
rate: Item<f64>,
) -> Item<f64> {
Item::new_from_element(ctx.try_animation_time().unwrap_or_default() * *rate.element())
}
#[node_macro::node(category("Debug"))]
fn quantize_real_time<T>(
ctx: impl Ctx + ExtractRealTime + DeriveCtx,
#[implementations(
Context -> bool,
Context -> u32,
Context -> u64,
Context -> f32,
Context -> f64,
Context -> String,
Context -> DAffine2,
Context -> Footprint,
Context -> DVec2,
Context -> Item<bool>,
Context -> Item<u32>,
Context -> Item<u64>,
Context -> Item<f32>,
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<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<Artboard>,
Context -> List<GradientStops>,
Context -> List<String>,
Context -> List<f64>,
Context -> (),
)]
value: impl Node<Context<'_>, Output = T>,
#[default(1)]
#[unit("sec")]
quantum: f64,
quantum: Item<f64>,
) -> GPoll<T> {
let time = ctx.try_real_time().unwrap_or_default();
let time = time / 1000.;
let quantum = quantum.into_element();
let mut quantized_time = (time * quantum.recip()).round() / quantum.recip();
if !quantized_time.is_finite() {
quantized_time = time;
@@ -105,32 +116,40 @@ fn quantize_real_time<T>(
fn quantize_animation_time<T>(
ctx: impl Ctx + ExtractAnimationTime + DeriveCtx,
#[implementations(
Context -> bool,
Context -> u32,
Context -> u64,
Context -> f32,
Context -> f64,
Context -> String,
Context -> DAffine2,
Context -> Footprint,
Context -> DVec2,
Context -> Item<bool>,
Context -> Item<u32>,
Context -> Item<u64>,
Context -> Item<f32>,
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<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<Artboard>,
Context -> List<GradientStops>,
Context -> List<String>,
Context -> List<f64>,
Context -> (),
)]
value: impl Node<Context<'_>, Output = T>,
#[default(1)]
#[unit("sec")]
quantum: f64,
quantum: Item<f64>,
) -> GPoll<T> {
let time = ctx.try_animation_time().unwrap_or_default();
let quantum = quantum.into_element();
let mut quantized_time = (time * quantum.recip()).round() / quantum.recip();
if !quantized_time.is_finite() {
quantized_time = time;
@@ -141,8 +160,8 @@ fn quantize_animation_time<T>(
/// Produces the current position of the user's pointer within the document canvas.
#[node_macro::node(category("Animation"))]
fn pointer_position(ctx: impl Ctx + ExtractPointerPosition) -> DVec2 {
ctx.try_pointer_position().unwrap_or_default()
fn pointer_position(ctx: impl Ctx + ExtractPointerPosition) -> Item<DVec2> {
Item::new_from_element(ctx.try_pointer_position().unwrap_or_default())
}
// TODO: These nodes require more sophisticated algorithms for giving the correct result

View File

@@ -1,14 +1,14 @@
use core_types::gpoll::{Extent, GPoll, GraphError, Interrupt};
use core_types::list::List;
use core_types::list::{Item, List};
use core_types::{Color, ExtractVarArgs};
use core_types::{Ctx, ExtractIndex, ExtractIndices, ExtractPosition};
use glam::DVec2;
use graphic_types::vector_types::GradientStops;
use graphic_types::vector_types::Gradient;
use graphic_types::{Graphic, Vector};
use raster_types::{CPU, Raster};
#[node_macro::node(category("Context"), path(graphene_core::vector))]
fn read_graphic(ctx: impl Ctx + ExtractVarArgs) -> List<Graphic<'static>> {
fn read_graphic(ctx: impl Ctx + ExtractVarArgs) -> Item<Graphic<'static>> {
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
let var_arg = var_arg as &dyn std::any::Any;
@@ -16,7 +16,7 @@ fn read_graphic(ctx: impl Ctx + ExtractVarArgs) -> List<Graphic<'static>> {
}
#[node_macro::node(category("Context"), path(graphene_core::vector))]
fn read_vector(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
fn read_vector(ctx: impl Ctx + ExtractVarArgs) -> Item<Vector> {
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
let var_arg = var_arg as &dyn std::any::Any;
@@ -24,7 +24,7 @@ fn read_vector(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
}
#[node_macro::node(category("Context"), path(graphene_core::vector))]
fn read_raster(ctx: impl Ctx + ExtractVarArgs) -> List<Raster<CPU>> {
fn read_raster(ctx: impl Ctx + ExtractVarArgs) -> Item<Raster<CPU>> {
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
let var_arg = var_arg as &dyn std::any::Any;
@@ -32,7 +32,7 @@ fn read_raster(ctx: impl Ctx + ExtractVarArgs) -> List<Raster<CPU>> {
}
#[node_macro::node(category("Context"), path(graphene_core::vector))]
fn read_color(ctx: impl Ctx + ExtractVarArgs) -> List<Color> {
fn read_color(ctx: impl Ctx + ExtractVarArgs) -> Item<Color> {
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
let var_arg = var_arg as &dyn std::any::Any;
@@ -40,7 +40,7 @@ fn read_color(ctx: impl Ctx + ExtractVarArgs) -> List<Color> {
}
#[node_macro::node(category("Context"), path(graphene_core::vector))]
fn read_gradient(ctx: impl Ctx + ExtractVarArgs) -> List<GradientStops> {
fn read_gradient(ctx: impl Ctx + ExtractVarArgs) -> Item<Gradient> {
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
let var_arg = var_arg as &dyn std::any::Any;
@@ -126,9 +126,10 @@ fn read_position(
/// The number of nested loops to traverse outwards (from the innermost loop) to get the position from. The most upstream loop is level 0, and downstream loops add levels.
///
/// In programming terms: inside the double loop `i { j { ... } }`, *Loop Level* 0 = `j` and 1 = `i`. After inserting a third loop `k { ... }`, inside it, levels would be 0 = `k`, 1 = `j`, and 2 = `i`.
loop_level: u32,
) -> DVec2 {
ctx.try_position().and_then(|mut iter| iter.nth(loop_level as usize).or_else(|| iter.last())).unwrap_or(DVec2::ZERO)
loop_level: Item<u32>,
) -> Item<DVec2> {
let loop_level = *loop_level.element();
Item::new_from_element(ctx.try_position().and_then(|mut iter| iter.nth(loop_level as usize).or_else(|| iter.last())).unwrap_or(DVec2::ZERO))
}
// TODO: Return u32, u64, or usize instead of f64 after #1621 is resolved and has allowed us to implement automatic type conversion in the node graph for nodes with generic type inputs.
@@ -145,9 +146,10 @@ fn read_index(
/// The number of nested loops to traverse outwards (from the innermost loop) to get the index from. The most upstream loop is level 0, and downstream loops add levels.
///
/// In programming terms: inside the double loop `i { j { ... } }`, *Loop Level* 0 = `j` and 1 = `i`. After inserting a third loop `k { ... }`, inside it, levels would be 0 = `k`, 1 = `j`, and 2 = `i`.
loop_level: u32,
) -> f64 {
loop_level: Item<u32>,
) -> Item<f64> {
let loop_level = *loop_level.element();
// The chain's innermost entry is the consuming input's own lane from the
// decompose-and-promote split; the loops the reader counts sit above it.
ctx.try_index().and_then(|mut iter| iter.nth(loop_level as usize + 1)).unwrap_or(0) as f64
Item::new_from_element(ctx.try_index().and_then(|mut iter| iter.nth(loop_level as usize + 1)).unwrap_or(0) as f64)
}

View File

@@ -1,35 +1,11 @@
use core_types::Ctx;
use core_types::list::Item;
use glam::{DAffine2, DVec2};
use raster_types::{CPU, Raster};
/// Meant for debugging purposes, not general use. Logs the input value to the console and passes it through unchanged.
#[node_macro::node(category("Debug"), name("Log to Console"))]
fn log_to_console<T: std::fmt::Debug>(_: impl Ctx, #[implementations(bool, f64, u32, u64, DVec2, DAffine2, String)] value: T) -> T {
fn log_to_console<T: std::fmt::Debug>(_: impl Ctx, #[implementations(bool, f64, u32, u64, DVec2, DAffine2, String)] value: Item<T>) -> Item<T> {
// KEEP THIS `debug!()` - It acts as the output for the debug node itself
log::debug!("{value:#?}");
value
}
/// Meant for debugging purposes, not general use. Returns the size of the input type in bytes.
#[node_macro::node(category("Debug"))]
fn size_of(_: impl Ctx, ty: core_types::Type) -> Option<usize> {
ty.size()
}
/// Meant for debugging purposes, not general use. Wraps the input value in the Some variant of an Option.
#[node_macro::node(category("Debug"))]
fn some<T>(_: impl Ctx, #[implementations(f64, f32, u32, u64, String)] input: T) -> Option<T> {
Some(input)
}
/// Meant for debugging purposes, not general use. Unwraps the input value from an Option, returning the default value if the input is None.
#[node_macro::node(category("Debug"))]
fn unwrap_option<T: Default>(_: impl Ctx, #[implementations(Option<f64>, Option<u32>, Option<u64>, Option<String>)] input: Option<T>) -> T {
input.unwrap_or_default()
}
/// Clones the element out of its record input.
#[node_macro::node(category("Debug"))]
fn clone<T: Clone>(_: impl Ctx, #[implementations(Raster<CPU>, f64)] value: &T) -> T {
value.clone()
}

View File

@@ -1,3 +1,4 @@
use core_types::list::Item;
use core_types::{CacheHash, Ctx};
use dyn_any::DynAny;
use glam::{DVec2, IVec2, UVec2};
@@ -6,11 +7,16 @@ use glam::{DVec2, IVec2, UVec2};
///
/// The inverse of this node is "Vec2 Value", which can have either or both its X and Y parameters exposed as graph inputs.
#[node_macro::node(name("Extract XY"), category("Math: Vector"))]
fn extract_xy<T: Into<DVec2>>(_: impl Ctx, #[implementations(DVec2, IVec2, UVec2)] vector: T, axis: XY) -> f64 {
match axis {
fn extract_xy<T: Into<DVec2>>(_: impl Ctx, #[implementations(DVec2, IVec2, UVec2)] vector: Item<T>, axis: Item<XY>) -> Item<f64> {
let vector = vector.into_element();
let axis = axis.into_element();
let result = match axis {
XY::X => vector.into().x,
XY::Y => vector.into().y,
}
};
Item::new_from_element(result)
}
/// The X or Y component of a vec2.

View File

@@ -58,7 +58,7 @@ pub mod subpath {
}
pub mod gradient {
pub use vector_types::{GradientStop, GradientStops};
pub use vector_types::{Gradient, GradientStop};
}
pub mod transform {

View File

@@ -6,11 +6,13 @@ use canvas_utils::{Canvas, CanvasHandle};
use core_types::attribute::{Attr, OwnedAttr, Transform};
use core_types::color::SRGBA8;
use core_types::gpoll::GPoll;
use core_types::list::Item;
#[cfg(target_family = "wasm")]
use core_types::list::List;
#[cfg(target_family = "wasm")]
use core_types::math::bbox::Bbox;
use core_types::ops::Convert;
use core_types::runtime::SourceFuture;
#[cfg(target_family = "wasm")]
use core_types::transform::Footprint;
@@ -31,12 +33,11 @@ use graphic_types::Vector;
#[cfg(target_family = "wasm")]
use graphic_types::markers::EditorMergedLayers;
use graphic_types::raster_types::Image;
use graphic_types::raster_types::{CPU, Raster};
use graphic_types::raster_types::{CPU, GPU, Raster};
#[cfg(target_family = "wasm")]
use graphic_types::vector_types::gradient::GradientStops;
use graphic_types::vector_types::gradient::Gradient;
#[cfg(target_family = "wasm")]
use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
use std::sync::Arc;
fn parse_headers(headers: &str) -> reqwest::header::HeaderMap {
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
@@ -59,11 +60,14 @@ async fn get_request(
_primary: (),
/// The web address to send the GET request to.
#[name("URL")]
url: String,
url: Item<String>,
/// Makes the request run in the background without waiting on a response. This is useful for triggering webhooks without blocking the continued execution of the graph.
discard_result: bool,
#[widget(ParsedWidgetOverride::Custom = "text_area")] headers: String,
) -> String {
discard_result: Item<bool>,
#[widget(ParsedWidgetOverride::Custom = "text_area")] headers: Item<String>,
) -> Item<String> {
let (url, headers) = (url.into_element(), headers.into_element());
let discard_result = *discard_result.element();
let header_map = parse_headers(&headers);
let request = reqwest::Client::new().get(url).headers(header_map);
@@ -76,13 +80,13 @@ async fn get_request(
tokio::spawn(async move {
let _ = request.send().await;
});
return String::new();
return Item::default();
}
let Ok(response) = request.send().await else {
return String::new();
return Item::default();
};
response.text().await.ok().unwrap_or_default()
Item::new_from_element(response.text().await.ok().unwrap_or_default())
}
/// Sends an HTTP POST request to a specified URL with the provided binary data and optionally waits for the response (unless discarded) which is output as a string.
@@ -92,16 +96,19 @@ async fn post_request(
_primary: (),
/// The web address to send the POST request to.
#[name("URL")]
url: String,
url: Item<String>,
/// The binary data to include in the body of the POST request.
body: Arc<[u8]>,
body: Item<Resource>,
/// Makes the request run in the background without waiting on a response. This is useful for triggering webhooks without blocking the continued execution of the graph.
discard_result: bool,
#[widget(ParsedWidgetOverride::Custom = "text_area")] headers: String,
) -> String {
discard_result: Item<bool>,
#[widget(ParsedWidgetOverride::Custom = "text_area")] headers: Item<String>,
) -> Item<String> {
let (url, headers) = (url.into_element(), headers.into_element());
let discard_result = *discard_result.element();
let mut header_map = parse_headers(&headers);
header_map.insert("Content-Type", "application/octet-stream".parse().unwrap());
let body_bytes: Vec<u8> = body.to_vec();
let body_bytes: Vec<u8> = body.element().as_ref().to_vec();
let request = reqwest::Client::new().post(url).body(body_bytes).headers(header_map);
if discard_result {
@@ -113,29 +120,26 @@ async fn post_request(
tokio::spawn(async move {
let _ = request.send().await;
});
return String::new();
return Item::default();
}
let Ok(response) = request.send().await else {
return String::new();
return Item::default();
};
response.text().await.ok().unwrap_or_default()
Item::new_from_element(response.text().await.ok().unwrap_or_default())
}
/// Converts a text string to raw binary data. Useful for transmission over HTTP or writing to files.
#[node_macro::node(category("Web Request"), name("String to Bytes"))]
fn string_to_bytes(_: impl Ctx, string: String) -> Arc<[u8]> {
Arc::from(string.into_bytes())
fn string_to_bytes(_: impl Ctx, string: Item<String>) -> Item<Resource> {
Item::new_from_element(Resource::new(string.into_element().into_bytes()))
}
/// Converts extracted raw RGBA pixel data from an input image. Each pixel becomes 4 sequential bytes. Useful for transmission over HTTP or writing to files.
#[node_macro::node(category("Web Request"), name("Image to Bytes"))]
fn image_to_bytes(_: impl Ctx, image: IList<Raster<CPU>>) -> Arc<[u8]> {
if image.is_empty() {
return Arc::from(Vec::new());
}
fn image_to_bytes(_: impl Ctx, image: Item<Raster<CPU>>) -> Item<Resource> {
let bytes: Vec<u8> = image
.element_ref(0)
.element()
.data
.iter()
.flat_map(|color| {
@@ -143,13 +147,15 @@ fn image_to_bytes(_: impl Ctx, image: IList<Raster<CPU>>) -> Arc<[u8]> {
[red, green, blue, alpha]
})
.collect();
Arc::from(bytes)
Item::new_from_element(Resource::new(bytes))
}
/// Loads binary from URLs and local asset paths. Returns a transparent placeholder if the resource fails to load, allowing rendering to continue.
#[node_macro::node(category("Web Request"))]
async fn load_resource(_: impl Ctx, _primary: (), #[name("URL")] url: String) -> Arc<[u8]> {
let placeholder = || -> Arc<[u8]> { Arc::from(Vec::<u8>::new()) };
async fn load_resource(_: impl Ctx, _primary: (), #[name("URL")] url: Item<String>) -> Item<Resource> {
let url = url.into_element();
let placeholder = || -> Item<Resource> { Item::new_from_element(Resource::empty()) };
let response = match reqwest::Client::new().get(&url).send().await {
Ok(response) => response,
@@ -160,7 +166,7 @@ async fn load_resource(_: impl Ctx, _primary: (), #[name("URL")] url: String) ->
};
match response.bytes().await {
Ok(bytes) => Arc::from(bytes.to_vec()),
Ok(bytes) => Item::new_from_element(Resource::new(bytes)),
Err(error) => {
log::error!("Failed to read HTTP response for `{url}`: {error}");
placeholder()
@@ -172,10 +178,10 @@ async fn load_resource(_: impl Ctx, _primary: (), #[name("URL")] url: String) ->
///
/// Works with standard image format (PNG, JPEG, WebP, etc.). Automatically converts the color space to linear sRGB for accurate compositing.
#[node_macro::node(category("Web Request"))]
fn decode_image(_: impl Ctx, data: Arc<[u8]>) -> Raster<CPU> {
// A zero-size raster renders as nothing, matching the legacy empty list
fn decode_image(_: impl Ctx, data: Item<Resource>) -> Item<Raster<CPU>> {
let data = data.into_element();
let Some(image) = image::load_from_memory(data.as_ref()).ok() else {
return Raster::new_cpu(Image::default());
return Item::default();
};
let image = image.to_rgba32f();
let image = Image {
@@ -192,13 +198,13 @@ fn decode_image(_: impl Ctx, data: Arc<[u8]>) -> Raster<CPU> {
..Default::default()
};
Raster::new_cpu(image)
Item::new_from_element(Raster::new_cpu(image))
}
#[cfg(target_family = "wasm")]
#[node_macro::node(category(""))]
fn create_canvas(_: impl Ctx) -> CanvasHandle {
CanvasHandle::new()
fn create_canvas(_: impl Ctx) -> Item<CanvasHandle> {
Item::new_from_element(CanvasHandle::new())
}
/// Renders a view of the input graphic within an area defined by the *Footprint*.
@@ -212,17 +218,21 @@ async fn rasterize<T: WasmNotSend + Clone>(
List<Raster<CPU>>,
List<Graphic>,
List<Color>,
List<GradientStops>,
List<Gradient>,
)]
mut data: List<T>,
footprint: Footprint,
mut canvas: CanvasHandle,
data: List<T>,
footprint: Item<Footprint>,
canvas: Item<CanvasHandle>,
) -> (Raster<CPU>, Attr<Transform>, OwnedAttr<EditorMergedLayers>)
where
List<T>: Render + Clone + graphic_types::IntoGraphicList,
{
let mut data = data;
let mut canvas = canvas.into_element();
use glam::{DAffine2, DVec2};
let footprint = footprint.into_element();
if footprint.transform.matrix2.determinant() == 0. {
log::trace!("Invalid footprint received for rasterization");
// A zero-size raster renders as nothing, matching the legacy empty list
@@ -274,7 +284,7 @@ where
}
#[node_macro::node(category(""), inject_scope)]
pub fn editor_api(_: impl Ctx, #[scope("editor-api")] editor_api: Arc<PlatformEditorApi>) -> Arc<PlatformEditorApi> {
pub fn editor_api(_: impl Ctx, #[scope("editor-api")] editor_api: Item<Arc<PlatformEditorApi>>) -> Item<Arc<PlatformEditorApi>> {
editor_api
}

View File

@@ -1,5 +1,6 @@
use core_types::ExtractVarArgs;
use core_types::color::Linear;
use core_types::list::Item;
use core_types::transform::Footprint;
use core_types::uuid::generate_uuid;
use core_types::{Ctx, ExtractFootprint};
@@ -12,7 +13,11 @@ use wgpu::util::DeviceExt;
use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache};
#[node_macro::node(category(""))]
fn render_background(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(composite_background_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache, data: RenderOutput) -> RenderOutput {
fn render_background(
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
#[scope(composite_background_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
data: Item<RenderOutput>,
) -> Item<RenderOutput> {
let footprint = ctx.footprint();
let render_params = ctx
.vararg(0)
@@ -24,14 +29,14 @@ fn render_background(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(
return data;
}
let RenderOutput { data: foreground_data, metadata } = data;
let RenderOutput { data: foreground_data, metadata } = data.into_element();
let mut render_params = render_params.clone();
render_params.footprint = *footprint;
let data = match foreground_data {
RenderOutputType::Texture(foreground_texture) => {
let doc_to_screen = render_params.footprint.transform.as_affine2();
let blended = pipeline.run::<CompositeBackground>(&CompositeBackgroundArgs {
let blended = pipeline.into_element().run::<CompositeBackground>(&CompositeBackgroundArgs {
foreground: foreground_texture.as_ref(),
backgrounds: &metadata.backgrounds,
document_to_screen: doc_to_screen,
@@ -111,19 +116,19 @@ fn render_background(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(
_ => unreachable!("Render background node received unsupported render output type"),
};
RenderOutput { data, metadata }
Item::new_from_element(RenderOutput { data, metadata })
}
#[node_macro::node(category(""), inject_scope)]
fn composite_background_pipeline(
_ctx: impl Ctx,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<wgpu_executor::WgpuExecutorHandle>,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<wgpu_executor::WgpuExecutorHandle>>,
#[data] pipeline: WgpuPipelineCache,
) -> WgpuPipelineCache {
if let Some(executor) = executor {
) -> Item<WgpuPipelineCache> {
if let Some(executor) = executor.into_element() {
executor.pipeline_init::<CompositeBackground>(pipeline);
}
pipeline.clone()
Item::new_from_element(pipeline.clone())
}
pub struct CompositeBackground {

View File

@@ -1,6 +1,7 @@
//! Tile-based render caching for efficient viewport panning.
use core_types::gpoll::Interrupt;
use core_types::list::Item;
use core_types::math::bbox::AxisAlignedBbox;
use core_types::transform::{Footprint, RenderQuality, Transform};
use core_types::{Ctx, DeriveCtx, ExtractAll};
@@ -323,11 +324,11 @@ fn flood_fill(start: &TileCoord, tile_set: &HashSet<TileCoord>, visited: &mut Ha
#[node_macro::node(category(""))]
pub fn render_output_cache(
ctx: impl Ctx + ExtractAll + DeriveCtx,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<wgpu_executor::WgpuExecutorHandle>,
#[scope(crate::platform_application_io::editor_api::IDENTIFIER)] editor_api: std::sync::Arc<PlatformEditorApi>,
data: impl Node<Context<'_>, Output = RenderOutput>,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<wgpu_executor::WgpuExecutorHandle>>,
#[scope(crate::platform_application_io::editor_api::IDENTIFIER)] editor_api: Item<std::sync::Arc<PlatformEditorApi>>,
data: impl Node<Context<'_>, Output = Item<RenderOutput>>,
#[data] tile_cache: TileCache,
) -> Result<RenderOutput, Interrupt> {
) -> Result<Item<RenderOutput>, Interrupt> {
let footprint = *ctx.footprint();
let Some(render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::<RenderParams>()) else {
log::warn!("render_output_cache: missing or invalid render params, falling back to direct render");
@@ -349,7 +350,7 @@ pub fn render_output_cache(
end: footprint.resolution.as_dvec2() - device_origin_offset,
};
let max_region_area = editor_api.editor_preferences.max_render_region_area();
let max_region_area = editor_api.into_element().editor_preferences.max_render_region_area();
let cache_key = CacheKey::new(
max_region_area,
@@ -416,15 +417,15 @@ pub fn render_output_cache(
return data.eval(&ctx.derived());
}
let executor = executor.expect("GPU executor not available");
let executor = executor.into_element().expect("GPU executor not available");
let output_texture = executor.request_texture(physical_resolution);
let combined_metadata = composite_cached_regions(&all_regions, &output_texture, &device_origin_offset, &footprint.transform, &executor);
Ok(RenderOutput {
Ok(Item::new_from_element(RenderOutput {
data: RenderOutputType::Texture(output_texture),
metadata: combined_metadata,
})
}))
}
fn composite_cached_regions(

View File

@@ -1,5 +1,5 @@
use core_types::gpoll::Interrupt;
use core_types::list::List;
use core_types::list::{Item, List};
use core_types::transform::{Footprint, Transform};
use core_types::{Color, Context, Ctx, DeriveCtx, ExtractFootprint, ExtractIndex, ExtractVarArgs, InjectIndex, VarArgLink, VarArgSlots, WasmNotSend};
use graph_craft::document::value::{RenderOutput, RenderOutputType};
@@ -26,7 +26,7 @@ fn intermediate_of<R: Render>(data: &R, render_params: &RenderParams) -> RenderI
let footprint = Footprint::default();
let mut metadata = RenderMetadata::default();
data.collect_metadata(&mut metadata, footprint, None);
match &render_params.render_output_type {
let intermediate = match &render_params.render_output_type {
RenderOutputTypeRequest::Vello => {
let mut scene = vello::Scene::new();
@@ -48,7 +48,9 @@ fn intermediate_of<R: Render>(data: &R, render_params: &RenderParams) -> RenderI
metadata,
}
}
}
};
Item::new_from_element(intermediate)
}
#[node_macro::node(category(""))]
@@ -99,9 +101,9 @@ where
#[node_macro::node(category(""))]
fn render(
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<wgpu_executor::WgpuExecutorHandle>,
data: RenderIntermediate,
) -> RenderOutput {
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<wgpu_executor::WgpuExecutorHandle>>,
data: Item<RenderIntermediate>,
) -> Item<RenderOutput> {
let footprint = ctx.footprint();
let render_params = ctx
.vararg(0)
@@ -111,7 +113,7 @@ fn render(
let mut render_params = render_params.clone();
render_params.footprint = *footprint;
let RenderIntermediate { ty, mut metadata } = data;
let RenderIntermediate { ty, mut metadata } = data.into_element();
metadata.apply_transform(footprint.transform);
let data = match (render_params.render_output_type, ty) {
@@ -154,6 +156,7 @@ fn render(
}
let texture = executor
.into_element()
.expect("GPU executor not available")
.render_vello_scene(&transformed_scene, footprint.resolution, context, None)
.expect("Failed to render Vello scene");
@@ -162,7 +165,7 @@ fn render(
_ => unreachable!("Render node did not receive its requested data type"),
};
RenderOutput { data, metadata }
Item::new_from_element(RenderOutput { data, metadata })
}
#[node_macro::node(category(""))]

View File

@@ -1,4 +1,5 @@
use core_types::gpoll::Interrupt;
use core_types::list::Item;
use core_types::transform::{Footprint, Transform};
use core_types::{Ctx, DeriveCtx, ExtractAll};
use glam::{DAffine2, DVec2, UVec2, Vec2};
@@ -11,9 +12,9 @@ use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache};
#[node_macro::node(category(""))]
pub fn render_pixel_preview(
ctx: impl Ctx + ExtractAll + DeriveCtx,
#[scope(pixel_preview_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache,
data: impl Node<Context<'_>, Output = RenderOutput>,
) -> Result<RenderOutput, Interrupt> {
#[scope(pixel_preview_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
data: impl Node<Context<'_>, Output = Item<RenderOutput>>,
) -> Result<Item<RenderOutput>, Interrupt> {
let Some(render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::<RenderParams>()).cloned() else {
log::error!("invalid render params for pixel preview");
return data.eval(&ctx.derived());
@@ -51,14 +52,16 @@ pub fn render_pixel_preview(
};
let scoped = ctx.push_vararg(&render_params);
let mut result = data.eval(&scoped.ctx().with_footprint(&upstream_footprint))?;
let mut result = data.eval(&scoped.ctx().with_footprint(&upstream_footprint))?.into_element();
let RenderOutputType::Texture(ref source_texture) = result.data else { return Ok(result) };
let RenderOutputType::Texture(ref source_texture) = result.data else {
return Ok(Item::new_from_element(result));
};
let logical_transform = DAffine2::from_scale(DVec2::splat(1. / physical_scale)) * footprint.transform;
let transform = DAffine2::from_translation(-upstream_min) * logical_transform.inverse() * DAffine2::from_scale(logical_resolution);
let resampled = pipeline.run::<PixelPreview>(&PixelPreviewArgs {
let resampled = pipeline.into_element().run::<PixelPreview>(&PixelPreviewArgs {
source: source_texture.as_ref(),
transform: &transform,
size: physical_resolution,
@@ -68,19 +71,19 @@ pub fn render_pixel_preview(
result.metadata.apply_transform(footprint.transform * DAffine2::from_translation(upstream_min));
Ok(result)
Ok(Item::new_from_element(result))
}
#[node_macro::node(category(""), inject_scope)]
fn pixel_preview_pipeline(
_ctx: impl Ctx,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<wgpu_executor::WgpuExecutorHandle>,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<wgpu_executor::WgpuExecutorHandle>>,
#[data] pipeline: WgpuPipelineCache,
) -> WgpuPipelineCache {
if let Some(executor) = executor {
) -> Item<WgpuPipelineCache> {
if let Some(executor) = executor.into_element() {
executor.pipeline_init::<PixelPreview>(pipeline);
}
pipeline.clone()
Item::new_from_element(pipeline.clone())
}
pub struct PixelPreview {

View File

@@ -1,11 +1,11 @@
use core_types::consts::{DEFAULT_FONT_SIZE, DEFAULT_LINE_HEIGHT};
use core_types::list::List;
use core_types::{ATTR_FONT_SIZE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, Ctx};
use core_types::list::{Item, List};
use core_types::{ATTR_FONT, ATTR_FONT_SIZE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_TEXT_ALIGN, Ctx};
use graph_craft::application_io::resource::Resource;
use graphic_types::Vector;
pub use text_nodes::*;
/// Produces a styled `String[]` carrying all typographic attributes.
/// Produces a styled text string carrying all typographic attributes.
///
/// Use the **Text to Vector** node to convert this into vector geometry if desired.
#[node_macro::node(category("Text"))]
@@ -15,15 +15,15 @@ fn text(
/// The text content to be drawn.
#[widget(ParsedWidgetOverride::Custom = "text_area")]
#[default("Lorem ipsum")]
text: String,
text: Item<String>,
/// The loaded font file used to draw the text. The editor resolves the chosen typeface to these bytes via the resource system.
#[widget(ParsedWidgetOverride::Custom = "text_font")]
font: Resource,
font: Item<Resource>,
/// The font size used to draw the text.
#[unit(" px")]
#[default(24.)]
#[hard(1..)]
size: f64,
size: Item<f64>,
/// The line height ratio, relative to the font size. Each line is drawn lower than its previous line by the distance of *Size* × *Line Height*.
///
/// 0 means all lines overlap. 1 means all lines are spaced by just the font size. 1.2 is a common default for readable text. 2 means double-spaced text.
@@ -31,74 +31,87 @@ fn text(
#[hard(0..)]
#[step(0.1)]
#[default(1.2)]
line_height: f64,
line_height: Item<f64>,
/// Additional spacing, in pixels, added between each character.
#[unit(" px")]
#[step(0.1)]
letter_spacing: f64,
letter_spacing: Item<f64>,
/// The angle of faux italic slant applied to each glyph.
#[unit("°")]
#[hard(-85..85)]
letter_tilt: f64,
letter_tilt: Item<f64>,
/// Enables the maximum width constraint so lines can wrap.
#[widget(ParsedWidgetOverride::Hidden)]
has_max_width: bool,
has_max_width: Item<bool>,
/// The maximum width that the text block can occupy before wrapping to a new line. Otherwise, lines do not wrap.
#[unit(" px")]
#[hard(1..)]
#[widget(ParsedWidgetOverride::Custom = "optional_f64")]
max_width: f64,
max_width: Item<f64>,
/// Whether the *Max Height* property is enabled so that lines beyond it are not drawn.
#[widget(ParsedWidgetOverride::Hidden)]
has_max_height: bool,
has_max_height: Item<bool>,
/// The maximum height that the text block can occupy. Excess lines are not drawn.
#[unit(" px")]
#[hard(1..)]
#[widget(ParsedWidgetOverride::Custom = "optional_f64")]
max_height: f64,
max_height: Item<f64>,
/// The horizontal alignment of each line of text within its surrounding box. To have an effect on a single line of text, *Max Width* must be set.
#[widget(ParsedWidgetOverride::Custom = "text_align")]
align: TextAlign,
) -> List<String> {
let mut list = List::new_from_element(text);
align: Item<TextAlign>,
) -> Item<String> {
let text = text.into_element();
let font = font.into_element();
let (size, line_height, letter_spacing, letter_tilt) = (*size.element(), *line_height.element(), *letter_spacing.element(), *letter_tilt.element());
let (has_max_width, max_width, has_max_height, max_height) = (*has_max_width.element(), *max_width.element(), *has_max_height.element(), *max_height.element());
let align = align.into_element();
let mut item = Item::new_from_element(text);
if font != Resource::default() {
list.set_attribute(ATTR_FONT, 0, font);
item.set_attribute(ATTR_FONT, font);
}
if (size - DEFAULT_FONT_SIZE).abs() > f64::EPSILON {
list.set_attribute(ATTR_FONT_SIZE, 0, size);
item.set_attribute(ATTR_FONT_SIZE, size);
}
if (line_height - DEFAULT_LINE_HEIGHT).abs() > f64::EPSILON {
list.set_attribute(ATTR_LINE_HEIGHT, 0, line_height);
item.set_attribute(ATTR_LINE_HEIGHT, line_height);
}
if letter_spacing != 0. {
list.set_attribute(ATTR_LETTER_SPACING, 0, letter_spacing);
item.set_attribute(ATTR_LETTER_SPACING, letter_spacing);
}
if letter_tilt != 0. {
list.set_attribute(ATTR_LETTER_TILT, 0, letter_tilt);
item.set_attribute(ATTR_LETTER_TILT, letter_tilt);
}
if has_max_width {
list.set_attribute(ATTR_MAX_WIDTH, 0, Some(max_width));
item.set_attribute(ATTR_MAX_WIDTH, Some(max_width));
}
if has_max_height {
list.set_attribute(ATTR_MAX_HEIGHT, 0, Some(max_height));
item.set_attribute(ATTR_MAX_HEIGHT, Some(max_height));
}
if align != TextAlign::default() {
list.set_attribute(ATTR_TEXT_ALIGN, 0, align);
item.set_attribute(ATTR_TEXT_ALIGN, align);
}
list
item
}
/// Converts a styled `String[]` into vector geometry.
/// Converts a styled text string into a vector compound path.
#[node_macro::node(category("Text"), name("Text to Vector"))]
fn text_to_vector(
_: impl Ctx,
/// A styled list of text strings produced by the **Text** node (or any other `String[]` source).
#[implementations(List<String>)]
strings: List<String>,
/// Whether to split every letterform into its own vector item. Otherwise, a single vector compound path is produced.
separate_glyphs: bool,
) -> List<Vector> {
shape_text_list(&strings, separate_glyphs)
/// A styled text string produced by the **Text** node (or any other string source).
string: Item<String>,
) -> Item<Vector> {
shape_text_item(&string, false).into_iter().next().unwrap_or_default()
}
/// Splits a styled text string into a separate vector item for each of its glyphs (letterforms).
#[node_macro::node(category("Text"), name("Text to Vector Glyphs"))]
fn text_to_vector_glyphs(
_: impl Ctx,
/// A styled text string produced by the **Text** node (or any other string source).
string: Item<String>,
) -> List<Vector> {
shape_text_item(&string, true)
}

File diff suppressed because it is too large Load Diff

View File

@@ -13,7 +13,7 @@ impl Adjust<Color> for Color {
mod adjust_std {
use super::*;
use raster_types::{CPU, Raster};
use vector_types::GradientStops;
use vector_types::Gradient;
impl Adjust<Color> for Raster<CPU> {
fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) {
@@ -22,7 +22,7 @@ mod adjust_std {
}
}
}
impl Adjust<Color> for GradientStops {
impl Adjust<Color> for Gradient {
fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) {
for color in self.color.iter_mut() {
*color = map_fn(color);

View File

@@ -3,9 +3,13 @@
use crate::adjust::Adjust;
use crate::cubic_spline::CubicSplines;
use core::fmt::Debug;
#[cfg(feature = "std")]
use core_types::list::Item;
use glam::Vec3;
use no_std_types::color::{Color, linear_to_srgb, srgb_to_linear};
use no_std_types::context::Ctx;
#[cfg(not(feature = "std"))]
use no_std_types::list::ShaderItem as Item;
use no_std_types::registry::types::{AngleF32, PercentageF32, SignedPercentageF32};
use node_macro::BufferStruct;
use num_enum::{FromPrimitive, IntoPrimitive};
@@ -14,7 +18,7 @@ use num_traits::float::Float;
#[cfg(feature = "std")]
use raster_types::{CPU, Raster};
#[cfg(feature = "std")]
use vector_types::GradientStops;
use vector_types::Gradient;
// TODO: Implement the following:
// Color Balance
@@ -53,13 +57,16 @@ fn luminance<T: Adjust<Color> + Clone + Send + Sync + no_std_types::context::Cac
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut input: T,
luminance_calc: LuminanceCalculation,
) -> T {
input.adjust(|color| {
input: Item<T>,
luminance_calc: Item<LuminanceCalculation>,
) -> Item<T> {
let mut input = input;
let luminance_calc = luminance_calc.into_element();
input.element_mut().adjust(|color| {
let luminance = match luminance_calc {
LuminanceCalculation::SRGB => color.luminance_rec_709(),
LuminanceCalculation::Perceptual => color.luminance_perceptual(),
@@ -78,19 +85,23 @@ fn gamma_correction<T: Adjust<Color> + Clone + Send + Sync + no_std_types::conte
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut input: T,
input: Item<T>,
#[default(2.2)]
#[range]
#[hard(0.0001..)]
#[soft(0.01..10)]
gamma: f32,
inverse: bool,
) -> T {
gamma: Item<f32>,
inverse: Item<bool>,
) -> Item<T> {
let mut input = input;
let gamma = gamma.into_element();
let inverse = inverse.into_element();
let exponent = if inverse { 1. / gamma } else { gamma };
input.adjust(|color| color.apply_gamma_exponent(exponent));
input.element_mut().adjust(|color| color.apply_gamma_exponent(exponent));
input
}
@@ -100,13 +111,16 @@ fn extract_channel<T: Adjust<Color> + Clone + Send + Sync + no_std_types::contex
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut input: T,
channel: RedGreenBlueAlpha,
) -> T {
input.adjust(|color| {
input: Item<T>,
channel: Item<RedGreenBlueAlpha>,
) -> Item<T> {
let mut input = input;
let channel = channel.into_element();
input.element_mut().adjust(|color| {
let extracted_value = match channel {
RedGreenBlueAlpha::Red => color.r(),
RedGreenBlueAlpha::Green => color.g(),
@@ -124,12 +138,13 @@ fn make_opaque<T: Adjust<Color> + Clone + Send + Sync + no_std_types::context::C
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut input: T,
) -> T {
input.adjust(|color| {
input: Item<T>,
) -> Item<T> {
let mut input = input;
input.element_mut().adjust(|color| {
if color.a() == 0. {
return color.with_alpha(1.);
}
@@ -146,13 +161,17 @@ fn brightness_contrast_classic<T: Adjust<Color> + Clone + Send + Sync + no_std_t
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut input: T,
brightness: SignedPercentageF32,
contrast: SignedPercentageF32,
) -> T {
input: Item<T>,
brightness: Item<SignedPercentageF32>,
contrast: Item<SignedPercentageF32>,
) -> Item<T> {
let mut input = input;
let brightness = brightness.into_element();
let contrast = contrast.into_element();
let brightness = brightness / 255.;
let contrast = contrast / 100.;
@@ -160,7 +179,7 @@ fn brightness_contrast_classic<T: Adjust<Color> + Clone + Send + Sync + no_std_t
let offset = brightness * contrast + brightness - contrast / 2.;
input.adjust(|color| color.map_gamma_rgb(|c| (c + c * contrast + offset).clamp(0., 1.)));
input.element_mut().adjust(|color| color.map_gamma_rgb(|c| (c + c * contrast + offset).clamp(0., 1.)));
input
}
@@ -177,18 +196,23 @@ fn brightness_contrast<T: Adjust<Color> + Clone + Send + Sync + no_std_types::co
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut input: T,
brightness: SignedPercentageF32,
contrast: SignedPercentageF32,
use_classic: bool,
) -> T {
input: Item<T>,
brightness: Item<SignedPercentageF32>,
contrast: Item<SignedPercentageF32>,
use_classic: Item<bool>,
) -> Item<T> {
let use_classic = use_classic.into_element();
if use_classic {
return brightness_contrast_classic(_ctx, input, brightness, contrast);
}
let mut input = input;
let brightness = brightness.into_element();
let contrast = contrast.into_element();
const WINDOW_SIZE: usize = 1024;
// Brightness LUT
@@ -239,7 +263,7 @@ fn brightness_contrast<T: Adjust<Color> + Clone + Send + Sync + no_std_types::co
});
let lut_max = (combined_lut.len() - 1) as f32;
input.adjust(|color| color.map_gamma_rgb(|c| combined_lut[(c * lut_max).round() as usize]));
input.element_mut().adjust(|color| color.map_gamma_rgb(|c| combined_lut[(c * lut_max).round() as usize]));
input
}
@@ -258,17 +282,24 @@ fn levels<T: Adjust<Color> + Clone + Send + Sync + no_std_types::context::CacheH
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut image: T,
#[default(0.)] shadows: PercentageF32,
#[default(50.)] midtones: PercentageF32,
#[default(100.)] highlights: PercentageF32,
#[default(0.)] output_minimums: PercentageF32,
#[default(100.)] output_maximums: PercentageF32,
) -> T {
image.adjust(|color| {
image: Item<T>,
#[default(0.)] shadows: Item<PercentageF32>,
#[default(50.)] midtones: Item<PercentageF32>,
#[default(100.)] highlights: Item<PercentageF32>,
#[default(0.)] output_minimums: Item<PercentageF32>,
#[default(100.)] output_maximums: Item<PercentageF32>,
) -> Item<T> {
let mut image = image;
let shadows = shadows.into_element();
let midtones = midtones.into_element();
let highlights = highlights.into_element();
let output_minimums = output_minimums.into_element();
let output_maximums = output_maximums.into_element();
image.element_mut().adjust(|color| {
// Levels math operates in gamma space
let [mut r, mut g, mut b, a] = color.to_gamma_srgb_channels();
@@ -330,44 +361,52 @@ fn levels<T: Adjust<Color> + Clone + Send + Sync + no_std_types::context::CacheH
// Algorithm from:
// https://stackoverflow.com/a/55233732/775283
// Works the same for gamma and linear color
// TODO: Currently the un-List-wrapped `tint` Color is causing a type error. Put this back in the "Raster: Adjustment" category once that's fixed.
#[node_macro::node(name("Black & White"), category(""), properties("black_and_white_properties"), shader_node(PerPixelAdjust))]
fn black_and_white<T: Adjust<Color> + Clone + Send + Sync + no_std_types::context::CacheHash + 'static>(
#[node_macro::node(name("Black & White"), category("Raster: Adjustment"), properties("black_and_white_properties"), shader_node(PerPixelAdjust))]
fn black_and_white<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut image: T,
#[default(Color::BLACK)] tint: Color,
image: Item<T>,
#[default(Color::BLACK)] tint: Item<Color>,
#[default(40.)]
#[range]
#[soft(-200..300)]
reds: PercentageF32,
reds: Item<PercentageF32>,
#[default(60.)]
#[range]
#[soft(-200..300)]
yellows: PercentageF32,
yellows: Item<PercentageF32>,
#[default(40.)]
#[range]
#[soft(-200..300)]
greens: PercentageF32,
greens: Item<PercentageF32>,
#[default(60.)]
#[range]
#[soft(-200..300)]
cyans: PercentageF32,
cyans: Item<PercentageF32>,
#[default(20.)]
#[range]
#[soft(-200..300)]
blues: PercentageF32,
blues: Item<PercentageF32>,
#[default(80.)]
#[range]
#[soft(-200..300)]
magentas: PercentageF32,
) -> T {
image.adjust(|color| {
magentas: Item<PercentageF32>,
) -> Item<T> {
let mut image = image;
let tint = tint.into_element();
let reds = reds.into_element();
let yellows = yellows.into_element();
let greens = greens.into_element();
let cyans = cyans.into_element();
let blues = blues.into_element();
let magentas = magentas.into_element();
image.element_mut().adjust(|color| {
// Black & White channel weights are tuned for gamma-space values
let [r, g, b, alpha_part] = color.to_gamma_srgb_channels();
@@ -420,15 +459,20 @@ fn hue_saturation<T: Adjust<Color> + Clone + Send + Sync + no_std_types::context
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut input: T,
hue_shift: AngleF32,
saturation_shift: SignedPercentageF32,
lightness_shift: SignedPercentageF32,
) -> T {
input.adjust(|color| {
input: Item<T>,
hue_shift: Item<AngleF32>,
saturation_shift: Item<SignedPercentageF32>,
lightness_shift: Item<SignedPercentageF32>,
) -> Item<T> {
let mut input = input;
let hue_shift = hue_shift.into_element();
let saturation_shift = saturation_shift.into_element();
let lightness_shift = lightness_shift.into_element();
input.element_mut().adjust(|color| {
// HSL operates on gamma-space channels
let [hue, saturation, lightness, alpha] = color.to_hsla();
@@ -452,12 +496,13 @@ fn invert<T: Adjust<Color> + Clone + Send + Sync + no_std_types::context::CacheH
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut input: T,
) -> T {
input.adjust(|color| {
input: Item<T>,
) -> Item<T> {
let mut input = input;
input.element_mut().adjust(|color| {
// Invert in gamma space relative to alpha
let [r, g, b, a] = color.to_gamma_srgb_channels();
Color::from_gamma_srgb_channels(a - r, a - g, a - b, a)
@@ -473,15 +518,20 @@ fn threshold<T: Adjust<Color> + Clone + Send + Sync + no_std_types::context::Cac
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut image: T,
#[default(50.)] min_luminance: PercentageF32,
#[default(100.)] max_luminance: PercentageF32,
luminance_calc: LuminanceCalculation,
) -> T {
image.adjust(|color| {
image: Item<T>,
#[default(50.)] min_luminance: Item<PercentageF32>,
#[default(100.)] max_luminance: Item<PercentageF32>,
luminance_calc: Item<LuminanceCalculation>,
) -> Item<T> {
let mut image = image;
let min_luminance = min_luminance.into_element();
let max_luminance = max_luminance.into_element();
let luminance_calc = luminance_calc.into_element();
image.element_mut().adjust(|color| {
let min_luminance = srgb_to_linear(min_luminance / 100.);
let max_luminance = srgb_to_linear(max_luminance / 100.);
@@ -519,13 +569,16 @@ fn vibrance<T: Adjust<Color> + Clone + Send + Sync + no_std_types::context::Cach
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut image: T,
vibrance: SignedPercentageF32,
) -> T {
image.adjust(|color| {
image: Item<T>,
vibrance: Item<SignedPercentageF32>,
) -> Item<T> {
let mut image = image;
let vibrance = vibrance.into_element();
image.element_mut().adjust(|color| {
let r_raw = color.r();
let g_raw = color.g();
let b_raw = color.b();
@@ -721,69 +774,76 @@ fn channel_mixer<T: Adjust<Color> + Clone + Send + Sync + no_std_types::context:
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut image: T,
image: Item<T>,
monochrome: bool,
monochrome: Item<bool>,
#[default(40.)]
#[name("Red")]
monochrome_r: f32,
monochrome_r: Item<f32>,
#[default(40.)]
#[name("Green")]
monochrome_g: f32,
monochrome_g: Item<f32>,
#[default(20.)]
#[name("Blue")]
monochrome_b: f32,
monochrome_b: Item<f32>,
#[default(0.)]
#[name("Constant")]
monochrome_c: f32,
monochrome_c: Item<f32>,
#[default(100.)]
#[name("(Red) Red")]
red_r: f32,
red_r: Item<f32>,
#[default(0.)]
#[name("(Red) Green")]
red_g: f32,
red_g: Item<f32>,
#[default(0.)]
#[name("(Red) Blue")]
red_b: f32,
red_b: Item<f32>,
#[default(0.)]
#[name("(Red) Constant")]
red_c: f32,
red_c: Item<f32>,
#[default(0.)]
#[name("(Green) Red")]
green_r: f32,
green_r: Item<f32>,
#[default(100.)]
#[name("(Green) Green")]
green_g: f32,
green_g: Item<f32>,
#[default(0.)]
#[name("(Green) Blue")]
green_b: f32,
green_b: Item<f32>,
#[default(0.)]
#[name("(Green) Constant")]
green_c: f32,
green_c: Item<f32>,
#[default(0.)]
#[name("(Blue) Red")]
blue_r: f32,
blue_r: Item<f32>,
#[default(0.)]
#[name("(Blue) Green")]
blue_g: f32,
blue_g: Item<f32>,
#[default(100.)]
#[name("(Blue) Blue")]
blue_b: f32,
blue_b: Item<f32>,
#[default(0.)]
#[name("(Blue) Constant")]
blue_c: f32,
blue_c: Item<f32>,
// Display-only properties (not used within the node)
_output_channel: RedGreenBlue,
) -> T {
image.adjust(|color| {
_output_channel: Item<RedGreenBlue>,
) -> Item<T> {
let mut image = image;
let monochrome = monochrome.into_element();
let (monochrome_r, monochrome_g, monochrome_b, monochrome_c) = (monochrome_r.into_element(), monochrome_g.into_element(), monochrome_b.into_element(), monochrome_c.into_element());
let (red_r, red_g, red_b, red_c) = (red_r.into_element(), red_g.into_element(), red_b.into_element(), red_c.into_element());
let (green_r, green_g, green_b, green_c) = (green_r.into_element(), green_g.into_element(), green_b.into_element(), green_c.into_element());
let (blue_r, blue_g, blue_b, blue_c) = (blue_r.into_element(), blue_g.into_element(), blue_b.into_element(), blue_c.into_element());
image.element_mut().adjust(|color| {
let [r, g, b, a] = color.to_gamma_srgb_channels();
let (out_r, out_g, out_b) = if monochrome {
@@ -853,61 +913,73 @@ fn selective_color<T: Adjust<Color> + Clone + Send + Sync + no_std_types::contex
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut image: T,
image: Item<T>,
mode: RelativeAbsolute,
mode: Item<RelativeAbsolute>,
#[name("(Reds) Cyan")] r_c: f32,
#[name("(Reds) Magenta")] r_m: f32,
#[name("(Reds) Yellow")] r_y: f32,
#[name("(Reds) Black")] r_k: f32,
#[name("(Reds) Cyan")] r_c: Item<f32>,
#[name("(Reds) Magenta")] r_m: Item<f32>,
#[name("(Reds) Yellow")] r_y: Item<f32>,
#[name("(Reds) Black")] r_k: Item<f32>,
#[name("(Yellows) Cyan")] y_c: f32,
#[name("(Yellows) Magenta")] y_m: f32,
#[name("(Yellows) Yellow")] y_y: f32,
#[name("(Yellows) Black")] y_k: f32,
#[name("(Yellows) Cyan")] y_c: Item<f32>,
#[name("(Yellows) Magenta")] y_m: Item<f32>,
#[name("(Yellows) Yellow")] y_y: Item<f32>,
#[name("(Yellows) Black")] y_k: Item<f32>,
#[name("(Greens) Cyan")] g_c: f32,
#[name("(Greens) Magenta")] g_m: f32,
#[name("(Greens) Yellow")] g_y: f32,
#[name("(Greens) Black")] g_k: f32,
#[name("(Greens) Cyan")] g_c: Item<f32>,
#[name("(Greens) Magenta")] g_m: Item<f32>,
#[name("(Greens) Yellow")] g_y: Item<f32>,
#[name("(Greens) Black")] g_k: Item<f32>,
#[name("(Cyans) Cyan")] c_c: f32,
#[name("(Cyans) Magenta")] c_m: f32,
#[name("(Cyans) Yellow")] c_y: f32,
#[name("(Cyans) Black")] c_k: f32,
#[name("(Cyans) Cyan")] c_c: Item<f32>,
#[name("(Cyans) Magenta")] c_m: Item<f32>,
#[name("(Cyans) Yellow")] c_y: Item<f32>,
#[name("(Cyans) Black")] c_k: Item<f32>,
#[name("(Blues) Cyan")] b_c: f32,
#[name("(Blues) Magenta")] b_m: f32,
#[name("(Blues) Yellow")] b_y: f32,
#[name("(Blues) Black")] b_k: f32,
#[name("(Blues) Cyan")] b_c: Item<f32>,
#[name("(Blues) Magenta")] b_m: Item<f32>,
#[name("(Blues) Yellow")] b_y: Item<f32>,
#[name("(Blues) Black")] b_k: Item<f32>,
#[name("(Magentas) Cyan")] m_c: f32,
#[name("(Magentas) Magenta")] m_m: f32,
#[name("(Magentas) Yellow")] m_y: f32,
#[name("(Magentas) Black")] m_k: f32,
#[name("(Magentas) Cyan")] m_c: Item<f32>,
#[name("(Magentas) Magenta")] m_m: Item<f32>,
#[name("(Magentas) Yellow")] m_y: Item<f32>,
#[name("(Magentas) Black")] m_k: Item<f32>,
#[name("(Whites) Cyan")] w_c: f32,
#[name("(Whites) Magenta")] w_m: f32,
#[name("(Whites) Yellow")] w_y: f32,
#[name("(Whites) Black")] w_k: f32,
#[name("(Whites) Cyan")] w_c: Item<f32>,
#[name("(Whites) Magenta")] w_m: Item<f32>,
#[name("(Whites) Yellow")] w_y: Item<f32>,
#[name("(Whites) Black")] w_k: Item<f32>,
#[name("(Neutrals) Cyan")] n_c: f32,
#[name("(Neutrals) Magenta")] n_m: f32,
#[name("(Neutrals) Yellow")] n_y: f32,
#[name("(Neutrals) Black")] n_k: f32,
#[name("(Neutrals) Cyan")] n_c: Item<f32>,
#[name("(Neutrals) Magenta")] n_m: Item<f32>,
#[name("(Neutrals) Yellow")] n_y: Item<f32>,
#[name("(Neutrals) Black")] n_k: Item<f32>,
#[name("(Blacks) Cyan")] k_c: f32,
#[name("(Blacks) Magenta")] k_m: f32,
#[name("(Blacks) Yellow")] k_y: f32,
#[name("(Blacks) Black")] k_k: f32,
#[name("(Blacks) Cyan")] k_c: Item<f32>,
#[name("(Blacks) Magenta")] k_m: Item<f32>,
#[name("(Blacks) Yellow")] k_y: Item<f32>,
#[name("(Blacks) Black")] k_k: Item<f32>,
_colors: SelectiveColorChoice,
) -> T {
image.adjust(|color| {
_colors: Item<SelectiveColorChoice>,
) -> Item<T> {
let mut image = image;
let mode = mode.into_element();
let (r_c, r_m, r_y, r_k) = (r_c.into_element(), r_m.into_element(), r_y.into_element(), r_k.into_element());
let (y_c, y_m, y_y, y_k) = (y_c.into_element(), y_m.into_element(), y_y.into_element(), y_k.into_element());
let (g_c, g_m, g_y, g_k) = (g_c.into_element(), g_m.into_element(), g_y.into_element(), g_k.into_element());
let (c_c, c_m, c_y, c_k) = (c_c.into_element(), c_m.into_element(), c_y.into_element(), c_k.into_element());
let (b_c, b_m, b_y, b_k) = (b_c.into_element(), b_m.into_element(), b_y.into_element(), b_k.into_element());
let (m_c, m_m, m_y, m_k) = (m_c.into_element(), m_m.into_element(), m_y.into_element(), m_k.into_element());
let (w_c, w_m, w_y, w_k) = (w_c.into_element(), w_m.into_element(), w_y.into_element(), w_k.into_element());
let (n_c, n_m, n_y, n_k) = (n_c.into_element(), n_m.into_element(), n_y.into_element(), n_k.into_element());
let (k_c, k_m, k_y, k_k) = (k_c.into_element(), k_m.into_element(), k_y.into_element(), k_k.into_element());
image.element_mut().adjust(|color| {
let [r, g, b, a] = color.to_gamma_srgb_channels();
let min = |a: f32, b: f32, c: f32| a.min(b).min(c);
@@ -997,16 +1069,18 @@ fn posterize<T: Adjust<Color> + Clone + Send + Sync + no_std_types::context::Cac
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut input: T,
input: Item<T>,
#[default(4)]
#[hard(2..)]
levels: u32,
) -> T {
let levels = levels as f32;
input.adjust(|color| {
levels: Item<u32>,
) -> Item<T> {
let mut input = input;
let levels = levels.into_element() as f32;
input.element_mut().adjust(|color| {
let number_of_areas = levels.recip();
let size_of_areas = (levels - 1.).recip();
color.map_gamma_rgb(|c| (c / number_of_areas).floor() * size_of_areas)
@@ -1026,19 +1100,24 @@ fn exposure<T: Adjust<Color> + Clone + Send + Sync + no_std_types::context::Cach
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut input: T,
exposure: f32,
offset: f32,
input: Item<T>,
exposure: Item<f32>,
offset: Item<f32>,
#[default(1.)]
#[range]
#[hard(0.0001..)]
#[soft(0.01..10)]
gamma_correction: f32,
) -> T {
input.adjust(|color| {
gamma_correction: Item<f32>,
) -> Item<T> {
let mut input = input;
let exposure = exposure.into_element();
let offset = offset.into_element();
let gamma_correction = gamma_correction.into_element();
input.element_mut().adjust(|color| {
let adjusted = color
// Exposure
.map_rgb(|c: f32| c * 2_f32.powf(exposure))

View File

@@ -1,12 +1,16 @@
use crate::adjust::Adjust;
#[cfg(feature = "std")]
use core_types::list::Item;
use no_std_types::Ctx;
use no_std_types::blending::BlendMode;
use no_std_types::color::{Color, Pixel};
#[cfg(not(feature = "std"))]
use no_std_types::list::ShaderItem as Item;
use no_std_types::registry::types::PercentageF32;
#[cfg(feature = "std")]
use raster_types::{CPU, Raster};
#[cfg(feature = "std")]
use vector_types::{GradientStop, GradientStops};
use vector_types::{Gradient, GradientStop};
pub trait Blend<P: Pixel> {
fn blend(&self, under: &Self, blend_fn: impl Fn(P, P) -> P) -> Self;
@@ -27,6 +31,7 @@ mod blend_std {
impl Blend<Color> for Raster<CPU> {
fn blend(&self, under: &Self, blend_fn: impl Fn(Color, Color) -> Color) -> Self {
let data = self.data.iter().zip(under.data.iter()).map(|(a, b)| blend_fn(*a, *b)).collect();
Raster::new_cpu(Image {
data,
width: self.width,
@@ -35,8 +40,7 @@ mod blend_std {
})
}
}
impl Blend<Color> for GradientStops {
impl Blend<Color> for Gradient {
fn blend(&self, under: &Self, blend_fn: impl Fn(Color, Color) -> Color) -> Self {
let mut combined_stops = self.position.iter().chain(under.position.iter()).copied().collect::<Vec<_>>();
combined_stops.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
@@ -47,7 +51,7 @@ mod blend_std {
let color = blend_fn(over_color, under_color);
GradientStop { position, midpoint: 0.5, color }
});
GradientStops::new(stops)
Gradient::new(stops)
}
}
}
@@ -111,22 +115,28 @@ fn mix<T: Blend<Color> + Clone + Send + Sync + core_types::CacheHash + 'static>(
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
over: T,
over: Item<T>,
#[expose]
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
under: T,
blend_mode: BlendMode,
#[default(100.)] opacity: PercentageF32,
) -> T {
over.blend(&under, |a, b| blend_colors(a, b, blend_mode, opacity / 100.))
under: Item<T>,
blend_mode: Item<BlendMode>,
#[default(100.)] opacity: Item<PercentageF32>,
) -> Item<T> {
let mut over = over;
let blend_mode = blend_mode.into_element();
let opacity = opacity.into_element();
let blended = over.element().blend(under.element(), |a, b| blend_colors(a, b, blend_mode, opacity / 100.));
*over.element_mut() = blended;
over
}
#[node_macro::node(category("Raster: Adjustment"), shader_node(PerPixelAdjust))]
@@ -135,17 +145,22 @@ fn color_overlay<T: Adjust<Color> + Clone + Send + Sync + no_std_types::context:
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
#[gpu_image]
mut image: T,
#[default(Color::BLACK)] color: Color,
blend_mode: BlendMode,
#[default(100.)] opacity: PercentageF32,
) -> T {
image: Item<T>,
#[default(Color::BLACK)] color: Item<Color>,
blend_mode: Item<BlendMode>,
#[default(100.)] opacity: Item<PercentageF32>,
) -> Item<T> {
let mut image = image;
let color = color.into_element();
let blend_mode = blend_mode.into_element();
let opacity = opacity.into_element();
let opacity = (opacity / 100.).clamp(0., 1.);
image.adjust(|pixel| {
image.element_mut().adjust(|pixel| {
let image = pixel.map_rgb(|channel| channel * (1. - opacity));
// The apply blend mode function divides rgb by the alpha channel for the background. This undoes that.
@@ -161,6 +176,7 @@ fn color_overlay<T: Adjust<Color> + Clone + Send + Sync + no_std_types::context:
mod test {
use core_types::blending::BlendMode;
use core_types::color::Color;
use core_types::list::Item;
use raster_types::Image;
use raster_types::Raster;
@@ -175,7 +191,14 @@ mod test {
// 100% of the output should come from the multiplied value
let opacity = 100.;
let result = super::color_overlay(&(), Raster::new_cpu(image.clone()), overlay_color, BlendMode::Multiply, opacity);
let result = super::color_overlay(
(),
Item::new_from_element(Raster::new_cpu(image.clone())),
overlay_color.into(),
BlendMode::Multiply.into(),
opacity.into(),
);
let result = result.into_element();
// The output should just be the original green and alpha channels (as we multiply them by 1 and other channels by 0)
assert_eq!(result.data[0], Color::from_rgbaf32_unchecked(0., image_color.g(), 0., image_color.a()));

View File

@@ -1,4 +1,5 @@
use core_types::context::Ctx;
use core_types::list::Item;
use core_types::registry::types::Percentage;
use image::{DynamicImage, GenericImage, GenericImageView, GrayImage, ImageBuffer, Luma, Rgba, RgbaImage};
use ndarray::{Array2, ArrayBase, Dim, OwnedRepr};
@@ -7,11 +8,15 @@ use raster_types::{CPU, Raster};
use std::cmp::{max, min};
#[node_macro::node(category("Raster: Filter"))]
fn dehaze(_: impl Ctx, image_frame: Raster<CPU>, strength: Percentage) -> Raster<CPU> {
let image = image_frame;
async fn dehaze(_: impl Ctx, image_frame: Item<Raster<CPU>>, strength: Item<Percentage>) -> Item<Raster<CPU>> {
let strength = *strength.element();
let (image, attributes) = image_frame.into_parts();
let (width, height) = (image.width, image.height);
// Prepare the image data for processing
let image_data = bytemuck::cast_vec(image.data.clone());
let image_buffer = image::Rgba32FImage::from_raw(image.width, image.height, image_data).expect("Failed to convert internal image format into image-rs data type.");
let image_data = bytemuck::cast_vec(image.into_data().data);
let image_buffer = image::Rgba32FImage::from_raw(width, height, image_data).expect("Failed to convert internal image format into image-rs data type.");
let dynamic_image: DynamicImage = image_buffer.into();
// Run the dehaze algorithm
@@ -21,13 +26,13 @@ fn dehaze(_: impl Ctx, image_frame: Raster<CPU>, strength: Percentage) -> Raster
let buffer = dehazed_dynamic_image.to_rgba32f().into_raw();
let color_vec = bytemuck::cast_vec(buffer);
let dehazed_image = Image {
width: image.width,
height: image.height,
width,
height,
data: color_vec,
base64_string: None,
};
Raster::new_cpu(dehazed_image)
Item::from_parts(Raster::new_cpu(dehazed_image), attributes)
}
// There is no real point in modifying these values because they do not change the final result all that much.

View File

@@ -1,6 +1,7 @@
use bytemuck::{Pod, Zeroable};
use core_types::color::{Alpha, Color, Pixel, RGB};
use core_types::context::Ctx;
use core_types::list::Item;
use core_types::registry::types::PixelLength;
use raster_types::Image;
use raster_types::{Bitmap, BitmapMut};
@@ -89,26 +90,31 @@ fn unpremultiply_gamma_to_linear(buffer: Image<PremultipliedGammaPixel>) -> Imag
fn blur(
_: impl Ctx,
/// The image to be blurred.
image_frame: Raster<CPU>,
image_frame: Item<Raster<CPU>>,
/// The radius of the blur kernel.
#[range]
#[hard(0..)]
#[soft(..100)]
radius: PixelLength,
radius: Item<PixelLength>,
/// Use a lower-quality box kernel instead of a circular Gaussian kernel. This is faster but produces boxy artifacts.
box_blur: bool,
box_blur: Item<bool>,
/// Opt to incorrectly apply the filter with color calculations in gamma space for compatibility with the results from other software.
gamma: bool,
) -> Raster<CPU> {
// Run blur algorithm
if radius < 0.1 {
gamma: Item<bool>,
) -> Item<Raster<CPU>> {
let (radius, box_blur, gamma) = (*radius.element(), *box_blur.element(), *gamma.element());
let (image, attributes) = image_frame.into_parts();
let blurred_image = if radius < 0.1 {
// Minimum blur radius
image_frame
image
} else if box_blur {
Raster::new_cpu(box_blur_algorithm(image_frame.into_data(), radius, gamma))
Raster::new_cpu(box_blur_algorithm(image.into_data(), radius, gamma))
} else {
Raster::new_cpu(gaussian_blur_algorithm(image_frame.into_data(), radius, gamma))
}
Raster::new_cpu(gaussian_blur_algorithm(image.into_data(), radius, gamma))
};
Item::from_parts(blurred_image, attributes)
}
/// Applies a median filter to reduce noise while preserving edges.
@@ -116,20 +122,25 @@ fn blur(
fn median_filter(
_: impl Ctx,
/// The image to be filtered.
image_frame: Raster<CPU>,
image_frame: Item<Raster<CPU>>,
/// The radius of the filter kernel. Larger values remove more noise but may blur fine details.
#[range]
#[hard(0..)]
#[soft(..50)]
radius: PixelLength,
) -> Raster<CPU> {
// Apply median filter
if radius < 0.5 {
radius: Item<PixelLength>,
) -> Item<Raster<CPU>> {
let radius = *radius.element();
let (image, attributes) = image_frame.into_parts();
let filtered_image = if radius < 0.5 {
// Minimum filter radius
image_frame
image
} else {
Raster::new_cpu(median_filter_algorithm(image_frame.into_data(), radius as u32))
}
Raster::new_cpu(median_filter_algorithm(image.into_data(), radius as u32))
};
Item::from_parts(filtered_image, attributes)
}
// 1D gaussian kernel

View File

@@ -1,31 +1,31 @@
//! Not immediately shader compatible due to needing [`GradientStops`] as a param, which needs [`Vec`]
//! Not immediately shader compatible due to needing [`Gradient`] as a param, which needs [`Vec`]
use crate::adjust::Adjust;
use core_types::list::Item;
use core_types::{Color, Ctx};
use raster_types::{CPU, Raster};
use vector_types::GradientStops;
use vector_types::Gradient;
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27grdm%27%20%3D%20Gradient%20Map
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=Gradient%20settings%20(Photoshop%206.0)
#[node_macro::node(category("Raster: Adjustment"))]
fn gradient_map<T: Adjust<Color> + Clone + Send + Sync + core_types::CacheHash + 'static>(
async fn gradient_map<T: Adjust<Color> + Send>(
_: impl Ctx,
#[implementations(
Raster<CPU>,
Color,
GradientStops,
Gradient,
)]
mut image: T,
gradient: IList<GradientStops>,
reverse: bool,
) -> T {
if gradient.is_empty() {
return image;
}
let gradient = gradient.element_ref(0);
image: Item<T>,
gradient: Item<Gradient>,
reverse: Item<bool>,
) -> Item<T> {
let mut image = image;
let gradient = gradient.into_element();
let reverse = reverse.into_element();
image.adjust(|color| {
image.element_mut().adjust(|color| {
let intensity = color.luminance_rec_709();
let intensity = if reverse { 1. - intensity } else { intensity };
gradient.evaluate(intensity as f64)

View File

@@ -26,18 +26,17 @@ fn image_color_palette(
let g = pixel.g() * GRID;
let b = pixel.b() * GRID;
let bin = (r * GRID + g * GRID + b * GRID) as usize;
let bin = (r * GRID + g * GRID + b * GRID) as usize;
histogram[bin] += 1;
color_bins[bin].push(pixel.to_gamma_srgb_channels());
}
histogram[bin] += 1;
color_bins[bin].push(pixel.to_gamma_srgb_channels());
}
let shorted = histogram.iter().enumerate().filter(|&(_, &count)| count > 0).map(|(i, _)| i).collect::<Vec<usize>>();
let palette: Vec<Color> = shorted
.iter()
.take(count as usize)
.take(*count.element() as usize)
.flat_map(|&i| {
let list = &color_bins[i];

View File

@@ -5,6 +5,7 @@ use core_types::color::{Alpha, AlphaMut, Channel, LinearChannel, Luminance, RGBM
use core_types::context::{Ctx, ExtractFootprint, ExtractIndex, InjectIndex};
use core_types::extent::{LevelIn, ListIn, ValueIn};
use core_types::gpoll::{Extent, GPoll, GraphError, Interrupt};
use core_types::list::Item;
use core_types::math::bbox::Bbox;
use core_types::transform::Transform;
use dyn_any::DynAny;
@@ -369,32 +370,32 @@ pub fn image(_: impl Ctx, resource: Resource) -> Raster<CPU> {
pub fn noise_pattern(
ctx: impl ExtractFootprint + Ctx,
_primary: (),
#[default(true)] clip: bool,
seed: u32,
#[default(true)] clip: Item<bool>,
seed: Item<u32>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_scale")]
#[default(10.)]
scale: f64,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_noise_type")] noise_type: NoiseType,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_domain_warp_type")] domain_warp_type: DomainWarpType,
scale: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_noise_type")] noise_type: Item<NoiseType>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_domain_warp_type")] domain_warp_type: Item<DomainWarpType>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_domain_warp_amplitude")]
#[default(100.)]
domain_warp_amplitude: f64,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_type")] fractal_type: FractalType,
domain_warp_amplitude: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_type")] fractal_type: Item<FractalType>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_octaves")]
#[default(3)]
fractal_octaves: u32,
fractal_octaves: Item<u32>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_lacunarity")]
#[default(2.)]
fractal_lacunarity: f64,
fractal_lacunarity: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_gain")]
#[default(0.5)]
fractal_gain: f64,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_weighted_strength")] fractal_weighted_strength: f64,
fractal_gain: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_weighted_strength")] fractal_weighted_strength: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_ping_pong_strength")]
#[default(2.)]
fractal_ping_pong_strength: f64,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_cellular_distance_function")] cellular_distance_function: CellularDistanceFunction,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_cellular_return_type")] cellular_return_type: CellularReturnType,
fractal_ping_pong_strength: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_cellular_distance_function")] cellular_distance_function: Item<CellularDistanceFunction>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_cellular_return_type")] cellular_return_type: Item<CellularReturnType>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_cellular_jitter")]
#[default(1.)]
cellular_jitter: f64,

View File

@@ -51,8 +51,8 @@ pub fn repeat_array<T>(
content: impl Node<Context<'_>, Output = (T, Attr<TransformAttr>)>,
#[default(100., 100.)]
// TODO: When using a custom Properties panel layout in document_node_definitions.rs and this default is set, the widget weirdly doesn't show up in the Properties panel. Investigation is needed.
direction: PixelSize,
angle: Angle,
direction: Item<PixelSize>,
angle: Item<Angle>,
#[default(5)]
#[hard(1..)]
count: u32,
@@ -95,7 +95,7 @@ fn repeat_radial<T>(
start_angle: Angle,
#[unit(" px")]
#[default(5)]
radius: f64,
radius: Item<f64>,
#[default(5)]
#[hard(1..)]
count: u32,
@@ -186,6 +186,7 @@ mod test {
use core_types::record::{FieldWrite, FrameClaim, Layout, RecordSource, Served, capture, element_write};
use core_types::value::ValueSource;
use vector_types::subpath::Subpath;
use vector_types::vector::misc::BoxCorners;
struct TransformSource {
layout: Layout,

View File

@@ -14,37 +14,44 @@ fn format_json(
_: impl Ctx,
/// The JSON string to reformat.
#[name("JSON")]
json: String,
json: Item<String>,
/// Removes optional spaces within curly brackets and after colons and commas.
compact: bool,
compact: Item<bool>,
/// Break arrays and objects across multiple lines when they exceed the line break length.
#[default(true)]
#[name("Multi-Line")]
multi_line: bool,
multi_line: Item<bool>,
/// The indentation string used for each nesting level. Escape sequences like `\t` (the tab character) are supported. Two or four spaces are also common choices.
#[default("\\t")]
indent: String,
indent: Item<String>,
/// The maximum line length before a container (array or object) is broken across lines. Set this to 0 to always break containers. (Requires *Multi-Line* to take effect.)
///
/// This is not a maximum line length guarantee. Deep nesting and long keys or values may exceed this length.
#[default(120)]
break_length: u32,
break_length: Item<u32>,
/// Always break a container (array or object) across lines if it holds another container, even if it would fit within the break length. (Requires *Multi-Line* to take effect.)
#[default(true)]
break_nested: bool,
) -> String {
let cleaned = strip_trailing_commas(&json);
break_nested: Item<bool>,
) -> Item<String> {
let mut json = json;
let (compact, multi_line, break_length, break_nested) = (*compact.element(), *multi_line.element(), *break_length.element(), *break_nested.element());
let indent = indent.element().clone();
let cleaned = strip_trailing_commas(json.element());
let Ok(value) = serde_json::from_str::<serde_json::Value>(&cleaned) else { return json };
let indent = unescape_string(indent);
let colon = if compact { ":" } else { ": " };
let comma_space = if compact { "," } else { ", " };
let line_width = break_length as usize;
if multi_line {
let result = if multi_line {
format_value(&value, 0, &indent, colon, comma_space, compact, break_nested, line_width)
} else {
format_inline(&value, colon, comma_space, compact)
}
};
*json.element_mut() = result;
json
}
/// Strips trailing commas before `]` and `}` to accept JSON-with-trailing-commas input.
@@ -188,7 +195,7 @@ fn query_json(
_: impl Ctx,
/// The JSON string to extract a value from.
#[name("JSON")]
json: String,
json: Item<String>,
/// Determines which contained value to extract from within the JSON.
///
/// The path syntax is like JavaScript's accessor syntax that follows an array/object value. It also supports negative indexing to count backwards from the end. Additionally, `[]` accesses all array and object values instead of just one.
@@ -198,19 +205,29 @@ fn query_json(
/// Use `.size` or `["size"]` to get the `size` property of `{ "size": 10 }`. The latter form is required if the key contains spaces or special characters like `["this key with spaces!"]`.
/// Use chained accessors like `.fonts[0].name` to query deeper.
/// Use the `[]` accessor to query all elements, like `.fonts[].weights[]` to get every weight of every font.
path: String,
path: Item<String>,
/// Strips the surrounding double quotes from string values, returning the raw text. Other types are never wrapped in quotes.
#[default(true)]
unquote_strings: bool,
) -> String {
let cleaned = strip_trailing_commas(&json);
let Ok(value): Result<Value, _> = serde_json::from_str(&cleaned) else { return String::new() };
let Some(segments) = parse_json_path(path.trim()) else { return String::new() };
unquote_strings: Item<bool>,
) -> Item<String> {
let mut json = json;
let path = path.element().clone();
let unquote_strings = *unquote_strings.element();
let mut results = Vec::new();
resolve_all(&value, &segments, !unquote_strings, &mut results);
let cleaned = strip_trailing_commas(json.element());
results.into_iter().next().map(|(text, _ty)| text).unwrap_or_default()
let result = match (serde_json::from_str::<Value>(&cleaned), parse_json_path(path.trim())) {
(Ok(value), Some(segments)) => {
let mut results = Vec::new();
resolve_all(&value, &segments, !unquote_strings, &mut results);
results.into_iter().next().map(|(text, _ty)| text).unwrap_or_default()
}
_ => String::new(),
};
*json.element_mut() = result;
json
}
/// Extracts every matched value from a JSON string using a path expression (see that parameter's description for its syntax). A list of zero or more resultant strings is produced. The `[]` path accessor is used to read more than one value.
@@ -226,7 +243,7 @@ fn query_json_all(
_: impl Ctx,
/// The JSON string to extract values from.
#[name("JSON")]
json: String,
json: Item<String>,
/// Determines which contained values to extract from within the JSON.
///
/// The path syntax is like JavaScript's accessor syntax that follows an array/object value. It also supports negative indexing to count backwards from the end. Additionally, `[]` accesses all array and object values instead of just one.
@@ -236,17 +253,17 @@ fn query_json_all(
/// Use `.size` or `["size"]` to get the `size` property of `{ "size": 10 }`. The latter form is required if the key contains spaces or special characters like `["this key with spaces!"]`.
/// Use chained accessors like `.fonts[0].name` to query deeper.
/// Use the `[]` accessor to query all elements, like `.fonts[].weights[]` to get every weight of every font.
path: String,
path: Item<String>,
/// Strips the surrounding double quotes from string values, returning the raw text. Other types are never wrapped in quotes.
#[default(true)]
unquote_strings: bool,
unquote_strings: Item<bool>,
) -> List<String> {
let cleaned = strip_trailing_commas(&json);
let cleaned = strip_trailing_commas(json.element());
let Ok(value): Result<Value, _> = serde_json::from_str(&cleaned) else { return List::new() };
let Some(segments) = parse_json_path(path.trim()) else { return List::new() };
let Some(segments) = parse_json_path(path.element().trim()) else { return List::new() };
let mut results = Vec::new();
resolve_all(&value, &segments, !unquote_strings, &mut results);
resolve_all(&value, &segments, !*unquote_strings.element(), &mut results);
results.into_iter().map(|(text, ty)| Item::new_from_element(text).with_attribute(ATTR_TYPE, ty.to_string())).collect()
}

View File

@@ -187,34 +187,43 @@ pub enum StringCapitalization {
/// Constructs a string value which may be set to any plain text.
#[node_macro::node(category("Value"))]
fn string_value(_: impl Ctx, _primary: (), string: TextArea) -> String {
fn string_value(_: impl Ctx, _primary: (), string: Item<TextArea>) -> Item<String> {
string
}
/// Type-asserts a value to be a string.
#[node_macro::node(category("Debug"))]
fn as_string(_: impl Ctx, value: String) -> String {
fn as_string(_: impl Ctx, value: Item<String>) -> Item<String> {
value
}
/// Joins two strings together.
#[node_macro::node(category("Text"))]
fn string_concatenate(_: impl Ctx, #[implementations(String)] first: String, second: TextArea) -> String {
first + &second
fn string_concatenate(_: impl Ctx, #[implementations(String)] first: Item<String>, second: Item<TextArea>) -> Item<String> {
let mut first = first;
first.element_mut().push_str(second.element());
first
}
/// Replaces all occurrences of "From" with "To" in the input string.
#[node_macro::node(category("Text"))]
fn string_replace(_: impl Ctx, string: String, from: TextArea, to: TextArea) -> String {
string.replace(&from, &to)
fn string_replace(_: impl Ctx, string: Item<String>, from: Item<TextArea>, to: Item<TextArea>) -> Item<String> {
let mut string = string;
let result = string.element().replace(from.element().as_str(), to.element());
*string.element_mut() = result;
string
}
/// Extracts a substring from the input string, starting at "Start" and ending before "End".
///
/// Negative indices count from the end of the string. If the index of "Start" equals or exceeds "End", the result is an empty string.
#[node_macro::node(category("Text"))]
fn string_slice(_: impl Ctx, string: String, start: SignedInteger, end: SignedInteger) -> String {
let total_graphemes = string.graphemes(true).count();
fn string_slice(_: impl Ctx, string: Item<String>, start: Item<SignedInteger>, end: Item<SignedInteger>) -> Item<String> {
let mut string = string;
let (start, end) = (*start.element(), *end.element());
let total_graphemes = string.element().graphemes(true).count();
let start = if start < 0. {
total_graphemes.saturating_sub(start.abs() as usize)
@@ -227,11 +236,14 @@ fn string_slice(_: impl Ctx, string: String, start: SignedInteger, end: SignedIn
(end as usize).min(total_graphemes)
};
if start >= end {
return String::new();
}
let result = if start >= end {
String::new()
} else {
string.element().graphemes(true).skip(start).take(end - start).collect()
};
string.graphemes(true).skip(start).take(end - start).collect()
*string.element_mut() = result;
string
}
/// Clips the string to a maximum character length, optionally appending a suffix (like "…") when truncation occurs. Strings already within the limit are not modified.
@@ -239,27 +251,30 @@ fn string_slice(_: impl Ctx, string: String, start: SignedInteger, end: SignedIn
fn string_truncate(
_: impl Ctx,
/// The string to truncate.
string: String,
string: Item<String>,
/// The maximum number of characters allowed, including the suffix if one is appended.
#[default(80)]
length: u32,
length: Item<u32>,
/// A suffix appended to indicate truncation occurred, unless empty. Its length counts towards the character budget.
#[default("")]
suffix: String,
) -> String {
let max_length = length as usize;
let grapheme_count = string.graphemes(true).count();
suffix: Item<String>,
) -> Item<String> {
let mut string = string;
let max_length = *length.element() as usize;
let grapheme_count = string.element().graphemes(true).count();
if grapheme_count <= max_length {
return string;
}
let suffix: String = suffix.graphemes(true).take(max_length).collect();
let suffix: String = suffix.element().graphemes(true).take(max_length).collect();
let keep = max_length - suffix.graphemes(true).count();
let mut truncated: String = string.graphemes(true).take(keep).collect();
let mut truncated: String = string.element().graphemes(true).take(keep).collect();
truncated.push_str(&suffix);
truncated
*string.element_mut() = truncated;
string
}
/// Formats a number as a string with control over decimal places, decimal separator, and thousands grouping.
@@ -267,25 +282,31 @@ fn string_truncate(
fn format_number(
_: impl Ctx,
/// The number to format as a string.
number: f64,
number: Item<f64>,
/// The amount of digits after the decimal point. The value is rounded to fit. Set to 0 to show only whole numbers.
#[default(2)]
decimal_places: u32,
decimal_places: Item<u32>,
/// The character(s) used as the decimal point.
#[default(".")]
decimal_separator: String,
decimal_separator: Item<String>,
/// Always show the exact number of decimal places, even if they are trailing zeros.
#[default(true)]
fixed_decimals: bool,
fixed_decimals: Item<bool>,
/// Whether to group digits with a thousands separator.
use_thousands_separator: bool,
use_thousands_separator: Item<bool>,
/// The character(s) inserted between digit groups.
#[default(",")]
thousands_separator: String,
thousands_separator: Item<String>,
/// Don't group 4-digit numbers with a thousands separator (only start grouping at 10,000 and above).
#[name("Start at 10,000")]
start_at_10000: bool,
) -> String {
start_at_10000: Item<bool>,
) -> Item<String> {
let (number, attributes) = number.into_parts();
let (decimal_places, fixed_decimals, use_thousands_separator, start_at_10000) =
(*decimal_places.element(), *fixed_decimals.element(), *use_thousands_separator.element(), *start_at_10000.element());
let decimal_separator = decimal_separator.element().clone();
let thousands_separator = thousands_separator.element().clone();
// Find the maximum meaningful decimal precision by detecting where float noise begins.
// This works correctly whether the value originated as f32 or f64, since we find the
// shortest decimal representation that round-trips back to the same f64 value.
@@ -340,36 +361,38 @@ fn format_number(
};
// Build the final string
let Some(decimal_string) = decimal_string else {
if fixed_decimals && requested_places > 0 {
let result = match decimal_string {
None if fixed_decimals && requested_places > 0 => {
let zeros = "0".repeat(requested_places);
return format!("{sign}{grouped_whole}{decimal_separator}{zeros}");
format!("{sign}{grouped_whole}{decimal_separator}{zeros}")
}
None => format!("{sign}{grouped_whole}"),
Some(decimal_string) if fixed_decimals => format!("{sign}{grouped_whole}{decimal_separator}{decimal_string}"),
Some(decimal_string) => {
let trimmed = decimal_string.trim_end_matches('0');
if trimmed.is_empty() {
format!("{sign}{grouped_whole}")
} else {
format!("{sign}{grouped_whole}{decimal_separator}{trimmed}")
}
}
return format!("{sign}{grouped_whole}");
};
if fixed_decimals {
format!("{sign}{grouped_whole}{decimal_separator}{decimal_string}")
} else {
let trimmed = decimal_string.trim_end_matches('0');
if trimmed.is_empty() {
format!("{sign}{grouped_whole}")
} else {
format!("{sign}{grouped_whole}{decimal_separator}{trimmed}")
}
}
Item::from_parts(result, attributes)
}
/// Parses a string into a number. Falls back to the chosen value if the string is not a valid number.
#[node_macro::node(category("Text"))]
#[node_macro::node(category("Text"), name("String to Number"))]
fn string_to_number(
_: impl Ctx,
/// The string containing a number. Surrounding whitespace is ignored, a decimal point (.) may be included, sign prefixes (+/-) are respected, and scientific notation (e.g. "1e-3") is supported.
string: String,
string: Item<String>,
/// The value of the result if the string cannot be parsed as a valid number.
fallback: f64,
) -> f64 {
string.trim().parse::<f64>().unwrap_or(fallback)
fallback: Item<f64>,
) -> Item<f64> {
let (string, attributes) = string.into_parts();
Item::from_parts(string.trim().parse::<f64>().unwrap_or(*fallback.element()), attributes)
}
/// Removes leading and/or trailing whitespace from a string. Common whitespace characters include spaces, tabs, and newlines.
@@ -377,20 +400,26 @@ fn string_to_number(
fn string_trim(
_: impl Ctx,
/// The string that may contain leading and trailing whitespace that should be removed.
string: String,
string: Item<String>,
/// Whether the start of the string should have its whitespace removed.
#[default(true)]
start: bool,
start: Item<bool>,
/// Whether the end of the string should have its whitespace removed.
#[default(true)]
end: bool,
) -> String {
match (start, end) {
(true, true) => string.trim().to_string(),
(true, false) => string.trim_start().to_string(),
(false, true) => string.trim_end().to_string(),
(false, false) => string,
}
end: Item<bool>,
) -> Item<String> {
let mut string = string;
let (start, end) = (*start.element(), *end.element());
let result = match (start, end) {
(true, true) => string.element().trim().to_string(),
(true, false) => string.element().trim_start().to_string(),
(false, true) => string.element().trim_end().to_string(),
(false, false) => return string,
};
*string.element_mut() = result;
string
}
/// Converts between literal escape sequences and their corresponding control characters within a string.
@@ -401,12 +430,18 @@ fn string_trim(
fn string_escape(
_: impl Ctx,
/// The string that contains either literal escape sequences or control characters to be converted to the opposite representation.
string: String,
string: Item<String>,
/// Convert the control characters back into their escape sequence representations.
#[default(true)]
unescape: bool,
) -> String {
if unescape { unescape_string(string) } else { escape_string(string) }
unescape: Item<bool>,
) -> Item<String> {
let mut string = string;
let input = std::mem::take(string.element_mut());
let result = if *unescape.element() { unescape_string(input) } else { escape_string(input) };
*string.element_mut() = result;
string
}
/// Reverses the sequence of characters making up the string so it reads back-to-front. ("Backwards text" becomes "txet sdrawkcaB".)
@@ -414,9 +449,13 @@ fn string_escape(
fn string_reverse(
_: impl Ctx,
/// The string to be reversed.
string: String,
) -> String {
string.graphemes(true).rev().collect()
string: Item<String>,
) -> Item<String> {
let mut string = string;
let result: String = string.element().graphemes(true).rev().collect();
*string.element_mut() = result;
string
}
/// Repeats the string a given number of times, optionally with a separator between each repetition.
@@ -424,31 +463,35 @@ fn string_reverse(
fn string_repeat(
_: impl Ctx,
/// The string to be repeated.
string: String,
string: Item<String>,
/// The number of times the string should appear in the output.
#[default(2)]
#[hard(1..)]
count: u32,
count: Item<u32>,
/// The string placed between each repetition.
#[default("\\n")]
separator: String,
separator: Item<String>,
/// Whether to convert escape sequences found in the separator into their corresponding characters:
/// "\n" (newline), "\r" (carriage return), "\t" (tab), "\0" (null), and "\\" (backslash).
#[default(true)]
separator_escaping: bool,
) -> String {
let separator = if separator_escaping { unescape_string(separator) } else { separator };
separator_escaping: Item<bool>,
) -> Item<String> {
let mut string = string;
let separator = separator.element().clone();
let separator = if *separator_escaping.element() { unescape_string(separator) } else { separator };
let count = count as usize;
let count = *count.element() as usize;
let mut result = String::with_capacity((string.len() + separator.len()) * count);
let mut result = String::with_capacity((string.element().len() + separator.len()) * count);
for i in 0..count {
if i > 0 {
result.push_str(&separator);
}
result.push_str(&string);
result.push_str(string.element());
}
result
*string.element_mut() = result;
string
}
/// Pads the string to a target length by filling with the given repeated substring. If the string already meets or exceeds the target length, it is returned unchanged.
@@ -456,21 +499,25 @@ fn string_repeat(
fn string_pad(
_: impl Ctx,
/// The string to be padded to a target length.
string: String,
string: Item<String>,
/// The target character length after padding. When "Up To" is set, this length concerns only the portion before (or after) that substring.
#[default(10)]
length: u32,
length: Item<u32>,
/// The repeated substring used to fill the remaining space. A multi-charcter substring may end partway through its final repetition.
#[default("#")]
padding: String,
padding: Item<String>,
/// Pad only the length of the string encountered before the start of the first (or after the end of the last) occurrence of this substring, if given and present (otherwise the full string is considered).
///
/// For example, this can pad numbers with leading zeros to align them before the decimal point.
up_to: String,
up_to: Item<String>,
/// Pad at the end of the string instead of the start.
from_end: bool,
) -> String {
let target_length = length as usize;
from_end: Item<bool>,
) -> Item<String> {
let mut string = string;
let target_length = *length.element() as usize;
let padding = padding.element().clone();
let up_to = up_to.element().clone();
let from_end = *from_end.element();
if padding.is_empty() {
return string;
@@ -478,9 +525,9 @@ fn string_pad(
// Split the string at the "up to" substring if provided, and only pad that portion
if !up_to.is_empty()
&& let Some(position) = if from_end { string.rfind(&*up_to) } else { string.find(&*up_to) }
&& let Some(position) = if from_end { string.element().rfind(&*up_to) } else { string.element().find(&*up_to) }
{
let (before, after) = string.split_at(position);
let (before, after) = string.element().split_at(position);
if from_end {
// Pad the portion after the substring
@@ -491,7 +538,10 @@ fn string_pad(
}
let pad_length = target_length - current_length;
let padding: String = padding.graphemes(true).cycle().take(pad_length).collect();
return format!("{before}{up_to}{after_substring}{padding}");
let result = format!("{before}{up_to}{after_substring}{padding}");
*string.element_mut() = result;
return string;
} else {
// Pad the portion before the substring
let current_length = before.graphemes(true).count();
@@ -500,11 +550,14 @@ fn string_pad(
}
let pad_length = target_length - current_length;
let padding: String = padding.graphemes(true).cycle().take(pad_length).collect();
return format!("{padding}{before}{after}");
let result = format!("{padding}{before}{after}");
*string.element_mut() = result;
return string;
}
}
let current_length = string.graphemes(true).count();
let current_length = string.element().graphemes(true).count();
if current_length >= target_length {
return string;
}
@@ -512,7 +565,10 @@ fn string_pad(
let pad_length = target_length - current_length;
let padding: String = padding.graphemes(true).cycle().take(pad_length).collect();
if from_end { string + &padding } else { padding + &string }
let result = if from_end { string.element().clone() + &padding } else { padding + string.element() };
*string.element_mut() = result;
string
}
/// Checks whether the string contains the given substring. Optionally restricts the match to only the start and/or end of the string.
@@ -520,20 +576,26 @@ fn string_pad(
fn string_contains(
_: impl Ctx,
/// The string to search within.
string: String,
string: Item<String>,
/// The substring to search for.
substring: String,
substring: Item<String>,
/// Only match if the substring appears at the start of the string.
at_start: bool,
at_start: Item<bool>,
/// Only match if the substring appears at the end of the string.
at_end: bool,
) -> bool {
match (at_start, at_end) {
(true, true) => string.starts_with(&*substring) && string.ends_with(&*substring),
(true, false) => string.starts_with(&*substring),
(false, true) => string.ends_with(&*substring),
(false, false) => string.contains(&*substring),
}
at_end: Item<bool>,
) -> Item<bool> {
let (string, attributes) = string.into_parts();
let substring = substring.element().as_str();
let (at_start, at_end) = (*at_start.element(), *at_end.element());
let result = match (at_start, at_end) {
(true, true) => string.starts_with(substring) && string.ends_with(substring),
(true, false) => string.starts_with(substring),
(false, true) => string.ends_with(substring),
(false, false) => string.contains(substring),
};
Item::from_parts(result, attributes)
}
/// Similar to the **String Contains** node, this searches within the input string for the first (or last) occurrence of a substring and returns the index of where that begins, or -1 if not found.
@@ -541,28 +603,35 @@ fn string_contains(
fn string_find_index(
_: impl Ctx,
/// The string to search within.
string: String,
string: Item<String>,
/// The substring to search for.
substring: String,
substring: Item<String>,
/// Find the start index of the last occurrence instead of the first.
from_end: bool,
) -> f64 {
from_end: Item<bool>,
) -> Item<f64> {
let (string, attributes) = string.into_parts();
let substring = substring.element().as_str();
let from_end = *from_end.element();
if substring.is_empty() {
return if from_end { string.graphemes(true).count() as f64 } else { 0. };
let result = if from_end { string.graphemes(true).count() as f64 } else { 0. };
return Item::from_parts(result, attributes);
}
if from_end {
let result = if from_end {
// Search backwards by finding all byte-level matches and taking the last one
string
.rmatch_indices(&*substring)
.rmatch_indices(substring)
.next()
.map_or(-1., |(byte_index, _)| string[..byte_index].graphemes(true).count() as f64)
} else {
string
.match_indices(&*substring)
.match_indices(substring)
.next()
.map_or(-1., |(byte_index, _)| string[..byte_index].graphemes(true).count() as f64)
}
};
Item::from_parts(result, attributes)
}
/// Counts the number of occurrences of a substring within the string.
@@ -570,22 +639,25 @@ fn string_find_index(
fn string_occurrences(
_: impl Ctx,
/// The string to search within.
string: String,
string: Item<String>,
/// The substring to count occurrences of.
substring: String,
substring: Item<String>,
/// Whether to count overlapping occurrences, using the substring as a sliding window.
///
/// For example, "aa" occurs twice in "aaaa" without overlapping but three times with overlapping.
overlapping: bool,
) -> f64 {
overlapping: Item<bool>,
) -> Item<f64> {
let (string, attributes) = string.into_parts();
let substring = substring.element().as_str();
if substring.is_empty() {
return 0.;
return Item::from_parts(0., attributes);
}
// NON-OVERLAPPING: Simple linear scan.
// O(n), where n = string length
if !overlapping {
return string.matches(&*substring).count() as f64;
if !*overlapping.element() {
return Item::from_parts(string.matches(substring).count() as f64, attributes);
}
// OVERLAPPING: KMP (Knuth-Morris-Pratt) algorithm.
@@ -631,7 +703,7 @@ fn string_occurrences(
}
}
count as f64
Item::from_parts(count as f64, attributes)
}
/// Converts a string's capitalization style to another of the common upper and lower case patterns, optionally joining words with a chosen separator.
@@ -639,47 +711,49 @@ fn string_occurrences(
fn string_capitalization(
_: impl Ctx,
/// The string to have its letter capitalization converted.
string: String,
string: Item<String>,
/// The capitalization style to apply.
capitalization: StringCapitalization,
capitalization: Item<StringCapitalization>,
/// Whether to split the string into words and reconnect with the chosen joiner. When disabled, the existing word structure separators are preserved.
use_joiner: bool,
use_joiner: Item<bool>,
/// The string placed between each word.
joiner: String,
) -> String {
joiner: Item<String>,
) -> Item<String> {
let mut string = string;
let capitalization = *capitalization.element();
let use_joiner = *use_joiner.element();
let joiner = joiner.element().clone();
let input = std::mem::take(string.element_mut());
// When the joiner is enabled, apply word-level casing and optionally reconnect words with the selected joiner
if use_joiner {
let result = if use_joiner {
match capitalization {
// Simple case mappings that preserve the string's existing structure
StringCapitalization::LowerCase => string.to_lowercase(),
StringCapitalization::UpperCase => string.to_uppercase(),
StringCapitalization::LowerCase => input.to_lowercase(),
StringCapitalization::UpperCase => input.to_uppercase(),
// Word-aware capitalizations that split on word boundaries and rejoin with the joiner
StringCapitalization::CapitalCase => Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::capital).set_delim(&joiner).convert(&string),
StringCapitalization::CapitalCase => Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::capital).set_delim(&joiner).convert(&input),
StringCapitalization::HeadlineCase => {
// First split into words with convert_case so word boundaries like "AlphaNumeric" are detected consistently with other modes,
// then apply the titlecase crate for smart capitalization (lowercasing short words like "of", "the", etc.),
// then rejoin with the custom joiner without mangling the capitalization
let spaced = Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::capital).set_delim(" ").convert(&string);
let spaced = Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::capital).set_delim(" ").convert(&input);
let headline = titlecase::titlecase(&spaced);
Converter::new().set_boundaries(&[Boundary::SPACE]).set_pattern(pattern::noop).set_delim(&joiner).convert(&headline)
}
StringCapitalization::SentenceCase => Converter::new()
.set_boundaries(&Boundary::defaults())
.set_pattern(pattern::sentence)
.set_delim(&joiner)
.convert(&string),
StringCapitalization::CamelCase => Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::camel).set_delim(&joiner).convert(&string),
StringCapitalization::SentenceCase => Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::sentence).set_delim(&joiner).convert(&input),
StringCapitalization::CamelCase => Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::camel).set_delim(&joiner).convert(&input),
}
}
// When the joiner is disabled, apply only character-level casing while preserving the string's existing structure
else {
match capitalization {
StringCapitalization::LowerCase => string.to_lowercase(),
StringCapitalization::UpperCase => string.to_uppercase(),
StringCapitalization::LowerCase => input.to_lowercase(),
StringCapitalization::UpperCase => input.to_uppercase(),
StringCapitalization::CapitalCase => {
let mut capitalize_next = true;
string.chars().fold(String::with_capacity(string.len()), |mut result, c| {
input.chars().fold(String::with_capacity(input.len()), |mut result, c| {
if c.is_whitespace() || c == '_' || c == '-' {
capitalize_next = true;
result.push(c);
@@ -692,9 +766,9 @@ fn string_capitalization(
result
})
}
StringCapitalization::HeadlineCase => titlecase::titlecase(&string),
StringCapitalization::HeadlineCase => titlecase::titlecase(&input),
StringCapitalization::SentenceCase => {
let mut chars = string.chars();
let mut chars = input.chars();
match chars.next() {
Some(first) => first.to_uppercase().to_string() + &chars.as_str().to_lowercase(),
None => String::new(),
@@ -702,7 +776,7 @@ fn string_capitalization(
}
StringCapitalization::CamelCase => {
let mut capitalize_next = false;
string.chars().fold(String::with_capacity(string.len()), |mut result, c| {
input.chars().fold(String::with_capacity(input.len()), |mut result, c| {
if c.is_whitespace() || c == '_' || c == '-' {
capitalize_next = true;
result.push(c);
@@ -716,15 +790,20 @@ fn string_capitalization(
})
}
}
}
};
*string.element_mut() = result;
string
}
// TODO: Return u32, u64, or usize instead of f64 after #1621 is resolved and has allowed us to implement automatic type conversion in the node graph for nodes with generic type inputs.
// TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.)
/// Counts the number of characters in a string.
#[node_macro::node(category("Text"))]
fn string_length(_: impl Ctx, string: String) -> f64 {
string.graphemes(true).count() as f64
fn string_length(_: impl Ctx, string: Item<String>) -> Item<f64> {
let (string, attributes) = string.into_parts();
Item::from_parts(string.graphemes(true).count() as f64, attributes)
}
/// Splits a string into a list of substrings based on the specified delimiter. This is the inverse of the **String Join** node.
@@ -734,18 +813,19 @@ fn string_length(_: impl Ctx, string: String) -> f64 {
fn string_split(
_: impl Ctx,
/// The string to split into substrings.
string: String,
string: Item<String>,
/// The character(s) that separate the substrings. These are not included in the outputs.
#[default("\\n")]
delimiter: String,
delimiter: Item<String>,
/// Whether to convert escape sequences found in the delimiter into their corresponding characters:
/// "\n" (newline), "\r" (carriage return), "\t" (tab), "\0" (null), and "\\" (backslash).
#[default(true)]
delimiter_escaping: bool,
delimiter_escaping: Item<bool>,
) -> List<String> {
let delimiter = if delimiter_escaping { unescape_string(delimiter) } else { delimiter };
let delimiter = delimiter.element().clone();
let delimiter = if *delimiter_escaping.element() { unescape_string(delimiter) } else { delimiter };
string.split(&delimiter).map(str::to_string).map(Item::new_from_element).collect()
string.element().split(&delimiter).map(str::to_string).map(Item::new_from_element).collect()
}
/// Joins a list of strings together with a separator between each pair. This is the inverse of the **String Split** node.
@@ -758,15 +838,18 @@ fn string_join(
strings: List<String>,
/// The text placed between each pair of strings.
#[default(", ")]
separator: String,
separator: Item<String>,
/// Whether to convert escape sequences found in the separator into their corresponding characters:
/// "\n" (newline), "\r" (carriage return), "\t" (tab), "\0" (null), and "\\" (backslash).
#[default(true)]
separator_escaping: bool,
) -> String {
separator_escaping: Item<bool>,
) -> Item<String> {
let (separator, separator_escaping) = (separator.into_element(), separator_escaping.into_element());
let separator = if separator_escaping { unescape_string(separator) } else { separator };
strings.iter_element_values().map(|s| s.as_str()).collect::<Vec<_>>().join(&separator)
let joined = strings.iter_element_values().map(|s| s.as_str()).collect::<Vec<_>>().join(&separator);
Item::new_from_element(joined)
}
/// Iterates over a list of strings, evaluating the mapped operation for each one. Use the **Read String** node to access the current string inside the loop.
@@ -775,18 +858,17 @@ fn map_string(
ctx: impl Ctx + DeriveCtx,
strings: List<String>,
#[expose]
#[implementations(Context -> String)]
mapped: impl Node<Context<'_>, Output = String>,
#[implementations(Context -> Item<String>)]
mapped: impl Node<Context<'_>, Output = Item<String>>,
) -> Result<List<String>, Interrupt> {
let spilled = ctx.index_head();
let mut result = List::new();
for (i, row) in strings.into_iter().enumerate() {
let string = row.into_element();
let scoped = ctx.push_vararg(&string);
let scoped = ctx.push_vararg(&row);
let mapped_string = mapped.eval(&scoped.ctx().promoted(&spilled, i as u64))?;
result.push(Item::new_from_element(mapped_string));
result.push(mapped_string);
}
Ok(result)
@@ -794,15 +876,19 @@ fn map_string(
/// Reads the current string from within a **Map String** node's loop.
#[node_macro::node(category("Context"))]
fn read_string(ctx: impl Ctx + ExtractVarArgs) -> String {
let Ok(var_arg) = ctx.vararg(0) else { return String::new() };
fn read_string(ctx: impl Ctx + ExtractVarArgs) -> Item<String> {
let Ok(var_arg) = ctx.vararg(0) else { return Item::new_from_element(String::new()) };
let var_arg = var_arg as &dyn std::any::Any;
var_arg.downcast_ref::<String>().cloned().unwrap_or_default()
var_arg.downcast_ref::<Item<String>>().cloned().unwrap_or_default()
}
/// Converts a value to a JSON string representation.
#[node_macro::node(category("Debug"))]
fn serialize<T: serde::Serialize>(_: impl Ctx, #[implementations(String, bool, f64, u32, u64, DVec2, DAffine2)] value: T) -> String {
serde_json::to_string(&value).unwrap_or_else(|_| "Serialization Error".to_string())
fn serialize<T: serde::Serialize>(_: impl Ctx, #[implementations(String, bool, f64, u32, u64, DVec2, DAffine2)] value: Item<T>) -> Item<String> {
let (value, attributes) = value.into_parts();
let result = serde_json::to_string(&value).unwrap_or_else(|_| "Serialization Error".to_string());
Item::from_parts(result, attributes)
}

View File

@@ -202,7 +202,7 @@ impl PathBuilder {
}
}
// "Separate Glyphs" off: widen the accumulated AABBs and bundle as one override `Vector`
// Glyph separation off: widen the accumulated AABBs and bundle as one override `Vector`
if !self.merged_click_target_bboxes.is_empty() {
let mut bboxes = self.merged_click_target_bboxes;
widen_horizontal_gaps(&mut bboxes, &self.merged_click_target_baselines);

View File

@@ -7,18 +7,22 @@ use core_types::{ATTR_END, ATTR_NAME, ATTR_START, Ctx};
fn regex_contains(
_: impl Ctx,
/// The string to search within.
string: String,
string: Item<String>,
/// The regular expression pattern to search for.
pattern: String,
pattern: Item<String>,
/// Match letters regardless of case.
case_insensitive: bool,
case_insensitive: Item<bool>,
/// Make `^` and `$` match the start and end of each line, not just the whole string.
multiline: bool,
multiline: Item<bool>,
/// Only match if the pattern appears at the start of the string.
at_start: bool,
at_start: Item<bool>,
/// Only match if the pattern appears at the end of the string.
at_end: bool,
) -> bool {
at_end: Item<bool>,
) -> Item<bool> {
let (string, attributes) = string.into_parts();
let pattern = pattern.element();
let (case_insensitive, multiline, at_start, at_end) = (*case_insensitive.element(), *multiline.element(), *at_start.element(), *at_end.element());
let flags = match (case_insensitive, multiline) {
(false, false) => "",
(true, false) => "(?i)",
@@ -34,29 +38,34 @@ fn regex_contains(
let Ok(regex) = fancy_regex::Regex::new(&anchored_pattern) else {
log::error!("Invalid regex pattern: {pattern}");
return false;
return Item::from_parts(false, attributes);
};
regex.is_match(&string).unwrap_or(false)
Item::from_parts(regex.is_match(&string).unwrap_or(false), attributes)
}
/// Replaces matches of a regular expression pattern in the string. The replacement string can reference captures: `$0` for the whole match and `$1`, `$2`, etc. for capture groups.
#[node_macro::node(category("Text: Regex"))]
fn regex_replace(
_: impl Ctx,
string: String,
string: Item<String>,
/// The regular expression pattern to search for.
pattern: String,
pattern: Item<String>,
/// The replacement string. Use `$0` for the whole match and `$1`, `$2`, etc. for capture groups.
replacement: String,
replacement: Item<String>,
/// Replace all matches. When disabled, only the first match is replaced.
#[default(true)]
replace_all: bool,
replace_all: Item<bool>,
/// Match letters regardless of case.
case_insensitive: bool,
case_insensitive: Item<bool>,
/// Make `^` and `$` match the start and end of each line, not just the whole string.
multiline: bool,
) -> String {
multiline: Item<bool>,
) -> Item<String> {
let mut string = string;
let pattern = pattern.element().clone();
let replacement = replacement.element().clone();
let (replace_all, case_insensitive, multiline) = (*replace_all.element(), *case_insensitive.element(), *multiline.element());
let flags = match (case_insensitive, multiline) {
(false, false) => "",
(true, false) => "(?i)",
@@ -70,11 +79,14 @@ fn regex_replace(
return string;
};
if replace_all {
regex.replace_all(&string, replacement.as_str()).into_owned()
let result = if replace_all {
regex.replace_all(string.element(), replacement.as_str()).into_owned()
} else {
regex.replace(&string, replacement.as_str()).into_owned()
}
regex.replace(string.element(), replacement.as_str()).into_owned()
};
*string.element_mut() = result;
string
}
/// Finds a regex match in the string and returns its components. The result is a list where the first item is the whole match (`$0`) and subsequent items are the capture groups (`$1`, `$2`, etc., if any).
@@ -87,16 +99,20 @@ fn regex_replace(
fn regex_find(
_: impl Ctx,
/// The string to search within.
string: String,
string: Item<String>,
/// The regular expression pattern to search for.
pattern: String,
pattern: Item<String>,
/// Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.
match_index: SignedInteger,
match_index: Item<SignedInteger>,
/// Match letters regardless of case.
case_insensitive: bool,
case_insensitive: Item<bool>,
/// Make `^` and `$` match the start and end of each line, not just the whole string.
multiline: bool,
multiline: Item<bool>,
) -> List<String> {
let string = string.element();
let pattern = pattern.element();
let (match_index, case_insensitive, multiline) = (*match_index.element(), *case_insensitive.element(), *multiline.element());
if pattern.is_empty() {
return List::new();
}
@@ -118,7 +134,7 @@ fn regex_find(
let capture_names: Vec<Option<String>> = regex.capture_names().map(|name| name.map(str::to_string)).collect();
// Collect all matches since we need to support negative indexing
let matches: Vec<_> = regex.captures_iter(&string).filter_map(|c| c.ok()).collect();
let matches: Vec<_> = regex.captures_iter(string).filter_map(|c| c.ok()).collect();
let match_index = match_index as i32;
let resolved_index = if match_index < 0 {
@@ -158,14 +174,18 @@ fn regex_find(
fn regex_find_all(
_: impl Ctx,
/// The string to search within.
string: String,
string: Item<String>,
/// The regular expression pattern to search for.
pattern: String,
pattern: Item<String>,
/// Match letters regardless of case.
case_insensitive: bool,
case_insensitive: Item<bool>,
/// Make `^` and `$` match the start and end of each line, not just the whole string.
multiline: bool,
multiline: Item<bool>,
) -> List<String> {
let string = string.element();
let pattern = pattern.element();
let (case_insensitive, multiline) = (*case_insensitive.element(), *multiline.element());
if pattern.is_empty() {
return List::new();
}
@@ -184,7 +204,7 @@ fn regex_find_all(
};
regex
.find_iter(&string)
.find_iter(string)
.filter_map(|m| m.ok())
.map(|m| {
Item::new_from_element(m.as_str().to_string())
@@ -201,16 +221,19 @@ fn regex_find_all(
fn regex_split(
_: impl Ctx,
/// The string to split into substrings.
string: String,
string: Item<String>,
/// The regular expression pattern to split on. Matches are consumed and not included in the output.
pattern: String,
pattern: Item<String>,
/// Match letters regardless of case.
case_insensitive: bool,
case_insensitive: Item<bool>,
/// Make `^` and `$` match the start and end of each line, not just the whole string.
multiline: bool,
multiline: Item<bool>,
) -> List<String> {
let pattern = pattern.element().clone();
let (case_insensitive, multiline) = (*case_insensitive.element(), *multiline.element());
if pattern.is_empty() {
return List::new_from_element(string);
return List::new_from_item(string);
}
let flags = match (case_insensitive, multiline) {
@@ -223,8 +246,8 @@ fn regex_split(
let Ok(regex) = fancy_regex::Regex::new(&full_pattern) else {
log::error!("Invalid regex pattern: {pattern}");
return List::new_from_element(string);
return List::new_from_item(string);
};
regex.split(&string).filter_map(|s| s.ok()).map(|s| s.to_string()).map(Item::new_from_element).collect()
regex.split(string.element()).filter_map(|s| s.ok()).map(|s| s.to_string()).map(Item::new_from_element).collect()
}

View File

@@ -2,8 +2,7 @@ use super::TypesettingConfig;
use super::text_context::TextContext;
use crate::markers::{ATTR_FONT, ATTR_TEXT_ALIGN};
use core_types::blending::BlendMode;
use core_types::list::List;
use core_types::uuid::NodeId;
use core_types::list::{Item, List, NodeIdPath};
use core_types::{
ATTR_BLEND_MODE, ATTR_EDITOR_LAYER_PATH, ATTR_FONT_SIZE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM,
};
@@ -23,60 +22,71 @@ pub fn lines_clipping(text: &str, font: &Resource, typesetting: TypesettingConfi
TextContext::with_thread_local(|ctx| ctx.lines_clipping(text, font, typesetting))
}
/// Shapes each string item of a styled `List<String>` into vector geometry, reading its font and typesetting
/// from the item's attributes (as set by the 'Text' node) and re-applying its transform and blending
/// attributes onto the produced paths. With `separate_glyphs`, each glyph becomes its own item.
/// Shapes a single styled string item into vector geometry, reading its font and typesetting from the item's
/// attributes (as set by the 'Text' node) and re-applying its transform and blending attributes onto the produced
/// paths. With `separate_glyphs`, each glyph becomes its own item; otherwise a single compound path is produced.
pub fn shape_text_item(item: &Item<String>, separate_glyphs: bool) -> List<Vector> {
let text = item.element();
if text.is_empty() {
return List::new();
}
// Use fallback font when none is explicitly attached.
let font: Resource = {
let font: Resource = item.attribute_cloned_or_default(ATTR_FONT);
if font.is_empty() { super::FALLBACK_FONT_RESOURCE.clone() } else { font }
};
let defaults = TypesettingConfig::default();
let typesetting = TypesettingConfig {
font_size: item.attribute_cloned_or(ATTR_FONT_SIZE, defaults.font_size),
line_height_ratio: item.attribute_cloned_or(ATTR_LINE_HEIGHT, defaults.line_height_ratio),
letter_spacing: item.attribute_cloned_or(ATTR_LETTER_SPACING, defaults.letter_spacing),
letter_tilt: item.attribute_cloned_or(ATTR_LETTER_TILT, defaults.letter_tilt),
max_width: item.attribute_cloned_or::<Option<f64>>(ATTR_MAX_WIDTH, defaults.max_width),
max_height: item.attribute_cloned_or::<Option<f64>>(ATTR_MAX_HEIGHT, defaults.max_height),
align: item.attribute_cloned_or(ATTR_TEXT_ALIGN, defaults.align),
};
let vectors = to_path(text, &font, typesetting, separate_glyphs);
let transform = item.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
let layer_path = item.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH).cloned();
let blend_mode = item.attribute::<BlendMode>(ATTR_BLEND_MODE).copied();
let opacity = item.attribute::<f64>(ATTR_OPACITY).copied();
let opacity_fill = item.attribute::<f64>(ATTR_OPACITY_FILL).copied();
let mut result = List::new();
for mut produced in vectors.into_iter() {
if transform != DAffine2::IDENTITY {
let local = produced.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
produced.set_attribute(ATTR_TRANSFORM, transform * local);
}
if let Some(layer_path) = &layer_path {
produced.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.clone());
}
if let Some(blend_mode) = blend_mode {
produced.set_attribute(ATTR_BLEND_MODE, blend_mode);
}
if let Some(opacity) = opacity {
produced.set_attribute(ATTR_OPACITY, opacity);
}
if let Some(opacity_fill) = opacity_fill {
produced.set_attribute(ATTR_OPACITY_FILL, opacity_fill);
}
result.push(produced);
}
result
}
/// Shapes each string item of a styled `List<String>` into vector geometry, flattening the per-item results.
pub fn shape_text_list(strings: &List<String>, separate_glyphs: bool) -> List<Vector> {
let mut result = List::new();
for index in 0..strings.len() {
let Some(text) = strings.element(index) else { continue };
if text.is_empty() {
continue;
}
// Use fallback font when none is explicitly attached.
let font: Resource = {
let f: Resource = strings.attribute_cloned_or_default(ATTR_FONT, index);
if f.is_empty() { super::FALLBACK_FONT_RESOURCE.clone() } else { f }
};
let defaults = TypesettingConfig::default();
let typesetting = TypesettingConfig {
font_size: strings.attribute_cloned_or(ATTR_FONT_SIZE, index, defaults.font_size),
line_height_ratio: strings.attribute_cloned_or(ATTR_LINE_HEIGHT, index, defaults.line_height_ratio),
letter_spacing: strings.attribute_cloned_or(ATTR_LETTER_SPACING, index, defaults.letter_spacing),
letter_tilt: strings.attribute_cloned_or(ATTR_LETTER_TILT, index, defaults.letter_tilt),
max_width: strings.attribute_cloned_or::<Option<f64>>(ATTR_MAX_WIDTH, index, defaults.max_width),
max_height: strings.attribute_cloned_or::<Option<f64>>(ATTR_MAX_HEIGHT, index, defaults.max_height),
align: strings.attribute_cloned_or(ATTR_TEXT_ALIGN, index, defaults.align),
};
let vectors = to_path(text, &font, typesetting, separate_glyphs);
let transform = strings.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, index);
let layer_path = strings.attribute_cloned_or_default::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH, index);
let blend_mode = strings.attribute::<BlendMode>(ATTR_BLEND_MODE, index).copied();
let opacity = strings.attribute::<f64>(ATTR_OPACITY, index).copied();
let opacity_fill = strings.attribute::<f64>(ATTR_OPACITY_FILL, index).copied();
for mut item in vectors.into_iter() {
if transform != DAffine2::IDENTITY {
let local = item.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
item.set_attribute(ATTR_TRANSFORM, transform * local);
}
if !layer_path.is_empty() {
item.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.clone());
}
if let Some(blend_mode) = blend_mode {
item.set_attribute(ATTR_BLEND_MODE, blend_mode);
}
if let Some(opacity) = opacity {
item.set_attribute(ATTR_OPACITY, opacity);
}
if let Some(opacity_fill) = opacity_fill {
item.set_attribute(ATTR_OPACITY_FILL, opacity_fill);
}
result.push(item);
let Some(item) = strings.clone_item(index) else { continue };
for produced in shape_text_item(&item, separate_glyphs).into_iter() {
result.push(produced);
}
}

View File

@@ -6,10 +6,9 @@ use core_types::gpoll::{Extent, GPoll, Interrupt};
use core_types::transform::{ApplyTransform, ScaleType, Transform};
use core_types::{CacheHash, Context, Ctx, DeriveCtx, InjectFootprint, ModifyFootprint};
use glam::{DAffine2, DMat2, DVec2};
use graphic_types::Graphic;
use graphic_types::Vector;
use graphic_types::raster_types::{CPU, GPU, Raster};
use vector_types::GradientStops;
use graphic_types::{Artboard, Graphic, Vector};
use vector_types::Gradient;
/// Applies the specified transform to each lane of the input, composing onto the lane's transform attribute.
#[node_macro::node(category("Math: Transform"), extent(transform_extent))]
@@ -106,35 +105,44 @@ fn extract_transform<T: Clone + Send + Sync + CacheHash + 'static>(_: impl Ctx,
/// Produces the inverse of the input transform, which is the transform that undoes the effect of the original transform.
#[node_macro::node(category("Math: Transform"))]
fn invert_transform(_: impl Ctx, transform: DAffine2) -> DAffine2 {
transform.inverse()
fn invert_transform(_: impl Ctx, transform: Item<DAffine2>) -> Item<DAffine2> {
let (transform, attributes) = transform.into_parts();
let result = transform.inverse();
Item::from_parts(result, attributes)
}
/// Extracts the translation component from the input transform.
#[node_macro::node(category("Math: Transform"))]
fn decompose_translation(_: impl Ctx, transform: DAffine2) -> DVec2 {
transform.translation
fn decompose_translation(_: impl Ctx, transform: Item<DAffine2>) -> Item<DVec2> {
Item::new_from_element(transform.into_element().translation)
}
/// Extracts the rotation component (in degrees) from the input transform.
#[node_macro::node(category("Math: Transform"))]
fn decompose_rotation(_: impl Ctx, transform: DAffine2) -> f64 {
transform.decompose_rotation().to_degrees()
fn decompose_rotation(_: impl Ctx, transform: Item<DAffine2>) -> Item<f64> {
Item::new_from_element(transform.into_element().decompose_rotation().to_degrees())
}
/// Extracts the scale component from the input transform.
/// **Magnitude** returns the visual length of each axis (always positive, includes any skew contribution).
/// **Pure** returns the isolated scale factors with rotation and skew stripped away (can be negative for flipped axes).
#[node_macro::node(category("Math: Transform"))]
fn decompose_scale(_: impl Ctx, transform: DAffine2, scale_type: ScaleType) -> DVec2 {
match scale_type {
fn decompose_scale(_: impl Ctx, transform: Item<DAffine2>, scale_type: Item<ScaleType>) -> Item<DVec2> {
let transform = transform.into_element();
let scale_type = scale_type.into_element();
let result = match scale_type {
ScaleType::Magnitude => transform.scale_magnitudes(),
ScaleType::Pure => transform.decompose_scale(),
}
};
Item::new_from_element(result)
}
/// Extracts the skew angle (in degrees) from the input transform.
#[node_macro::node(category("Math: Transform"))]
fn decompose_skew(_: impl Ctx, transform: DAffine2) -> f64 {
transform.decompose_skew().atan().to_degrees()
fn decompose_skew(_: impl Ctx, transform: Item<DAffine2>) -> Item<f64> {
Item::new_from_element(transform.into_element().decompose_skew().atan().to_degrees())
}

View File

@@ -67,7 +67,10 @@ impl Preprocessor {
let resource_id = *hash_to_node_id.entry(hash).or_insert_with(|| {
let id = NodeId::new();
let resource_node = DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::ResourceHash(hash), false), NodeInput::scope("editor-api")],
inputs: vec![
NodeInput::scope(platform_application_io::editor_api::IDENTIFIER),
NodeInput::value(TaggedValue::ResourceHash(hash), false),
],
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::resource::IDENTIFIER),
..Default::default()
};
@@ -153,38 +156,82 @@ impl Preprocessor {
.take(wrapper_input_count)
.enumerate()
.map(|(i, inputs)| {
// A field registering the Item/List wire pair gets a input adapter instead of a typed conversion
if inputs.len() != 1
&& let Some(list_input) = collapse_item_list_pair(inputs)
{
let element_name = match list_input.nested_type() {
Type::List(element) => element.identifier_name(),
nested => nested.identifier_name(),
};
let input_adapter_identifier = ProtoNodeIdentifier::with_owned_string(format!("input_adapter<{element_name}>"));
let document_node = if into_node_registry.keys().any(|ident| ident.as_str() == input_adapter_identifier.as_str()) {
generated_nodes += 1;
let mut original_location = OriginalLocation::default();
original_location.auto_convert_index = Some(i);
DocumentNode {
inputs: vec![NodeInput::import(generic!(X), i)],
implementation: DocumentNodeImplementation::ProtoNode(input_adapter_identifier),
visible: true,
original_location,
..Default::default()
}
} else {
DocumentNode {
inputs: vec![NodeInput::import(generic!(X), i)],
implementation: DocumentNodeImplementation::ProtoNode(passthrough_node.clone()),
visible: false,
..Default::default()
}
};
return (NodeId(i as u64), document_node);
}
let single_wire_type = match inputs.len() {
1 => inputs.iter().next(),
_ => None,
};
(
NodeId(i as u64),
match inputs.len() {
1 => {
let input = inputs.iter().next().unwrap();
match single_wire_type {
Some(input) => {
let input_ty = input.nested_type();
let mut inputs = vec![NodeInput::import(input.clone(), i)];
let into_node_identifier = ProtoNodeIdentifier::with_owned_string(format!("graphene_core::ops::IntoNode<{}>", input_ty.identifier_name()));
let convert_node_identifier = ProtoNodeIdentifier::with_owned_string(format!("graphene_core::ops::ConvertNode<{}>", input_ty.identifier_name()));
let proto_node = if into_node_registry.keys().any(|ident: &ProtoNodeIdentifier| ident.as_str() == into_node_identifier.as_str()) {
generated_nodes += 1;
into_node_identifier
} else if into_node_registry.keys().any(|ident| ident.as_str() == convert_node_identifier.as_str()) {
generated_nodes += 1;
inputs.push(NodeInput::value(TaggedValue::None, false));
convert_node_identifier
} else {
passthrough_node.clone()
// A single-registered ranked field gets the input adapter, so ranked wires pass through and convertible elements cast
let element_name = match input_ty {
Type::Item(element) => Some(element.identifier_name()),
Type::List(element) => Some(element.identifier_name()),
_ => (input_ty.identifier_name() == "ListDyn").then(|| "ListDyn".to_string()),
};
if let Some(element_name) = element_name {
let input_adapter_identifier = ProtoNodeIdentifier::with_owned_string(format!("input_adapter<{element_name}>"));
if into_node_registry.keys().any(|ident| ident.as_str() == input_adapter_identifier.as_str()) {
generated_nodes += 1;
let mut original_location = OriginalLocation::default();
original_location.auto_convert_index = Some(i);
let document_node = DocumentNode {
inputs: vec![NodeInput::import(generic!(X), i)],
implementation: DocumentNodeImplementation::ProtoNode(input_adapter_identifier),
visible: true,
original_location,
..Default::default()
};
return (NodeId(i as u64), document_node);
}
}
let mut original_location = OriginalLocation::default();
original_location.auto_convert_index = Some(i);
DocumentNode {
inputs,
implementation: DocumentNodeImplementation::ProtoNode(proto_node),
inputs: vec![NodeInput::import(input.clone(), i)],
implementation: DocumentNodeImplementation::ProtoNode(passthrough_node.clone()),
visible: true,
original_location,
..Default::default()
}
}
_ => DocumentNode {
None => DocumentNode {
inputs: vec![NodeInput::import(generic!(X), i)],
implementation: DocumentNodeImplementation::ProtoNode(passthrough_node.clone()),
visible: false,
@@ -275,12 +322,13 @@ pub fn node_inputs(fields: &[registry::FieldMetadata], first_node_io: &NodeIOTyp
let Some(ty) = field.default_type.as_ref().or_else(|| first_node_io.inputs.get(index)) else {
return NodeInput::value(TaggedValue::None, true);
};
let exposed = if index == 0 { *ty != fn_type_fut!(Context, ()) } else { field.exposed };
let ty = ty.clone().normalize_rank();
let exposed = if index == 0 { ty != fn_type_fut!(Context, ()) } else { field.exposed };
match &field.value_source {
RegistryValueSource::None => {}
RegistryValueSource::Default(data) => {
if let Some(custom_default) = TaggedValue::from_primitive_string(data, ty) {
if let Some(custom_default) = TaggedValue::from_primitive_string(data, &ty) {
return NodeInput::value(custom_default, exposed);
} else {
// It is incredibly useful to get a warning when the default type cannot be parsed rather than defaulting to `()`.
@@ -291,9 +339,17 @@ pub fn node_inputs(fields: &[registry::FieldMetadata], first_node_io: &NodeIOTyp
RegistryValueSource::SourceId => return NodeInput::Reflection(DocumentNodeMetadata::SourceId),
};
if let Some(type_default) = TaggedValue::from_type(ty) {
// A ranked `Item<T>` type prefers a bare `T` value (promoted at resolution), since bare values drive the Properties panel widgets
if let Type::Item(element) = &ty
&& let Some(type_default) = TaggedValue::from_type(element)
{
return NodeInput::value(type_default, exposed);
}
if let Some(type_default) = TaggedValue::from_type(&ty) {
return NodeInput::value(type_default, exposed);
}
NodeInput::value(TaggedValue::None, true)
})
.collect()
@@ -311,3 +367,64 @@ impl std::fmt::Display for PreprocessorError {
}
}
}
/// Collapses an element-wise node's dual wire registration for one field, `{Item<X>, List<X>}`, to its `List<X>` document wire form.
fn collapse_item_list_pair(types: &HashSet<Type>) -> Option<&Type> {
let mut types_iterator = types.iter();
let (first, second) = (types_iterator.next()?, types_iterator.next()?);
if types_iterator.next().is_some() {
return None;
}
for (item, list) in [(first, second), (second, first)] {
if let Type::List(list_element) = list.nested_type()
&& let Type::Item(item_element) = item.nested_type()
&& list_element == item_element
{
return Some(list);
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn item_list_wire_pair_collapses_to_list() {
let registry = core_types::registry::NODE_REGISTRY.lock().unwrap();
let identifier = ProtoNodeIdentifier::new("core_types::vector::BoundingBoxNode");
let implementations = registry.get(&identifier).expect("Bounding Box should be registered");
let primary_types: HashSet<_> = implementations.iter().map(|(_, node_io)| node_io.inputs[0].clone()).collect();
assert_eq!(primary_types.len(), 2, "An element-wise node should register Item and List wire variants for its primary input");
let collapsed = collapse_item_list_pair(&primary_types).expect("The Item/List wire pair should collapse");
assert!(
matches!(collapsed.nested_type(), Type::List(_)),
"The collapse should pick the structural List form, but got {}",
collapsed.nested_type()
);
}
#[test]
fn fill_paint_color_default_parses_against_its_list_wire() {
let node_registry = core_types::registry::NODE_REGISTRY.lock().unwrap();
let metadata_registry = core_types::registry::NODE_METADATA.lock().unwrap();
let identifier = graphene_std::vector::fill::IDENTIFIER;
let implementations = node_registry.get(&identifier).expect("Fill should be registered");
let first_node_io = implementations.first().map(|(_, node_io)| node_io).expect("Fill should have at least one implementation");
let metadata = metadata_registry.get(&identifier).expect("Fill should have registered metadata");
let inputs = node_inputs(&metadata.fields, first_node_io);
let paint = inputs[1].as_value().expect("The paint input should hold a value");
assert_eq!(
*paint,
TaggedValue::Color(Color::BLACK),
"The paint input's `Color::BLACK` default should parse against its `List<Graphic>` wire type"
);
}
}