mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-09-15 22:28:10 +08:00
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:
@@ -16,6 +16,7 @@ wgpu = ["dep:raster-types", "raster-types/wgpu"]
|
||||
# Local dependencies
|
||||
dyn-any = { workspace = true }
|
||||
core-types = { workspace = true }
|
||||
graphene-hash = { workspace = true, features = ["derive"] }
|
||||
vector-types = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
|
||||
@@ -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;
|
||||
@@ -54,7 +56,7 @@ pub trait GetEditorPreferences {
|
||||
fn max_render_region_area(&self) -> u32;
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum ExportFormat {
|
||||
#[default]
|
||||
@@ -62,14 +64,14 @@ pub enum ExportFormat {
|
||||
Raster,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny)]
|
||||
#[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)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct RenderConfig {
|
||||
pub viewport: Footprint,
|
||||
@@ -83,6 +85,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 {
|
||||
@@ -127,7 +136,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);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,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.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use crate::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use crate::math::quad::Quad;
|
||||
use crate::transform::ApplyTransform;
|
||||
use dyn_any::{StaticType, StaticTypeSized};
|
||||
use crate::uuid::NodeId;
|
||||
use dyn_any::{DynAny, StaticType, StaticTypeSized};
|
||||
use glam::DAffine2;
|
||||
use graphene_hash::CacheHash;
|
||||
use std::fmt::Debug;
|
||||
@@ -22,7 +23,7 @@ pub const ATTR_OPACITY: &str = "opacity";
|
||||
pub const ATTR_OPACITY_FILL: &str = "opacity_fill";
|
||||
/// `bool` for whether an item inherits the alpha of the content beneath it (clipping mask).
|
||||
pub const ATTR_CLIPPING_MASK: &str = "clipping_mask";
|
||||
/// `List<NodeId>` path from the root network to the layer node owning this item.
|
||||
/// `NodeIdPath` path from the root network to the layer node owning this item.
|
||||
/// Used by editor tools to route clicks/selection back to the originating layer.
|
||||
pub const ATTR_EDITOR_LAYER_PATH: &str = "editor:layer_path";
|
||||
/// `List<Graphic>` snapshot of the upstream content that fed into a destructive merge
|
||||
@@ -79,6 +80,54 @@ pub const ATTR_LETTER_TILT: &str = "letter_tilt";
|
||||
/// Text item's `TextAlign` horizontal alignment of lines within the block.
|
||||
pub const ATTR_TEXT_ALIGN: &str = "text_align";
|
||||
|
||||
// =====================
|
||||
// TYPE: NodeIdPath
|
||||
// =====================
|
||||
|
||||
/// A single path of `NodeId`s locating a node (or its owning layer) within the nested document graph.
|
||||
/// Wraps a `List<NodeId>` so it flows as one rank-0 value (`Item<NodeIdPath>`) rather than a rank-1
|
||||
/// `List<NodeId>` that the element-wise machinery would wrongly zip over per ID.
|
||||
#[derive(Default, Debug, Clone, PartialEq, CacheHash, DynAny)]
|
||||
pub struct NodeIdPath(pub List<NodeId>);
|
||||
|
||||
impl From<Vec<NodeId>> for NodeIdPath {
|
||||
fn from(ids: Vec<NodeId>) -> Self {
|
||||
Self(ids.into_iter().map(Item::new_from_element).collect())
|
||||
}
|
||||
}
|
||||
|
||||
// ================
|
||||
// TYPE: Bundle
|
||||
// ================
|
||||
|
||||
/// A whole `List<T>` treated as one rank-0 value (`Item<Bundle<T>>`) rather than a rank-1 `List<T>`.
|
||||
/// Bundling a collection lets it pass through a connector that selects or carries the entire collection as one opaque
|
||||
/// cell (such as a Switch branch), instead of the element-wise machinery zipping over it per element.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Bundle<T>(pub List<T>);
|
||||
|
||||
impl<T> Default for Bundle<T> {
|
||||
fn default() -> Self {
|
||||
Self(List::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: CacheHash> CacheHash for Bundle<T> {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.0.cache_hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<List<T>> for Bundle<T> {
|
||||
fn from(list: List<T>) -> Self {
|
||||
Self(list)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl<T: StaticTypeSized> StaticType for Bundle<T> {
|
||||
type Static = Bundle<T::Static>;
|
||||
}
|
||||
|
||||
// ===========================
|
||||
// Implicit attribute defaults
|
||||
// ===========================
|
||||
@@ -125,6 +174,13 @@ pub trait AnyAttributeValue: std::any::Any + Send + Sync {
|
||||
/// Returns a debug-formatted string representation of this value.
|
||||
fn display_string(&self) -> String;
|
||||
|
||||
/// Hashes this value into the given hasher (object-safe wrapper around `CacheHash`).
|
||||
fn cache_hash_dyn(&self, state: &mut dyn core::hash::Hasher);
|
||||
|
||||
/// Compares this value to another for value-by-value equality (object-safe wrapper around `PartialEq`).
|
||||
/// Returns `false` if the underlying types differ.
|
||||
fn eq_dyn(&self, other: &dyn AnyAttributeValue) -> bool;
|
||||
|
||||
/// Wraps this scalar value into a new attribute, preceded by `preceding_defaults` implicit defaults for `key`.
|
||||
fn into_attribute(self: Box<Self>, key: &str, preceding_defaults: usize) -> Box<dyn AnyAttribute>;
|
||||
}
|
||||
@@ -155,6 +211,17 @@ impl<T: Clone + Send + Sync + Default + Sized + Debug + PartialEq + CacheHash +
|
||||
format!("{:?}", self)
|
||||
}
|
||||
|
||||
/// Hashes this value into the given hasher (object-safe wrapper around `CacheHash`).
|
||||
fn cache_hash_dyn(&self, state: &mut dyn core::hash::Hasher) {
|
||||
self.cache_hash(&mut DynHasher(state));
|
||||
}
|
||||
|
||||
/// Compares this value to another for value-by-value equality (object-safe wrapper around `PartialEq`).
|
||||
/// Returns `false` if the underlying types differ.
|
||||
fn eq_dyn(&self, other: &dyn AnyAttributeValue) -> bool {
|
||||
other.as_any().downcast_ref::<Self>().is_some_and(|other| self == other)
|
||||
}
|
||||
|
||||
/// Wraps this scalar value into a new attribute, preceded by `preceding_defaults` implicit defaults for `key`.
|
||||
fn into_attribute(self: Box<Self>, key: &str, preceding_defaults: usize) -> Box<dyn AnyAttribute> {
|
||||
let mut attribute: Box<dyn AnyAttribute> = Box::new(Attribute::<T>(Vec::with_capacity(preceding_defaults + 1)));
|
||||
@@ -361,83 +428,12 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
|
||||
}
|
||||
}
|
||||
|
||||
// ============
|
||||
// AttributeDyn
|
||||
// ============
|
||||
|
||||
/// Type-erased list of attribute values, used as a node graph parameter type.
|
||||
/// Lets a node accept any `List<U>` source via the auto-inserted `Convert<AttributeDyn, ()>`
|
||||
/// without monomorphizing over `U` (so the cartesian product of `(content T, source U)` collapses to just `T`).
|
||||
pub struct AttributeDyn(pub Box<dyn AnyAttribute>);
|
||||
|
||||
impl AttributeDyn {
|
||||
/// Number of values in this attribute.
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
/// Whether this attribute has zero values.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.len() == 0
|
||||
}
|
||||
|
||||
/// Builds a new attribute matching `target_len` items, taking values from this attribute (wrapping if shorter, truncating if longer).
|
||||
pub fn cloned_to_length(&self, key: &str, target_len: usize) -> Box<dyn AnyAttribute> {
|
||||
let mut result = self.0.new_with_defaults(0);
|
||||
let source_len = self.0.len();
|
||||
if source_len == 0 {
|
||||
pad_with_implicit_default(key, &mut result, target_len);
|
||||
return result;
|
||||
}
|
||||
for i in 0..target_len {
|
||||
let value = self.0.clone_value(i % source_len).expect("source_len > 0");
|
||||
result.push(value);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for AttributeDyn {
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone_box())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AttributeDyn {
|
||||
fn default() -> Self {
|
||||
Self(Box::new(Attribute::<bool>(Vec::new())))
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for AttributeDyn {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "AttributeDyn(len: {})", self.0.len())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for AttributeDyn {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.0.eq_dyn(&*other.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl CacheHash for AttributeDyn {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.0.cache_hash_dyn(state);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl StaticType for AttributeDyn {
|
||||
type Static = Self;
|
||||
}
|
||||
|
||||
// ==================
|
||||
// AttributeValueDyn
|
||||
// ==================
|
||||
|
||||
/// Type-erased single attribute value, used as a node graph parameter type.
|
||||
/// Lets a node accept a value of any concrete type via the auto-inserted `Convert<AttributeValueDyn, ()>`
|
||||
/// without monomorphizing over the value type.
|
||||
/// Lets a node accept a value of any valid concrete type via the auto-inserted input adapter conversion without monomorphizing over the value type.
|
||||
pub struct AttributeValueDyn(pub Box<dyn AnyAttributeValue>);
|
||||
|
||||
impl Clone for AttributeValueDyn {
|
||||
@@ -576,6 +572,17 @@ impl Debug for ItemAttributeValues {
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for ItemAttributeValues {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.0.len() == other.0.len()
|
||||
&& self
|
||||
.0
|
||||
.iter()
|
||||
.zip(&other.0)
|
||||
.all(|((self_key, self_value), (other_key, other_value))| self_key == other_key && self_value.eq_dyn(other_value.as_ref()))
|
||||
}
|
||||
}
|
||||
|
||||
impl ItemAttributeValues {
|
||||
/// Creates an empty set of attributes.
|
||||
pub fn new() -> Self {
|
||||
@@ -646,6 +653,11 @@ impl ItemAttributeValues {
|
||||
self.0.iter().map(|(key, _)| key.as_str())
|
||||
}
|
||||
|
||||
/// Returns a type-erased reference to the value of the attribute with the given key, if it exists.
|
||||
pub fn get_any(&self, key: &str) -> Option<&dyn std::any::Any> {
|
||||
self.0.iter().find_map(|(existing_key, value)| if existing_key == key { Some((**value).as_any()) } else { None })
|
||||
}
|
||||
|
||||
/// Returns a debug-formatted string representation of the attribute value for the given key, if it exists.
|
||||
/// The `overrides` function can provide custom formatting for specific type.
|
||||
pub fn display_value(&self, key: &str, overrides: fn(&dyn std::any::Any) -> Option<String>) -> Option<String> {
|
||||
@@ -1065,14 +1077,6 @@ impl<T> List<T> {
|
||||
self.attributes.set_value(key, index, value);
|
||||
}
|
||||
|
||||
/// Replaces (or adds) an attribute from a type-erased source. The source is wrapped or truncated to match this list's item count.
|
||||
pub fn set_attribute_dyn(&mut self, key: impl Into<String>, source: AttributeDyn) {
|
||||
let key = key.into();
|
||||
self.attributes.attributes.retain(|(k, _)| k != &key);
|
||||
let new_attribute = source.cloned_to_length(&key, self.element.len());
|
||||
self.attributes.attributes.push((key, new_attribute));
|
||||
}
|
||||
|
||||
/// Sets a single type-erased attribute value at the given index, creating the attribute from the value's underlying type if it doesn't exist (padded with defaults to match the list's length).
|
||||
/// Falls back to default if the value's type doesn't match an existing attribute.
|
||||
pub fn set_attribute_value_dyn(&mut self, key: impl Into<String>, index: usize, value: AttributeValueDyn) {
|
||||
@@ -1280,7 +1284,7 @@ impl<T> FromIterator<Item<T>> for List<T> {
|
||||
/// An owned item containing an element of type `T` and a set of type-erased scalar attributes.
|
||||
///
|
||||
/// Used to build individual items before pushing them into a [`List`], or when consuming items out of a list via [`IntoIterator`].
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Item<T> {
|
||||
element: T,
|
||||
attributes: ItemAttributeValues,
|
||||
@@ -1292,9 +1296,15 @@ impl<T: Default> Default for Item<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PartialEq> PartialEq for Item<T> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.element == other.element
|
||||
impl<T: CacheHash> CacheHash for Item<T> {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.element.cache_hash(state);
|
||||
|
||||
// Hash every attribute (key + value) so attribute changes invalidate downstream caches, mirroring `List`
|
||||
for (key, attribute) in &self.attributes.0 {
|
||||
std::hash::Hash::hash(key.as_str(), state);
|
||||
attribute.cache_hash_dyn(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1386,6 +1396,42 @@ impl<T> Item<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<T> for Item<T> {
|
||||
fn from(element: T) -> Self {
|
||||
Self::new_from_element(element)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<Item<T>> for List<T> {
|
||||
fn from(item: Item<T>) -> Self {
|
||||
Self::new_from_item(item)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<T> for List<T> {
|
||||
fn from(element: T) -> Self {
|
||||
Self::new_from_element(element)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ApplyTransform for Item<T> {
|
||||
/// Right-multiplies the modification into the item's transform attribute.
|
||||
fn apply_transform(&mut self, modification: &DAffine2) {
|
||||
let transform = self.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM);
|
||||
*transform *= *modification;
|
||||
}
|
||||
|
||||
/// Left-multiplies the modification into the item's transform attribute.
|
||||
fn left_apply_transform(&mut self, modification: &DAffine2) {
|
||||
let transform = self.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM);
|
||||
*transform = *modification * *transform;
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl<T: StaticTypeSized> StaticType for Item<T> {
|
||||
type Static = Item<T::Static>;
|
||||
}
|
||||
|
||||
// ===========
|
||||
// ItemIter<T>
|
||||
// ===========
|
||||
|
||||
@@ -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),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
use crate::Node;
|
||||
use crate::list::{Attribute, AttributeDyn, AttributeValueDyn, Item, List, ListDyn};
|
||||
use crate::transform::Footprint;
|
||||
use glam::DVec2;
|
||||
use graphene_hash::CacheHash;
|
||||
use std::future::Future;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
@@ -47,79 +45,12 @@ pub trait Convert<T, C>: Sized {
|
||||
fn convert(self, footprint: Footprint, converter: C) -> impl Future<Output = T> + Send;
|
||||
}
|
||||
|
||||
impl<T: ToString + Send> Convert<String, ()> for T {
|
||||
/// Converts this type into a `String` using its `ToString` implementation.
|
||||
#[inline]
|
||||
async fn convert(self, _: Footprint, _converter: ()) -> String {
|
||||
self.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ListConvert<U> {
|
||||
fn convert_item(self) -> U;
|
||||
}
|
||||
|
||||
impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> {
|
||||
async fn convert(self, _: Footprint, _: ()) -> List<U> {
|
||||
let list: List<U> = self
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
let (element, attributes) = row.into_parts();
|
||||
Item::from_parts(element.convert_item(), attributes)
|
||||
})
|
||||
.collect();
|
||||
list
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps each row's element into a type-erased attribute. Lets nodes that accept a source attribute
|
||||
/// from any `List<U>` express their signature as `AttributeDyn` and avoid monomorphizing
|
||||
/// over `U`; the compiler inserts this convert to bridge concrete-typed graph wires to the dyn input.
|
||||
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeDyn, ()> for List<T> {
|
||||
async fn convert(self, _: Footprint, _: ()) -> AttributeDyn {
|
||||
let values: Vec<T> = self.into_iter().map(|row| row.into_element()).collect();
|
||||
AttributeDyn(Box::new(Attribute(values)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps a value into a type-erased attribute value. Lets nodes that take a per-item value source
|
||||
/// (such as `write_attribute`'s value-producing input) be generic over the destination list type
|
||||
/// alone, with the compiler-inserted convert handling each concrete value type at the wire level.
|
||||
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeValueDyn, ()> for T {
|
||||
async fn convert(self, _: Footprint, _: ()) -> AttributeValueDyn {
|
||||
AttributeValueDyn(Box::new(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// Erases a `List<T>`'s element type, exposing only its attributes and row count. Lets nodes that
|
||||
/// only need attribute access (such as the `read_attribute_*` family) take a single `ListDyn` input
|
||||
/// instead of monomorphizing over every possible carrier list type.
|
||||
impl<T: Send> Convert<ListDyn, ()> for List<T> {
|
||||
async fn convert(self, _: Footprint, _: ()) -> ListDyn {
|
||||
self.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Convert<DVec2, ()> for DVec2 {
|
||||
async fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs `Self` from a single anchor point at the given position. Implemented by the vector crate's
|
||||
/// path type so the `Convert` impl below can build a single-point path without core-types depending on
|
||||
/// that crate (mirroring how [`ListConvert`] bridges per-item list conversions).
|
||||
/// path type so a position wire can convert to a single-point path without core-types depending on that crate.
|
||||
pub trait FromAnchorPosition {
|
||||
fn from_anchor_position(position: DVec2) -> Self;
|
||||
}
|
||||
|
||||
// Converts a position into a vector path composed of a single anchor point
|
||||
impl<T: FromAnchorPosition + Send> Convert<List<T>, ()> for DVec2 {
|
||||
async fn convert(self, _: Footprint, _: ()) -> List<T> {
|
||||
List::new_from_item(Item::new_from_element(T::from_anchor_position(self)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Implements the [`Convert`] trait for conversion between the cartesian product of Rust's primitive numeric types.
|
||||
macro_rules! impl_convert {
|
||||
($from:ty, $to:ty) => {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -52,8 +52,48 @@ macro_rules! generic {
|
||||
($type:ty) => {{ $crate::Type::Generic($crate::Cow::Borrowed(stringify!($type))) }};
|
||||
}
|
||||
|
||||
/// Constructs the [`Type`] of an `Item` holding the given element type, e.g. `item!(f64)` is the type of an `Item<f64>`.
|
||||
/// The two-argument form tags the element descriptor with an alias, preserving the source spelling for widget dispatch.
|
||||
#[macro_export]
|
||||
macro_rules! item {
|
||||
(Item<$inner:ty>) => {
|
||||
$crate::Type::Item(Box::new($crate::item!($inner)))
|
||||
};
|
||||
($element:ty) => {
|
||||
$crate::Type::Item(Box::new($crate::concrete!($element)))
|
||||
};
|
||||
($element:ty, $alias:ty) => {
|
||||
$crate::Type::Item(Box::new($crate::concrete!($element, $alias)))
|
||||
};
|
||||
}
|
||||
|
||||
/// Constructs the [`Type`] of a `List` holding the given element type, e.g. `list!(f64)` is the type of a `List<f64>`.
|
||||
#[macro_export]
|
||||
macro_rules! list {
|
||||
(List<$inner:ty>) => {
|
||||
$crate::Type::List(Box::new($crate::list!($inner)))
|
||||
};
|
||||
($element:ty) => {
|
||||
$crate::Type::List(Box::new($crate::concrete!($element)))
|
||||
};
|
||||
}
|
||||
|
||||
// The `List<...>`/`Item<...>` rules must appear before the generic `$type:ty` rules, and in each macro that sees the literal tokens,
|
||||
// because a type captured as `ty` becomes opaque to any inner macro's ranked pattern
|
||||
#[macro_export]
|
||||
macro_rules! future {
|
||||
(List<$inner:ty>) => {
|
||||
$crate::Type::Future(Box::new($crate::list!($inner)))
|
||||
};
|
||||
(List<$inner:ty>, $name:ty) => {
|
||||
$crate::Type::Future(Box::new($crate::list!($inner)))
|
||||
};
|
||||
(Item<$inner:ty>) => {
|
||||
$crate::Type::Future(Box::new($crate::item!($inner)))
|
||||
};
|
||||
(Item<$inner:ty>, $name:ty) => {
|
||||
$crate::Type::Future(Box::new($crate::item!($inner, $name)))
|
||||
};
|
||||
($type:ty) => {{ $crate::Type::Future(Box::new(concrete!($type))) }};
|
||||
($type:ty, $name:ty) => {
|
||||
$crate::Type::Future(Box::new(concrete!($type, $name)))
|
||||
@@ -62,9 +102,27 @@ macro_rules! future {
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! fn_type {
|
||||
(List<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::list!($inner)))
|
||||
};
|
||||
(Item<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::item!($inner)))
|
||||
};
|
||||
($type:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!(())), Box::new(concrete!($type)))
|
||||
};
|
||||
($in_type:ty, List<$inner:ty>, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::list!($inner)))
|
||||
};
|
||||
($in_type:ty, List<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::list!($inner)))
|
||||
};
|
||||
($in_type:ty, Item<$inner:ty>, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::item!($inner, $inner)))
|
||||
};
|
||||
($in_type:ty, Item<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::item!($inner)))
|
||||
};
|
||||
($in_type:ty, $type:ty, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(concrete!($type, $outname)))
|
||||
};
|
||||
@@ -74,9 +132,27 @@ macro_rules! fn_type {
|
||||
}
|
||||
#[macro_export]
|
||||
macro_rules! fn_type_fut {
|
||||
(List<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::Type::Future(Box::new($crate::list!($inner)))))
|
||||
};
|
||||
(Item<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::Type::Future(Box::new($crate::item!($inner)))))
|
||||
};
|
||||
($type:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!(())), Box::new(future!($type)))
|
||||
};
|
||||
($in_type:ty, List<$inner:ty>, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::list!($inner)))))
|
||||
};
|
||||
($in_type:ty, List<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::list!($inner)))))
|
||||
};
|
||||
($in_type:ty, Item<$inner:ty>, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::item!($inner, $inner)))))
|
||||
};
|
||||
($in_type:ty, Item<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::item!($inner)))))
|
||||
};
|
||||
($in_type:ty, $type:ty, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(future!($type, $outname)))
|
||||
};
|
||||
@@ -99,6 +175,15 @@ impl NodeIOTypes {
|
||||
Self { call_argument, return_value, inputs }
|
||||
}
|
||||
|
||||
/// Applies [`Type::normalize_rank`] to every type in the signature.
|
||||
pub fn normalize_rank(self) -> Self {
|
||||
Self {
|
||||
call_argument: self.call_argument.normalize_rank(),
|
||||
return_value: self.return_value.normalize_rank(),
|
||||
inputs: self.inputs.into_iter().map(Type::normalize_rank).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn empty() -> Self {
|
||||
let tds1 = TypeDescriptor {
|
||||
id: None,
|
||||
@@ -235,6 +320,10 @@ pub enum Type {
|
||||
Fn(Box<Type>, Box<Type>),
|
||||
/// Represents a future which promises to return the inner type.
|
||||
Future(Box<Type>),
|
||||
/// Represents a recursive [Type] allowing nested levels of types to represent the type of an Item<T>.
|
||||
Item(Box<Type>),
|
||||
/// Represents a list of this recursive [Type] allowing nested levels of types to represent the type of a List<T>.
|
||||
List(Box<Type>),
|
||||
}
|
||||
|
||||
impl Default for Type {
|
||||
@@ -308,6 +397,8 @@ impl Type {
|
||||
Self::Concrete(ty) => Some(ty.size),
|
||||
Self::Fn(_, _) => None,
|
||||
Self::Future(_) => None,
|
||||
Self::Item(_) => None,
|
||||
Self::List(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -317,6 +408,8 @@ impl Type {
|
||||
Self::Concrete(ty) => Some(ty.align),
|
||||
Self::Fn(_, _) => None,
|
||||
Self::Future(_) => None,
|
||||
Self::Item(_) => None,
|
||||
Self::List(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -326,6 +419,8 @@ impl Type {
|
||||
Self::Concrete(_) => self,
|
||||
Self::Fn(_, output) => output.nested_type(),
|
||||
Self::Future(output) => output.nested_type(),
|
||||
Self::Item(_) => self,
|
||||
Self::List(_) => self,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,6 +433,8 @@ impl Type {
|
||||
Self::Concrete(_) => None,
|
||||
Self::Fn(_, output) => output.replace_nested(f),
|
||||
Self::Future(output) => output.replace_nested(f),
|
||||
Self::Item(_) => None,
|
||||
Self::List(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -347,6 +444,62 @@ impl Type {
|
||||
Type::Concrete(ty) => simplify_identifier_name(&ty.name),
|
||||
Type::Fn(call_arg, return_value) => format!("{} called with {}", return_value.identifier_name(), call_arg.identifier_name()),
|
||||
Type::Future(ty) => ty.identifier_name(),
|
||||
Type::Item(element) => element.identifier_name(),
|
||||
Type::List(element) => format!("{}[]", element.identifier_name()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs the [`Type`] of a `List` holding elements of the given type, the expression-position counterpart of [`list!`].
|
||||
pub fn list_of(element: Type) -> Type {
|
||||
Type::List(Box::new(element))
|
||||
}
|
||||
|
||||
/// The element type if this is a rank-1 `List` wire type.
|
||||
pub fn list_element(&self) -> Option<&Type> {
|
||||
match self {
|
||||
Type::List(element) => Some(element),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The element name if this is the type of an `Item<Bundle<X>>` cell carrying a whole list, e.g. `f64` from `Item<Bundle<f64>>`.
|
||||
/// The `Bundle` layer stays name-encoded inside the structural `Item` since it has no structural variant.
|
||||
pub fn bundle_element_name(&self) -> Option<&str> {
|
||||
let Type::Item(element) = self else { return None };
|
||||
let Type::Concrete(descriptor) = element.as_ref() else { return None };
|
||||
descriptor.name.strip_prefix("core_types::list::Bundle<")?.strip_suffix('>')
|
||||
}
|
||||
|
||||
/// Converts a name-encoded `List` or `Item` concrete type into its structural form, recursively.
|
||||
/// Structurally-built types pass through unchanged, so sources which cannot construct ranked types
|
||||
/// (reflection and opaque macro captures) converge with macro-built ones at this single point.
|
||||
pub fn normalize_rank(self) -> Type {
|
||||
fn parse_element(element_name: &str) -> Type {
|
||||
let element = Type::Concrete(TypeDescriptor {
|
||||
id: None,
|
||||
name: Cow::Owned(element_name.to_string()),
|
||||
alias: None,
|
||||
size: 0,
|
||||
align: 0,
|
||||
});
|
||||
element.normalize_rank()
|
||||
}
|
||||
|
||||
match self {
|
||||
Type::Concrete(descriptor) => {
|
||||
if let Some(element_name) = descriptor.name.strip_prefix("core_types::list::List<").and_then(|rest| rest.strip_suffix('>')) {
|
||||
return Type::List(Box::new(parse_element(element_name)));
|
||||
}
|
||||
if let Some(element_name) = descriptor.name.strip_prefix("core_types::list::Item<").and_then(|rest| rest.strip_suffix('>')) {
|
||||
return Type::Item(Box::new(parse_element(element_name)));
|
||||
}
|
||||
Type::Concrete(descriptor)
|
||||
}
|
||||
Type::Fn(input, output) => Type::Fn(Box::new(input.normalize_rank()), Box::new(output.normalize_rank())),
|
||||
Type::Future(inner) => Type::Future(Box::new(inner.normalize_rank())),
|
||||
Type::Item(element) => Type::Item(Box::new(element.normalize_rank())),
|
||||
Type::List(element) => Type::List(Box::new(element.normalize_rank())),
|
||||
Type::Generic(_) => self,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -371,12 +524,13 @@ pub fn make_type_user_readable(ty: &str) -> String {
|
||||
.replace("UVec2", "Vec2")
|
||||
.replace("&str", "String");
|
||||
|
||||
rewrite_list_as_array_brackets(&ty)
|
||||
rewrite_ranked_type_wrappers(&ty)
|
||||
}
|
||||
|
||||
/// Rewrites `List<T>` as `T[]`. Handles nesting (e.g. `List<List<Vector>>` becomes `Vector[][]`).
|
||||
/// Respects word boundaries so unrelated identifiers that happen to end in `List` are not affected.
|
||||
fn rewrite_list_as_array_brackets(input: &str) -> String {
|
||||
/// Rewrites `List<T>` and the whole-collection `Bundle<T>` as `T[]`, and unwraps `Item<T>` to `T`, so ranked wires read as their element type.
|
||||
/// Handles nesting (e.g. `List<List<Vector>>` becomes `Vector[][]`).
|
||||
/// Respects word boundaries so unrelated identifiers that happen to end in `List` or `Item` are not affected.
|
||||
fn rewrite_ranked_type_wrappers(input: &str) -> String {
|
||||
let bytes = input.as_bytes();
|
||||
let mut result = String::with_capacity(input.len());
|
||||
let mut i = 0;
|
||||
@@ -387,12 +541,31 @@ fn rewrite_list_as_array_brackets(input: &str) -> String {
|
||||
let inner_start = i + b"List<".len();
|
||||
if let Some(close) = find_matching_angle_bracket(bytes, inner_start) {
|
||||
let inner = &input[inner_start..close];
|
||||
result.push_str(&rewrite_list_as_array_brackets(inner));
|
||||
result.push_str(&rewrite_ranked_type_wrappers(inner));
|
||||
result.push_str("[]");
|
||||
i = close + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if at_word_boundary && bytes[i..].starts_with(b"Bundle<") {
|
||||
let inner_start = i + b"Bundle<".len();
|
||||
if let Some(close) = find_matching_angle_bracket(bytes, inner_start) {
|
||||
let inner = &input[inner_start..close];
|
||||
result.push_str(&rewrite_ranked_type_wrappers(inner));
|
||||
result.push_str("[]");
|
||||
i = close + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if at_word_boundary && bytes[i..].starts_with(b"Item<") {
|
||||
let inner_start = i + b"Item<".len();
|
||||
if let Some(close) = find_matching_angle_bracket(bytes, inner_start) {
|
||||
let inner = &input[inner_start..close];
|
||||
result.push_str(&rewrite_ranked_type_wrappers(inner));
|
||||
i = close + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if bytes[i].is_ascii() {
|
||||
result.push(bytes[i] as char);
|
||||
i += 1;
|
||||
@@ -441,6 +614,8 @@ impl std::fmt::Display for Type {
|
||||
Type::Concrete(ty) => write!(f, "{ty}"),
|
||||
Type::Fn(_, return_value) => write!(f, "{return_value}"),
|
||||
Type::Future(ty) => write!(f, "{ty}"),
|
||||
Type::Item(element) => write!(f, "{element}"),
|
||||
Type::List(element) => write!(f, "{element}[]"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use crate::Node;
|
||||
use crate::list::Item;
|
||||
use crate::registry::DynFuture;
|
||||
use crate::{Node, WasmNotSend};
|
||||
use std::cell::{Cell, RefCell, RefMut};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
@@ -110,6 +112,26 @@ impl<T: Clone> From<T> for ClonedNode<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Yields a precomputed `Item<T>` as a ready future, ignoring its input context.
|
||||
/// Generated list-content variants feed each already-evaluated content slot through this so the kernel's own
|
||||
/// context modifications become no-ops (the slot was evaluated once, up front, at the ambient footprint).
|
||||
pub struct PrecomputedItemNode<T>(pub Item<T>);
|
||||
|
||||
impl<'i, T: Clone + WasmNotSend + 'i, I: 'i> Node<'i, I> for PrecomputedItemNode<T> {
|
||||
type Output = DynFuture<'i, Item<T>>;
|
||||
#[inline(always)]
|
||||
fn eval(&'i self, _input: I) -> Self::Output {
|
||||
let item = self.0.clone();
|
||||
Box::pin(async move { item })
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> PrecomputedItemNode<T> {
|
||||
pub const fn new(item: Item<T>) -> Self {
|
||||
Self(item)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
/// The DebugClonedNode logs every time it is evaluated.
|
||||
/// This is useful for debugging.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,35 +1,31 @@
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_FILL, ATTR_STROKE, ItemAttributeValues, List};
|
||||
use core_types::ops::{FromAnchorPosition, ListConvert};
|
||||
use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, ItemAttributeValues, List, NodeIdPath};
|
||||
use core_types::ops::FromAnchorPosition;
|
||||
use core_types::render_complexity::RenderComplexity;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use std::borrow::Cow;
|
||||
use vector_types::GradientStops;
|
||||
use vector_types::Gradient;
|
||||
pub use vector_types::Vector;
|
||||
|
||||
/// The possible forms of graphical content that can be rendered by the Render node into either an image or SVG syntax.
|
||||
#[derive(Clone, Debug, CacheHash, PartialEq, DynAny)]
|
||||
#[derive(Clone, Debug, Default, CacheHash, PartialEq, DynAny)]
|
||||
pub enum Graphic {
|
||||
/// The absence of graphical content, like CSS's `none` keyword: painting it produces nothing.
|
||||
#[default]
|
||||
None,
|
||||
Graphic(List<Graphic>),
|
||||
Vector(List<Vector>),
|
||||
RasterCPU(List<Raster<CPU>>),
|
||||
RasterGPU(List<Raster<GPU>>),
|
||||
Color(List<Color>),
|
||||
Gradient(List<GradientStops>),
|
||||
Gradient(List<Gradient>),
|
||||
Text(List<String>),
|
||||
}
|
||||
|
||||
impl Default for Graphic {
|
||||
fn default() -> Self {
|
||||
Self::Graphic(List::new())
|
||||
}
|
||||
}
|
||||
|
||||
// Graphic
|
||||
impl From<List<Graphic>> for Graphic {
|
||||
fn from(graphic: List<Graphic>) -> Self {
|
||||
@@ -91,14 +87,14 @@ impl From<List<Color>> for Graphic {
|
||||
// Note: List conversions handled by blanket impl in gcore
|
||||
// Note: List<Color> -> Option<Color> is in gcore (Color is defined there)
|
||||
|
||||
// GradientStops
|
||||
impl From<GradientStops> for Graphic {
|
||||
fn from(gradient: GradientStops) -> Self {
|
||||
// Gradient
|
||||
impl From<Gradient> for Graphic {
|
||||
fn from(gradient: Gradient) -> Self {
|
||||
Graphic::Gradient(List::new_from_element(gradient))
|
||||
}
|
||||
}
|
||||
impl From<List<GradientStops>> for Graphic {
|
||||
fn from(gradient: List<GradientStops>) -> Self {
|
||||
impl From<List<Gradient>> for Graphic {
|
||||
fn from(gradient: List<Gradient>) -> Self {
|
||||
Graphic::Gradient(gradient)
|
||||
}
|
||||
}
|
||||
@@ -126,9 +122,9 @@ fn flatten_graphic_list<T>(content: List<Graphic>, extract_variant: fn(Graphic)
|
||||
let parent_has_transform = current_graphic_item.attribute::<DAffine2>(ATTR_TRANSFORM).is_some();
|
||||
let parent_has_opacity = current_graphic_item.attribute::<f64>(ATTR_OPACITY).is_some();
|
||||
let parent_has_fill = current_graphic_item.attribute::<f64>(ATTR_OPACITY_FILL).is_some();
|
||||
let parent_has_layer_path = current_graphic_item.attribute::<List<NodeId>>(ATTR_EDITOR_LAYER_PATH).is_some();
|
||||
let parent_has_layer_path = current_graphic_item.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH).is_some();
|
||||
|
||||
let layer_path: List<NodeId> = current_graphic_item.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH);
|
||||
let layer_path: NodeIdPath = current_graphic_item.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH);
|
||||
let current_transform: DAffine2 = current_graphic_item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let current_opacity: f64 = current_graphic_item.attribute_cloned_or(ATTR_OPACITY, 1.);
|
||||
let current_fill: f64 = current_graphic_item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
|
||||
@@ -232,6 +228,7 @@ pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DA
|
||||
fn bake_graphic_paint_transform(graphics: &mut List<Graphic>, transform: DAffine2) {
|
||||
for graphic in graphics.iter_element_values_mut() {
|
||||
match graphic {
|
||||
Graphic::None => {}
|
||||
Graphic::Graphic(list) => bake_list_transform(list, transform),
|
||||
Graphic::Vector(list) => bake_list_transform(list, transform),
|
||||
Graphic::RasterCPU(list) => bake_list_transform(list, transform),
|
||||
@@ -274,7 +271,7 @@ impl TryFromGraphic for Color {
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for GradientStops {
|
||||
impl TryFromGraphic for Gradient {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
if let Graphic::Gradient(t) = graphic { Some(t) } else { None }
|
||||
}
|
||||
@@ -307,11 +304,11 @@ impl IntoGraphicList for List<Graphic> {
|
||||
|
||||
impl IntoGraphicList for List<Vector> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
// Propagate `editor:layer_path` from item 0 onto the wrapper Graphic item so a subsequent
|
||||
// `flatten_graphic_list` doesn't overwrite the inner Vector's stamp with an empty value
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
|
||||
// Propagate the `editor:layer_path` column (if present) from item 0 onto the wrapper Graphic item so a
|
||||
// subsequent `flatten_graphic_list` doesn't drop the inner Vector's layer stamp
|
||||
let layer_path = self.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, 0).cloned();
|
||||
let mut graphic_list = List::new_from_element(Graphic::Vector(self));
|
||||
if !layer_path.is_empty() {
|
||||
if let Some(layer_path) = layer_path {
|
||||
graphic_list.set_attribute(ATTR_EDITOR_LAYER_PATH, 0, layer_path);
|
||||
}
|
||||
graphic_list
|
||||
@@ -336,7 +333,7 @@ impl IntoGraphicList for List<Color> {
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<GradientStops> {
|
||||
impl IntoGraphicList for List<Gradient> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
List::new_from_element(Graphic::Gradient(self))
|
||||
}
|
||||
@@ -344,32 +341,32 @@ impl IntoGraphicList for List<GradientStops> {
|
||||
|
||||
impl IntoGraphicList for List<String> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
|
||||
let layer_path = self.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, 0).cloned();
|
||||
let mut graphic_list = List::new_from_element(Graphic::Text(self));
|
||||
if !layer_path.is_empty() {
|
||||
if let Some(layer_path) = layer_path {
|
||||
graphic_list.set_attribute(ATTR_EDITOR_LAYER_PATH, 0, layer_path);
|
||||
}
|
||||
graphic_list
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for DAffine2 {
|
||||
impl IntoGraphicList for Item<DAffine2> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
List::new_from_element(Graphic::default())
|
||||
}
|
||||
}
|
||||
|
||||
// DAffine2
|
||||
impl From<DAffine2> for Graphic {
|
||||
fn from(_: DAffine2) -> Self {
|
||||
impl From<Item<DAffine2>> for Graphic {
|
||||
fn from(_: Item<DAffine2>) -> Self {
|
||||
Graphic::default()
|
||||
}
|
||||
}
|
||||
|
||||
// DVec2
|
||||
impl From<DVec2> for Graphic {
|
||||
fn from(position: DVec2) -> Self {
|
||||
Graphic::Vector(List::new_from_element(Vector::from_anchor_position(position)))
|
||||
impl From<Item<DVec2>> for Graphic {
|
||||
fn from(position: Item<DVec2>) -> Self {
|
||||
Graphic::Vector(List::new_from_element(Vector::from_anchor_position(position.into_element())))
|
||||
}
|
||||
}
|
||||
// Note: List conversions handled by blanket impl in gcore
|
||||
@@ -423,6 +420,7 @@ impl Graphic {
|
||||
}
|
||||
|
||||
match self {
|
||||
Graphic::None => true,
|
||||
Graphic::Vector(list) => all_clipped(list),
|
||||
Graphic::Graphic(list) => all_clipped(list),
|
||||
Graphic::RasterCPU(list) => all_clipped(list),
|
||||
@@ -452,6 +450,7 @@ impl Graphic {
|
||||
|
||||
pub fn is_opaque(&self) -> bool {
|
||||
match self {
|
||||
Graphic::None => false,
|
||||
Graphic::Graphic(list) => !list.is_empty() && list.iter_element_values().all(Graphic::is_opaque),
|
||||
Graphic::Vector(list) => {
|
||||
let is_paint_opaque_at = |key: &str, index: usize| graphic_list_at(list, index, key).is_some_and(|graphic_list| graphic_list.element(0).is_some_and(|graphic| graphic.is_opaque()));
|
||||
@@ -474,6 +473,7 @@ impl Graphic {
|
||||
|
||||
pub fn is_fully_transparent(&self) -> bool {
|
||||
match self {
|
||||
Graphic::None => true,
|
||||
Graphic::Graphic(list) => list.iter_element_values().all(Graphic::is_fully_transparent),
|
||||
Graphic::Vector(list) => (0..list.len()).all(|i| {
|
||||
let Some(vector) = list.element(i) else { return false };
|
||||
@@ -501,9 +501,10 @@ impl Graphic {
|
||||
matches!(self, Graphic::Color(_) | Graphic::Gradient(_)) && self.is_opaque()
|
||||
}
|
||||
|
||||
/// Returns true if this graphic's inner list is empty.
|
||||
/// Returns true if this graphic contains no content.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
match self {
|
||||
Graphic::None => true,
|
||||
Graphic::Graphic(list) => list.is_empty(),
|
||||
Graphic::Vector(list) => list.is_empty(),
|
||||
Graphic::Color(list) => list.is_empty(),
|
||||
@@ -518,6 +519,7 @@ impl Graphic {
|
||||
impl BoundingBox for Graphic {
|
||||
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
match self {
|
||||
Graphic::None => RenderBoundingBox::None,
|
||||
Graphic::Vector(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::RasterCPU(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::RasterGPU(list) => list.bounding_box(transform, include_stroke),
|
||||
@@ -530,6 +532,7 @@ impl BoundingBox for Graphic {
|
||||
|
||||
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
match self {
|
||||
Graphic::None => RenderBoundingBox::None,
|
||||
Graphic::Vector(vector) => vector.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::RasterCPU(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::RasterGPU(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
|
||||
@@ -541,25 +544,10 @@ impl BoundingBox for Graphic {
|
||||
}
|
||||
}
|
||||
|
||||
impl ListConvert<Graphic> for Vector {
|
||||
fn convert_item(self) -> Graphic {
|
||||
Graphic::Vector(List::new_from_element(self))
|
||||
}
|
||||
}
|
||||
impl ListConvert<Graphic> for Raster<CPU> {
|
||||
fn convert_item(self) -> Graphic {
|
||||
Graphic::RasterCPU(List::new_from_element(self))
|
||||
}
|
||||
}
|
||||
impl ListConvert<Graphic> for Raster<GPU> {
|
||||
fn convert_item(self) -> Graphic {
|
||||
Graphic::RasterGPU(List::new_from_element(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderComplexity for Graphic {
|
||||
fn render_complexity(&self) -> usize {
|
||||
match self {
|
||||
Self::None => 0,
|
||||
Self::Graphic(list) => list.render_complexity(),
|
||||
Self::Vector(list) => list.render_complexity(),
|
||||
Self::RasterCPU(list) => list.render_complexity(),
|
||||
@@ -688,7 +676,7 @@ mod graphic_is_opaque_tests {
|
||||
Graphic::Color(List::new_from_element(color))
|
||||
}
|
||||
|
||||
fn gradient_graphic(gradient: GradientStops) -> Graphic {
|
||||
fn gradient_graphic(gradient: Gradient) -> Graphic {
|
||||
let mut gradient_list = List::new_from_element(gradient);
|
||||
gradient_list.set_attribute(ATTR_SPREAD_METHOD, 0, GradientSpreadMethod::Pad);
|
||||
Graphic::Gradient(gradient_list)
|
||||
@@ -716,7 +704,7 @@ mod graphic_is_opaque_tests {
|
||||
fn gradient_with_all_opaque_stops_is_opaque() {
|
||||
let color_1 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
|
||||
let color_2 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
|
||||
let gradient = GradientStops::new(vec![
|
||||
let gradient = Gradient::new(vec![
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
@@ -736,7 +724,7 @@ mod graphic_is_opaque_tests {
|
||||
fn gradient_with_transparent_stop_is_not_opaque() {
|
||||
let color_1 = Color::from_rgbaf32(1., 0., 0., 0.5).unwrap();
|
||||
let color_2 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
|
||||
let gradient = GradientStops::new(vec![
|
||||
let gradient = Gradient::new(vec![
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
|
||||
@@ -20,11 +20,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,
|
||||
@@ -36,11 +36,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;
|
||||
@@ -63,7 +63,7 @@ pub mod migrations {
|
||||
DAffine2::IDENTITY
|
||||
};
|
||||
|
||||
Gradient {
|
||||
LegacyGradient {
|
||||
start,
|
||||
end,
|
||||
transform,
|
||||
@@ -80,15 +80,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 {
|
||||
@@ -162,7 +162,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.);
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
41
node-graph/libraries/no-std-types/src/list.rs
Normal file
41
node-graph/libraries/no-std-types/src/list.rs
Normal 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)
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use graphic_types::Graphic;
|
||||
use graphic_types::vector_types::gradient::GradientType;
|
||||
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)]
|
||||
@@ -76,7 +76,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.
|
||||
@@ -241,6 +241,7 @@ impl RenderExt for List<Graphic> {
|
||||
let gradient_id = gradient_list.render(svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params, target);
|
||||
format!(r##" {paint_attr}="url(#{gradient_id})""##)
|
||||
}
|
||||
Some(Graphic::None) => format!(r#" {paint_attr}="none""#),
|
||||
Some(Graphic::Vector(_)) | Some(Graphic::RasterCPU(_)) | Some(Graphic::RasterGPU(_)) | Some(Graphic::Graphic(_)) | Some(Graphic::Text(_)) => {
|
||||
let bounds = if target == PaintTarget::Stroke {
|
||||
// To prevent a wraparound artefact occurring when the tile boundary and the stroke region are perfectly aligned, the local coordinate is expanded slightly.
|
||||
|
||||
@@ -7,7 +7,7 @@ use core_types::bounds::RenderBoundingBox;
|
||||
use core_types::color::Color;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::consts::DEFAULT_FONT_SIZE;
|
||||
use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, List};
|
||||
use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, List, NodeIdPath};
|
||||
use core_types::math::quad::Quad;
|
||||
use core_types::render_complexity::RenderComplexity;
|
||||
use core_types::transform::Footprint;
|
||||
@@ -23,7 +23,7 @@ use graphene_hash::CacheHashWrapper;
|
||||
use graphene_resource::Resource;
|
||||
use graphic_types::graphic::{graphic_list_at, has_paint_at, is_paint_present, set_paint_attribute};
|
||||
use graphic_types::raster_types::{BitmapMut, CPU, GPU, Image, Raster, Texture};
|
||||
use graphic_types::vector_types::gradient::{GradientStops, GradientType};
|
||||
use graphic_types::vector_types::gradient::{Gradient, GradientType};
|
||||
use graphic_types::vector_types::subpath::Subpath;
|
||||
use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint};
|
||||
use graphic_types::vector_types::vector::style::{PaintOrder, RenderMode, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
@@ -394,7 +394,7 @@ pub(crate) fn gradient_placement(transform: DAffine2, gradient_type: GradientTyp
|
||||
}
|
||||
}
|
||||
|
||||
fn create_peniko_gradient_brush(gradient_list: &List<GradientStops>, multiplied_transform: &DAffine2) -> Option<(peniko::Brush, DAffine2)> {
|
||||
fn create_peniko_gradient_brush(gradient_list: &List<Gradient>, multiplied_transform: &DAffine2) -> Option<(peniko::Brush, DAffine2)> {
|
||||
let stops = gradient_list.element(0)?;
|
||||
|
||||
let gradient_type: GradientType = gradient_list.attribute_cloned_or_default(ATTR_GRADIENT_TYPE, 0);
|
||||
@@ -546,6 +546,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(list) => list.render_svg(render, render_params),
|
||||
Graphic::RasterCPU(list) => list.render_svg(render, render_params),
|
||||
@@ -558,6 +559,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(list) => list.render_to_vello(scene, transform, context, render_params),
|
||||
Graphic::RasterCPU(list) => list.render_to_vello(scene, transform, context, render_params),
|
||||
@@ -571,6 +573,7 @@ impl Render for Graphic {
|
||||
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option<NodeId>) {
|
||||
if let Some(element_id) = element_id {
|
||||
match self {
|
||||
Graphic::None => {}
|
||||
Graphic::Graphic(_) => {
|
||||
metadata.upstream_footprints.insert(element_id, footprint);
|
||||
}
|
||||
@@ -578,7 +581,7 @@ impl Render for Graphic {
|
||||
metadata.upstream_footprints.insert(element_id, footprint);
|
||||
// TODO: Find a way to handle more than the first item
|
||||
if !list.is_empty() {
|
||||
let layer_path: List<NodeId> = list.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
|
||||
let layer_path: List<NodeId> = list.attribute_cloned_or_default::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, 0).0;
|
||||
let layer = layer_path.iter_element_values().next_back().copied();
|
||||
let transform: DAffine2 = list.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
|
||||
@@ -630,6 +633,7 @@ impl Render for Graphic {
|
||||
}
|
||||
|
||||
match self {
|
||||
Graphic::None => (),
|
||||
Graphic::Graphic(list) => list.collect_metadata(metadata, footprint, element_id),
|
||||
Graphic::Vector(list) => list.collect_metadata(metadata, footprint, element_id),
|
||||
Graphic::RasterCPU(list) => list.collect_metadata(metadata, footprint, element_id),
|
||||
@@ -642,6 +646,7 @@ impl Render for Graphic {
|
||||
|
||||
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>) {
|
||||
match self {
|
||||
Graphic::None => (),
|
||||
Graphic::Graphic(list) => list.add_upstream_click_targets(click_targets),
|
||||
Graphic::Vector(list) => list.add_upstream_click_targets(click_targets),
|
||||
Graphic::RasterCPU(list) => list.add_upstream_click_targets(click_targets),
|
||||
@@ -654,6 +659,7 @@ impl Render for Graphic {
|
||||
|
||||
fn add_upstream_outline_targets(&self, outlines: &mut Vec<ClickTarget>) {
|
||||
match self {
|
||||
Graphic::None => (),
|
||||
Graphic::Graphic(list) => list.add_upstream_outline_targets(outlines),
|
||||
Graphic::Vector(list) => list.add_upstream_outline_targets(outlines),
|
||||
Graphic::RasterCPU(list) => list.add_upstream_outline_targets(outlines),
|
||||
@@ -666,6 +672,7 @@ impl Render for Graphic {
|
||||
|
||||
fn contains_artboard(&self) -> bool {
|
||||
match self {
|
||||
Graphic::None => false,
|
||||
Graphic::Graphic(list) => list.contains_artboard(),
|
||||
Graphic::Vector(list) => list.contains_artboard(),
|
||||
Graphic::RasterCPU(list) => list.contains_artboard(),
|
||||
@@ -678,6 +685,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(list) => list.new_ids_from_hash(reference),
|
||||
Graphic::RasterCPU(_) => (),
|
||||
@@ -792,7 +800,7 @@ impl Render for List<Artboard> {
|
||||
let Some(content) = self.element(index).map(Artboard::as_graphic_list) else { continue };
|
||||
let (location, dimensions, _background, clip) = read_artboard_attributes(self, index);
|
||||
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, index);
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, index).0;
|
||||
let element_id = layer_path.iter_element_values().next_back().copied();
|
||||
|
||||
if let Some(element_id) = element_id {
|
||||
@@ -964,7 +972,7 @@ impl Render for List<Graphic> {
|
||||
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option<NodeId>) {
|
||||
for index in 0..self.len() {
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, index);
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, index).0;
|
||||
let layer = layer_path.iter_element_values().next_back().copied();
|
||||
let element = self.element(index).unwrap();
|
||||
|
||||
@@ -1046,9 +1054,9 @@ impl Render for List<Graphic> {
|
||||
}
|
||||
|
||||
fn new_ids_from_hash(&mut self, _reference: Option<NodeId>) {
|
||||
let (elements, layers) = self.element_and_attribute_slices_mut::<List<NodeId>>(ATTR_EDITOR_LAYER_PATH);
|
||||
let (elements, layers) = self.element_and_attribute_slices_mut::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH);
|
||||
for (element, layer) in elements.iter_mut().zip(layers.iter()) {
|
||||
element.new_ids_from_hash(layer.iter_element_values().next_back().copied());
|
||||
element.new_ids_from_hash(layer.0.iter_element_values().next_back().copied());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1348,6 +1356,7 @@ impl Render for List<Vector> {
|
||||
for paint_index in 0..fill_graphic.len() {
|
||||
let Some(paint) = fill_graphic.element(paint_index) else { continue };
|
||||
match paint {
|
||||
Graphic::None => continue,
|
||||
Graphic::Color(list) => {
|
||||
let Some(color) = list.element(0) else { continue };
|
||||
|
||||
@@ -1430,6 +1439,7 @@ impl Render for List<Vector> {
|
||||
};
|
||||
|
||||
match stroke_graphic {
|
||||
Graphic::None => continue,
|
||||
Graphic::Color(list) => {
|
||||
let Some(color) = list.element(0) else { continue };
|
||||
let brush = peniko::Brush::Solid(SRGBA8::from(*color).to_peniko_color());
|
||||
@@ -1546,7 +1556,7 @@ impl Render for List<Vector> {
|
||||
}
|
||||
|
||||
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, caller_element_id: Option<NodeId>) {
|
||||
// Aggregate all items' targets per element_id so multi-item lists (e.g. 'Text' node with "Separate Glyphs" active) produce hit areas for every glyph.
|
||||
// Aggregate all items' targets per element_id so multi-item lists (e.g. the "Text to Vector Glyphs" node) produce hit areas for every glyph.
|
||||
// Targets are baked relative to item 0's transform since `Graphic::collect_metadata` records that as `local_transforms[element_id]`.
|
||||
let item_zero_transform: DAffine2 = if !self.is_empty() {
|
||||
self.attribute_cloned_or_default(ATTR_TRANSFORM, 0)
|
||||
@@ -1565,7 +1575,7 @@ impl Render for List<Vector> {
|
||||
for index in 0..self.len() {
|
||||
let Some(source) = self.element(index) else { continue };
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, index);
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, index).0;
|
||||
let layer = layer_path.iter_element_values().next_back().copied();
|
||||
|
||||
if let Some(element_id) = caller_element_id.or(layer) {
|
||||
@@ -2047,7 +2057,7 @@ impl Render for List<Color> {
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for List<GradientStops> {
|
||||
impl Render for List<Gradient> {
|
||||
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
|
||||
// For thumbnails the gradient fills a finite rect at the footprint's document space bounds, with a 1-unit margin to cover the `as u32` truncation of `Footprint::resolution`.
|
||||
// The viewBox crops the overshoot. Canvas rendering keeps the polyline path since Chrome rejects rects larger than ~20 million.
|
||||
@@ -2562,7 +2572,7 @@ impl Render for List<String> {
|
||||
let mut accumulated_click_targets: HashMap<NodeId, Vec<Arc<ClickTarget>>> = HashMap::new();
|
||||
|
||||
for index in 0..self.len() {
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, index);
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, index).0;
|
||||
let layer = layer_path.iter_element_values().next_back().copied();
|
||||
let Some(element_id) = caller_element_id.or(layer) else { continue };
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -8,7 +8,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 math::{QuadExt, RectExt};
|
||||
pub use subpath::Subpath;
|
||||
pub use vector::Vector;
|
||||
|
||||
@@ -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];
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ impl PipelineCache {
|
||||
pub async fn run<P: Pipeline>(&self, args: &P::Args<'_>) -> P::Out {
|
||||
let executor = self.executor.get().expect("PipelineCache not initialized");
|
||||
let entry = self.pipeline.get().expect("PipelineCache not initialized");
|
||||
let pipeline = (&**entry)
|
||||
let pipeline = (**entry)
|
||||
.downcast_ref::<P>()
|
||||
.unwrap_or_else(|| panic!("PipelineCache type mismatch: run::<{}>() but init used a different pipeline type", std::any::type_name::<P>(),));
|
||||
pipeline.run(executor, args).await
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use crate::WgpuExecutor;
|
||||
use core_types::Color;
|
||||
use core_types::Ctx;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::ops::Convert;
|
||||
@@ -20,7 +19,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,
|
||||
@@ -247,15 +246,3 @@ impl<'i> Convert<Raster<CPU>, &'i WgpuExecutor> for Raster<GPU> {
|
||||
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 async fn upload_texture<'a: 'n, T: Convert<List<Raster<GPU>>, &'a WgpuExecutor>>(
|
||||
_: impl Ctx,
|
||||
#[implementations(List<Raster<CPU>>, List<Raster<GPU>>)] input: T,
|
||||
executor: &'a WgpuExecutor,
|
||||
) -> List<Raster<GPU>> {
|
||||
input.convert(Footprint::DEFAULT, executor).await
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user