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:
@@ -58,7 +58,7 @@ pub mod subpath {
|
||||
}
|
||||
|
||||
pub mod gradient {
|
||||
pub use vector_types::{GradientStop, GradientStops};
|
||||
pub use vector_types::{Gradient, GradientStop};
|
||||
}
|
||||
|
||||
pub mod transform {
|
||||
|
||||
@@ -3,10 +3,12 @@ use base64::Engine;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use canvas_utils::{Canvas, CanvasHandle};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::list::Item;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::list::List;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::math::bbox::Bbox;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::ops::Convert;
|
||||
use core_types::transform::Footprint;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::{ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, WasmNotSend};
|
||||
@@ -23,12 +25,11 @@ use graphic_types::IntoGraphicList;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use graphic_types::Vector;
|
||||
use graphic_types::raster_types::Image;
|
||||
use graphic_types::raster_types::{CPU, Raster};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
#[cfg(target_family = "wasm")]
|
||||
use graphic_types::vector_types::gradient::GradientStops;
|
||||
use graphic_types::vector_types::gradient::Gradient;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn parse_headers(headers: &str) -> reqwest::header::HeaderMap {
|
||||
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
|
||||
@@ -51,11 +52,14 @@ async fn get_request(
|
||||
_primary: (),
|
||||
/// The web address to send the GET request to.
|
||||
#[name("URL")]
|
||||
url: String,
|
||||
url: Item<String>,
|
||||
/// Makes the request run in the background without waiting on a response. This is useful for triggering webhooks without blocking the continued execution of the graph.
|
||||
discard_result: bool,
|
||||
#[widget(ParsedWidgetOverride::Custom = "text_area")] headers: String,
|
||||
) -> String {
|
||||
discard_result: Item<bool>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "text_area")] headers: Item<String>,
|
||||
) -> Item<String> {
|
||||
let (url, headers) = (url.into_element(), headers.into_element());
|
||||
let discard_result = *discard_result.element();
|
||||
|
||||
let header_map = parse_headers(&headers);
|
||||
let request = reqwest::Client::new().get(url).headers(header_map);
|
||||
|
||||
@@ -68,13 +72,13 @@ async fn get_request(
|
||||
tokio::spawn(async move {
|
||||
let _ = request.send().await;
|
||||
});
|
||||
return String::new();
|
||||
return Item::default();
|
||||
}
|
||||
|
||||
let Ok(response) = request.send().await else {
|
||||
return String::new();
|
||||
return Item::default();
|
||||
};
|
||||
response.text().await.ok().unwrap_or_default()
|
||||
Item::new_from_element(response.text().await.ok().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Sends an HTTP POST request to a specified URL with the provided binary data and optionally waits for the response (unless discarded) which is output as a string.
|
||||
@@ -84,16 +88,19 @@ async fn post_request(
|
||||
_primary: (),
|
||||
/// The web address to send the POST request to.
|
||||
#[name("URL")]
|
||||
url: String,
|
||||
url: Item<String>,
|
||||
/// The binary data to include in the body of the POST request.
|
||||
body: List<u8>,
|
||||
body: Item<Resource>,
|
||||
/// Makes the request run in the background without waiting on a response. This is useful for triggering webhooks without blocking the continued execution of the graph.
|
||||
discard_result: bool,
|
||||
#[widget(ParsedWidgetOverride::Custom = "text_area")] headers: String,
|
||||
) -> String {
|
||||
discard_result: Item<bool>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "text_area")] headers: Item<String>,
|
||||
) -> Item<String> {
|
||||
let (url, headers) = (url.into_element(), headers.into_element());
|
||||
let discard_result = *discard_result.element();
|
||||
|
||||
let mut header_map = parse_headers(&headers);
|
||||
header_map.insert("Content-Type", "application/octet-stream".parse().unwrap());
|
||||
let body_bytes: Vec<u8> = body.iter_element_values().copied().collect();
|
||||
let body_bytes: Vec<u8> = body.element().as_ref().to_vec();
|
||||
let request = reqwest::Client::new().post(url).body(body_bytes).headers(header_map);
|
||||
|
||||
if discard_result {
|
||||
@@ -105,40 +112,42 @@ async fn post_request(
|
||||
tokio::spawn(async move {
|
||||
let _ = request.send().await;
|
||||
});
|
||||
return String::new();
|
||||
return Item::default();
|
||||
}
|
||||
|
||||
let Ok(response) = request.send().await else {
|
||||
return String::new();
|
||||
return Item::default();
|
||||
};
|
||||
response.text().await.ok().unwrap_or_default()
|
||||
Item::new_from_element(response.text().await.ok().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Converts a text string to raw binary data. Useful for transmission over HTTP or writing to files.
|
||||
#[node_macro::node(category("Web Request"), name("String to Bytes"))]
|
||||
fn string_to_bytes(_: impl Ctx, string: String) -> List<u8> {
|
||||
string.into_bytes().into_iter().map(Item::new_from_element).collect()
|
||||
fn string_to_bytes(_: impl Ctx, string: Item<String>) -> Item<Resource> {
|
||||
Item::new_from_element(Resource::new(string.into_element().into_bytes()))
|
||||
}
|
||||
|
||||
/// Converts extracted raw RGBA pixel data from an input image. Each pixel becomes 4 sequential bytes. Useful for transmission over HTTP or writing to files.
|
||||
#[node_macro::node(category("Web Request"), name("Image to Bytes"))]
|
||||
fn image_to_bytes(_: impl Ctx, image: List<Raster<CPU>>) -> List<u8> {
|
||||
let Some(image) = image.element(0) else { return List::new() };
|
||||
image
|
||||
fn image_to_bytes(_: impl Ctx, image: Item<Raster<CPU>>) -> Item<Resource> {
|
||||
let bytes: Vec<u8> = image
|
||||
.element()
|
||||
.data
|
||||
.iter()
|
||||
.flat_map(|color| {
|
||||
let SRGBA8 { red, green, blue, alpha } = (*color).into();
|
||||
[red, green, blue, alpha]
|
||||
})
|
||||
.map(Item::new_from_element)
|
||||
.collect()
|
||||
.collect();
|
||||
|
||||
Item::new_from_element(Resource::new(bytes))
|
||||
}
|
||||
|
||||
/// Loads binary from URLs and local asset paths. Returns a transparent placeholder if the resource fails to load, allowing rendering to continue.
|
||||
#[node_macro::node(category("Web Request"))]
|
||||
async fn load_resource<'a: 'n>(_: impl Ctx, _primary: (), #[name("URL")] url: String) -> Arc<[u8]> {
|
||||
let placeholder = || -> Arc<[u8]> { Arc::from(Vec::<u8>::new()) };
|
||||
async fn load_resource<'a: 'n>(_: impl Ctx, _primary: (), #[name("URL")] url: Item<String>) -> Item<Resource> {
|
||||
let url = url.into_element();
|
||||
let placeholder = || -> Item<Resource> { Item::new_from_element(Resource::empty()) };
|
||||
|
||||
let response = match reqwest::Client::new().get(&url).send().await {
|
||||
Ok(response) => response,
|
||||
@@ -149,7 +158,7 @@ async fn load_resource<'a: 'n>(_: impl Ctx, _primary: (), #[name("URL")] url: St
|
||||
};
|
||||
|
||||
match response.bytes().await {
|
||||
Ok(bytes) => Arc::from(bytes.to_vec()),
|
||||
Ok(bytes) => Item::new_from_element(Resource::new(bytes)),
|
||||
Err(error) => {
|
||||
log::error!("Failed to read HTTP response for `{url}`: {error}");
|
||||
placeholder()
|
||||
@@ -161,9 +170,10 @@ async fn load_resource<'a: 'n>(_: impl Ctx, _primary: (), #[name("URL")] url: St
|
||||
///
|
||||
/// Works with standard image format (PNG, JPEG, WebP, etc.). Automatically converts the color space to linear sRGB for accurate compositing.
|
||||
#[node_macro::node(category("Web Request"))]
|
||||
fn decode_image(_: impl Ctx, data: Arc<[u8]>) -> List<Raster<CPU>> {
|
||||
fn decode_image(_: impl Ctx, data: Item<Resource>) -> Item<Raster<CPU>> {
|
||||
let data = data.into_element();
|
||||
let Some(image) = image::load_from_memory(data.as_ref()).ok() else {
|
||||
return List::new();
|
||||
return Item::default();
|
||||
};
|
||||
let image = image.to_rgba32f();
|
||||
let image = Image {
|
||||
@@ -180,13 +190,13 @@ fn decode_image(_: impl Ctx, data: Arc<[u8]>) -> List<Raster<CPU>> {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
List::new_from_element(Raster::new_cpu(image))
|
||||
Item::new_from_element(Raster::new_cpu(image))
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[node_macro::node(category(""))]
|
||||
async fn create_canvas(_: impl Ctx) -> CanvasHandle {
|
||||
CanvasHandle::new()
|
||||
async fn create_canvas(_: impl Ctx) -> Item<CanvasHandle> {
|
||||
Item::new_from_element(CanvasHandle::new())
|
||||
}
|
||||
|
||||
/// Renders a view of the input graphic within an area defined by the *Footprint*.
|
||||
@@ -199,17 +209,21 @@ async fn rasterize<T: WasmNotSend + Clone + 'n>(
|
||||
List<Raster<CPU>>,
|
||||
List<Graphic>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<Gradient>,
|
||||
)]
|
||||
mut data: List<T>,
|
||||
footprint: Footprint,
|
||||
mut canvas: CanvasHandle,
|
||||
data: List<T>,
|
||||
footprint: Item<Footprint>,
|
||||
canvas: Item<CanvasHandle>,
|
||||
) -> List<Raster<CPU>>
|
||||
where
|
||||
List<T>: Render + Clone + graphic_types::IntoGraphicList,
|
||||
{
|
||||
let mut data = data;
|
||||
let mut canvas = canvas.into_element();
|
||||
use glam::{DAffine2, DVec2};
|
||||
|
||||
let footprint = footprint.into_element();
|
||||
|
||||
if footprint.transform.matrix2.determinant() == 0. {
|
||||
log::trace!("Invalid footprint received for rasterization");
|
||||
return List::new();
|
||||
@@ -262,29 +276,48 @@ where
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub async fn editor_api<'a: 'n>(_: impl Ctx, #[scope("editor-api")] editor_api: &'a PlatformEditorApi) -> &'a PlatformEditorApi {
|
||||
pub async fn editor_api<'a: 'n>(_: impl Ctx, #[scope("editor-api")] editor_api: Item<&'a PlatformEditorApi>) -> Item<&'a PlatformEditorApi> {
|
||||
editor_api
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
pub async fn resource<'a: 'n>(_: impl Ctx, hash: ResourceHash, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> Resource {
|
||||
let application_io = editor_api.application_io.as_ref().expect("ApplicationIo must be available when using resources");
|
||||
application_io.load_resource(hash).await.unwrap_or_else(|| {
|
||||
panic!("Resource {hash} not found");
|
||||
})
|
||||
pub async fn resource<'a: 'n>(
|
||||
_: impl Ctx,
|
||||
/// The scope-provided editor API giving access to the platform's resource storage.
|
||||
#[scope(editor_api::IDENTIFIER)]
|
||||
editor_api: Item<&'a PlatformEditorApi>,
|
||||
/// The content hash identifying which stored resource to load.
|
||||
hash: Item<ResourceHash>,
|
||||
) -> Item<Resource> {
|
||||
let hash = hash.into_element();
|
||||
let application_io = editor_api.into_element().application_io.as_ref().expect("ApplicationIo must be available when using resources");
|
||||
let resource = application_io.load_resource(hash).await.unwrap_or_else(|| panic!("Resource {hash} not found"));
|
||||
Item::new_from_element(resource)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub async fn wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> &'a ::wgpu_executor::WgpuExecutor {
|
||||
editor_api
|
||||
pub async fn wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Item<&'a PlatformEditorApi>) -> Item<&'a ::wgpu_executor::WgpuExecutor> {
|
||||
let executor = editor_api
|
||||
.into_element()
|
||||
.application_io
|
||||
.as_ref()
|
||||
.expect("ApplicationIo not not available")
|
||||
.expect("ApplicationIo not available")
|
||||
.gpu_executor()
|
||||
.expect("GPU executor not available")
|
||||
.expect("GPU executor not available");
|
||||
Item::new_from_element(executor)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub async fn try_wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> Option<&'a ::wgpu_executor::WgpuExecutor> {
|
||||
editor_api.application_io.as_ref()?.gpu_executor()
|
||||
pub async fn try_wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Item<&'a PlatformEditorApi>) -> Item<Option<&'a ::wgpu_executor::WgpuExecutor>> {
|
||||
let executor = editor_api.into_element().application_io.as_ref().and_then(|application_io| application_io.gpu_executor());
|
||||
Item::new_from_element(executor)
|
||||
}
|
||||
|
||||
/// Uploads image data from CPU memory into a GPU texture so that GPU-based nodes can process it.
|
||||
#[node_macro::node(category("Debug"), memoize)]
|
||||
pub async fn upload_texture<'a: 'n>(_: impl Ctx, content: Item<Raster<CPU>>, #[scope(wgpu_executor::IDENTIFIER)] executor: Item<&'a ::wgpu_executor::WgpuExecutor>) -> Item<Raster<GPU>> {
|
||||
let executor = executor.into_element();
|
||||
let (raster, attributes) = content.into_parts();
|
||||
|
||||
Item::from_parts(raster.convert(Footprint::DEFAULT, executor).await, attributes)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use core_types::ExtractVarArgs;
|
||||
use core_types::color::Linear;
|
||||
use core_types::list::Item;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::generate_uuid;
|
||||
use core_types::{Ctx, ExtractFootprint};
|
||||
@@ -14,9 +15,9 @@ use wgpu_executor::{AsyncWgpuPipeline, WgpuExecutor, WgpuPipelineCache};
|
||||
#[node_macro::node(category(""))]
|
||||
async fn render_background<'a: 'n>(
|
||||
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
|
||||
#[scope(composite_background_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache,
|
||||
data: RenderOutput,
|
||||
) -> RenderOutput {
|
||||
#[scope(composite_background_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
data: Item<RenderOutput>,
|
||||
) -> Item<RenderOutput> {
|
||||
let footprint = ctx.footprint();
|
||||
let render_params = ctx
|
||||
.vararg(0)
|
||||
@@ -28,7 +29,7 @@ async fn render_background<'a: 'n>(
|
||||
return data;
|
||||
}
|
||||
|
||||
let RenderOutput { data: foreground_data, metadata } = data;
|
||||
let RenderOutput { data: foreground_data, metadata } = data.into_element();
|
||||
let mut render_params = render_params.clone();
|
||||
render_params.footprint = *footprint;
|
||||
|
||||
@@ -36,6 +37,7 @@ async fn render_background<'a: 'n>(
|
||||
RenderOutputType::Texture(foreground_texture) => {
|
||||
let doc_to_screen = render_params.footprint.transform.as_affine2();
|
||||
let blended = pipeline
|
||||
.into_element()
|
||||
.run::<CompositeBackground>(&CompositeBackgroundArgs {
|
||||
foreground: foreground_texture.as_ref(),
|
||||
backgrounds: &metadata.backgrounds,
|
||||
@@ -117,19 +119,19 @@ async fn render_background<'a: 'n>(
|
||||
_ => unreachable!("Render background node received unsupported render output type"),
|
||||
};
|
||||
|
||||
RenderOutput { data, metadata }
|
||||
Item::new_from_element(RenderOutput { data, metadata })
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
async fn composite_background_pipeline<'a: 'n>(
|
||||
_ctx: impl Ctx,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<&'a WgpuExecutor>>,
|
||||
#[data] pipeline: WgpuPipelineCache,
|
||||
) -> WgpuPipelineCache {
|
||||
if let Some(executor) = executor {
|
||||
) -> Item<WgpuPipelineCache> {
|
||||
if let Some(executor) = executor.into_element() {
|
||||
executor.pipeline_init::<CompositeBackground>(pipeline);
|
||||
}
|
||||
pipeline.clone()
|
||||
Item::new_from_element(pipeline.clone())
|
||||
}
|
||||
|
||||
pub struct CompositeBackground {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Tile-based render caching for efficient viewport panning.
|
||||
|
||||
use core_types::list::Item;
|
||||
use core_types::math::bbox::AxisAlignedBbox;
|
||||
use core_types::transform::{Footprint, RenderQuality, Transform};
|
||||
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, OwnedContextImpl};
|
||||
@@ -323,11 +324,11 @@ fn flood_fill(start: &TileCoord, tile_set: &HashSet<TileCoord>, visited: &mut Ha
|
||||
#[node_macro::node(category(""))]
|
||||
pub async fn render_output_cache<'a: 'n>(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs + ExtractRealTime + ExtractAnimationTime + ExtractPointerPosition + Sync,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>,
|
||||
#[scope(crate::platform_application_io::editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi,
|
||||
data: impl Node<Context<'static>, Output = RenderOutput> + Send + Sync,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<&'a WgpuExecutor>>,
|
||||
#[scope(crate::platform_application_io::editor_api::IDENTIFIER)] editor_api: Item<&'a PlatformEditorApi>,
|
||||
data: impl Node<Context<'static>, Output = Item<RenderOutput>> + Send + Sync,
|
||||
#[data] tile_cache: TileCache,
|
||||
) -> RenderOutput {
|
||||
) -> Item<RenderOutput> {
|
||||
let footprint = ctx.footprint();
|
||||
let Some(render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::<RenderParams>()) else {
|
||||
log::warn!("render_output_cache: missing or invalid render params, falling back to direct render");
|
||||
@@ -351,7 +352,7 @@ pub async fn render_output_cache<'a: 'n>(
|
||||
end: footprint.resolution.as_dvec2() - device_origin_offset,
|
||||
};
|
||||
|
||||
let max_region_area = editor_api.editor_preferences.max_render_region_area();
|
||||
let max_region_area = editor_api.into_element().editor_preferences.max_render_region_area();
|
||||
|
||||
let cache_key = CacheKey::new(
|
||||
max_region_area,
|
||||
@@ -389,15 +390,15 @@ pub async fn render_output_cache<'a: 'n>(
|
||||
return data.eval(context.into_context()).await;
|
||||
}
|
||||
|
||||
let executor = executor.expect("GPU executor not available");
|
||||
let executor = executor.into_element().expect("GPU executor not available");
|
||||
let output_texture = executor.request_texture(physical_resolution).await;
|
||||
|
||||
let combined_metadata = composite_cached_regions(&all_regions, &output_texture, &device_origin_offset, &footprint.transform, executor);
|
||||
|
||||
RenderOutput {
|
||||
Item::new_from_element(RenderOutput {
|
||||
data: RenderOutputType::Texture(output_texture),
|
||||
metadata: combined_metadata,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn render_missing_region<F, Fut>(
|
||||
@@ -410,7 +411,7 @@ async fn render_missing_region<F, Fut>(
|
||||
) -> CachedRegion
|
||||
where
|
||||
F: Fn(Context<'static>) -> Fut,
|
||||
Fut: std::future::Future<Output = RenderOutput>,
|
||||
Fut: std::future::Future<Output = Item<RenderOutput>>,
|
||||
{
|
||||
let min_tile = region.tiles.iter().fold(IVec2::new(i32::MAX, i32::MAX), |acc, t| acc.min(IVec2::new(t.x, t.y)));
|
||||
let max_tile = region.tiles.iter().fold(IVec2::new(i32::MIN, i32::MIN), |acc, t| acc.max(IVec2::new(t.x, t.y)));
|
||||
@@ -428,7 +429,7 @@ where
|
||||
|
||||
let region_params = render_params.clone();
|
||||
let region_ctx = OwnedContextImpl::from(ctx).with_footprint(region_footprint).with_vararg(Box::new(region_params)).into_context();
|
||||
let mut result = render_fn(region_ctx).await;
|
||||
let mut result = render_fn(region_ctx).await.into_element();
|
||||
|
||||
let RenderOutputType::Texture(texture) = result.data else {
|
||||
unreachable!("render_missing_region: expected texture output from Vello render");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use core_types::list::List;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
use core_types::{CloneVarArgs, ExtractAll, ExtractVarArgs};
|
||||
use core_types::{Color, Context, Ctx, ExtractFootprint, OwnedContextImpl, WasmNotSend};
|
||||
@@ -8,7 +8,7 @@ use graphic_types::raster_types::{CPU, Raster};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use rendering::{Render, RenderMetadata, RenderOutputType as RenderOutputTypeRequest, RenderParams, SvgRender, SvgRenderOutput};
|
||||
use std::sync::Arc;
|
||||
use vector_types::GradientStops;
|
||||
use vector_types::Gradient;
|
||||
use wgpu_executor::{RenderContext, WgpuExecutor};
|
||||
|
||||
#[derive(Clone, dyn_any::DynAny)]
|
||||
@@ -31,11 +31,11 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send +
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<String>,
|
||||
)]
|
||||
data: impl Node<Context<'static>, Output = T>,
|
||||
) -> RenderIntermediate {
|
||||
) -> Item<RenderIntermediate> {
|
||||
let render_params = ctx
|
||||
.vararg(0)
|
||||
.expect("Did not find var args")
|
||||
@@ -48,7 +48,7 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send +
|
||||
let footprint = Footprint::default();
|
||||
let mut metadata = RenderMetadata::default();
|
||||
data.collect_metadata(&mut metadata, footprint, None);
|
||||
match &render_params.render_output_type {
|
||||
let intermediate = match &render_params.render_output_type {
|
||||
RenderOutputTypeRequest::Vello => {
|
||||
let mut scene = vello::Scene::new();
|
||||
|
||||
@@ -70,15 +70,17 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send +
|
||||
metadata,
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Item::new_from_element(intermediate)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
async fn render<'a: 'n>(
|
||||
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>,
|
||||
data: RenderIntermediate,
|
||||
) -> RenderOutput {
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<&'a WgpuExecutor>>,
|
||||
data: Item<RenderIntermediate>,
|
||||
) -> Item<RenderOutput> {
|
||||
let footprint = ctx.footprint();
|
||||
let render_params = ctx
|
||||
.vararg(0)
|
||||
@@ -88,7 +90,7 @@ async fn render<'a: 'n>(
|
||||
let mut render_params = render_params.clone();
|
||||
render_params.footprint = *footprint;
|
||||
|
||||
let RenderIntermediate { ty, mut metadata } = data;
|
||||
let RenderIntermediate { ty, mut metadata } = data.into_element();
|
||||
metadata.apply_transform(footprint.transform);
|
||||
|
||||
let data = match (render_params.render_output_type, ty) {
|
||||
@@ -131,6 +133,7 @@ async fn render<'a: 'n>(
|
||||
}
|
||||
|
||||
let texture = executor
|
||||
.into_element()
|
||||
.expect("GPU executor not available")
|
||||
.render_vello_scene(&transformed_scene, footprint.resolution, context, None)
|
||||
.await
|
||||
@@ -140,15 +143,20 @@ async fn render<'a: 'n>(
|
||||
_ => unreachable!("Render node did not receive its requested data type"),
|
||||
};
|
||||
|
||||
RenderOutput { data, metadata }
|
||||
Item::new_from_element(RenderOutput { data, metadata })
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
async fn create_context<'a: 'n>(
|
||||
// Context injections are defined in the wrap_network_in_scope function
|
||||
render_config: RenderConfig,
|
||||
data: impl Node<Context<'static>, Output = RenderOutput>,
|
||||
) -> RenderOutput {
|
||||
// The executor boundary supplies the render config as the sole vararg (see `wrap_network_in_scope()`)
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs + Sync,
|
||||
data: impl Node<Context<'static>, Output = Item<RenderOutput>>,
|
||||
) -> Item<RenderOutput> {
|
||||
let render_config = ctx.vararg(0).ok().and_then(|config| config.downcast_ref::<RenderConfig>()).copied().unwrap_or_else(|| {
|
||||
log::error!("The boundary context is missing its render config vararg");
|
||||
RenderConfig::default()
|
||||
});
|
||||
|
||||
let render_output_type = match render_config.export_format {
|
||||
ExportFormat::Svg => RenderOutputTypeRequest::Svg,
|
||||
ExportFormat::Raster => RenderOutputTypeRequest::Vello,
|
||||
@@ -179,6 +187,6 @@ async fn create_context<'a: 'n>(
|
||||
|
||||
let mut result = data.eval(ctx).await;
|
||||
|
||||
result.metadata.apply_transform(glam::DAffine2::from_scale(glam::DVec2::splat(1. / render_config.scale)));
|
||||
result.element_mut().metadata.apply_transform(glam::DAffine2::from_scale(glam::DVec2::splat(1. / render_config.scale)));
|
||||
result
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use core_types::list::Item;
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2, UVec2, Vec2};
|
||||
@@ -10,9 +11,9 @@ use wgpu_executor::{AsyncWgpuPipeline, WgpuExecutor, WgpuPipelineCache};
|
||||
#[node_macro::node(category(""))]
|
||||
pub async fn render_pixel_preview<'a: 'n>(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs + Sync,
|
||||
#[scope(pixel_preview_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache,
|
||||
data: impl Node<Context<'static>, Output = RenderOutput> + Send + Sync,
|
||||
) -> RenderOutput {
|
||||
#[scope(pixel_preview_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
data: impl Node<Context<'static>, Output = Item<RenderOutput>> + Send + Sync,
|
||||
) -> Item<RenderOutput> {
|
||||
let Some(render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::<RenderParams>()).cloned() else {
|
||||
log::error!("invalid render params for pixel preview");
|
||||
let context = OwnedContextImpl::from(ctx).into_context();
|
||||
@@ -52,14 +53,17 @@ pub async fn render_pixel_preview<'a: 'n>(
|
||||
};
|
||||
|
||||
let new_ctx = OwnedContextImpl::from(ctx).with_footprint(upstream_footprint).with_vararg(Box::new(render_params)).into_context();
|
||||
let mut result = data.eval(new_ctx).await;
|
||||
let mut result = data.eval(new_ctx).await.into_element();
|
||||
|
||||
let RenderOutputType::Texture(ref source_texture) = result.data else { return result };
|
||||
let RenderOutputType::Texture(ref source_texture) = result.data else {
|
||||
return Item::new_from_element(result);
|
||||
};
|
||||
|
||||
let logical_transform = DAffine2::from_scale(DVec2::splat(1. / physical_scale)) * footprint.transform;
|
||||
let transform = DAffine2::from_translation(-upstream_min) * logical_transform.inverse() * DAffine2::from_scale(logical_resolution);
|
||||
|
||||
let resampled = pipeline
|
||||
.into_element()
|
||||
.run::<PixelPreview>(&PixelPreviewArgs {
|
||||
source: source_texture.as_ref(),
|
||||
transform: &transform,
|
||||
@@ -71,19 +75,19 @@ pub async fn render_pixel_preview<'a: 'n>(
|
||||
|
||||
result.metadata.apply_transform(footprint.transform * DAffine2::from_translation(upstream_min));
|
||||
|
||||
result
|
||||
Item::new_from_element(result)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
async fn pixel_preview_pipeline<'a: 'n>(
|
||||
_ctx: impl Ctx,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<&'a WgpuExecutor>>,
|
||||
#[data] pipeline: WgpuPipelineCache,
|
||||
) -> WgpuPipelineCache {
|
||||
if let Some(executor) = executor {
|
||||
) -> Item<WgpuPipelineCache> {
|
||||
if let Some(executor) = executor.into_element() {
|
||||
executor.pipeline_init::<PixelPreview>(pipeline);
|
||||
}
|
||||
pipeline.clone()
|
||||
Item::new_from_element(pipeline.clone())
|
||||
}
|
||||
|
||||
pub struct PixelPreview {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use core_types::consts::{DEFAULT_FONT_SIZE, DEFAULT_LINE_HEIGHT};
|
||||
use core_types::list::List;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{ATTR_FONT, ATTR_FONT_SIZE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_TEXT_ALIGN, Ctx};
|
||||
use graph_craft::application_io::resource::Resource;
|
||||
use graphic_types::Vector;
|
||||
pub use text_nodes::*;
|
||||
|
||||
/// Produces a styled `String[]` carrying all typographic attributes.
|
||||
/// Produces a styled text string carrying all typographic attributes.
|
||||
///
|
||||
/// Use the **Text to Vector** node to convert this into vector geometry if desired.
|
||||
#[node_macro::node(category("Text"))]
|
||||
@@ -15,15 +15,15 @@ fn text(
|
||||
/// The text content to be drawn.
|
||||
#[widget(ParsedWidgetOverride::Custom = "text_area")]
|
||||
#[default("Lorem ipsum")]
|
||||
text: String,
|
||||
text: Item<String>,
|
||||
/// The loaded font file used to draw the text. The editor resolves the chosen typeface to these bytes via the resource system.
|
||||
#[widget(ParsedWidgetOverride::Custom = "text_font")]
|
||||
font: Resource,
|
||||
font: Item<Resource>,
|
||||
/// The font size used to draw the text.
|
||||
#[unit(" px")]
|
||||
#[default(24.)]
|
||||
#[hard(1..)]
|
||||
size: f64,
|
||||
size: Item<f64>,
|
||||
/// The line height ratio, relative to the font size. Each line is drawn lower than its previous line by the distance of *Size* × *Line Height*.
|
||||
///
|
||||
/// 0 means all lines overlap. 1 means all lines are spaced by just the font size. 1.2 is a common default for readable text. 2 means double-spaced text.
|
||||
@@ -31,74 +31,87 @@ fn text(
|
||||
#[hard(0..)]
|
||||
#[step(0.1)]
|
||||
#[default(1.2)]
|
||||
line_height: f64,
|
||||
line_height: Item<f64>,
|
||||
/// Additional spacing, in pixels, added between each character.
|
||||
#[unit(" px")]
|
||||
#[step(0.1)]
|
||||
letter_spacing: f64,
|
||||
letter_spacing: Item<f64>,
|
||||
/// The angle of faux italic slant applied to each glyph.
|
||||
#[unit("°")]
|
||||
#[hard(-85..85)]
|
||||
letter_tilt: f64,
|
||||
letter_tilt: Item<f64>,
|
||||
/// Enables the maximum width constraint so lines can wrap.
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
has_max_width: bool,
|
||||
has_max_width: Item<bool>,
|
||||
/// The maximum width that the text block can occupy before wrapping to a new line. Otherwise, lines do not wrap.
|
||||
#[unit(" px")]
|
||||
#[hard(1..)]
|
||||
#[widget(ParsedWidgetOverride::Custom = "optional_f64")]
|
||||
max_width: f64,
|
||||
max_width: Item<f64>,
|
||||
/// Whether the *Max Height* property is enabled so that lines beyond it are not drawn.
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
has_max_height: bool,
|
||||
has_max_height: Item<bool>,
|
||||
/// The maximum height that the text block can occupy. Excess lines are not drawn.
|
||||
#[unit(" px")]
|
||||
#[hard(1..)]
|
||||
#[widget(ParsedWidgetOverride::Custom = "optional_f64")]
|
||||
max_height: f64,
|
||||
max_height: Item<f64>,
|
||||
/// The horizontal alignment of each line of text within its surrounding box. To have an effect on a single line of text, *Max Width* must be set.
|
||||
#[widget(ParsedWidgetOverride::Custom = "text_align")]
|
||||
align: TextAlign,
|
||||
) -> List<String> {
|
||||
let mut list = List::new_from_element(text);
|
||||
align: Item<TextAlign>,
|
||||
) -> Item<String> {
|
||||
let text = text.into_element();
|
||||
let font = font.into_element();
|
||||
let (size, line_height, letter_spacing, letter_tilt) = (*size.element(), *line_height.element(), *letter_spacing.element(), *letter_tilt.element());
|
||||
let (has_max_width, max_width, has_max_height, max_height) = (*has_max_width.element(), *max_width.element(), *has_max_height.element(), *max_height.element());
|
||||
let align = align.into_element();
|
||||
|
||||
let mut item = Item::new_from_element(text);
|
||||
|
||||
if font != Resource::default() {
|
||||
list.set_attribute(ATTR_FONT, 0, font);
|
||||
item.set_attribute(ATTR_FONT, font);
|
||||
}
|
||||
if (size - DEFAULT_FONT_SIZE).abs() > f64::EPSILON {
|
||||
list.set_attribute(ATTR_FONT_SIZE, 0, size);
|
||||
item.set_attribute(ATTR_FONT_SIZE, size);
|
||||
}
|
||||
if (line_height - DEFAULT_LINE_HEIGHT).abs() > f64::EPSILON {
|
||||
list.set_attribute(ATTR_LINE_HEIGHT, 0, line_height);
|
||||
item.set_attribute(ATTR_LINE_HEIGHT, line_height);
|
||||
}
|
||||
if letter_spacing != 0. {
|
||||
list.set_attribute(ATTR_LETTER_SPACING, 0, letter_spacing);
|
||||
item.set_attribute(ATTR_LETTER_SPACING, letter_spacing);
|
||||
}
|
||||
if letter_tilt != 0. {
|
||||
list.set_attribute(ATTR_LETTER_TILT, 0, letter_tilt);
|
||||
item.set_attribute(ATTR_LETTER_TILT, letter_tilt);
|
||||
}
|
||||
if has_max_width {
|
||||
list.set_attribute(ATTR_MAX_WIDTH, 0, Some(max_width));
|
||||
item.set_attribute(ATTR_MAX_WIDTH, Some(max_width));
|
||||
}
|
||||
if has_max_height {
|
||||
list.set_attribute(ATTR_MAX_HEIGHT, 0, Some(max_height));
|
||||
item.set_attribute(ATTR_MAX_HEIGHT, Some(max_height));
|
||||
}
|
||||
if align != TextAlign::default() {
|
||||
list.set_attribute(ATTR_TEXT_ALIGN, 0, align);
|
||||
item.set_attribute(ATTR_TEXT_ALIGN, align);
|
||||
}
|
||||
|
||||
list
|
||||
item
|
||||
}
|
||||
|
||||
/// Converts a styled `String[]` into vector geometry.
|
||||
/// Converts a styled text string into a vector compound path.
|
||||
#[node_macro::node(category("Text"), name("Text to Vector"))]
|
||||
fn text_to_vector(
|
||||
_: impl Ctx,
|
||||
/// A styled list of text strings produced by the **Text** node (or any other `String[]` source).
|
||||
#[implementations(List<String>)]
|
||||
strings: List<String>,
|
||||
/// Whether to split every letterform into its own vector item. Otherwise, a single vector compound path is produced.
|
||||
separate_glyphs: bool,
|
||||
) -> List<Vector> {
|
||||
shape_text_list(&strings, separate_glyphs)
|
||||
/// A styled text string produced by the **Text** node (or any other string source).
|
||||
string: Item<String>,
|
||||
) -> Item<Vector> {
|
||||
shape_text_item(&string, false).into_iter().next().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Splits a styled text string into a separate vector item for each of its glyphs (letterforms).
|
||||
#[node_macro::node(category("Text"), name("Text to Vector Glyphs"))]
|
||||
fn text_to_vector_glyphs(
|
||||
_: impl Ctx,
|
||||
/// A styled text string produced by the **Text** node (or any other string source).
|
||||
string: Item<String>,
|
||||
) -> List<Vector> {
|
||||
shape_text_item(&string, true)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user