Compare commits

..
Author SHA1 Message Date
Dennis Kobert 9d3abe385f Sweep the data-flow wire and edge wording to input and source 2026-09-06 15:14:55 +00:00
Dennis Kobert 96521333d6 Rename SharedEdge to SharedSource 2026-09-06 15:13:57 +00:00
Dennis Kobert d80651e85c Rename ElementEdge to ElementInput 2026-09-06 15:13:32 +00:00
Dennis Kobert a16a4c6354 Rename RecordEdgeInput to RecordInput 2026-09-06 15:13:22 +00:00
Dennis Kobert d294d75198 Rename DerivedRecordEdge to DerivedRecordInput 2026-09-06 15:12:54 +00:00
Dennis Kobert 8f7d3936f8 Rename serve_edge to serve_input 2026-09-06 15:12:46 +00:00
Dennis Kobert 6961687172 Split the record module by abstraction level 2026-09-06 14:25:09 +00:00
Dennis Kobert 38d479bdfa Key the paint list park sites so a group-free paint moves 2026-09-05 13:12:17 +00:00
Dennis Kobert 14660bdb64 Key the element park path and its replay to the element type 2026-09-05 13:12:17 +00:00
Dennis Kobert b362452ff2 Guard arena moves by the park's static type instead of its size 2026-09-05 13:12:17 +00:00
Dennis Kobert 30573e6eb6 Condense the narrative comments to their constraints 2026-09-05 13:12:17 +00:00
Dennis Kobert 9ac039074d Scope the paint graphics import to the test that uses it 2026-09-05 13:11:45 +00:00
Dennis Kobert fdde760259 Drop the unread kernel field from the intent IR 2026-09-05 13:11:45 +00:00
Dennis Kobert 1be90ebb4a Delete the orphaned graphic accessor, introspection helper, and fn type macro 2026-09-05 13:11:45 +00:00
Dennis Kobert 8fa250a9f9 Delete the attribute helpers the refactor orphaned 2026-09-05 13:11:45 +00:00
Dennis Kobert 0b70b18338 Delete the unused record batch buffer accessors 2026-09-05 13:11:45 +00:00
Dennis Kobert 40efbc3261 Name the generic-carry predicate for what it now covers 2026-09-05 12:23:34 +00:00
Dennis Kobert 39ce55ab61 Convert rasterize to an async record source with an owned merged-layers write 2026-09-05 12:17:06 +00:00
Dennis Kobert 3e1a9a1acf Let an async source write an owned attribute through its claim 2026-09-05 11:58:02 +00:00
Dennis Kobert ab93e1f071 Add the owned attribute crossing over the deep field glue 2026-09-05 11:52:42 +00:00
Dennis Kobert aa50c42930 Measure the promoted paint list's retained heap 2026-09-02 08:26:26 +00:00
Dennis Kobert c73976f407 Refuse a mistyped park in the arena move 2026-09-02 08:26:26 +00:00
Dennis Kobert cac1c47b86 Cover the promoted paint field's sharing and move laws 2026-09-02 00:10:07 +00:00
Dennis Kobert 1426f6401f Route graphic-list field promotes straight into the persistent region 2026-09-02 00:10:07 +00:00
Dennis Kobert 6b951c1806 Add an opt-in promote half to the deep field glue 2026-09-02 00:09:46 +00:00
Dennis Kobert 1f860aae6a Move group-free graphic and artboard headers at the promote 2026-09-01 22:51:18 +00:00
Dennis Kobert e415714b04 Promote a leaf element by moving its header into the persistent region 2026-09-01 22:51:18 +00:00
Dennis Kobert a6016b2c03 Move a parked payload between arenas instead of cloning its heap 2026-09-01 22:51:18 +00:00
Dennis Kobert c12f8f1115 Add changing-seasons to the gungraun benchmark arguments 2026-09-01 13:18:01 +00:00
Dennis Kobert 4e7d72d4b8 Flush the persistent region on its heap budget 2026-08-31 23:52:44 +00:00
Dennis Kobert 41d42fe794 Delete the now unused frame table 2026-08-31 23:52:44 +00:00
Dennis Kobert 21dfe04bf8 Insert the boundary memo at context nullification 2026-08-31 23:52:34 +00:00
Dennis Kobert 0f26893ec1 Split the memo roles between the span memo and memoize 2026-08-31 23:52:34 +00:00
Dennis Kobert 0cd428f1b1 Share persistent graphic interiors when promoting 2026-08-31 23:52:21 +00:00
Dennis Kobert 39ed962e16 Promote memo levels by provenance 2026-08-31 23:52:21 +00:00
Dennis Kobert 6a5417ed3d Report an arena's occupancy and retained heap 2026-08-31 23:52:21 +00:00
Dennis Kobert 29052a58db Let async source kernels write attributes through their frame claim 2026-08-29 23:00:17 +00:00
Dennis Kobert 84d11b9285 Serve memo hits out of the persistent region 2026-08-29 22:07:27 +00:00
Dennis Kobert 5a6192bbd6 Give the executor a persistent arena flushed between evaluations 2026-08-29 22:07:27 +00:00
Dennis Kobert ca831c00db Promote a materialized batch into a target region 2026-08-29 22:07:27 +00:00
Dennis Kobert fe8ca88752 Name a persistent region on the evaluation scope 2026-08-29 22:07:27 +00:00
Dennis Kobert 8fd2529e27 Flag an arena whose reservation was refused 2026-08-29 22:07:27 +00:00
Dennis Kobert 641fcc88c6 Read declared attributes through one core-types helper 2026-08-29 20:16:17 +00:00
Dennis Kobert 78e35eb6ea Re-derive the shared edge pointer and type-check the paint transmute 2026-08-29 20:16:12 +00:00
Dennis Kobert 3302a3b0b8 Mint attribute reads through a layout-checked field token 2026-08-29 20:16:05 +00:00
Dennis Kobert 41d295f140 Tie a record view to the storage it points into 2026-08-29 20:14:44 +00:00
Dennis Kobert a955d6b458 Run cargo fmt 2026-08-29 18:40:02 +00:00
Dennis Kobert 97bc10e4c3 Pass frame space by argument and delete the record stack 2026-08-29 18:33:23 +00:00
Dennis Kobert 3af6834d3c Flip the Node trait from eval onto the frame claim's serve 2026-08-29 12:26:46 +00:00
Dennis Kobert 277641d27e Delete the plain edge kind 2026-08-29 10:07:10 +00:00
Dennis Kobert f3e945c5d8 Introduce the serve surface: the frame claim's proof-bearing lift on Node 2026-08-28 19:18:54 +00:00
Dennis Kobert aef750153b Claim the node frame once and close every exit through its drop 2026-08-28 19:11:38 +00:00
Dennis Kobert f4d37524c8 Structure record stack rewinds as scope guards and make reserve unsafe 2026-08-28 18:02:50 +00:00
Dennis Kobert e5b910f840 Adopt serving lifetimes and the safe record surfaces in the node crates 2026-08-28 13:30:06 +00:00
Dennis Kobert 25f49e8750 Give the graphic types the serving lifetime 2026-08-28 13:30:06 +00:00
Dennis Kobert 1ef7c9c2c2 Support author-named serving lifetimes in the node macro 2026-08-28 13:30:06 +00:00
Dennis Kobert f34ec257e7 Normalize lifetime arguments out of registry type names 2026-08-28 13:30:05 +00:00
Dennis Kobert 1e5b2c7f62 Serve group items at the evaluation lifetime 2026-08-28 13:30:05 +00:00
Dennis Kobert c6b669fc88 Key the element glue on static type projections 2026-08-28 13:30:05 +00:00
Dennis Kobert d814b610da Migrate test sources and assertions onto the safe record builders 2026-08-27 21:17:31 +00:00
Dennis Kobert 5181c74205 Add the frame builder and captured record reads 2026-08-27 21:17:31 +00:00
Dennis Kobert 4cb711e3f8 Stamp value types on layout fields and include type identity in layout equality 2026-08-27 21:17:31 +00:00
Dennis Kobert e8aea0728a Build native groups at the legacy conversion seams 2026-08-27 20:22:24 +00:00
Dennis Kobert 6f809fda73 Add the run builder and census-driven list adoption 2026-08-27 19:28:41 +00:00
Dennis Kobert ba84e2a968 De-table the graphic leaf variants 2026-08-27 18:55:32 +00:00
Dennis Kobert 72387d17ad Read the vector kernel seams natively 2026-08-27 15:57:10 +00:00
Dennis Kobert 048a4c4b70 Flatten boolean content natively 2026-08-27 15:45:36 +00:00
Dennis Kobert b262195549 Flatten vector rows natively and serve solidify per lane 2026-08-27 15:35:13 +00:00
Dennis Kobert 68a2fb2be3 Render root levels natively and remove the unconstructed stack form 2026-08-27 14:44:19 +00:00
Dennis Kobert 50911a6a25 Recreate introspection data from the monitor's context snapshot 2026-08-27 13:53:25 +00:00
Dennis Kobert 79f3571b02 Store paint content in its native form 2026-08-27 12:33:44 +00:00
Dennis Kobert 34ea9c59fd Deepen graphic-list field values at the persistence seams 2026-08-27 12:05:14 +00:00
Dennis Kobert 92ec2069ad Carry group content across memo seams in an owned form 2026-08-27 11:27:26 +00:00
Dennis Kobert 20e70e7bc9 Exclude executor teardown from the measured bench regions 2026-08-27 10:09:18 +00:00
Dennis Kobert 084f14e973 Resolve paint and transform columns once per lane loop 2026-08-26 23:03:17 +00:00
Dennis Kobert 694d3d34b3 Reduce measurement overhead for run_once benchmark 2026-08-27 00:37:25 +02:00
Dennis Kobert ed457093b1 Store artboard content as a native group 2026-08-26 21:50:36 +00:00
Dennis Kobert 7d44f6ec9e Collect a group element as its typed lowering 2026-08-26 21:50:35 +00:00
Dennis Kobert 54c140e4f3 Walk groups natively with lane paint threaded down 2026-08-26 19:43:32 +00:00
Dennis Kobert 5987c449b2 Serve bounding boxes through the lane source 2026-08-26 19:43:31 +00:00
Dennis Kobert c7605d12a6 Drive every render body from the lane source 2026-08-26 17:47:50 +00:00
Dennis Kobert d9533de9ea Look up paint through the paint markers instead of string keys 2026-08-26 17:47:38 +00:00
Dennis Kobert bc33e14c35 Read gradient columns per lane and drive color rendering from the lane source 2026-08-26 15:59:24 +00:00
Dennis Kobert 2b06d27729 Distinguish an absent column from a defaulted one on the lane source 2026-08-26 15:48:01 +00:00
Dennis Kobert b685ca77f2 Serve record runs through the lane source surface 2026-08-26 15:17:06 +00:00
Dennis Kobert e5b1fad675 Read render attributes through census markers instead of string keys 2026-08-26 14:55:27 +00:00
Dennis Kobert eb11eec5bb Store paint attributes in the paint markers' owned optional form 2026-08-26 14:02:01 +00:00
Dennis Kobert 182c2a1554 Cover the batch path that rebinds a lane-varying eager input 2026-08-25 21:15:12 +00:00
Dennis Kobert 913d7093ea Restore the index declaration on single-lane leveled values 2026-08-25 21:07:52 +00:00
Dennis Kobert 938fc1783a Treat a single-lane leveled value as invariant under the addressed lane 2026-08-25 20:27:39 +00:00
Dennis Kobert d452ac0de1 Hoist a batch input only where the compiler proves it cannot vary per lane 2026-08-25 20:09:12 +00:00
Dennis Kobert 95bbeb6634 Push the flat copy number Repeat on Points declares as its level extent 2026-08-25 17:15:00 +00:00
Dennis Kobert 5176bfd331 Query per-copy extents with the same chain shape the value path builds 2026-08-25 16:36:49 +00:00
Dennis Kobert db761cf8ed Drop a duplicated wasm import 2026-08-25 11:19:22 +00:00
Dennis Kobert 34e03038df Cargo fmt 2026-08-25 11:17:17 +00:00
Dennis Kobert bb3643541d Resolve context features from the registry at compile instead of persisting them 2026-08-25 11:16:56 +00:00
Dennis Kobert ff99f3605c Drop unread index bounds from fold kernels and mark re-addressing nodes ModifyIndex 2026-08-25 11:05:38 +00:00
Dennis Kobert 9cf037e992 Treat Modify bounds as transparent and drop the redundant fold-context validation 2026-08-25 11:04:57 +00:00
Dennis Kobert 888cdf17b0 Compress nullified index chains by dropping trailing zeroed levels 2026-08-25 11:04:57 +00:00
Dennis Kobert 9aef511891 Cargo fmt 2026-08-24 23:15:10 +02:00
Dennis Kobert 0d88e8be9f Inline status cell calls 2026-08-24 23:14:06 +02:00
Dennis Kobert 56d38b3f61 Re-save the demo artwork in its migrated form 2026-08-24 21:06:51 +00:00
Dennis Kobert a6c56c8655 Resolve index levels from the registry instead of persisting them 2026-08-24 20:40:51 +00:00
Dennis Kobert 2c84bb478f Derive pushed index levels per input and pop them when lifting requirements 2026-08-24 17:06:07 +00:00
Dennis Kobert 9cdaf06ca9 Count assign colors lanes without legacy conversion and cache the offsets 2026-08-24 17:06:07 +00:00
Dennis Kobert 027218f16c Declare which index levels a node reads and nullify the rest 2026-08-24 17:06:07 +00:00
Dennis Kobert f1ccb74625 Serve the monitored lane from its own capture materialization 2026-08-24 16:42:28 +00:00
Dennis Kobert cb5fabc6ad Add an env-gated arena allocation trace 2026-08-24 14:31:21 +00:00
Dennis Kobert 2448157af8 Close the memoize frame on a valueless materialization and trace node exits 2026-08-24 14:11:46 +00:00
Dennis Kobert d718cdb225 Keep the monitor's whole-extent capture off the record stack 2026-08-24 12:23:32 +00:00
Dennis Kobert dcc9059041 Give To Graphic a unit row so an unconnected content input renders as nothing 2026-08-24 12:02:46 +00:00
Dennis Kobert d70eae205d Quiet the clippy type-complexity and closure lints on the record kernels 2026-08-24 11:07:14 +00:00
Dennis Kobert ed6922d7eb Read the layer path in its owned form and retarget the introspection tests 2026-08-24 10:26:24 +00:00
Dennis Kobert abb099a1c3 Take brush on record wires and keep its legacy core behind brush_core 2026-08-24 09:27:52 +00:00
Dennis Kobert a4d01bfd11 Route the whole record through switch and drop its fifteen typed rows 2026-08-24 08:51:12 +00:00
Dennis Kobert d38c767312 Gather a chosen subject lane through a Lane output and convert pack_strips 2026-08-24 08:22:25 +00:00
Dennis Kobert aba941e81d Collapse typed levels in To Graphic like the pre-flip list conversion 2026-08-24 01:35:32 +00:00
Dennis Kobert 8c67ad508f Restore pre-flip color parity: rng replay, typed wrap, boolean marker paints 2026-08-24 00:43:44 +00:00
Dennis Kobert 9ca897963f Prune the unused legacy Adjust and Blend list implementations 2026-08-23 20:00:24 +00:00
Dennis Kobert 2575b94e8f Swap the leveled repeat_radial and repeat_on_points in for the eager variants 2026-08-23 19:50:36 +00:00
Dennis Kobert b03e4fb215 Let record nodes take element-consuming lazy inputs and convert map_points 2026-08-23 19:28:27 +00:00
Dennis Kobert c0eb2ee4ff Remove the runtime-named attribute family and its type-erased bridges 2026-08-23 19:05:26 +00:00
Dennis Kobert faa5c9d3db Install the resolved layout in the create_context test 2026-08-23 18:18:13 +00:00
Dennis Kobert bedb0d4159 Turn the byte-list wires into plain shared slices 2026-08-23 17:46:04 +00:00
Dennis Kobert 94b9d279a2 Retarget the palette executor test at the folded record wire 2026-08-23 17:29:43 +00:00
Dennis Kobert 7c4b029d76 Convert the math color and gradient family to element and marker kernels 2026-08-23 17:22:46 +00:00
Dennis Kobert 9ba3c16e79 Convert blur, median_filter, color_overlay, and image_color_palette to record kernels 2026-08-23 17:10:00 +00:00
Dennis Kobert 511b4da9f5 Convert the raster std and adjustments families to element kernels and keep the unit primary's slot 2026-08-23 16:52:43 +00:00
Dennis Kobert 2c15dc838e Convert dehaze, empty_image, extend_image_to_bounds, and image to record kernels 2026-08-23 10:11:34 +00:00
Dennis Kobert 73b2ef1d58 Convert cut_path, separate_subpaths, and path_is_closed to fold kernels 2026-08-23 09:56:09 +00:00
Dennis Kobert 9d2031f7d0 Convert the per-lane vector geometry nodes and the level measures to record kernels 2026-08-23 09:44:25 +00:00
Dennis Kobert 7b609ea781 Parse primitive defaults through record wire types 2026-08-23 08:39:35 +00:00
Dennis Kobert 5e918af371 Restore the sample_polyline test attribute and drop dead scaffolding 2026-08-23 08:31:40 +00:00
Dennis Kobert 6e9cac3b32 Trace record stack frames under an env gate 2026-08-23 08:31:39 +00:00
Dennis Kobert 893cbfe450 Close the frame on interrupt exits and rewind extent value queries 2026-08-23 08:31:39 +00:00
Dennis Kobert e40ee486a9 Claim the node frame on every cache serve and reclaim extracted edges 2026-08-23 08:31:39 +00:00
Dennis Kobert 58182bc2d3 Keep the executor arena at 128 MiB 2026-08-23 00:57:37 +00:00
Dennis Kobert 3fb8b10f80 Cache materialized spans per context and size emitter extents from the subject query 2026-08-23 00:57:37 +00:00
Dennis Kobert 6fe533a875 Cache whole levels in memoize and gate the monitor capture to lane zero 2026-08-23 00:57:37 +00:00
Dennis Kobert feea006fc3 Skip the consuming lane in the index reader 2026-08-23 00:57:37 +00:00
Dennis Kobert 73897111d0 Stop declaring derived index injection as a context feature 2026-08-23 00:57:37 +00:00
Dennis Kobert e76dcb15aa Convert mix and gradient value to element kernels 2026-08-22 22:15:03 +00:00
Dennis Kobert 538959ea90 Convert morph to a fold emitter 2026-08-22 22:15:03 +00:00
Dennis Kobert c33f8ae75b Convert mirror to a fold emitter and bridge levels into the erased list 2026-08-22 22:15:03 +00:00
Dennis Kobert 3126a5b278 Convert copy to points, sample polyline, scatter, spline, jitter, and assign colors 2026-08-22 20:59:37 +00:00
Dennis Kobert 5f6c18893e Grow the executor arena for per-copy paint parks 2026-08-22 20:59:37 +00:00
Dennis Kobert cdc6f11d92 Add an env-gated inferred type dump 2026-08-22 20:59:37 +00:00
Dennis Kobert c4b22c03b9 Size extent-path materialization by the total flat span 2026-08-22 20:59:37 +00:00
Dennis Kobert 6ab9d0360a Convert flatten path and solidify stroke to fold kernels 2026-08-22 19:11:48 +00:00
Dennis Kobert 01da817f61 Grow the executor arena for fold snapshots 2026-08-22 19:11:48 +00:00
Dennis Kobert 040bd71f82 Add an env-gated resolved layout depth dump 2026-08-22 19:11:48 +00:00
Dennis Kobert f2b0f7c533 Defer an empty side's inner extent in extend 2026-08-22 19:11:48 +00:00
Dennis Kobert a2918887f6 Collapse the whole subject wire in materialized folds 2026-08-22 19:11:48 +00:00
Dennis Kobert 7b993c5de6 Place lane paint onto the vector interiors at the legacy boundary 2026-08-22 17:29:51 +00:00
Dennis Kobert 3da7f6cea3 Drop the legacy fill and stroke rows for single-typed paint 2026-08-22 17:29:51 +00:00
Dennis Kobert 7569bdb9cb Convert path modify to a flip kernel over one default lane 2026-08-22 17:29:51 +00:00
Dennis Kobert 4e8a44650e Push the repeat array copies onto a derived level 2026-08-22 17:29:51 +00:00
Dennis Kobert b4346fd47d Convert the generators to element producers 2026-08-22 17:29:51 +00:00
Dennis Kobert e9a18a6437 Emit boolean results as elements with parked attributes 2026-08-22 17:29:51 +00:00
Dennis Kobert 77b0be5c15 Lift shallower sources in the layout union 2026-08-22 16:22:54 +00:00
Dennis Kobert 4bceae26f2 Add the leveled fill rows and the graphic coercion entries 2026-08-22 16:13:01 +00:00
Dennis Kobert c0f50d41d7 Drop the manual extent overrides in favor of the derivation 2026-08-22 15:55:49 +00:00
Dennis Kobert 0b2aa3798a Derive extent forwarding for level-preserving passthroughs 2026-08-22 15:34:22 +00:00
Dennis Kobert 13cd718c90 Drop an unused import 2026-08-22 15:02:01 +00:00
Dennis Kobert 39c7ba39cf Lift the artboard element onto a level and migrate demos for smoke tests 2026-08-22 15:01:27 +00:00
Dennis Kobert 6635e0aeff Convert the artboard constructor to an attribute kernel behind a footprint translate 2026-08-22 14:46:29 +00:00
Dennis Kobert 98dabd7ff5 Materialize the boolean operation's content level 2026-08-22 14:36:42 +00:00
Dennis Kobert a244cc13d0 Convert the blending family to attribute kernels 2026-08-22 14:32:15 +00:00
Dennis Kobert fb71ea426d Bridge legacy seams and convert the transform family 2026-08-22 14:25:31 +00:00
Dennis Kobert 217f32eb88 Type the list-typed value defaults by their element 2026-08-22 12:59:37 +00:00
Dennis Kobert 7fb36123e9 Point the render wrapper at the leveled intermediate 2026-08-22 12:50:47 +00:00
Dennis Kobert 46220ac268 Switch the tagged list values and layer internals onto leveled wires 2026-08-22 12:47:31 +00:00
Dennis Kobert 887dbaca2c Re-home the layer-path stamp and switch the node path to its plain value form 2026-08-22 12:35:48 +00:00
Dennis Kobert 44369cb12b Swap the repeat node to its leveled form in place 2026-08-22 12:29:16 +00:00
Dennis Kobert 56c772de4c Swap the map and index family nodes to their leveled forms in place 2026-08-22 12:27:53 +00:00
Dennis Kobert 93e34d00e5 Swap the graphic structural nodes to their leveled forms in place 2026-08-22 12:24:02 +00:00
Dennis Kobert 46f048b07c Add the leveled render intermediate beside the legacy rows 2026-08-22 12:15:08 +00:00
Dennis Kobert 4b130b4319 Map element-typed wires to their list forms' defaults and widgets 2026-08-22 11:48:27 +00:00
Dennis Kobert da0f70bb5f Stage the flip's document reset markers 2026-08-22 11:48:27 +00:00
Dennis Kobert 5821816228 Add the leveled boundary helpers and the deep group element copy 2026-08-22 11:48:26 +00:00
Dennis Kobert 8eaa541c8c Add the leveled value source and the dormant leveled edge form 2026-08-22 10:52:21 +00:00
Dennis Kobert e4adf16eba Move the paint and merged-layer markers to graphic-types as optional references 2026-08-22 10:23:02 +00:00
Dennis Kobert a8d257e7d6 Move the downstream-typed attribute markers to their value types' crates 2026-08-22 09:34:24 +00:00
Dennis Kobert 49c592013c Declare the core-typed attribute markers and re-export their names 2026-08-22 09:20:17 +00:00
Dennis Kobert 80db9c13c8 Signal past-end for repeat overruns so drains cross structure nodes 2026-08-21 22:17:06 +00:00
Dennis Kobert cf87796072 Probe lower-bound inner levels to their exact span 2026-08-21 22:17:06 +00:00
Dennis Kobert 8859e6b1a0 Add the layer-path stamp carrier 2026-08-21 22:03:31 +00:00
Dennis Kobert 1f23991a72 Add the editor layer path marker 2026-08-21 22:03:31 +00:00
Dennis Kobert 2be252d7b4 Fold a color level into evenly spaced gradient stops 2026-08-21 21:48:21 +00:00
Dennis Kobert 2c1acbdc62 Render groups through the legacy conversion 2026-08-21 20:36:06 +00:00
Dennis Kobert 61e751f278 Convert groups to their legacy list form 2026-08-21 20:36:06 +00:00
Dennis Kobert cdd62ed269 Retarget the wrap and flatten pilots onto group storage 2026-08-21 20:16:19 +00:00
Dennis Kobert f12094ced6 Add in-place group adoption for arena-resident batches 2026-08-21 20:16:19 +00:00
Dennis Kobert b5c4aa4598 Add the group variant to Graphic with typed run walks 2026-08-21 19:34:03 +00:00
Dennis Kobert da8ae2be43 Tag record layouts with their element type 2026-08-21 19:34:02 +00:00
Dennis Kobert 157c011953 Pick hashed element glue in the macro emissions 2026-08-21 18:21:38 +00:00
Dennis Kobert ae6807f8e3 Add content hashing and equality glue to record layouts 2026-08-21 18:21:38 +00:00
Dennis Kobert 17ba74485a Add arena-adopted group storage for nested records 2026-08-21 16:52:23 +00:00
Dennis Kobert 1f2eef5f8f Add the wrap collector beside the production node 2026-08-21 16:52:23 +00:00
Dennis Kobert 1b6513b954 Treat a free side as one lane in the extend split 2026-08-21 16:52:23 +00:00
Dennis Kobert 74fddff589 Add leveled vararg sources beside the production read nodes 2026-08-21 14:38:26 +00:00
Dennis Kobert 7e24f810c6 Register the map family for each production content type 2026-08-21 13:14:49 +00:00
Dennis Kobert 306cf1110f Emit one registry row per ranked implementation 2026-08-21 13:14:49 +00:00
Dennis Kobert b610eede20 Carry ranked element generics as struct parameters 2026-08-21 13:14:49 +00:00
Dennis Kobert 21f671555a Derive lower-bound extents for leveled outputs and drop the map extent fns 2026-08-21 12:37:57 +00:00
Dennis Kobert 951059aa3a Drain lower-bound reducer subjects by guess-and-double 2026-08-21 12:36:41 +00:00
Dennis Kobert e68254eff3 Carry an extent hint on batch returns 2026-08-21 12:32:57 +00:00
Dennis Kobert 61cf619f4b Add the lower-bound extent and the past-end signal 2026-08-21 12:22:09 +00:00
Dennis Kobert 7914a09d4b Carry only the element in the map vararg 2026-08-21 12:19:54 +00:00
Dennis Kobert 95e2cbca15 Test extend associativity and the batched fold across the seam 2026-08-21 09:18:45 +00:00
Dennis Kobert 724bb0fc17 Reject ragged inner extents in the extend concat 2026-08-21 09:18:37 +00:00
Dennis Kobert fb171cd5ac Test the partial fold keeping its subject's outer level 2026-08-19 21:43:14 +00:00
Dennis Kobert cb46be0430 Emit the reducer extent shift and the flat-span materialization 2026-08-19 21:43:14 +00:00
Dennis Kobert 7ffc9b9e3b Add the folded subject to LayoutMeta and derive reducer depth from it 2026-08-19 21:43:14 +00:00
Dennis Kobert 58a65c69e9 Add the map, flat_map, and flatten_levels pilots 2026-08-18 11:02:25 +00:00
Dennis Kobert d1d50ec469 Classify routing sources through IList nesting 2026-08-18 11:02:25 +00:00
Dennis Kobert e25e32ee8a Add the per-copy inner extent accessor 2026-08-18 11:02:25 +00:00
Dennis Kobert d560a39856 Add the flatten pilot over graphic content 2026-08-18 10:06:11 +00:00
Dennis Kobert 00e08359a3 Park droppable elements in the record tail store 2026-08-18 10:06:11 +00:00
Dennis Kobert 116ce622d4 Test batch lane equivalence and single eager bind per batch 2026-08-18 08:53:38 +00:00
Dennis Kobert 082fb5d959 Hoist non-lazy inputs in the default batch implementation 2026-08-18 08:53:38 +00:00
Dennis Kobert 043f28cc23 Add StatusCell snapshot, List copy, and interrupt-to-batch conversion 2026-08-18 08:53:38 +00:00
Dennis Kobert b7413dd22c Add the replaced context derivation for same-level remaps 2026-08-17 14:47:41 +00:00
Dennis Kobert 586737247e Fold nested list levels flat in a single kernel 2026-08-17 14:47:24 +00:00
Dennis Kobert 055b7f0055 Add the rank-model mirror over a materialized level 2026-08-17 14:47:24 +00:00
Dennis Kobert 4a042bade2 Key materialization on declared list nesting and carriers on non-materialized subjects 2026-08-17 14:46:48 +00:00
Dennis Kobert 3aa018a15c Add the rank-model read-by-index family: omit, index elements, extract element 2026-08-17 11:59:40 +00:00
Dennis Kobert 8508dc6c9d Add the rank-model extend concatenating two sources at the top level 2026-08-17 11:42:52 +00:00
Dennis Kobert fbba0cd037 Gate the gpu converter imports the sweep wrongly removed 2026-08-17 10:56:45 +00:00
Dennis Kobert ae7c51a964 Drop stale imports left behind by the record-wire port 2026-08-17 10:28:29 +00:00
Dennis Kobert 0c49026c9a Error on out-of-range copy addressing instead of wrapping in the repeat family 2026-08-17 10:28:28 +00:00
Dennis Kobert bc29166d4c Add the rank-model repeat on points flattening every points row 2026-08-17 09:26:59 +00:00
Dennis Kobert 0f3e3f7337 Materialize ranked non-subject inputs whole and expose them to extent overrides 2026-08-17 09:26:59 +00:00
Dennis Kobert a03db0ac6c Decompose the flat index over the content extent in structure creators 2026-08-17 08:09:27 +00:00
Dennis Kobert 932ed8653e Add the rank-model repeat radial rotating each copy around the center 2026-08-16 18:17:30 +00:00
Dennis Kobert 5ab3f067fe Add the rank-model repeat array over a lazy transform-reading carrier 2026-08-16 17:47:25 +00:00
Dennis Kobert 3df028cb18 Wire record-io plain values as record edges in the registry, extracted at construction 2026-08-16 17:47:25 +00:00
Dennis Kobert e423dd96de Support lazy record carriers so a creator can read and rewrite attrs per copy 2026-08-16 17:13:19 +00:00
Dennis Kobert bef58bf395 Give the generic repeat its production shape with reverse in the index mapping 2026-08-16 17:13:19 +00:00
Dennis Kobert 131abf5883 Give extent overrides a typed input surface instead of the raw node form 2026-08-16 15:55:17 +00:00
Dennis Kobert 3859bd713e Install element layouts on the runtime test graphs 2026-08-16 11:29:20 +00:00
Dennis Kobert ac40f1838f Store record batches in caller-owned frame buffers instead of aliased stack pointers 2026-08-16 11:29:20 +00:00
Dennis Kobert 9055a5f3d5 Drop the stale layout unwraps in the math wire tests 2026-08-16 11:28:33 +00:00
Dennis Kobert d32caeab52 Add a generic lazy repeat that evaluates its content at each copy index 2026-08-16 11:28:11 +00:00
Dennis Kobert 15f4aa8f98 Strip IList nesting from kernel returns at parse time 2026-08-16 11:27:13 +00:00
Dennis Kobert 99ce2ea565 Require a node registry to compile so the layout pass always runs 2026-08-15 14:49:25 +00:00
Dennis Kobert 87200f3c2a Gate a flipped shader node's layout metadata out of the GPU build 2026-08-15 14:49:19 +00:00
Dennis Kobert 214632c5ec Reserve the record stack before direct edge evals in executor tests 2026-08-15 12:27:39 +00:00
Dennis Kobert 64fb4eda61 Fold the record-stack peak in the layout pass, not the executor 2026-08-15 12:20:52 +00:00
Dennis Kobert f9e30c4c77 Install record layouts from the pass via set_layout 2026-08-15 11:20:01 +00:00
Dennis Kobert bfa48439c8 Resolve coercion nodes and dynamic values in the layout pass 2026-08-15 08:48:29 +00:00
Dennis Kobert a717403db8 Diagnose a materializing node's missing InjectIndex and Copy bounds 2026-08-14 21:31:14 +00:00
Dennis Kobert fdf13f91cb Materialize a reducer's ranked input into a List and fold it 2026-08-14 21:19:20 +00:00
Dennis Kobert 65e0969721 Recognize a reducer's IList input level in build 2026-08-14 10:13:53 +00:00
Dennis Kobert 8f265e7660 Report a creator's pushed-level extent from its count 2026-08-14 09:56:31 +00:00
Dennis Kobert 98e6b97072 Reshape the extent trait to a written extent_at and a derived composite 2026-08-14 09:10:04 +00:00
Dennis Kobert a3e9074955 Scatter a creator's per-copy attribute from the copy index 2026-08-14 08:24:44 +00:00
Dennis Kobert 04afada5b3 Lower a creator's IList return to a level-pushing record 2026-08-14 08:22:29 +00:00
Dennis Kobert 3e183fbd28 Read a creator's IList return level in build 2026-08-14 08:11:59 +00:00
Dennis Kobert 849d6a17be Delete the Class taxonomy in favor of the intent IR 2026-08-13 23:46:07 +00:00
Dennis Kobert 20ba069fe0 Derive record-io construction wiring from the intent IR 2026-08-13 23:26:22 +00:00
Dennis Kobert c82093f153 Derive codegen node-kind predicates from the intent IR 2026-08-13 23:09:48 +00:00
Dennis Kobert 010785d8db Derive single-row registry entries from the intent IR 2026-08-13 22:08:04 +00:00
Dennis Kobert 69774d445c Derive the eval tail from the intent IR 2026-08-13 21:08:41 +00:00
Dennis Kobert b42c632474 Derive input bindings from the intent IR 2026-08-13 19:32:25 +00:00
Dennis Kobert f195e363a5 Emit layout metadata from the intent IR 2026-08-13 16:11:58 +00:00
Dennis Kobert 40f99152ce Bridge-verify build against the resolved class 2026-08-13 15:35:07 +00:00
Dennis Kobert 3b1170b148 Derive inputs, output, and monomorphizations in build 2026-08-13 15:18:35 +00:00
Dennis Kobert 3a20091d3a Derive the node-level intent axes in build 2026-08-13 14:19:49 +00:00
Dennis Kobert e5206c3b50 Add the node intent IR types 2026-08-13 14:00:15 +00:00
Dennis Kobert fbc736e1cc Verify computed layouts match construction at node construction 2026-08-13 10:25:00 +00:00
Dennis Kobert d7da2ba9e7 Add the resolve_types and compute_layouts compiler passes 2026-08-13 10:24:59 +00:00
Dennis Kobert a5784c8f0b Port the create_context render test onto record wires 2026-08-12 13:11:48 +00:00
Dennis Kobert 83fbaca6f2 Unify the layout metadata model and collapse the single-row entry emitters 2026-08-12 13:11:48 +00:00
Dennis Kobert b6f73b0691 Emit declarative LayoutMeta from the node macro into registry entries 2026-08-11 20:08:45 +00:00
Dennis Kobert 557f8020bb Add the leveled extent_at/depth trait surface and the push_level context helper 2026-08-11 20:08:45 +00:00
Dennis Kobert fb94d99807 Port the stale math-nodes and raster-nodes tests onto record wires 2026-08-11 09:54:48 +00:00
Dennis Kobert 264601c5f7 Return records from eval_batch through a RecordBatch view 2026-08-11 09:26:36 +00:00
Dennis Kobert 5db7e1816a Make Node::layout non-optional, defaulting to a shared empty layout 2026-08-11 09:20:02 +00:00
Dennis Kobert 5b02edfd9a Split the node macro codegen into classify, entries, and metadata modules 2026-08-10 16:15:31 +00:00
Dennis Kobert 7c0a4073e9 Select the eval tail form by class and dialect through an explicit Tail step 2026-08-10 15:57:58 +00:00
Dennis Kobert 275100eab0 Model the eval body as an EvalStep sequence with a structural stack discipline 2026-08-10 15:34:12 +00:00
Dennis Kobert 42cd2a4303 Resolve the dialect and input-role axes as node-model sum types 2026-08-10 15:21:59 +00:00
Dennis Kobert e4f81fc947 Drive the node macro from a single analyze pass, NodePlan, and shared NodeFields 2026-08-10 13:33:58 +00:00
Dennis Kobert 492cf18cb0 Flip the passthrough node onto record wires by dropping its dead lifetime 2026-08-10 13:33:58 +00:00
Dennis Kobert 05630bab6e Port the repeat node tests onto record-wire lazy inputs 2026-08-10 10:41:40 +00:00
Dennis Kobert a465948ad4 Always-spill records, retiring inline-16 and reclaiming read-out record frames 2026-08-10 10:29:22 +00:00
Dennis Kobert 63cf0151e2 Change stack return to standart sret semantics 2026-08-08 07:33:33 +00:00
Dennis Kobert 9c7a633d5b Adopt tuple attribute io and the carrier lowering, deleting the bridge adapters for record-only wires 2026-08-06 18:48:16 +00:00
Dennis Kobert 166241b0e8 Flip nested-generic nodes onto record wires by unifying row types against field types 2026-08-06 13:36:46 +00:00
Dennis Kobert ea49f3c2fc Delete the Ref wire type and its lend edge surface 2026-08-06 12:24:50 +00:00
Dennis Kobert 100f81c307 Retire the lend machinery and flip the clone node onto record wires 2026-08-06 11:57:18 +00:00
Dennis Kobert 886ff03ef2 Construct value nodes as native record sources 2026-08-06 10:24:44 +00:00
Dennis Kobert 7a1d1f3238 Define the frame memo through the record-opaque class over same-frame byte copies 2026-08-06 09:57:21 +00:00
Dennis Kobert 612afb7ebb Capture the input context snapshot on the monitor io record 2026-08-06 09:37:48 +00:00
Dennis Kobert daf3f25d21 Define the monitor through the record-opaque class and move introspection to element reads 2026-08-06 09:07:57 +00:00
Dennis Kobert a2de2a9c09 Add the record-opaque kernel class to the node macro and define memoize through it 2026-08-06 08:28:52 +00:00
Dennis Kobert 98be2b8c79 Carry erased element and re-park glue on layouts and collapse memoize to a generic record row 2026-08-06 08:01:19 +00:00
Dennis Kobert 83fda4f08c Update the core-types runtime tests to record wires 2026-08-06 06:46:28 +00:00
Dennis Kobert 20c6ba19d3 Flip async source nodes onto record wires by lifting their slot values 2026-08-05 23:54:42 +00:00
Dennis Kobert 7eeb7d84cd Flip poll kernels and derived-context lazy nodes onto record wires and land record roots at the host rim 2026-08-05 23:42:24 +00:00
Dennis Kobert 7ddc66adbe Flip lazy-input nodes onto record wires through the element lazy input 2026-08-05 23:12:43 +00:00
Dennis Kobert c20a243fc2 Flip lend-parameter nodes onto record wires and keep the clone adapter plain 2026-08-05 22:57:51 +00:00
Dennis Kobert 3eecc31bfd Flip generic value nodes onto record wires through phantom struct parameters 2026-08-05 22:39:25 +00:00
Dennis Kobert 7099f056dc Flip concrete value nodes onto record wires with bridge rows for every value type 2026-08-05 22:18:50 +00:00
Dennis Kobert 9680d34abf Carry record elements by the drop-glue rule and unify the lift and extract adapters 2026-08-05 22:17:50 +00:00
Dennis Kobert 592b2fbe32 Turn context modification into a generic record routing node and park droppable elements as arena references 2026-08-05 19:25:17 +00:00
Dennis Kobert 60f80682c5 Collapse duplicate proto nodes when assigning stable ids 2026-08-05 19:25:17 +00:00
Dennis Kobert 9fc4fcc7a0 Inline records of at most 16 bytes into the two-word RecordValue with layout-resolved storage 2026-08-05 17:23:09 +00:00
Dennis Kobert 7915800d73 Add per-field erased-read glue, the record monitor with introspection capture, and rename record constructors to new 2026-08-05 15:22:20 +00:00
Dennis Kobert c91be74a55 Add the Record wire type, record registry rows, lift and extract adapters, and executor stack reservation 2026-08-05 12:24:20 +00:00
Dennis Kobert abe2a565d1 Drop the list driver, make attribute values Copy over arena references, and land record-tier offset io on a per-thread record stack 2026-08-05 09:47:03 +00:00
Dennis Kobert 6154e4d219 Add the attribute census, node macro attribute io over list wires, and the rank-0 record tier 2026-08-04 22:05:02 +00:00
Dennis Kobert 62b7ccf40c Support bare reference parameters and lending outputs in the node macro and make the clone node the clone-out adapter 2026-08-03 18:29:16 +00:00
Dennis Kobert 9b45af854a Emit Ref wire types for lending rows and splice lend/clone_out adapters in the type checker 2026-08-03 16:33:27 +00:00
Dennis Kobert 562e6602eb Poll source tasks once at spawn and land inline completions in the first eval 2026-08-03 10:21:46 +00:00
Dennis Kobert 8fb18012cf Remove unuse allow dead code 2026-08-02 19:35:43 +02:00
Dennis Kobert 2b3161773f Propagate tokio runtime creation failure in graphene-cli 2026-08-02 19:29:33 +02:00
Dennis Kobert 167d733f02 Wire the async source runtimes into the hosts 2026-08-02 19:24:51 +02:00
Dennis Kobert ee499be31f Add test coverage for the repeat nodes 2026-08-02 16:18:07 +00:00
Dennis Kobert d385f3c69b Fix warnings 2026-08-02 15:06:11 +00:00
Dennis Kobert e372f78b7e Address pr review 2026-08-02 14:31:13 +00:00
Dennis Kobert 8686b2c891 Export the async-source flag from the macro and dispatch superseded type deltas in tests 2026-08-02 14:09:27 +00:00
Dennis Kobert e3aa32bc83 Fix wireing of async sources 2026-08-02 14:02:53 +02:00
Dennis Kobert 77d439ec35 Silence the dead-code warnings for groundwork the host wiring will use 2026-08-01 00:59:26 +02:00
Dennis Kobert c30054579f Adapt the cutover to the reviewed core-types API 2026-07-31 23:39:39 +02:00
Dennis Kobert 81a319430b Cut over to the graphene execution model 2026-07-31 23:19:42 +02:00
Dennis Kobert 1fb6fcb447 Remove the unused CtxSnapshot scope reconstruction 2026-07-31 22:55:53 +02:00
Dennis Kobert 32d244e700 Make the sources fields private and normalize them on every mutation 2026-07-31 22:00:22 +02:00
Dennis Kobert 0877f9d50e Park the arena during drop glue, guard filled batches, and normalize deserialized sources 2026-07-31 20:09:46 +02:00
Dennis Kobert 14c1dd0397 Guard the shared generation counter in tests and reject oversized batch ranges 2026-07-31 19:30:59 +02:00
Dennis Kobert daf7b3e7b9 Make arena generation exhaustion fallible with an unsafe counter rewind 2026-07-31 19:08:09 +02:00
Dennis Kobert bdf53070f2 Forward serialize through node wrappers and free abandoned frame table reservations 2026-07-31 18:12:53 +02:00
Dennis Kobert 0d0ec96709 Draw arena generations from a global counter so foreign handles never upgrade 2026-07-31 17:48:09 +02:00
Dennis Kobert 6feaf4ec9d Drop arena entries in reverse allocation order and require Send + Sync payloads 2026-07-31 17:21:11 +02:00
Dennis Kobert 5541769dc5 Fix frame table key aliasing and arena handle offset truncation 2026-07-31 16:46:20 +02:00
Dennis Kobert 1fccb112cb Add the core execution types, the borrowed context, and the seeded u64 fx hasher 2026-07-31 13:11:36 +00:00
Timon eb50be844b Remove now obsolete disable-registration special case from node macro (#4375) 2026-07-25 13:54:46 +00:00
Dennis Kobert 0f0f62c2e9 Enforce unwind safety on all public executor entry points (#4356) 2026-07-24 09:34:40 +00:00
Timon f5b1fee85f Fix node insertion crash caused by mismatched DefinitionIdentifier serialization (#4353) 2026-07-22 09:38:07 +00:00
Timon 6f8c4b2adb Desktop: Stop compiling the editor into the wasm wrapper (#4348)
* Make wasm wrapper not depend on editor on native

* Introduce pkg-native

* Fix tests

* Fix fmt

* Correct span and make cargo fmt work inside editor_commands block

* Review

* Fix lint
2026-07-18 10:33:38 +00:00
315 changed files with 45292 additions and 38246 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/6687dc6d3d8552948458d00d35e2bee3a40ab66b.tar.gz
7663b4a35f377a5d3363430a725a1d5f634fbdc56adca5e43167786b8fe1b253
https://github.com/Keavon/graphite-branded-assets/archive/0d004aa61e6b48d316e8e5db6d59ccc4788f192d.tar.gz
772d64518be43c99977ba56f69e574531c56e83d2df2f42ab066f77f74b0dd1f
Generated
+80 -108
View File
@@ -654,19 +654,6 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "chumsky"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14377e276b2c8300513dff55ba4cc4142b44e5d6de6d00eb5b2307d650bb4ec1"
dependencies = [
"hashbrown 0.15.5",
"regex-automata 0.3.9",
"serde",
"unicode-ident",
"unicode-segmentation",
]
[[package]]
name = "ciborium"
version = "0.2.2"
@@ -959,7 +946,7 @@ dependencies = [
"rustc-hash 2.1.1",
"serde",
"serde_json",
"skrifa 0.42.1",
"skrifa",
"tinyvec",
"tokio",
"tsify",
@@ -1154,15 +1141,6 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
[[package]]
name = "delaunator"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e1ee323c1275374f7e612d3724d12707079fb6a2117349fe144def656f5a880"
dependencies = [
"robust",
]
[[package]]
name = "deranged"
version = "0.4.0"
@@ -1549,8 +1527,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1e1dacd0d2082dfcf1351c4bdd566bbe89a2b263235a2b50058f1e130a47277"
dependencies = [
"bit-set 0.8.0",
"regex-automata 0.4.14",
"regex-syntax 0.8.6",
"regex-automata",
"regex-syntax",
]
[[package]]
@@ -1669,15 +1647,6 @@ dependencies = [
"bytemuck",
]
[[package]]
name = "font-types"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a7299a780854a6d391be2ae1c8521c9368471b559dbfd6a8dbd9f407eaff100"
dependencies = [
"bytemuck",
]
[[package]]
name = "fontconfig-parser"
version = "0.5.8"
@@ -1711,7 +1680,7 @@ dependencies = [
"linebender_resource_handle",
"memmap2 0.9.10",
"parlance",
"read-fonts 0.39.2",
"read-fonts",
"smallvec",
]
@@ -2039,6 +2008,7 @@ dependencies = [
"graphene-hash",
"graphic-types",
"gungraun",
"interpreted-executor",
"js-sys",
"log",
"mmap-io",
@@ -2212,7 +2182,6 @@ dependencies = [
"glam",
"graphic-types",
"node-macro",
"rand",
"raster-types",
"serde",
"vector-types",
@@ -2389,7 +2358,6 @@ dependencies = [
"serde",
"serde_bytes",
"serde_json",
"simplecss",
"spin",
"thiserror 2.0.18",
"tokio",
@@ -2426,7 +2394,6 @@ dependencies = [
"graphite-proc-macros",
"js-sys",
"log",
"node-macro",
"serde",
"serde-wasm-bindgen",
"serde_bytes",
@@ -2526,7 +2493,7 @@ dependencies = [
"bitflags 2.11.0",
"bytemuck",
"core_maths",
"read-fonts 0.39.2",
"read-fonts",
"smallvec",
]
@@ -2970,6 +2937,7 @@ dependencies = [
"graph-craft",
"graphene-core",
"graphene-std",
"graphic-types",
"gungraun",
"log",
"once_cell",
@@ -3380,7 +3348,7 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
dependencies = [
"regex-automata 0.4.14",
"regex-automata",
]
[[package]]
@@ -3401,9 +3369,11 @@ dependencies = [
name = "math-parser"
version = "0.0.0"
dependencies = [
"chumsky",
"criterion",
"lazy_static",
"num-complex",
"pest",
"pest_derive",
"thiserror 2.0.18",
]
@@ -3988,9 +3958,9 @@ dependencies = [
[[package]]
name = "once_cell"
version = "1.21.4"
version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "once_cell_polyfill"
@@ -4117,7 +4087,7 @@ dependencies = [
"linebender_resource_handle",
"parlance",
"parley_data",
"skrifa 0.42.1",
"skrifa",
]
[[package]]
@@ -4168,6 +4138,50 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pest"
version = "2.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1db05f56d34358a8b1066f67cbb203ee3e7ed2ba674a6263a1d5ec6db2204323"
dependencies = [
"memchr",
"thiserror 2.0.18",
"ucd-trie",
]
[[package]]
name = "pest_derive"
version = "2.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb056d9e8ea77922845ec74a1c4e8fb17e7c218cc4fc11a15c5d25e189aa40bc"
dependencies = [
"pest",
"pest_generator",
]
[[package]]
name = "pest_generator"
version = "2.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87e404e638f781eb3202dc82db6760c8ae8a1eeef7fb3fa8264b2ef280504966"
dependencies = [
"pest",
"pest_meta",
"proc-macro2",
"quote",
"syn 2.0.106",
]
[[package]]
name = "pest_meta"
version = "2.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edd1101f170f5903fde0914f899bb503d9ff5271d7ba76bbb70bea63690cc0d5"
dependencies = [
"pest",
"sha2",
]
[[package]]
name = "petgraph"
version = "0.7.1"
@@ -4773,18 +4787,7 @@ checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"
dependencies = [
"bytemuck",
"core_maths",
"font-types 0.11.3",
]
[[package]]
name = "read-fonts"
version = "0.41.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
dependencies = [
"bytemuck",
"font-types 0.12.2",
"once_cell",
"font-types",
]
[[package]]
@@ -4821,19 +4824,8 @@ checksum = "23d7fd106d8c02486a8d64e778353d1cffe08ce79ac2e82f540c86d0facf6912"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata 0.4.14",
"regex-syntax 0.8.6",
]
[[package]]
name = "regex-automata"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59b23e92ee4318893fa3fe3e6fb365258efbfe6ac6ab30f090cdcbb7aa37efa9"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax 0.7.5",
"regex-automata",
"regex-syntax",
]
[[package]]
@@ -4844,15 +4836,9 @@ checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax 0.8.6",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da"
[[package]]
name = "regex-syntax"
version = "0.8.6"
@@ -4881,7 +4867,7 @@ dependencies = [
"num-traits",
"parley",
"serde",
"skrifa 0.42.1",
"skrifa",
"text-nodes",
"usvg",
"vector-types",
@@ -4896,15 +4882,11 @@ dependencies = [
"core-types",
"dyn-any",
"glam",
"graphene-core",
"graphic-types",
"kurbo",
"log",
"node-macro",
"raster-types",
"serde",
"tokio",
"vector-nodes",
"vector-types",
]
@@ -5009,12 +4991,6 @@ dependencies = [
"serde",
]
[[package]]
name = "robust"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e27ee8bb91ca0adcf0ecb116293afa12d393f9c2b9b9cd54d33e8078fe19839"
[[package]]
name = "ron"
version = "0.12.0"
@@ -5554,17 +5530,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"
dependencies = [
"bytemuck",
"read-fonts 0.39.2",
]
[[package]]
name = "skrifa"
version = "0.44.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
dependencies = [
"bytemuck",
"read-fonts 0.41.0",
"read-fonts",
]
[[package]]
@@ -5956,7 +5922,7 @@ dependencies = [
"raster-types",
"serde",
"serde_json",
"skrifa 0.42.1",
"skrifa",
"titlecase",
"tsify",
"unicode-segmentation",
@@ -6337,7 +6303,7 @@ dependencies = [
"matchers",
"nu-ansi-term",
"once_cell",
"regex-automata 0.4.14",
"regex-automata",
"sharded-slab",
"smallvec",
"thread_local",
@@ -6416,6 +6382,12 @@ version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f"
[[package]]
name = "ucd-trie"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"
[[package]]
name = "unicode-bidi"
version = "0.3.18"
@@ -6602,7 +6574,6 @@ name = "vector-nodes"
version = "0.1.0"
dependencies = [
"core-types",
"delaunator",
"dyn-any",
"futures",
"glam",
@@ -6629,7 +6600,6 @@ version = "0.1.0"
dependencies = [
"bitflags 2.11.0",
"bytemuck",
"color",
"core-types",
"dyn-any",
"fixedbitset",
@@ -6644,7 +6614,6 @@ dependencies = [
"polycool",
"rustc-hash 2.1.1",
"serde",
"serde_json",
"tinyvec",
"tsify",
"wasm-bindgen",
@@ -6653,14 +6622,15 @@ dependencies = [
[[package]]
name = "vello"
version = "0.9.0"
source = "git+https://github.com/linebender/vello.git?rev=7073a85d61ee099d1d3595651ddf92302b074348#7073a85d61ee099d1d3595651ddf92302b074348"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "261359dbef879f8110ef7e1c442246c838d33d3d91cb05e0ea9288d432760c9f"
dependencies = [
"bytemuck",
"futures-intrusive",
"log",
"peniko",
"png 0.18.1",
"skrifa 0.44.0",
"skrifa",
"static_assertions",
"thiserror 2.0.18",
"vello_encoding",
@@ -6671,19 +6641,21 @@ dependencies = [
[[package]]
name = "vello_encoding"
version = "0.9.0"
source = "git+https://github.com/linebender/vello.git?rev=7073a85d61ee099d1d3595651ddf92302b074348#7073a85d61ee099d1d3595651ddf92302b074348"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2346f5f0d7dccb3582fcd397b4a57b43165209f1424e0d76e85dd814db164af7"
dependencies = [
"bytemuck",
"guillotiere",
"peniko",
"skrifa 0.44.0",
"skrifa",
"smallvec",
]
[[package]]
name = "vello_shaders"
version = "0.9.0"
source = "git+https://github.com/linebender/vello.git?rev=7073a85d61ee099d1d3595651ddf92302b074348#7073a85d61ee099d1d3595651ddf92302b074348"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9dd38937516fa4b47423d9255bb5e4a65e839ec9d57c38c4af6189ce56bf46b7"
dependencies = [
"bytemuck",
"log",
+2 -5
View File
@@ -166,12 +166,10 @@ url = "2.5"
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
# Linebender ecosystem (BEGIN)
kurbo = { version = "0.13", features = ["serde"] }
# TODO: Return to crates.io versions once a release after 0.9 ships the ramp bake's `interpolation_alpha_space` support
vello = { git = "https://github.com/linebender/vello.git", rev = "7073a85d61ee099d1d3595651ddf92302b074348" }
vello_encoding = { git = "https://github.com/linebender/vello.git", rev = "7073a85d61ee099d1d3595651ddf92302b074348" }
vello = "0.9"
vello_encoding = "0.9"
resvg = "0.47"
usvg = "0.47"
simplecss = "0.2"
parley = { version = "0.9", default-features = false, features = ["std"] }
skrifa = "0.42"
polycool = "0.4"
@@ -211,7 +209,6 @@ syn = { version = "2.0", default-features = false, features = [
"proc-macro",
] }
lyon_geom = "1.0"
delaunator = "1.0"
petgraph = { version = "0.7", default-features = false, features = ["graphmap"] }
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
tinyvec = { version = "1", features = ["std"] }
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":fLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1789832635968548900,{"inputs":[{"Node":{"node_id":1924303400883620400,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.9822506,"green":0.2050787Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"impleLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[4388711862172196665,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":"","sources":[]}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"ValueLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::artboard::Artboard>"}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Node":{"node_id":6,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[2,{"inputs":Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"outLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":null},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0]]},"regions":{"add":[],"remove":[],"segLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implemeLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[76,{"inputs":[{"Node":{"node_id":77,"output_index":0}},{"Node":{"node_id":16164610528699022118,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodesLine truncated
+5
View File
@@ -97,6 +97,11 @@ impl App {
});
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
let completion_render_sender = start_render_sender.clone();
DesktopWrapper::set_completion_notifier(move || {
let _ = completion_render_sender.try_send(());
});
Self {
render_state: None,
wgpu_context,
+1 -1
View File
@@ -228,7 +228,7 @@ impl RenderState {
return;
};
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
let result = futures::executor::block_on(self.executor.render_vello_scene(&scene, size, &Default::default(), None));
let result = self.executor.render_vello_scene(&scene, size, &Default::default(), None);
match result {
Ok(texture) => {
self.overlays_texture = Some(texture.into());
+4
View File
@@ -52,6 +52,10 @@ impl DesktopWrapper {
executor.execute()
}
pub fn set_completion_notifier(notifier: impl Fn() + Send + Sync + 'static) {
graphite_editor::node_graph_executor::set_completion_notifier(Arc::new(notifier));
}
pub async fn execute_node_graph() -> NodeGraphExecutionResult {
let result = graphite_editor::node_graph_executor::run_node_graph().await;
match result {
@@ -1,6 +1,5 @@
pub mod node {
pub const CALL_ARGUMENT: &str = "call_argument";
pub const CONTEXT_FEATURES: &str = "context_features";
pub const VISIBLE: &str = "visible";
pub const SKIP_DEDUPLICATION: &str = "skip_deduplication";
pub const REFLECTION_METADATA: &str = "reflection_metadata";
+2 -2
View File
@@ -92,7 +92,7 @@ impl Delta {
/// Op payload. Timestamps live on the wrapping `Delta` — one per delta, applied to all LWW-eligible
/// writes within. See `notes/document-format-collaboration.md`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum RegistryDelta {
AddNode {
id: NodeId,
@@ -190,7 +190,7 @@ pub enum RegistryDelta {
}
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AttributeDelta {
pub key: String,
pub value: Option<serde_json::Value>,
+26 -215
View File
@@ -1,7 +1,6 @@
use std::collections::HashMap;
use core_types::Context;
use core_types::context::ContextDependencies;
use core_types::uuid::NodeId as RuntimeNodeId;
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
@@ -182,40 +181,33 @@ fn convert_resources(resources: &graphene_resource::ResourceRegistry, referenced
if !referenced.contains(&id) {
continue;
}
if let Some(entry) = convert_resource_entry(resources, id, peer)? {
registry.resources.insert(id, entry);
let Some(info) = resources.info(&id) else { continue };
let mut entry = crate::ResourceEntry {
hash: info.hash.copied(),
hash_timestamp: TimeStamp::ORIGIN,
..Default::default()
};
for (position, source) in info.sources.iter().enumerate() {
let key = crate::SourceKey {
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
peer,
};
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
entry.set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
},
);
}
registry.resources.insert(id, entry);
}
Ok(())
}
/// Snapshot one runtime resource into a storage entry, or `None` if the runtime has no such resource.
pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, id: ResourceId, peer: PeerId) -> Result<Option<crate::ResourceEntry>, ConversionError> {
let Some(info) = resources.info(&id) else { return Ok(None) };
let mut entry = crate::ResourceEntry {
hash: info.hash.copied(),
hash_timestamp: TimeStamp::ORIGIN,
..Default::default()
};
for (position, source) in info.sources.iter().enumerate() {
let key = crate::SourceKey {
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
peer,
};
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
entry.set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
},
);
}
Ok(Some(entry))
}
/// Collect the `ResourceId`s referenced by `TaggedValue::Resource` inputs anywhere in the network
/// (recursively through nested networks). These are the resources the document actually uses; the
/// runtime cache may hold more (history-retained orphans) that shouldn't be snapshotted into storage.
@@ -286,7 +278,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
metadata_path,
runtime_node_id: *runtime_node_id,
};
let mut node = convert_node(doc_node, location, registry, ctx, true)?;
let mut node = convert_node(doc_node, location, registry, ctx)?;
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(runtime_node_id.0), TimeStamp::ORIGIN);
registry.node_instances.insert(global_id, node);
}
@@ -358,13 +350,7 @@ struct NodeLocation<'a> {
runtime_node_id: RuntimeNodeId,
}
fn convert_node<M: NodeMetadataSource + ?Sized>(
doc_node: &DocumentNode,
location: NodeLocation<'_>,
registry: &mut Registry,
ctx: &mut ConversionContext<'_, M>,
recurse: bool,
) -> Result<Node, ConversionError> {
fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, location: NodeLocation<'_>, registry: &mut Registry, ctx: &mut ConversionContext<'_, M>) -> Result<Node, ConversionError> {
let NodeLocation {
network_id,
parent_path,
@@ -396,16 +382,13 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
} else {
metadata_path
};
let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx, recurse)?;
let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx)?;
// Defaults match `DocumentNode::default()`; `to_runtime` rehydrates absent keys from the same defaults.
let mut attributes = crate::Attributes::new();
attributes
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
attributes
.set_if_not_default(node::CONTEXT_FEATURES, &doc_node.context_features, &ContextDependencies::default(), timestamp)
.map_err(map_serialization_error(node::CONTEXT_FEATURES))?;
attributes
.set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp)
.map_err(map_serialization_error(node::VISIBLE))?;
@@ -423,29 +406,6 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
})
}
/// Public form of the node ui-attribute encoding, for staging paths that encode single nodes.
pub fn encode_node_ui_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
metadata_path: &[RuntimeNodeId],
runtime_node_id: RuntimeNodeId,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
write_ui_attributes(attributes, metadata, metadata_path, runtime_node_id, timestamp)
}
/// Public form of the per-input ui-attribute encoding, matching `encode_node_ui_attributes`.
pub fn encode_input_ui_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
metadata_path: &[RuntimeNodeId],
runtime_node_id: RuntimeNodeId,
input_index: usize,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
write_ui_input_attributes(attributes, metadata, metadata_path, runtime_node_id, input_index, timestamp)
}
fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
@@ -569,7 +529,6 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
child_metadata_path: &[RuntimeNodeId],
registry: &mut Registry,
ctx: &mut ConversionContext<'_, M>,
recurse: bool,
) -> Result<Implementation, ConversionError> {
Ok(match implementation {
DocumentNodeImplementation::ProtoNode(identifier) => {
@@ -601,158 +560,10 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
// `to_runtime` -> `from_runtime` round trip reproduces the same `NetworkId` (and thus the
// same node-path hashes underneath it).
let nested_network_id = current_node_path.owned_network_id(ctx.peer);
if recurse {
convert_network(nested_network, nested_network_id, Some(current_node_path), child_metadata_path, registry, ctx)?;
}
convert_network(nested_network, nested_network_id, Some(current_node_path), child_metadata_path, registry, ctx)?;
Implementation::Network(nested_network_id)
}
// TODO: Support Extract in the Registry format.
DocumentNodeImplementation::Extract => return Err(ConversionError::UnsupportedImplementation),
})
}
/// Derives the stable storage IDs for entities addressed by runtime network paths, walking the
/// same path-hash chain as a full conversion so scoped and whole-document conversions agree.
pub struct PathResolver {
peer: PeerId,
}
impl PathResolver {
pub fn new(peer: PeerId) -> Self {
Self { peer }
}
/// The storage `NetworkId` of the network at `local_path` (`ROOT_NETWORK` for the empty path).
pub fn network_id(&self, local_path: &[RuntimeNodeId]) -> NetworkId {
match self.owner_path(local_path) {
None => ROOT_NETWORK,
Some(owner) => owner.owned_network_id(self.peer),
}
}
/// The storage `NodeId` of the node with `local_id` inside the network at `local_path`.
pub fn node_id(&self, local_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> NodeId {
let owner = self.owner_path(local_path);
child_path(owner.as_ref(), self.network_id(local_path), local_id).to_global_id(self.peer)
}
/// Converts one runtime input inside the network at `local_path` to its storage form, resolving
/// node references to their stable global IDs.
pub fn convert_input_at(&self, input: &GraphCraftNodeInput, local_path: &[RuntimeNodeId]) -> Result<NodeInput, ConversionError> {
let owner = self.owner_path(local_path);
convert_input(input, owner.as_ref(), self.network_id(local_path), self.peer)
}
/// The `NodePath` of the node owning the network at `local_path`, or `None` for the root network.
fn owner_path(&self, local_path: &[RuntimeNodeId]) -> Option<NodePath> {
let mut owner: Option<NodePath> = None;
for &local_id in local_path {
let network_id = match &owner {
None => ROOT_NETWORK,
Some(owner) => owner.owned_network_id(self.peer),
};
owner = Some(child_path(owner.as_ref(), network_id, local_id));
}
owner
}
}
/// Converts a chosen subset of runtime entities into a scratch [`Registry`] through the same
/// encoders as a whole-document conversion, so staging can derive deltas for just those entities.
pub struct ScopedConversion<'m, M: NodeMetadataSource + ?Sized> {
ctx: ConversionContext<'m, M>,
resolver: PathResolver,
}
impl<'m, M: NodeMetadataSource + ?Sized> ScopedConversion<'m, M> {
pub fn new(metadata: &'m M, peer: PeerId) -> Self {
Self {
ctx: ConversionContext {
declaration_ids: HashMap::new(),
declaration_bytes: HashMap::new(),
network_ids: HashMap::new(),
metadata,
peer,
},
resolver: PathResolver::new(peer),
}
}
/// Converts the node with `local_id` in the network at `local_path` into `registry` under its
/// stable IDs. `recurse` also converts the contents of any nested network the node implements;
/// without it only the node itself is converted, with its nested network referenced by ID.
pub fn convert_node_at(&mut self, registry: &mut Registry, local_path: &[RuntimeNodeId], local_id: RuntimeNodeId, doc_node: &DocumentNode, recurse: bool) -> Result<(), ConversionError> {
let owner_path = self.resolver.owner_path(local_path);
let location = NodeLocation {
network_id: self.resolver.network_id(local_path),
parent_path: owner_path.as_ref(),
metadata_path: local_path,
runtime_node_id: local_id,
};
let mut node = convert_node(doc_node, location, registry, &mut self.ctx, recurse)?;
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(local_id.0), TimeStamp::ORIGIN);
registry.node_instances.insert(self.resolver.node_id(local_path, local_id), node);
Ok(())
}
/// Converts the entry of the network at `local_path` (its export slots and network-level
/// attributes, not its nodes) into `registry`.
pub fn convert_network_entry_at(&mut self, registry: &mut Registry, local_path: &[RuntimeNodeId], node_network: &NodeNetwork) -> Result<(), ConversionError> {
let owner_path = self.resolver.owner_path(local_path);
let network_id = self.resolver.network_id(local_path);
let exports = node_network
.exports
.iter()
.map(|export| {
Ok(ExportSlot {
target: Some(convert_input(export, owner_path.as_ref(), network_id, self.ctx.peer)?),
timestamp: TimeStamp::ORIGIN,
})
})
.collect::<Result<Vec<_>, ConversionError>>()?;
let mut attributes = crate::Attributes::new();
write_ui_network_attributes(&mut attributes, self.ctx.metadata, local_path, TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.peer, TimeStamp::ORIGIN)?;
registry.networks.insert(network_id, Network { exports, attributes });
Ok(())
}
/// The extracted proto-node declaration bytes, for the caller to persist into its byte store.
pub fn finish(self) -> DeclarationBytes {
self.ctx.declaration_bytes
}
}
/// The `TaggedValue::Resource` IDs referenced by a stored node's value inputs.
///
/// Peeks at the externally-tagged serde shape (`{"Resource": <id>}`) rather than deserializing the
/// whole `TaggedValue`, which can be arbitrarily large. `resource_ref_shape_matches_serde` asserts
/// this stays in lockstep with the real serialization.
pub fn node_value_resource_refs(node: &Node) -> impl Iterator<Item = ResourceId> + '_ {
node.inputs.iter().filter_map(|slot| value_resource_ref(&slot.input))
}
/// The `TaggedValue::Resource` ID referenced by a stored value input, if any.
pub fn value_resource_ref(input: &NodeInput) -> Option<ResourceId> {
match input {
NodeInput::Value { value, .. } => value.get("Resource").and_then(|id| serde_json::from_value(id.clone()).ok()),
_ => None,
}
}
#[cfg(test)]
mod resource_ref_shape {
use super::*;
#[test]
fn resource_ref_shape_matches_serde() {
let id = ResourceId::from_hash(&ResourceHash::from(b"shape test".as_slice()));
let value = serde_json::to_value(TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
let parsed: Option<ResourceId> = value.get("Resource").and_then(|inner| serde_json::from_value(inner.clone()).ok());
assert_eq!(parsed, Some(id), "The shape peek in node_value_resource_refs must match TaggedValue's serde form");
}
}
+1 -4
View File
@@ -29,10 +29,7 @@ pub use resources::*;
pub use session::*;
#[cfg(any(feature = "conversion", test))]
pub use from_runtime::{
PathResolver, RuntimeConversion, ScopedConversion, convert_resource_entry, decode_declaration, encode_declaration, encode_input_ui_attributes, encode_node_ui_attributes, node_value_resource_refs,
value_resource_ref,
};
pub use from_runtime::{RuntimeConversion, decode_declaration, encode_declaration};
#[cfg(any(feature = "conversion", test))]
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
#[cfg(any(feature = "conversion", test))]
-6
View File
@@ -129,12 +129,6 @@ impl Session {
Ok(revs)
}
/// Stages ops computed outside the session (an incremental runtime projection) as hot ops, the
/// same way `stage_from_runtime` stages a diff's ops.
pub fn stage_computed_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
self.stage_ops(ops)
}
/// Apply each op as a hot op with a freshly-ticked timestamp, returning the staged frames in
/// order. Each tick is strictly later than the last, so the final frame carries the latest
/// timestamp, which is what the caller passes to `retire`.
@@ -14,7 +14,9 @@ use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry};
/// Test networks with Import inputs will fail compilation (which is expected).
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
let compiler = Compiler {};
compiler.compile_single(network.clone()).map_err(|e| format!("Compilation failed: {:?}", e))?;
compiler
.compile_single(network.clone(), &graph_craft::proto::Registry::new())
.map_err(|e| format!("Compilation failed: {:?}", e))?;
Ok(())
}
@@ -246,11 +248,6 @@ fn test_nested_network_flattening() {
#[test]
fn test_metadata_preservation() {
// Create a network with nodes that have non-default metadata
let context_features = ContextDependencies {
extract: core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
..Default::default()
};
let network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
@@ -260,7 +257,6 @@ fn test_metadata_preservation() {
inputs: vec![NodeInput::import(concrete!(f64), 0), NodeInput::import(Type::Generic(Cow::Borrowed("T")), 1)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::NodeWithMetadata")),
call_argument: concrete!(String),
context_features,
visible: false, // Non-default value
skip_deduplication: true, // Non-default value
..Default::default()
@@ -294,8 +290,12 @@ fn test_metadata_preservation() {
let conv_node_1 = converted.nodes.get(&NodeId(1)).unwrap();
assert_eq!(orig_node_1.call_argument, conv_node_1.call_argument, "call_argument for node 1 should be preserved");
// Verify context_features is preserved
assert_eq!(orig_node_0.context_features, conv_node_0.context_features, "context_features should be preserved");
// Verify context_features is not stored
assert_eq!(
conv_node_0.context_features,
ContextDependencies::default(),
"context_features should resolve at compile, not round-trip"
);
// Verify visible is preserved
assert_eq!(orig_node_0.visible, conv_node_0.visible, "visible should be preserved");
+1 -1
View File
@@ -310,8 +310,8 @@ fn convert_node(
implementation: convert_implementation(context, &node.implementation, metadata_path, runtime_node_id, node_collector, network_collector)?,
visible: node.attributes.get_or(node::VISIBLE, true),
skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false),
context_features: node.attributes.get_or_default(node::CONTEXT_FEATURES),
// Regenerated during compilation; not stored.
context_features: Default::default(),
original_location: Default::default(),
})
}
-1
View File
@@ -44,7 +44,6 @@ tsify = { workspace = true }
dyn-any = { workspace = true }
num_enum = { workspace = true }
usvg = { workspace = true }
simplecss = { workspace = true }
once_cell = { workspace = true }
web-sys = { workspace = true }
vello = { workspace = true }
@@ -8,7 +8,5 @@ pub enum EventMessage {
CanvasTransformed,
ToolAbort,
SelectionChanged,
/// The document graph's nodes or wires changed, so state derived from the selection's chains may be stale
GraphChanged,
WorkingColorChanged,
}
@@ -182,8 +182,13 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
let mut resource_ids = HashSet::new();
for item in &items {
match item {
ClipboardItem::Layer(entry) => entry.nodes.iter().for_each(|(_, template)| network_interface::collect_template_resources(template, &mut resource_ids)),
ClipboardItem::Nodes(nodes) => nodes.iter().for_each(|(_, template)| network_interface::collect_template_resources(template, &mut resource_ids)),
ClipboardItem::Layer(entry) => entry
.nodes
.iter()
.for_each(|(_, template)| network_interface::collect_node_resources(&template.document_node, &mut resource_ids)),
ClipboardItem::Nodes(nodes) => nodes
.iter()
.for_each(|(_, template)| network_interface::collect_node_resources(&template.document_node, &mut resource_ids)),
ClipboardItem::Vector(_) | ClipboardItem::Resource(_) => {}
}
}
@@ -247,20 +252,9 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
let mut vectors = Vec::new();
let mut resources = Vec::new();
for item in items {
// Pasted templates skip document migration, so stored types normalize here
match item {
ClipboardItem::Layer(mut entry) => {
for (_, template) in &mut entry.nodes {
template.normalize_stored_types();
}
layers.push(entry);
}
ClipboardItem::Nodes(mut nodes) => {
for (_, template) in &mut nodes {
template.normalize_stored_types();
}
node_groups.push(nodes);
}
ClipboardItem::Layer(entry) => layers.push(entry),
ClipboardItem::Nodes(nodes) => node_groups.push(nodes),
ClipboardItem::Vector(vector) => vectors.push(vector),
ClipboardItem::Resource(resource) => resources.push(resource),
}
@@ -1,6 +1,6 @@
use crate::messages::layout::utility_types::widgets::input_widgets::{SpectrumInputUpdate, VisualColorPickersInputUpdate};
use crate::messages::prelude::*;
use graphene_std::vector::style::{FillChoice, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread};
use graphene_std::vector::style::FillChoice;
/// Identifies which RGB channel a numeric input change targets.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -47,16 +47,6 @@ pub enum ColorPickerMessage {
/// `SpectrumInput` change: marker move/insert/delete, midpoint move/reset, or active marker selection changed.
GradientUpdate { update: SpectrumInputUpdate },
/// Gradient spread choice from the gradient "Ends" selection.
SetGradientSpread { gradient_spread: GradientSpread },
/// Gradient cyclic choice: whether the stops wrap as a cycle, from the "Cyclic" checkbox.
SetGradientCyclic { gradient_cyclic: bool },
/// Gradient space choice: the color space the stops interpolate in, from the "Space" dropdown.
SetGradientSpace { gradient_space: GradientSpace },
/// Gradient hue direction choice: which way around the hue wheel the stops interpolate in a polar space, from the "Arc" dropdown.
SetGradientHueDirection { gradient_hue_direction: GradientHueDirection },
/// Gradient interpolation choice: the path the stops interpolate along, from the "Intrp." dropdown.
SetGradientInterpolation { gradient_interpolation: GradientInterpolation },
/// Tell the frontend to start an undo transaction (forwarded as a `FrontendMessage` it bridges out to the picker's parent).
StartTransaction,
@@ -5,7 +5,7 @@ use crate::messages::prelude::*;
use graphene_std::Color;
use graphene_std::color::SRGBA8;
use graphene_std::core_types::misc::parse_css_color;
use graphene_std::vector::style::{FillChoice, Gradient, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops};
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientStops, GradientStopsUI};
/// Bounds for a midpoint position (relative to the interval between two adjacent gradient stops).
const MIN_MIDPOINT: f64 = 0.01;
@@ -28,12 +28,7 @@ pub struct ColorPickerMessageHandler {
old_is_none: bool,
// When set, the picker is editing a gradient: the visual pickers and inputs target the active stop's color.
gradient: Option<Gradient>,
gradient_spread: GradientSpread,
gradient_space: GradientSpace,
gradient_cyclic: bool,
gradient_hue_direction: GradientHueDirection,
gradient_interpolation: GradientInterpolation,
gradient: Option<GradientStops>,
active_marker_index: Option<u32>,
active_marker_is_midpoint: bool,
@@ -55,11 +50,6 @@ impl Default for ColorPickerMessageHandler {
old_alpha: 1.,
old_is_none: true,
gradient: None,
gradient_spread: GradientSpread::default(),
gradient_space: GradientSpace::default(),
gradient_cyclic: false,
gradient_hue_direction: GradientHueDirection::default(),
gradient_interpolation: GradientInterpolation::default(),
active_marker_index: None,
active_marker_is_midpoint: false,
allow_none: true,
@@ -80,36 +70,20 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
FillChoice::None => {
self.set_new_hsva(0., 0., 0., 1., true);
self.gradient = None;
self.gradient_spread = GradientSpread::default();
self.gradient_space = GradientSpace::default();
self.gradient_cyclic = false;
self.gradient_hue_direction = GradientHueDirection::default();
self.gradient_interpolation = GradientInterpolation::default();
self.active_marker_index = None;
self.active_marker_is_midpoint = false;
}
FillChoice::Solid(color) => {
self.gradient = None;
self.gradient_spread = GradientSpread::default();
self.gradient_space = GradientSpace::default();
self.gradient_cyclic = false;
self.gradient_hue_direction = GradientHueDirection::default();
self.gradient_interpolation = GradientInterpolation::default();
self.active_marker_index = None;
self.active_marker_is_midpoint = false;
self.adopt_color(color);
}
FillChoice::Gradient(ramp) => {
FillChoice::Gradient(stops) => {
self.active_marker_index = Some(0);
self.active_marker_is_midpoint = false;
self.gradient_spread = ramp.gradient_spread;
self.gradient_space = ramp.gradient_space;
self.gradient_cyclic = ramp.gradient_cyclic;
self.gradient_hue_direction = ramp.gradient_hue_direction;
self.gradient_interpolation = ramp.gradient_interpolation;
let gradient = Gradient::from(ramp);
let first_color = gradient.color(0).unwrap_or(Color::BLACK);
self.gradient = Some(gradient);
let first_color = stops.color.first().copied().unwrap_or(Color::BLACK);
self.gradient = Some(stops);
self.adopt_color(first_color);
}
}
@@ -180,7 +154,7 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
match preset {
FillChoice::None => {
self.set_new_hsva(0., 0., 0., 1., true);
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoice::<SRGBA8>::None });
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoiceUI::None });
}
FillChoice::Solid(color) => {
self.adopt_color(color);
@@ -205,62 +179,13 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
self.set_old_hsva(temp.0, temp.1, temp.2, temp.3, temp.4);
if self.is_none {
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoice::<SRGBA8>::None });
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoiceUI::None });
} else {
self.emit_color(responses);
}
self.send_layouts(responses);
}
ColorPickerMessage::GradientUpdate { update } => self.apply_gradient_update(update, responses),
ColorPickerMessage::SetGradientSpread { gradient_spread } => {
let Some(gradient) = &self.gradient else { return };
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
self.gradient_spread = gradient_spread;
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoice::Gradient(GradientRamp::from(gradient).with_settings(self.gradient_settings())),
});
self.send_layouts(responses);
}
ColorPickerMessage::SetGradientCyclic { gradient_cyclic } => {
let Some(gradient) = &mut self.gradient else { return };
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
let previous_cyclic = std::mem::replace(&mut self.gradient_cyclic, gradient_cyclic);
gradient.hold_positions_across_cyclic_change(previous_cyclic, gradient_cyclic);
let ramp = GradientRamp::from(&*gradient);
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoice::Gradient(ramp.with_settings(self.gradient_settings())),
});
self.send_layouts(responses);
}
ColorPickerMessage::SetGradientSpace { gradient_space } => {
let Some(gradient) = &self.gradient else { return };
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
self.gradient_space = gradient_space;
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoice::Gradient(GradientRamp::from(gradient).with_settings(self.gradient_settings())),
});
self.send_layouts(responses);
}
ColorPickerMessage::SetGradientHueDirection { gradient_hue_direction } => {
let Some(gradient) = &self.gradient else { return };
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
self.gradient_hue_direction = gradient_hue_direction;
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoice::Gradient(GradientRamp::from(gradient).with_settings(self.gradient_settings())),
});
self.send_layouts(responses);
}
ColorPickerMessage::SetGradientInterpolation { gradient_interpolation } => {
let Some(gradient) = &self.gradient else { return };
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
self.gradient_interpolation = gradient_interpolation;
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoice::Gradient(GradientRamp::from(gradient).with_settings(self.gradient_settings())),
});
self.send_layouts(responses);
}
ColorPickerMessage::StartTransaction => {
responses.add(FrontendMessage::ColorPickerStartHistoryTransaction);
}
@@ -309,17 +234,6 @@ impl ColorPickerMessageHandler {
self.old_is_none = is_none;
}
/// The whole-ramp settings the picker is currently editing with, bundled for sampling and for emitting ramps.
fn gradient_settings(&self) -> GradientSettings {
GradientSettings {
spread: self.gradient_spread,
cyclic: self.gradient_cyclic,
space: self.gradient_space,
hue_direction: self.gradient_hue_direction,
interpolation: self.gradient_interpolation,
}
}
fn snapshot_old(&mut self) {
self.old_hue = self.hue;
self.old_saturation = self.saturation;
@@ -352,16 +266,18 @@ impl ColorPickerMessageHandler {
if let Some(gradient) = &mut self.gradient
&& let Some(active_index) = self.active_marker_index
&& (active_index as usize) < gradient.len()
&& let Some(stop_color) = gradient.color.get_mut(active_index as usize)
{
gradient.set_color(active_index as usize, color);
let ramp = GradientRamp::from(&*gradient);
*stop_color = color;
let stops = gradient.clone();
let fill_choice = FillChoice::Gradient(stops);
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoice::Gradient(ramp.with_settings(self.gradient_settings())),
value: FillChoiceUI::from(&fill_choice),
});
} else {
let fill_choice = FillChoice::Solid(color);
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoice::Solid(SRGBA8::from(color)),
value: FillChoiceUI::from(&fill_choice),
});
}
}
@@ -389,7 +305,7 @@ impl ColorPickerMessageHandler {
self.active_marker_is_midpoint = active_marker_is_midpoint;
if let Some(index) = active_marker_index
&& let Some(gradient) = &self.gradient
&& let Some(color) = gradient.color(index as usize)
&& let Some(color) = gradient.color.get(index as usize).copied()
{
self.adopt_color(color);
self.snapshot_old();
@@ -402,31 +318,30 @@ impl ColorPickerMessageHandler {
match update {
SpectrumInputUpdate::MoveMarker { index, position } => {
let new_index = gradient.move_stop(index as usize, position, self.gradient_cyclic);
let new_index = gradient.move_stop(index as usize, position);
if Some(index) == self.active_marker_index {
self.active_marker_index = Some(new_index as u32);
}
}
SpectrumInputUpdate::MoveMidpoint { index, position } => {
if (index as usize) >= gradient.len() {
if let Some(midpoint) = gradient.midpoint.get_mut(index as usize) {
*midpoint = position.clamp(MIN_MIDPOINT, MAX_MIDPOINT);
} else {
return;
}
gradient.set_midpoint(index as usize, position.clamp(MIN_MIDPOINT, MAX_MIDPOINT));
}
SpectrumInputUpdate::InsertMarker { position } => {
let new_index = gradient.insert_stop(position, self.gradient_settings());
let new_index = gradient.insert_stop(position);
self.active_marker_index = Some(new_index as u32);
self.active_marker_is_midpoint = false;
if let Some(color) = gradient.color(new_index) {
if let Some(color) = gradient.color.get(new_index).copied() {
self.adopt_color(color);
self.snapshot_old();
}
}
SpectrumInputUpdate::InsertDuplicate { index, position } => {
let source = index as usize;
let Some(insert_index) = gradient.duplicate_stop(source, position, self.gradient_cyclic) else {
return;
};
let Some(insert_index) = gradient.duplicate_stop(source, position) else { return };
// The dragged stop (the duplication source) stays active. Its index shifts up if the frozen copy landed at or before it.
let dragged_index = if insert_index <= source { source + 1 } else { source };
self.active_marker_index = Some(dragged_index as u32);
@@ -434,7 +349,7 @@ impl ColorPickerMessageHandler {
}
SpectrumInputUpdate::RemoveDuplicate { index } => {
let anchor = index as usize;
if anchor >= gradient.len() || gradient.len() <= 2 {
if anchor >= gradient.position.len() || gradient.position.len() <= 2 {
return;
}
// Never remove the active (dragged) stop itself, this should only ever target the frozen copy.
@@ -451,14 +366,14 @@ impl ColorPickerMessageHandler {
}
SpectrumInputUpdate::DeleteMarker { index } => {
// Enforce minimum stop count. The gradient editor needs at least 2 stops to remain meaningful.
if gradient.len() <= 2 || (index as usize) >= gradient.len() {
if gradient.position.len() <= 2 || (index as usize) >= gradient.position.len() {
return;
}
gradient.remove(index as usize);
let new_active = (index as usize).min(gradient.len() - 1);
let new_active = (index as usize).min(gradient.position.len() - 1);
self.active_marker_index = Some(new_active as u32);
self.active_marker_is_midpoint = false;
if let Some(color) = gradient.color(new_active) {
if let Some(color) = gradient.color.get(new_active).copied() {
self.adopt_color(color);
self.snapshot_old();
}
@@ -468,17 +383,16 @@ impl ColorPickerMessageHandler {
}
SpectrumInputUpdate::ResetMarker { index } => {
let i = index as usize;
let count = gradient.len();
let count = gradient.position.len();
if i >= count {
return;
}
// Each stop's "natural" position is its evenly-spaced fraction along 0..1, e.g., for 5 stops: 0, 0.25, 0.5, 0.75, 1 (or fifths when cyclic, leaving the wrapped interval its share). Falls back to the midpoint between neighbors when the natural position would push the stop past another.
let left = if i == 0 { 0. } else { gradient.position(i - 1, self.gradient_cyclic) };
let right = if i + 1 < count { gradient.position(i + 1, self.gradient_cyclic) } else { 1. };
let denominator = if self.gradient_cyclic { count } else { count - 1 };
let natural = if count <= 1 { 0. } else { i as f64 / denominator as f64 };
// Each stop's "natural" position is its evenly-spaced fraction along 0..1, e.g., for 5 stops: 0, 0.25, 0.5, 0.75, 1. Falls back to the midpoint between neighbors when the natural position would push the stop past another.
let left = if i == 0 { 0. } else { gradient.position[i - 1] };
let right = gradient.position.get(i + 1).copied().unwrap_or(1.);
let natural = if count <= 1 { 0. } else { i as f64 / (count - 1) as f64 };
let new_position = if (left..=right).contains(&natural) { natural } else { (left + right) / 2. };
let new_index = gradient.move_stop(i, new_position, self.gradient_cyclic);
let new_index = gradient.move_stop(i, new_position);
if Some(index) == self.active_marker_index {
self.active_marker_index = Some(new_index as u32);
}
@@ -486,10 +400,11 @@ impl ColorPickerMessageHandler {
SpectrumInputUpdate::ActiveMarker { .. } => unreachable!("handled above"),
}
self.gradient = Some(gradient.clone());
let fill_choice = FillChoice::Gradient(gradient);
responses.add(FrontendMessage::ColorPickerColorChanged {
value: FillChoice::Gradient(GradientRamp::from(&gradient).with_settings(self.gradient_settings())),
value: FillChoiceUI::from(&fill_choice),
});
self.gradient = Some(gradient);
self.send_layouts(responses);
}
@@ -513,15 +428,9 @@ impl ColorPickerMessageHandler {
// Gradient editor (only present when the picker is in gradient mode)
if let Some(gradient) = &self.gradient {
// For gradient editing, the markers' handle colors mirror their gradient stop colors
let markers = (0..gradient.len())
.filter_map(|i| Some(SpectrumMarker::new(gradient.position(i, self.gradient_cyclic), gradient.midpoint(i), gradient.color(i)?)))
.collect();
let markers = gradient.iter().map(|stop| SpectrumMarker::new(stop.position, stop.midpoint, stop.color)).collect();
let mut row_widgets = vec![
SpectrumInput::new(GradientStops::from(gradient))
.track_space(self.gradient_space)
.track_cyclic(self.gradient_cyclic)
.track_hue_direction(self.gradient_hue_direction)
.track_interpolation(self.gradient_interpolation)
SpectrumInput::new(GradientStopsUI::from(gradient))
.markers(markers)
.active_marker_index(self.active_marker_index)
.active_marker_is_midpoint(self.active_marker_is_midpoint)
@@ -536,10 +445,10 @@ impl ColorPickerMessageHandler {
if let Some(active) = self.active_marker_index {
let active_index = active as usize;
let position_value = match (self.active_marker_is_midpoint, active_index < gradient.len()) {
(_, false) => 0.,
(true, true) => gradient.midpoint(active_index),
(false, true) => gradient.position(active_index, self.gradient_cyclic),
let position_value = if self.active_marker_is_midpoint {
gradient.midpoint.get(active_index).copied().unwrap_or(0.)
} else {
gradient.position.get(active_index).copied().unwrap_or(0.)
};
let is_midpoint = self.active_marker_is_midpoint;
let captured_index = active;
@@ -615,11 +524,7 @@ impl ColorPickerMessageHandler {
// Hex
groups.push(LayoutGroup::row(vec![
TextLabel::new("Hex")
.disabled(self.disabled)
.tooltip_label("Hex Color Code")
.tooltip_description(HEX_DESCRIPTION)
.widget_instance(),
TextLabel::new("Hex").tooltip_label("Hex Color Code").tooltip_description(HEX_DESCRIPTION).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextInput::new(hex_value)
.centered(true)
@@ -632,11 +537,7 @@ impl ColorPickerMessageHandler {
// RGB
groups.push(LayoutGroup::row(vec![
TextLabel::new("RGB")
.disabled(self.disabled)
.tooltip_label("Red/Green/Blue")
.tooltip_description("Integers 0–255.")
.widget_instance(),
TextLabel::new("RGB").tooltip_label("Red/Green/Blue").tooltip_description("Integers 0–255.").widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
rgb_input(RgbChannel::Red, rgb_255.map(|(r, _, _)| r), "Red Channel", self.disabled),
Separator::new(SeparatorStyle::Related).widget_instance(),
@@ -648,9 +549,8 @@ impl ColorPickerMessageHandler {
// HSV
groups.push(LayoutGroup::row(vec![
TextLabel::new("HSV")
.disabled(self.disabled)
.tooltip_label("Hue/Saturation/Value")
.tooltip_description("Also known as Hue/Saturation/Brightness (HSB), but distinct from Hue/Saturation/Lightness (HSL), a different color model.")
.tooltip_description("Also known as Hue/Saturation/Brightness (HSB). Not to be confused with Hue/Saturation/Lightness (HSL), a different color model.")
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
hsv_input(
@@ -686,11 +586,7 @@ impl ColorPickerMessageHandler {
// Alpha
groups.push(LayoutGroup::row(vec![
TextLabel::new("Alpha")
.disabled(self.disabled)
.tooltip_label("Alpha")
.tooltip_description(ALPHA_DESCRIPTION)
.widget_instance(),
TextLabel::new("Alpha").tooltip_label("Alpha").tooltip_description(ALPHA_DESCRIPTION).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(if self.is_none { None } else { Some(self.alpha * 100.) })
.disabled(self.disabled)
@@ -706,98 +602,6 @@ impl ColorPickerMessageHandler {
.widget_instance(),
]));
// Gradient spread, trailed by the cyclic wrap toggle (only present when the picker is in gradient mode)
if self.gradient.is_some() {
let entries = RadioEntryData::list_from_choice_type(|gradient_spread| ColorPickerMessage::SetGradientSpread { gradient_spread }.into());
groups.push(LayoutGroup::row(vec![
TextLabel::new("Ends")
.disabled(self.disabled)
.tooltip_label("Gradient Spread / Cyclic")
.tooltip_description(ENDS_DESCRIPTION)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
RadioInput::new(entries)
.narrow(true)
.selected_index(Some(self.gradient_spread as u32))
.disabled(self.disabled)
.widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(self.gradient_cyclic)
.icon("Link")
.disabled(self.disabled)
.tooltip_label("Cyclic")
.tooltip_description(CYCLIC_DESCRIPTION)
.on_update(|checkbox_input: &CheckboxInput| {
ColorPickerMessage::SetGradientCyclic {
gradient_cyclic: checkbox_input.checked,
}
.into()
})
.widget_instance(),
]));
}
// Gradient interpolation (only present when the picker is in gradient mode)
if self.gradient.is_some() {
let entries = MenuListEntry::sections_from_choice_type(|gradient_interpolation| ColorPickerMessage::SetGradientInterpolation { gradient_interpolation }.into());
groups.push(LayoutGroup::row(vec![
TextLabel::new("Intrp.")
.disabled(self.disabled)
.tooltip_label("Gradient Interpolation")
.tooltip_description(INTERPOLATION_DESCRIPTION)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
DropdownInput::new(entries)
.selected_index(Some(self.gradient_interpolation as u32))
.disabled(self.disabled)
.tooltip_label("Gradient Interpolation")
.tooltip_description(INTERPOLATION_DESCRIPTION)
.widget_instance(),
]));
}
// Gradient color space (only present when the picker is in gradient mode)
if self.gradient.is_some() {
let entries = MenuListEntry::sections_from_choice_type(|gradient_space| ColorPickerMessage::SetGradientSpace { gradient_space }.into());
groups.push(LayoutGroup::row(vec![
TextLabel::new("Space")
.disabled(self.disabled)
.tooltip_label("Gradient Space")
.tooltip_description(SPACE_DESCRIPTION)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
DropdownInput::new(entries)
.selected_index(Some(self.gradient_space as u32))
.disabled(self.disabled)
.tooltip_label("Gradient Space")
.tooltip_description(SPACE_DESCRIPTION)
.widget_instance(),
]));
}
// Gradient hue direction (only present when the chosen space is polar)
if self.gradient.is_some() && self.gradient_space.is_polar() {
let entries = MenuListEntry::sections_from_choice_type(|gradient_hue_direction| ColorPickerMessage::SetGradientHueDirection { gradient_hue_direction }.into());
groups.push(LayoutGroup::row(vec![
TextLabel::new("Arc")
.disabled(self.disabled)
.tooltip_label("Gradient Hue Direction")
.tooltip_description(HUE_DIRECTION_DESCRIPTION)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
DropdownInput::new(entries)
.selected_index(Some(self.gradient_hue_direction as u32))
.disabled(self.disabled)
.tooltip_label("Gradient Hue Direction")
.tooltip_description(HUE_DIRECTION_DESCRIPTION)
.widget_instance(),
]));
}
// Color presets (None / Black / White / pure colors / eyedropper)
groups.push(LayoutGroup::row(vec![
ColorPresetsInput::default()
@@ -851,11 +655,6 @@ const HUE_DESCRIPTION: &str = "The shade along the spectrum of the rainbow.";
const SATURATION_DESCRIPTION: &str = "The vividness from grayscale to full color.";
const VALUE_DESCRIPTION: &str = "The brightness from black to full color.";
const ALPHA_DESCRIPTION: &str = "The level of translucency, from transparent (0%) to opaque (100%).";
const ENDS_DESCRIPTION: &str = "The method for how the gradient continues beyond its ends, and whether its stops cycle back around from last to first.";
const CYCLIC_DESCRIPTION: &str = "Treats the stops as a cycle, interpolating from the last stop back around to the first.";
const SPACE_DESCRIPTION: &str = "The color space where stops interpolate toward their neighbors.";
const HUE_DIRECTION_DESCRIPTION: &str = "Which way around the hue wheel the stops interpolate.";
const INTERPOLATION_DESCRIPTION: &str = "The path the stops interpolate along, deciding whether the gradient jumps, turns corners, or flows smoothly through them.";
/// The popover's background color as sRGB gamma-encoded channels (the `--color-2-mildblack` design token, `#222`).
/// Used by the comparison swatch's outline computation to brighten the inset border for colors close to this background.
@@ -14,7 +14,7 @@ use crate::messages::prelude::*;
use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary;
use graph_craft::document::NodeId;
use graphene_std::color::SRGBA8;
use graphene_std::vector::style::FillChoice;
use graphene_std::vector::style::FillChoiceUI;
use std::path::PathBuf;
#[cfg(not(target_family = "wasm"))]
@@ -165,7 +165,7 @@ pub enum FrontendMessage {
},
/// The Rust color picker handler picked a new color/gradient. The frontend `<ColorPicker />` forwards this as its `colorOrGradient` event.
ColorPickerColorChanged {
value: FillChoice<SRGBA8>,
value: FillChoiceUI,
},
/// The Rust color picker handler is starting an undo transaction. The frontend `<ColorPicker />` forwards this as its `startHistoryTransaction` event.
ColorPickerStartHistoryTransaction,
@@ -3,7 +3,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::prelude::*;
use graphene_std::color::SRGBA8;
use graphene_std::vector::style::FillChoice;
use graphene_std::vector::style::FillChoiceUI;
use serde_json::Value;
use std::collections::HashMap;
@@ -117,26 +117,23 @@ impl LayoutMessageHandler {
}
LayoutGroup::Table(WidgetTable { rows, .. }) => {
for (row_index, row) in rows.iter().enumerate() {
for (cell_index, cell) in row.iter().enumerate() {
for (value_index, value) in cell.iter().enumerate() {
// Return if this is the correct ID
if value.widget_id == widget_id {
widget_path.push(row_index);
widget_path.push(cell_index);
widget_path.push(value_index);
return Some((value, widget_path));
}
for (value_index, value) in row.iter().enumerate() {
// Return if this is the correct ID
if value.widget_id == widget_id {
widget_path.push(row_index);
widget_path.push(value_index);
return Some((value, widget_path));
}
if let Widget::PopoverButton(popover) = &*value.widget {
stack.extend(
popover
.popover_layout
.0
.iter()
.enumerate()
.map(|(child, val)| ([widget_path.as_slice(), &[row_index, cell_index, value_index, child]].concat(), val)),
);
}
if let Widget::PopoverButton(popover) = &*value.widget {
stack.extend(
popover
.popover_layout
.0
.iter()
.enumerate()
.map(|(child, val)| ([widget_path.as_slice(), &[row_index, value_index, child]].concat(), val)),
);
}
}
}
@@ -197,16 +194,12 @@ impl LayoutMessageHandler {
let callback_message = match action {
WidgetValueAction::Commit => (color_button.on_commit.callback)(&()),
WidgetValueAction::Update => {
let Ok(fill_choice) = serde_json::from_value::<FillChoice<SRGBA8>>(value) else {
warn!("ColorInput update was not able to be parsed as FillChoice<SRGBA8>: {color_button:?}");
let Ok(fill_choice_ui) = serde_json::from_value::<FillChoiceUI>(value) else {
warn!("ColorInput update was not able to be parsed as FillChoiceUI: {color_button:?}");
return;
};
// The stored copy has to keep mirroring what the frontend was last sent, so the rebuilt layout still
// diffs against it and syncs picks that leave the swatch unchanged; the callback borrows the new one
let previous_value = std::mem::replace(&mut color_button.value, fill_choice);
let update_message = (color_button.on_update.callback)(color_button);
color_button.value = previous_value;
update_message
color_button.value = fill_choice_ui;
(color_button.on_update.callback)(color_button)
}
};
@@ -535,28 +528,9 @@ fn populate_computed_display_fields(layout: &mut Layout) {
color_input.chosen_gradient = color_input.value.to_css_background_image();
}
Widget::SpectrumInput(spectrum_input) => {
// The track strip spans exactly 0 to 1, which no spread affects, so the widget carries no spread of its own
let settings = graphene_std::vector::style::GradientSettings {
spread: Default::default(),
cyclic: spectrum_input.track_cyclic,
space: spectrum_input.track_space,
hue_direction: spectrum_input.track_hue_direction,
interpolation: spectrum_input.track_interpolation,
};
let track_gradient = graphene_std::vector::style::Gradient::from(&spectrum_input.track);
spectrum_input.track_samples = track_gradient
.interpolated_samples_or_black(settings)
.into_iter()
.map(|(position, color, _)| SpectrumSample::new(position, color))
.collect();
// The end caps sample the track's boundary colors, which a cyclic wrap makes the wrapped interval's boundary-crossing color rather than the outermost stops'
let track_evaluator = track_gradient.evaluator(settings);
let cap = |t: f64| {
let color = track_evaluator.evaluate(t);
SRGBA8::from(color).to_css_hex()
};
spectrum_input.track_start_css = cap(0.);
spectrum_input.track_end_css = cap(1.);
spectrum_input.track_css = spectrum_input.track.to_css_linear_gradient();
spectrum_input.track_start_css = spectrum_input.track.color.first().map(|color| color.to_css_hex()).unwrap_or_else(|| "black".to_string());
spectrum_input.track_end_css = spectrum_input.track.color.last().map(|color| color.to_css_hex()).unwrap_or_else(|| "black".to_string());
}
Widget::ColorComparisonInput(comparison) => {
let contrasting = |color: Option<SRGBA8>| color.map_or(SRGBA8::BLACK, |color| color.contrasting_text_color()).to_css_hex();
@@ -576,6 +550,7 @@ fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInp
let value = math_parser::evaluate(expression)
.inspect_err(|err| error!("Math parser error on \"{expression}\": {err}"))
.ok()?
.0
.inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err}"))
.ok()?;
@@ -273,7 +273,7 @@ impl<'a> Iterator for WidgetIter<'a> {
self.next()
}
Some(LayoutGroup::Table(WidgetTable { rows, .. })) => {
self.table.extend(rows.iter().flatten().flatten().rev());
self.table.extend(rows.iter().flatten().rev());
self.next()
}
Some(LayoutGroup::Section(WidgetSection { layout, .. })) => {
@@ -325,7 +325,7 @@ impl<'a> Iterator for WidgetIterMut<'a> {
self.next()
}
Some(LayoutGroup::Table(WidgetTable { rows, .. })) => {
self.table.extend(rows.iter_mut().flatten().flatten().rev());
self.table.extend(rows.iter_mut().flatten().rev());
self.next()
}
Some(LayoutGroup::Section(WidgetSection { layout, .. })) => {
@@ -365,9 +365,8 @@ pub struct WidgetRow {
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Default, Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct WidgetTable {
/// Rows of cells, each cell holding one or more widgets laid out inline.
#[serde(rename = "tableWidgets")]
pub rows: Vec<Vec<Vec<WidgetInstance>>>,
pub rows: Vec<Vec<WidgetInstance>>,
pub unstyled: bool,
}
@@ -413,14 +412,7 @@ impl LayoutGroup {
Self::Column(WidgetColumn { widgets })
}
/// A table with one widget per cell.
pub fn table(rows: Vec<Vec<WidgetInstance>>, unstyled: bool) -> Self {
let rows = rows.into_iter().map(|row| row.into_iter().map(|widget| vec![widget]).collect()).collect();
Self::Table(WidgetTable { rows, unstyled })
}
/// A table whose cells may each hold multiple widgets laid out inline.
pub fn table_of_cells(rows: Vec<Vec<Vec<WidgetInstance>>>, unstyled: bool) -> Self {
Self::Table(WidgetTable { rows, unstyled })
}
@@ -608,17 +600,13 @@ impl Diffable for LayoutGroup {
}
}
Self::Table(WidgetTable { rows, .. }) => {
for (row_index, row) in rows.iter().enumerate() {
for (column_index, cell) in row.iter().enumerate() {
for (widget_index, widget) in cell.iter().enumerate() {
widget_path.push(row_index);
widget_path.push(column_index);
widget_path.push(widget_index);
widget.collect_checkbox_ids(layout_target, widget_path, checkbox_map);
widget_path.pop();
widget_path.pop();
widget_path.pop();
}
for (row_idx, row) in rows.iter().enumerate() {
for (col_idx, widget) in row.iter().enumerate() {
widget_path.push(row_idx);
widget_path.push(col_idx);
widget.collect_checkbox_ids(layout_target, widget_path, checkbox_map);
widget_path.pop();
widget_path.pop();
}
}
}
@@ -638,17 +626,13 @@ impl Diffable for LayoutGroup {
}
}
Self::Table(WidgetTable { rows, .. }) => {
for (row_index, row) in rows.iter_mut().enumerate() {
for (column_index, cell) in row.iter_mut().enumerate() {
for (widget_index, widget) in cell.iter_mut().enumerate() {
widget_path.push(row_index);
widget_path.push(column_index);
widget_path.push(widget_index);
widget.replace_widget_ids(layout_target, widget_path, checkbox_map);
widget_path.pop();
widget_path.pop();
widget_path.pop();
}
for (row_idx, row) in rows.iter_mut().enumerate() {
for (col_idx, widget) in row.iter_mut().enumerate() {
widget_path.push(row_idx);
widget_path.push(col_idx);
widget.replace_widget_ids(layout_target, widget_path, checkbox_map);
widget_path.pop();
widget_path.pop();
}
}
}
@@ -4,8 +4,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
use crate::messages::tool::tool_messages::tool_prelude::WidgetCallback;
use derivative::*;
use graphene_std::color::SRGBA8;
use graphene_std::vector::style::FillChoice;
use graphene_std::vector::style::FillChoiceUI;
use graphite_proc_macros::WidgetBuilder;
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -192,9 +191,9 @@ pub struct ImageButton {
pub struct ColorInput {
// Content
#[widget_builder(constructor)]
pub value: FillChoice<SRGBA8>,
pub value: FillChoiceUI,
/// CSS `linear-gradient(...)` (or solid-color stand-in) for the swatch's `background-image`. Auto-populated from `value` at layout-send time.
/// `None` when `value` is `FillChoice::<SRGBA8>::None`, in which case the frontend uses its "none" fallback styling.
/// `None` when `value` is `FillChoiceUI::None`, in which case the frontend uses its "none" fallback styling.
#[serde(rename = "chosenGradient")]
#[widget_builder(skip)]
pub chosen_gradient: Option<String>,
@@ -1,13 +1,12 @@
use crate::messages::frontend::IconName;
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::message::Message;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use derivative::*;
use graphene_std::Color;
use graphene_std::color::SRGBA8;
use graphene_std::transform::ReferencePoint;
use graphene_std::vector::style::{FillChoice, GradientHueDirection, GradientInterpolation, GradientSpace, GradientStops};
use graphene_std::vector::style::{FillChoiceUI, GradientStopsUI};
use graphite_proc_macros::WidgetBuilder;
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -151,35 +150,6 @@ impl std::hash::Hash for MenuListEntry {
}
}
impl MenuListEntry {
/// One entry per variant of a choice type enum, keeping the choice type's section groupings, shown as the variant's label alongside its icon when it has one.
pub fn sections_from_choice_type<E>(to_message: impl Fn(E) -> Message + Clone + Send + Sync + 'static) -> MenuListEntrySections
where
E: graphene_std::choice_type::ChoiceTypeStatic + 'static,
{
E::list()
.iter()
.map(|section| {
section
.iter()
.map(|(variant, metadata)| {
let to_message = to_message.clone();
let variant = *variant;
let entry = MenuListEntry::new(metadata.name)
.label(metadata.label)
.tooltip_label(metadata.label)
.tooltip_description(metadata.description.unwrap_or_default())
.on_update(move |_| to_message(variant));
if let Some(icon) = metadata.icon { entry.icon(icon) } else { entry }
})
.collect()
})
.collect()
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder)]
#[derivative(Debug, PartialEq, Default)]
@@ -374,30 +344,6 @@ pub struct RadioEntryData {
pub on_commit: WidgetCallback<()>,
}
impl RadioEntryData {
/// One entry per variant of a choice type enum, shown as the variant's icon when it has one and its text label otherwise.
pub fn list_from_choice_type<E>(to_message: impl Fn(E) -> Message + Clone + Send + Sync + 'static) -> Vec<Self>
where
E: graphene_std::choice_type::ChoiceTypeStatic + 'static,
{
E::list()
.iter()
.flat_map(|section| section.iter())
.map(|(variant, metadata)| {
let to_message = to_message.clone();
let variant = *variant;
let entry = RadioEntryData::new(metadata.name)
.tooltip_label(metadata.label)
.tooltip_description(metadata.description.unwrap_or_default())
.on_update(move |_| to_message(variant));
if let Some(icon) = metadata.icon { entry.icon(icon) } else { entry.label(metadata.label) }
})
.collect()
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder)]
#[derivative(Debug, PartialEq, Default)]
@@ -574,7 +520,7 @@ pub struct ColorPresetsInput {
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum ColorPresetsInputUpdate {
Preset(FillChoice<SRGBA8>),
Preset(FillChoiceUI),
EyedropperColorCode(String),
}
@@ -585,28 +531,16 @@ pub struct SpectrumInput {
// Content
/// The colored gradient drawn behind the markers (display-only, caller-owned).
#[widget_builder(constructor)]
pub track: GradientStops<SRGBA8>,
/// The color space the track's stops interpolate in, used to bake `track_samples`. Not sent to the frontend.
#[serde(skip)]
pub track_space: GradientSpace,
/// Whether the track's stops wrap as a cycle, used to bake `track_samples` and by the frontend to draw the wrapped interval's midpoint diamond.
#[serde(rename = "trackCyclic")]
pub track_cyclic: bool,
/// The hue direction the track's stops interpolate with in a polar space, used to bake `track_samples`. Not sent to the frontend.
#[serde(skip)]
pub track_hue_direction: GradientHueDirection,
/// The path the track's stops interpolate along, used to bake `track_samples` and by the frontend to suppress the midpoint diamonds when stepped.
#[serde(rename = "trackInterpolation")]
pub track_interpolation: GradientInterpolation,
/// Straight-alpha samples the frontend draws as the stops of an SVG gradient filling the track strip. Auto-populated from `track` at layout-send time.
#[serde(rename = "trackSamples")]
pub track: GradientStopsUI,
/// CSS `linear-gradient(...)` string for the track strip's `background-image`. Auto-populated from `track` at layout-send time.
#[serde(rename = "trackCSS")]
#[widget_builder(skip)]
pub track_samples: Vec<SpectrumSample>,
/// Hex string for the track strip's leftmost solid-color end-cap. Auto-populated by evaluating `track` at position 0.
pub track_css: String,
/// Hex string for the track strip's leftmost solid-color end-cap. Auto-populated from `track`'s first stop.
#[serde(rename = "trackStartCSS")]
#[widget_builder(skip)]
pub track_start_css: String,
/// Hex string for the track strip's rightmost solid-color end-cap. Auto-populated by evaluating `track` at position 1.
/// Hex string for the track strip's rightmost solid-color end-cap. Auto-populated from `track`'s last stop.
#[serde(rename = "trackEndCSS")]
#[widget_builder(skip)]
pub track_end_css: String,
@@ -645,46 +579,22 @@ pub struct SpectrumInput {
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct SpectrumMarker {
/// Position of the marker along the spectrum track, normally from 0 to 1. A shifted or stretched non-cyclic ramp can
/// place it outside that range, where the track draws only the markers falling within its visible span.
/// Position (0..1) of the marker along the spectrum track.
position: f64,
/// Position (0..1) of the midpoint between this marker and the next, used only if `show_midpoints` is true.
/// The last marker's value controls the wrapped interval when `track_cyclic` is set, and is otherwise ignored.
/// Position (0..1) of the midpoint between this marker and the next, used only if `show_midpoints` is true. The last marker's value is ignored.
midpoint: f64,
/// CSS color string for the marker handle's fill. Set via `SpectrumMarker::new` from a linear [`Color`],
/// discarding any transparency so the handle always shows the RGB that steers the interpolation.
/// CSS color string for the marker handle's fill. Set via `SpectrumMarker::new` from a linear [`Color`].
#[serde(rename = "handleColorCSS")]
handle_color_css: String,
}
impl SpectrumMarker {
pub fn new(position: f64, midpoint: f64, handle_color: Color) -> Self {
let handle_color_css = format!("#{}", SRGBA8::from(handle_color).to_rgb_hex());
let handle_color_css = SRGBA8::from(handle_color).to_css_hex();
Self { position, midpoint, handle_color_css }
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct SpectrumSample {
/// Position (0..1) of the sample along the spectrum track, drawn as the SVG stop's `offset`.
position: f64,
/// `#rrggbb` hex of the sample's color, drawn as the SVG stop's `stop-color`.
color: String,
/// Straight alpha (0..1) of the sample, drawn as the SVG stop's `stop-opacity`.
alpha: f32,
}
impl SpectrumSample {
pub fn new(position: f64, color: Color) -> Self {
Self {
position,
color: format!("#{}", SRGBA8::from(color).to_rgb_hex()),
alpha: color.a(),
}
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum SpectrumInputUpdate {
@@ -37,8 +37,8 @@ pub enum PathStep {
#[derive(PartialEq, Eq, Clone, Copy, Default, Debug, serde::Serialize, serde::Deserialize)]
pub enum VectorTableTab {
#[default]
Properties,
Points,
Segments,
Regions,
Handles,
}
File diff suppressed because it is too large. Load diff
@@ -17,9 +17,9 @@ use super::utility_types::network_interface::storage_metadata::{StorageMetadataV
#[derivative(Clone, Debug, Default)]
pub struct DocumentHistory {
/// Stack of document network snapshots for previous history states.
legacy_undo_stack: VecDeque<NodeNetworkInterface>,
lagacy_undo_stack: VecDeque<NodeNetworkInterface>,
/// Stack of document network snapshots for future history states.
legacy_redo_stack: VecDeque<NodeNetworkInterface>,
lagacy_redo_stack: VecDeque<NodeNetworkInterface>,
/// The `Gdd` working copy: owns the CRDT `Session` and mirrors edits to disk. `None` until the mount
/// future built by `load_document` resolves.
#[derivative(Debug = "ignore")]
@@ -31,38 +31,38 @@ impl DocumentHistory {
/// Push a snapshot onto the undo stack, evicting the oldest entry past the history cap.
pub fn push_undo(&mut self, snapshot: NodeNetworkInterface) {
Self::push_capped(&mut self.legacy_undo_stack, snapshot);
Self::push_capped(&mut self.lagacy_undo_stack, snapshot);
}
/// Push a snapshot onto the redo stack, evicting the oldest entry past the history cap.
pub fn push_redo(&mut self, snapshot: NodeNetworkInterface) {
Self::push_capped(&mut self.legacy_redo_stack, snapshot);
Self::push_capped(&mut self.lagacy_redo_stack, snapshot);
}
/// Pop the most recent undo snapshot, or `None` when the stack is empty.
pub fn pop_undo(&mut self) -> Option<NodeNetworkInterface> {
self.legacy_undo_stack.pop_back()
self.lagacy_undo_stack.pop_back()
}
/// Pop the most recent redo snapshot, or `None` when the stack is empty.
pub fn pop_redo(&mut self) -> Option<NodeNetworkInterface> {
self.legacy_redo_stack.pop_back()
self.lagacy_redo_stack.pop_back()
}
/// Drop the most recently pushed undo snapshot (used to cancel a transaction that ended up unmodified).
pub fn discard_last_undo(&mut self) {
self.legacy_undo_stack.pop_back();
self.lagacy_undo_stack.pop_back();
}
/// Clear the redo stack, called when a fresh edit invalidates the redo future.
pub fn clear_redo(&mut self) {
self.legacy_redo_stack.clear();
self.lagacy_redo_stack.clear();
}
/// Add the resources referenced by every snapshot in both history stacks into `resources`, so
/// history-only resources stay alive for legacy undo/redo.
pub fn collect_used_resources(&self, resources: &mut HashSet<ResourceId>) {
for interface in self.legacy_undo_stack.iter().chain(&self.legacy_redo_stack) {
for interface in self.lagacy_undo_stack.iter().chain(&self.lagacy_redo_stack) {
interface.collect_used_resources(resources);
}
}
@@ -11,8 +11,9 @@ use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::prelude::*;
use glam::{DAffine2, IVec2};
use graph_craft::document::NodeId;
use graphene_std::Appearance;
use graphene_std::Color;
use graphene_std::Graphic;
use graphene_std::list::List;
use graphene_std::raster::BlendMode;
use graphene_std::raster::Image;
use graphene_std::transform::Footprint;
@@ -244,10 +245,14 @@ pub enum DocumentMessage {
vector_data: HashMap<NodeId, Arc<Vector>>,
},
// `Message` is only serialized at `editor_wrapper.rs`, and only inputs from JS pass through it.
// `UpdateAppearanceAttributes` is produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so it never reaches that serialization point.
// `UpdateFillAttributes` and `UpdateStrokeAttributes` are produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so it never reaches that serialization point.
#[serde(skip)]
UpdateAppearanceAttributes {
appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
UpdateFillAttributes {
fill_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
},
#[serde(skip)]
UpdateStrokeAttributes {
stroke_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
},
Undo,
UngroupSelectedLayers,
@@ -34,10 +34,10 @@ use crate::node_graph_executor::NodeGraphExecutor;
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::application_io::wgpu_available;
use graph_craft::descriptor;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
use graph_craft::list;
use graphene_std::Cover;
use graphene_std::graphic::is_paint_present;
use graphene_std::math::quad::Quad;
use graphene_std::path_bool_nodes::boolean_intersect;
use graphene_std::raster::BlendMode;
@@ -103,7 +103,6 @@ pub struct DocumentMessageHandler {
pub properties_panel_collapsed_sections: Vec<NodeId>,
/// The full Git commit hash of the Graphite repository that was used to build the editor.
/// We save this to provide a hint about which version of the editor was used to create the document.
#[serde(skip_deserializing, default)]
pub commit_hash: String,
/// The current pan, tilt, and zoom state of the viewport's view of the document canvas.
pub document_ptz: PTZ,
@@ -126,7 +125,7 @@ pub struct DocumentMessageHandler {
/// network path, the node itself, and its original relative gradient. The deferred migration removes each entry as its bake lands.
/// Transient migration state, but persisted in the saved document so unfinished bakes retry on the next open instead of losing placement.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) pending_gradient_bbox_bake: Vec<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient)>,
pub(crate) pending_gradient_bbox_bake: Vec<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::Gradient)>,
// =============================================
// Fields omitted from the saved document format
@@ -1503,9 +1502,9 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
.collect();
self.network_interface.update_vector_data(layer_vector_data);
}
DocumentMessage::UpdateAppearanceAttributes { appearance_attributes } => {
DocumentMessage::UpdateFillAttributes { fill_attributes } => {
// Convert NodeId keys to LayerNodeIdentifier keys, filtering to only layers
let layer_appearance_attributes = appearance_attributes
let layer_fill_attributes = fill_attributes
.into_iter()
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id))
.filter_map(|(node_id, attrs)| {
@@ -1515,7 +1514,21 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
})
})
.collect();
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
self.network_interface.update_fill_attributes(layer_fill_attributes);
}
DocumentMessage::UpdateStrokeAttributes { stroke_attributes } => {
// Convert NodeId keys to LayerNodeIdentifier keys, filtering to only layers
let layer_stroke_attributes = stroke_attributes
.into_iter()
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id))
.filter_map(|(node_id, attrs)| {
self.network_interface.is_layer(&node_id, &[]).then(|| {
let layer = LayerNodeIdentifier::new(node_id, &self.network_interface);
(layer, attrs)
})
})
.collect();
self.network_interface.update_stroke_attributes(layer_stroke_attributes);
}
DocumentMessage::Undo => {
if self.network_interface.transaction_status() != TransactionStatus::Finished {
@@ -1699,7 +1712,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
DocumentMessage::ZoomCanvasToFitAll => {
let bounds = if self.graph_view_overlay_open {
self.network_interface.all_nodes_bounding_box(&self.breadcrumb_network_path)
self.network_interface.all_nodes_bounding_box(&self.breadcrumb_network_path).cloned()
} else {
self.network_interface.document_bounds_document_space(true)
};
@@ -2401,26 +2414,22 @@ impl DocumentMessageHandler {
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, true, responses);
}
/// Installs a history snapshot as the active network interface, carrying over the current view state and structure load, and returns the replaced interface.
fn install_history_snapshot(&mut self, mut network_interface: NodeNetworkInterface, viewport: &ViewportMessageHandler) -> NodeNetworkInterface {
pub fn undo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
// If there is no history return and don't broadcast SelectionChanged
let mut network_interface = self.history.pop_undo()?;
// Set the previous network navigation metadata to the current navigation metadata
network_interface.copy_all_navigation_metadata(&self.network_interface);
std::mem::swap(&mut network_interface.resolved_types, &mut self.network_interface.resolved_types);
// Update the metadata transform based on document PTZ
//Update the metadata transform based on document PTZ
let transform = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
network_interface.set_document_to_viewport_transform(transform);
// Ensure document structure is loaded so that updating the selected nodes has the correct metadata
network_interface.load_structure();
std::mem::replace(&mut self.network_interface, network_interface)
}
pub fn undo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
// If there is no history return and don't broadcast SelectionChanged
let network_interface = self.history.pop_undo()?;
let previous_network = self.install_history_snapshot(network_interface, viewport);
let previous_network = std::mem::replace(&mut self.network_interface, network_interface);
// Push the UpdateOpenDocumentsList message to the bus in order to update the save status of the open documents
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
@@ -2445,9 +2454,17 @@ impl DocumentMessageHandler {
pub fn redo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
// If there is no history return and don't broadcast SelectionChanged
let network_interface = self.history.pop_redo()?;
let previous_network = self.install_history_snapshot(network_interface, viewport);
let mut network_interface = self.history.pop_redo()?;
// Set the previous network navigation metadata to the current navigation metadata
network_interface.copy_all_navigation_metadata(&self.network_interface);
std::mem::swap(&mut network_interface.resolved_types, &mut self.network_interface.resolved_types);
//Update the metadata transform based on document PTZ
let transform = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
network_interface.set_document_to_viewport_transform(transform);
let previous_network = std::mem::replace(&mut self.network_interface, network_interface);
// Push the UpdateOpenDocumentsList message to the bus in order to update the save status of the open documents
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
@@ -2600,11 +2617,7 @@ impl DocumentMessageHandler {
// If there's already a boolean operation on the selected layer, update it with the new operation
if let (Some(upstream_boolean_op), Some(only_selected_layer)) = (upstream_boolean_op, only_selected_layer) {
network_interface.set_input(
&InputConnector::node(upstream_boolean_op, graphene_std::path_bool_nodes::boolean_operation::OperationInput),
NodeInput::value(TaggedValue::BooleanOperation(operation), false),
&[],
);
network_interface.set_input(&InputConnector::node(upstream_boolean_op, 1), NodeInput::value(TaggedValue::BooleanOperation(operation), false), &[]);
responses.add(NodeGraphMessage::RunDocumentGraph);
@@ -2735,7 +2748,7 @@ impl DocumentMessageHandler {
}
/// For each selected layer, splits its fill and stroke into two stacked layers connected
/// to a shared `Solidify Stroke` node via two `Item at Index` nodes (indices 0 and 1).
/// to a shared `Solidify Stroke` node via two `Index Elements` nodes (indices 0 and 1).
/// Layers with only a stroke get just a `Solidify Stroke` added.
/// Layers with only a fill, or neither, are left untouched.
fn handle_expand_fill_stroke_on_selected_layers(&mut self, responses: &mut VecDeque<Message>) {
@@ -2745,24 +2758,25 @@ impl DocumentMessageHandler {
}
let solidify_stroke_definition = document_node_definitions::resolve_proto_node_type(graphene_std::vector::solidify_stroke::IDENTIFIER).expect("Solidify Stroke node should exist");
let item_at_index_definition = document_node_definitions::resolve_proto_node_type(graphene_std::graphic::item_at_index::IDENTIFIER).expect("Item at Index node should exist");
let index_elements_definition = document_node_definitions::resolve_proto_node_type(graphene_std::graphic::index_elements::IDENTIFIER).expect("Index Elements node should exist");
let mut resulting_layers: Vec<NodeId> = Vec::new();
for layer in selected_layers {
if !self.network_interface.document_metadata().layer_vector_data.contains_key(&layer) {
let Some(vector_data) = self.network_interface.document_metadata().layer_vector_data.get(&layer) else {
resulting_layers.push(layer.to_node());
continue;
}
};
let stroke = vector_data.stroke.as_ref();
let appearance = self.network_interface.document_metadata().layer_appearance_attributes.get(&layer);
let fill_graphic_list = self.network_interface.document_metadata().layer_fill_attributes.get(&layer);
let stroke_graphic_list = self.network_interface.document_metadata().layer_stroke_attributes.get(&layer);
let has_fill = appearance.is_some_and(|appearance| appearance.has_painted_cover(Cover::Fill));
// A visible stroke needs both renderable geometry (non-zero weight) and paint that draws something
let has_stroke = appearance.is_some_and(|appearance| {
appearance.first_coverage_of(Cover::Stroke).is_some_and(|coverage| coverage.stroke_params().has_renderable_stroke())
&& appearance.first_paint_of(Cover::Stroke).is_some_and(|paint| !paint.is_guaranteed_fully_transparent())
});
let has_fill = fill_graphic_list.is_some_and(|list| is_paint_present(list));
// `Vector.stroke` captures stroke geometry, even with weight 0 or transparent paint.
// So stroke visibility must be checked from `ATTR_STROKE`, the paint source of truth.
let stroke_visible = stroke_graphic_list.is_some_and(|list| list.element(0).is_some_and(|g| !g.is_fully_transparent()));
let has_stroke = stroke.as_ref().is_some_and(|s| s.has_renderable_stroke()) && stroke_visible;
// No stroke means there's nothing to solidify. Fill-only layers are already in the desired form, so skip.
if !has_stroke {
@@ -2777,7 +2791,7 @@ impl DocumentMessageHandler {
if has_fill && has_stroke {
let (existing_index, new_index) = (0_f64, 1_f64);
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(existing_index), false))]);
let existing_index_template = index_elements_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(existing_index), false))]);
let existing_index_id = NodeId::new();
self.network_interface.insert_node(existing_index_id, existing_index_template, &[]);
self.network_interface.move_node_to_chain_start(&existing_index_id, layer, &[], false);
@@ -2799,13 +2813,12 @@ impl DocumentMessageHandler {
self.network_interface.set_display_name(&new_layer_id, original_name, &[]);
}
let new_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(new_index), false))]);
let new_index_template = index_elements_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(new_index), false))]);
let new_index_id = NodeId::new();
self.network_interface.insert_node(new_index_id, new_index_template, &[]);
self.network_interface.move_node_to_chain_start(&new_index_id, new_layer, &[], false);
self.network_interface
.create_wire(&OutputConnector::primary_output(solidify_id), &InputConnector::primary_input(new_index_id), &[]);
self.network_interface.create_wire(&OutputConnector::node(solidify_id, 0), &InputConnector::node(new_index_id, 0), &[]);
resulting_layers.push(layer.to_node());
resulting_layers.push(new_layer.to_node());
@@ -3395,11 +3408,6 @@ impl DocumentMessageHandler {
let selected_nodes = self.network_interface.selected_nodes();
let selected_layers_except_artboards = selected_nodes.selected_layers_except_artboards(&self.network_interface);
// A layer whose chain cannot carry blending nodes has nowhere to put the value, so it disqualifies the whole selection
let all_layers_support_blending = selected_nodes
.selected_layers_except_artboards(&self.network_interface)
.all(|layer| self.network_interface.layer_hosts_blending_nodes(&layer.to_node(), &[]));
// Look up the current opacity and blend mode of the selected layers (if any), and split the iterator into the first tuple and the rest.
let mut blending_options = selected_layers_except_artboards.map(|layer| {
(
@@ -3411,8 +3419,8 @@ impl DocumentMessageHandler {
let first_blending_options = blending_options.next();
let result_blending_options = blending_options;
// If there are no selected layers, or any of them cannot host the nodes, disable the opacity and blend mode widgets.
let disabled = first_blending_options.is_none() || !all_layers_support_blending;
// If there are no selected layers, disable the opacity and blend mode widgets.
let disabled = first_blending_options.is_none();
// Amongst the selected layers, check if the opacities and blend modes are identical across all layers.
// The result is setting `option` and `blend_mode` to Some value if all their values are identical, or None if they are not.
@@ -3575,7 +3583,7 @@ impl DocumentMessageHandler {
// Showing only compatible types for the layer based on the output type of the node upstream from its horizontal input
let compatible_type = selected_layer.and_then(|layer| {
self.network_interface
.upstream_output_connector(&InputConnector::layer_secondary_input(layer.to_node()), &[])
.upstream_output_connector(&InputConnector::node(layer.to_node(), 1), &[])
.and_then(|upstream_output| self.network_interface.output_type(&upstream_output, &[]).add_node_string())
});
@@ -3781,7 +3789,7 @@ impl DocumentMessageHandler {
/// Create a network interface with a single export
fn default_document_network_interface() -> NodeNetworkInterface {
let mut network_interface = NodeNetworkInterface::default();
network_interface.add_export(TaggedValue::TypeDefault(list!(graphene_std::Artboard)), -1, "", &[]);
network_interface.add_export(TaggedValue::TypeDefault(descriptor!(graphene_std::list::List<graphene_std::Artboard>)), -1, "", &[]);
network_interface
}
@@ -3999,7 +4007,7 @@ mod document_message_handler_tests {
#[test]
fn pending_gradient_bakes_round_trip_through_serialization() {
let document = DocumentMessageHandler {
pending_gradient_bbox_bake: vec![(vec![NodeId(7)], NodeId(42), graphic_types::migrations::legacy::LegacyGradient::default())],
pending_gradient_bbox_bake: vec![(vec![NodeId(7)], NodeId(42), graphic_types::migrations::legacy::Gradient::default())],
..Default::default()
};
@@ -4310,40 +4318,4 @@ mod document_message_handler_tests {
Dist: {distance} (should be < 1)"
);
}
// Grouping choreography transiently disconnects the stack wire, and the stored default for that connector
// must stay an empty list rather than any value which materializes as a one-element phantom in the stack
#[tokio::test]
async fn grouping_adds_no_phantom_element_to_the_stack() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
})
.await;
let instrumented = editor.eval_graph().await.unwrap();
// The emptiness guards keep these assertions honest: a wrong `Output` type on `grab_all_input` yields no records at all, which would otherwise pass without checking anything
let base_lengths: Vec<usize> = instrumented
.grab_all_input::<graphene_std::graphic::extend::BaseInput, graphene_std::list::List<graphene_std::Graphic>>(&editor.runtime)
.map(|base| base.len())
.collect();
assert!(!base_lengths.is_empty(), "Instrumentation should have recorded at least one stack base");
assert!(base_lengths.iter().all(|&len| len == 0), "Every stack base should be empty, found lengths {base_lengths:?}");
let news: Vec<graphene_std::list::List<graphene_std::Graphic>> = instrumented
.grab_all_input::<graphene_std::graphic::extend::NewInput, graphene_std::list::List<graphene_std::Graphic>>(&editor.runtime)
.collect();
assert!(!news.is_empty(), "Instrumentation should have recorded at least one stacked element list");
let phantom_count = news
.iter()
.flat_map(|new| new.iter_element_values())
.filter(|graphic| matches!(graphic, graphene_std::Graphic::None(_)))
.count();
assert_eq!(phantom_count, 0, "No stacked element should be a phantom None graphic");
}
}
@@ -10,8 +10,8 @@ use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Image;
use graphene_std::subpath::Subpath;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
use graphene_std::vector::{Gradient, PointId, VectorModificationType};
use graphene_std::vector::style::{GradientSpreadMethod, GradientType, Stroke};
use graphene_std::vector::{GradientStops, PointId, VectorModificationType};
#[impl_message(Message, DocumentMessage, GraphOperation)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
@@ -20,16 +20,11 @@ pub enum GraphOperationMessage {
layer: LayerNodeIdentifier,
color: Option<Color>,
},
ColorValueSet {
layer: LayerNodeIdentifier,
color: Color,
},
FillGradientSet {
layer: LayerNodeIdentifier,
#[serde(skip)]
gradient: Gradient,
gradient_form: GradientForm,
gradient_settings: GradientSettings,
gradient: GradientStops,
gradient_type: GradientType,
spread_method: GradientSpreadMethod,
transform: DAffine2,
},
BlendingFillSet {
@@ -38,44 +33,19 @@ pub enum GraphOperationMessage {
},
GradientStopsSet {
layer: LayerNodeIdentifier,
#[serde(skip)]
stops: Gradient,
},
GradientPositionsSet {
layer: LayerNodeIdentifier,
positions: Vec<f64>,
},
GradientMidpointsSet {
layer: LayerNodeIdentifier,
midpoints: Vec<f64>,
stops: GradientStops,
},
GradientTransformSet {
layer: LayerNodeIdentifier,
transform: DAffine2,
},
GradientFormSet {
GradientTypeSet {
layer: LayerNodeIdentifier,
gradient_form: GradientForm,
gradient_type: GradientType,
},
GradientSpreadSet {
GradientSpreadMethodSet {
layer: LayerNodeIdentifier,
gradient_spread: GradientSpread,
},
GradientSpaceSet {
layer: LayerNodeIdentifier,
gradient_space: GradientSpace,
},
GradientCyclicSet {
layer: LayerNodeIdentifier,
gradient_cyclic: bool,
},
GradientHueDirectionSet {
layer: LayerNodeIdentifier,
gradient_hue_direction: GradientHueDirection,
},
GradientInterpolationSet {
layer: LayerNodeIdentifier,
gradient_interpolation: GradientInterpolation,
spread_method: GradientSpreadMethod,
},
OpacitySet {
layer: LayerNodeIdentifier,
@@ -93,10 +63,6 @@ pub enum GraphOperationMessage {
color: Option<Color>,
stroke: Stroke,
},
StrokeOrderSet {
layer: LayerNodeIdentifier,
paint_order: PaintOrder,
},
TransformChange {
layer: LayerNodeIdentifier,
transform: DAffine2,
@@ -1,19 +1,19 @@
use super::transform_utils;
use super::utility_types::{ModifyInputsContext, set_stroke_paint_order};
use super::utility_types::ModifyInputsContext;
use crate::consts::{LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP};
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{BLEND_PATH_INPUT_INDEX, DefinitionIdentifier};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::descriptor;
use graph_craft::document::{NodeId, NodeInput};
use graph_craft::list;
use graphene_std::list::List;
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{Gradient, GradientForm, GradientSettings, GradientSpace, GradientSpread, GradientStop, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::style::{GradientSpreadMethod, GradientStop, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::{Artboard, Color};
#[derive(ExtractField)]
@@ -39,20 +39,15 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
modify_inputs.fill_color_set(color);
}
}
GraphOperationMessage::ColorValueSet { layer, color } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.color_value_set(color);
}
}
GraphOperationMessage::FillGradientSet {
layer,
gradient,
gradient_form,
gradient_settings,
gradient_type,
spread_method,
transform,
} => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.fill_gradient_set(gradient, gradient_form, gradient_settings, transform);
modify_inputs.fill_gradient_set(gradient, gradient_type, spread_method, transform);
}
}
GraphOperationMessage::BlendingFillSet { layer, fill } => {
@@ -65,49 +60,19 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
modify_inputs.gradient_stops_set(stops);
}
}
GraphOperationMessage::GradientPositionsSet { layer, positions } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_positions_set(positions);
}
}
GraphOperationMessage::GradientMidpointsSet { layer, midpoints } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_midpoints_set(midpoints);
}
}
GraphOperationMessage::GradientTransformSet { layer, transform } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_transform_set(transform);
}
}
GraphOperationMessage::GradientFormSet { layer, gradient_form } => {
GraphOperationMessage::GradientTypeSet { layer, gradient_type } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_form_set(gradient_form);
modify_inputs.gradient_type_set(gradient_type);
}
}
GraphOperationMessage::GradientSpreadSet { layer, gradient_spread } => {
GraphOperationMessage::GradientSpreadMethodSet { layer, spread_method } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_spread_set(gradient_spread);
}
}
GraphOperationMessage::GradientSpaceSet { layer, gradient_space } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_space_set(gradient_space);
}
}
GraphOperationMessage::GradientCyclicSet { layer, gradient_cyclic } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_cyclic_set(gradient_cyclic);
}
}
GraphOperationMessage::GradientHueDirectionSet { layer, gradient_hue_direction } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_hue_direction_set(gradient_hue_direction);
}
}
GraphOperationMessage::GradientInterpolationSet { layer, gradient_interpolation } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_interpolation_set(gradient_interpolation);
modify_inputs.gradient_spread_method_set(spread_method);
}
}
GraphOperationMessage::OpacitySet { layer, opacity } => {
@@ -131,17 +96,6 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
modify_inputs.stroke_set(color, stroke);
}
}
GraphOperationMessage::StrokeOrderSet { layer, paint_order } => {
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
let Some(stroke_node_id) = ModifyInputsContext::locate_node_in_layer_chain(&stroke_reference, layer, network_interface) else {
return;
};
if set_stroke_paint_order(network_interface, &[], stroke_node_id, paint_order) {
responses.add(PropertiesPanelMessage::Refresh);
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SendGraph);
}
}
GraphOperationMessage::TransformChange {
layer,
transform,
@@ -178,7 +132,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
}
}
GraphOperationMessage::SetUpstreamToChain { layer } => {
let Some(OutputConnector::Node { node_id: first_chain_node, .. }) = network_interface.upstream_output_connector(&InputConnector::layer_secondary_input(layer.to_node()), &[]) else {
let Some(OutputConnector::Node { node_id: first_chain_node, .. }) = network_interface.upstream_output_connector(&InputConnector::node(layer.to_node(), 1), &[]) else {
return;
};
@@ -226,16 +180,16 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
}
// Set the bottom input of the artboard back to artboard
let bottom_input = NodeInput::type_default(list!(Artboard), true);
network_interface.set_input(&InputConnector::primary_input(artboard_layer.to_node()), bottom_input, &[]);
let bottom_input = NodeInput::type_default(descriptor!(List<Artboard>), true);
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 0), bottom_input, &[]);
} else {
// We have some non layers (e.g. just a rectangle node). We disconnect the bottom input and connect it to the left input.
network_interface.disconnect_input(&InputConnector::primary_input(artboard_layer.to_node()), &[]);
network_interface.set_input(&InputConnector::layer_secondary_input(artboard_layer.to_node()), primary_input, &[]);
network_interface.disconnect_input(&InputConnector::node(artboard_layer.to_node(), 0), &[]);
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 1), primary_input, &[]);
// Set the bottom input of the artboard back to artboard
let bottom_input = NodeInput::type_default(list!(Artboard), true);
network_interface.set_input(&InputConnector::primary_input(artboard_layer.to_node()), bottom_input, &[]);
let bottom_input = NodeInput::type_default(descriptor!(List<Artboard>), true);
network_interface.set_input(&InputConnector::node(artboard_layer.to_node(), 0), bottom_input, &[]);
}
}
responses.add_front(NodeGraphMessage::SelectedNodesSet { nodes: vec![id] });
@@ -258,14 +212,11 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
let layer = modify_inputs.create_layer(id);
// Insert the main chain node (Blend or Morph) depending on whether a blend count is provided, referencing
// its control path input by the Blend template's named position or the Morph proto node's parameter symbol
let (path_input_connector, layer_alias, path_alias) = if let Some(count) = blend_count {
let blend_node_id = modify_inputs.insert_blend_data(layer, count as f64);
(InputConnector::node_at_index(blend_node_id, BLEND_PATH_INPUT_INDEX), "Blend", "Blend Path")
// Insert the main chain node (Blend or Morph) depending on whether a blend count is provided
let (chain_node_id, layer_alias, path_alias) = if let Some(count) = blend_count {
(modify_inputs.insert_blend_data(layer, count as f64), "Blend", "Blend Path")
} else {
let morph_node_id = modify_inputs.insert_morph_data(layer);
(InputConnector::node(morph_node_id, graphene_std::vector::morph::PathInput), "Morph", "Morph Path")
(modify_inputs.insert_morph_data(layer), "Morph", "Morph Path")
};
// Create the control path layer (Path → Auto-Tangents → Origins to Polyline)
@@ -275,9 +226,9 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
network_interface.move_layer_to_stack(control_path_layer, parent, insert_index, &[]);
network_interface.move_layer_to_stack(layer, parent, insert_index + 1, &[]);
// Connect the Path node's output to the chain node's control path input.
// Connect the Path node's output to the chain node's path parameter input (input 4 for both Morph and Blend).
// Done after move_layer_to_stack so chain nodes have correct positions when converted to absolute.
network_interface.set_input(&path_input_connector, NodeInput::node(path_node_id, 0), &[]);
network_interface.set_input(&InputConnector::node(chain_node_id, 4), NodeInput::node(path_node_id, 0), &[]);
responses.add(NodeGraphMessage::SetDisplayNameImpl {
node_id: id,
@@ -295,29 +246,29 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
control_path_id,
} => {
// Find the chain node (Blend or Morph, first in chain of the layer)
let Some(OutputConnector::Node { node_id: chain_node, .. }) = network_interface.upstream_output_connector(&InputConnector::layer_secondary_input(interpolation_layer_id), &[]) else {
let Some(OutputConnector::Node { node_id: chain_node, .. }) = network_interface.upstream_output_connector(&InputConnector::node(interpolation_layer_id, 1), &[]) else {
log::error!("Could not find chain node for layer {interpolation_layer_id}");
return;
};
// Get what feeds into the chain node's primary input (the children stack)
let Some(OutputConnector::Node { node_id: children_id, output_index }) = network_interface.upstream_output_connector(&InputConnector::primary_input(chain_node), &[]) else {
let Some(OutputConnector::Node { node_id: children_id, output_index }) = network_interface.upstream_output_connector(&InputConnector::node(chain_node, 0), &[]) else {
log::error!("Could not find children stack feeding chain node {chain_node}");
return;
};
// Find the deepest node in the control path layer's chain (Origins to Polyline)
let mut deepest_chain_node = None;
let mut current_connector = InputConnector::layer_secondary_input(control_path_id);
let mut current_connector = InputConnector::node(control_path_id, 1);
while let Some(OutputConnector::Node { node_id, .. }) = network_interface.upstream_output_connector(&current_connector, &[]) {
deepest_chain_node = Some(node_id);
current_connector = InputConnector::primary_input(node_id);
current_connector = InputConnector::node(node_id, 0);
}
// Connect children to the deepest chain node's input 0 (or the layer's input 1 if no chain)
let target_connector = match deepest_chain_node {
Some(node_id) => InputConnector::primary_input(node_id),
None => InputConnector::layer_secondary_input(control_path_id),
Some(node_id) => InputConnector::node(node_id, 0),
None => InputConnector::node(control_path_id, 1),
};
network_interface.set_input(&target_connector, NodeInput::node(children_id, output_index), &[]);
@@ -348,7 +299,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
responses.add(NodeGraphMessage::AddNodes { nodes, new_ids });
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::layer_secondary_input(layer.to_node()),
input_connector: InputConnector::node(layer.to_node(), 1),
input: NodeInput::node(first_new_node_id, 0),
});
}
@@ -359,7 +310,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
GraphOperationMessage::NewColorFillLayer { node_id, color, parent, insert_index } => {
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
let layer = modify_inputs.create_layer(node_id);
modify_inputs.insert_color_value(color, layer, InputConnector::layer_secondary_input(layer.to_node()));
modify_inputs.insert_color_value(color, layer);
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
responses.add(NodeGraphMessage::RunDocumentGraph);
}
@@ -417,7 +368,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
input_node: NodeInput::node(document_node.inputs[1].as_node().unwrap_or_default(), 0),
output_nodes: network_interface
.outward_wires(&[])
.and_then(|outward_wires| outward_wires.get(&OutputConnector::primary_output(artboard.to_node())))
.and_then(|outward_wires| outward_wires.get(&OutputConnector::node(artboard.to_node(), 0)))
.cloned()
.unwrap_or_default(),
merge_node: node_id,
@@ -443,7 +394,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
for artboard in &artboard_data {
// Modify downstream connections
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::layer_secondary_input(artboard.1.merge_node),
input_connector: InputConnector::node(artboard.1.merge_node, 1),
input: NodeInput::node(artboard.1.input_node.as_node().unwrap_or_default(), 0),
});
@@ -451,7 +402,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
for outward_wire in &artboard.1.output_nodes {
let input = NodeInput::node(artboard_data[artboard.0].merge_node, 0);
let input_connector = match artboard_data.get(&outward_wire.node_id().unwrap_or_default()) {
Some(artboard_info) => InputConnector::node_at_index(artboard_info.merge_node, outward_wire.input_index()),
Some(artboard_info) => InputConnector::node(artboard_info.merge_node, outward_wire.input_index()),
_ => *outward_wire,
};
responses.add(NodeGraphMessage::SetInput { input_connector, input });
@@ -511,14 +462,18 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
};
placement_transform.translation = placement_transform.translation.round();
let gradient_info = SvgGradientInfo {
graphite_stops: extract_graphite_gradient_stops(&svg),
spaces: extract_gradient_spaces(&svg),
};
let graphite_gradient_stops = extract_graphite_gradient_stops(&svg);
// Pass identity so each leaf layer receives only its SVG-native transform from `abs_transform`.
// The placement offset is then applied once to the root group layer below.
import_usvg_node(&mut modify_inputs, &usvg::Node::Group(Box::new(tree.root().clone())), id, parent, insert_index, &gradient_info);
import_usvg_node(
&mut modify_inputs,
&usvg::Node::Group(Box::new(tree.root().clone())),
id,
parent,
insert_index,
&graphite_gradient_stops,
);
// After import, `layer_node` is set to the root group. Apply the placement transform to it
// (skipped automatically when identity, so file-open with content at origin creates no Transform node).
@@ -550,136 +505,11 @@ fn usvg_transform(c: usvg::Transform) -> DAffine2 {
const GRAPHITE_NAMESPACE: &str = "https://graphite.art";
/// Gradient information pre-parsed from the raw SVG XML, carrying what usvg's simplified tree drops.
struct SvgGradientInfo {
/// Real stops, keyed by gradient element `id`, for gradients Graphite exported with midpoint curve data.
graphite_stops: HashMap<String, Gradient>,
/// Gradient spaces, keyed by gradient element `id`, resolved from the `color-interpolation` property.
spaces: HashMap<String, GradientSpace>,
}
/// Pre-parses the raw SVG XML to resolve each gradient's inherited `color-interpolation` property, which usvg's
/// tree does not carry. Only `linearRGB` selects the linear space; `auto` and `sRGB` (browsers treat the
/// user-agent-defined `auto` as `sRGB`) mean gamma, as does any unrecognized value.
fn extract_gradient_spaces(svg: &str) -> HashMap<String, GradientSpace> {
let mut result = HashMap::new();
// Quick check: gradients in an SVG that never mentions `color-interpolation` all take the sRGB default
if !svg.contains("color-interpolation") {
return result;
}
let doc = match usvg::roxmltree::Document::parse(svg) {
Ok(doc) => doc,
Err(_) => return result,
};
// The document's `<style>` blocks apply to every element, so parse them once up front
let mut stylesheet = simplecss::StyleSheet::new();
for style_element in doc.descendants().filter(|node| node.tag_name().name() == "style") {
if !matches!(style_element.attribute("type"), None | Some("") | Some("text/css")) {
continue;
}
for text in style_element.children().filter(|child| child.is_text()).filter_map(|child| child.text()) {
stylesheet.parse_more(text);
}
}
for node in doc.descendants() {
match node.tag_name().name() {
"linearGradient" | "radialGradient" => {}
_ => continue,
}
if let Some(gradient_id) = node.attribute("id")
&& let Some(gradient_space) = resolve_color_interpolation(node, &stylesheet)
{
result.insert(gradient_id.to_string(), gradient_space);
}
}
result
}
/// The `color-interpolation` in effect for an element: the nearest self-or-ancestor declaration, taking each
/// element's own winning declaration per [`declared_color_interpolation`]'s cascade order.
fn resolve_color_interpolation(element: usvg::roxmltree::Node, stylesheet: &simplecss::StyleSheet) -> Option<GradientSpace> {
let mut next = Some(element);
while let Some(element) = next {
match declared_color_interpolation(element, stylesheet) {
Some("linearRGB") => return Some(GradientSpace::RgbLinear),
// `inherit` defers to the ancestors like an undeclared element
Some("inherit") | None => {}
Some(_) => return Some(GradientSpace::RgbGamma),
}
next = element.parent_element();
}
None
}
/// The winning `color-interpolation` declaration on a single element per the CSS cascade: `!important` declarations
/// beat normal ones, the inline `style` beats the `<style>` rules (already specificity-sorted, so their last match
/// wins), and the presentation attribute yields to them all. Later declarations win priority ties.
fn declared_color_interpolation<'a>(element: usvg::roxmltree::Node<'a, '_>, stylesheet: &simplecss::StyleSheet<'a>) -> Option<&'a str> {
let mut winner: Option<(u8, &'a str)> = None;
let mut consider = |priority: u8, value: &'a str| {
if winner.is_none_or(|(existing, _)| priority >= existing) {
winner = Some((priority, value));
}
};
if let Some(value) = element.attribute("color-interpolation") {
consider(0, value.trim());
}
for rule in stylesheet.rules.iter().filter(|rule| rule.selector.matches(&CssElement(element))) {
for declaration in rule.declarations.iter().filter(|declaration| declaration.name == "color-interpolation") {
consider(if declaration.important { 3 } else { 1 }, declaration.value);
}
}
if let Some(style) = element.attribute("style") {
for declaration in simplecss::DeclarationTokenizer::from(style).filter(|declaration| declaration.name == "color-interpolation") {
consider(if declaration.important { 4 } else { 2 }, declaration.value);
}
}
winner.map(|(_, value)| value)
}
/// Adapts a roxmltree element to simplecss's selector-matching interface.
struct CssElement<'a, 'input>(usvg::roxmltree::Node<'a, 'input>);
impl simplecss::Element for CssElement<'_, '_> {
fn parent_element(&self) -> Option<Self> {
self.0.parent_element().map(CssElement)
}
fn prev_sibling_element(&self) -> Option<Self> {
self.0.prev_sibling_element().map(CssElement)
}
fn has_local_name(&self, local_name: &str) -> bool {
self.0.tag_name().name() == local_name
}
fn attribute_matches(&self, local_name: &str, operator: simplecss::AttributeOperator) -> bool {
self.0.attribute(local_name).is_some_and(|value| operator.matches(value))
}
fn pseudo_class_matches(&self, class: simplecss::PseudoClass) -> bool {
matches!(class, simplecss::PseudoClass::FirstChild) && self.0.prev_sibling_element().is_none()
}
}
/// Pre-parses the raw SVG XML to extract gradient stops that have `graphite:midpoint` attributes.
/// Graphite exports gradients with midpoint curve data by writing interpolated approximation stops
/// alongside the real stops. Real stops are tagged with `graphite:midpoint` attributes.
/// Returns a map from gradient element `id` to `Gradient` containing only the real stops.
fn extract_graphite_gradient_stops(svg: &str) -> HashMap<String, Gradient> {
/// Returns a map from gradient element `id` to `GradientStops` containing only the real stops.
fn extract_graphite_gradient_stops(svg: &str) -> HashMap<String, GradientStops> {
let mut result = HashMap::new();
// Quick check: if the SVG doesn't reference `graphite:midpoint` at all, skip parsing
@@ -725,7 +555,7 @@ fn extract_graphite_gradient_stops(svg: &str) -> HashMap<String, Gradient> {
}
if has_any_midpoint && !real_stops.is_empty() {
result.insert(gradient_id, Gradient::new(real_stops));
result.insert(gradient_id, GradientStops::new(real_stops));
}
}
@@ -740,7 +570,7 @@ fn parse_hex_stop_color(hex: &str, opacity: f32) -> Option<Color> {
let r = u8::from_str_radix(&hex[0..2], 16).ok()? as f32 / 255.;
let g = u8::from_str_radix(&hex[2..4], 16).ok()? as f32 / 255.;
let b = u8::from_str_radix(&hex[4..6], 16).ok()? as f32 / 255.;
Some(Color::from_gamma_srgb_channels(r, g, b, opacity))
Some(Color::from_rgbaf32_unchecked(r, g, b, opacity))
}
/// Import a usvg node as the root of an SVG import operation.
@@ -749,7 +579,14 @@ fn parse_hex_stop_color(hex: &str, opacity: f32) -> Option<Color> {
/// interact with any existing layers in the parent stack. All descendant layers use a lightweight
/// O(n) import path that skips collision detection and instead calculates positions directly from
/// the known tree structure.
fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, id: NodeId, parent: LayerNodeIdentifier, insert_index: usize, gradient_info: &SvgGradientInfo) {
fn import_usvg_node(
modify_inputs: &mut ModifyInputsContext,
node: &usvg::Node,
id: NodeId,
parent: LayerNodeIdentifier,
insert_index: usize,
graphite_gradient_stops: &HashMap<String, GradientStops>,
) {
let layer = modify_inputs.create_layer(id);
modify_inputs.network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
@@ -769,7 +606,7 @@ fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
modify_inputs.import = true;
for child in group.children() {
let extent = import_usvg_node_inner(modify_inputs, child, NodeId::new(), layer, 0, gradient_info, &mut group_extents_map);
let extent = import_usvg_node_inner(modify_inputs, child, NodeId::new(), layer, 0, graphite_gradient_stops, &mut group_extents_map);
child_extents_svg_order.push(extent);
}
@@ -788,7 +625,7 @@ fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
modify_inputs.network_interface.unload_all_nodes_bounding_box(&[]);
}
usvg::Node::Path(path) => {
import_usvg_path(modify_inputs, node, path, layer, gradient_info);
import_usvg_path(modify_inputs, node, path, layer, graphite_gradient_stops);
}
usvg::Node::Image(_image) => {
warn!("Skip image");
@@ -812,7 +649,7 @@ fn import_usvg_node_inner(
id: NodeId,
parent: LayerNodeIdentifier,
insert_index: usize,
gradient_info: &SvgGradientInfo,
graphite_gradient_stops: &HashMap<String, GradientStops>,
group_extents_map: &mut HashMap<LayerNodeIdentifier, Vec<u32>>,
) -> u32 {
let layer = modify_inputs.create_layer(id);
@@ -823,7 +660,7 @@ fn import_usvg_node_inner(
usvg::Node::Group(group) => {
let mut child_extents: Vec<u32> = Vec::new();
for child in group.children() {
let extent = import_usvg_node_inner(modify_inputs, child, NodeId::new(), layer, 0, gradient_info, group_extents_map);
let extent = import_usvg_node_inner(modify_inputs, child, NodeId::new(), layer, 0, graphite_gradient_stops, group_extents_map);
child_extents.push(extent);
}
modify_inputs.layer_node = Some(layer);
@@ -838,7 +675,7 @@ fn import_usvg_node_inner(
total_extent
}
usvg::Node::Path(path) => {
import_usvg_path(modify_inputs, node, path, layer, gradient_info);
import_usvg_path(modify_inputs, node, path, layer, graphite_gradient_stops);
0
}
usvg::Node::Image(_image) => {
@@ -855,7 +692,7 @@ fn import_usvg_node_inner(
}
/// Helper to apply path data (vector geometry, fill, stroke, transform) to a layer.
fn import_usvg_path(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, path: &usvg::Path, layer: LayerNodeIdentifier, gradient_info: &SvgGradientInfo) {
fn import_usvg_path(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, path: &usvg::Path, layer: LayerNodeIdentifier, graphite_gradient_stops: &HashMap<String, GradientStops>) {
let subpaths = convert_usvg_path(path);
// Skip creating a Transform node entirely when the SVG-native transform is identity.
@@ -869,7 +706,7 @@ fn import_usvg_path(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
}
if let Some(fill) = path.fill() {
apply_usvg_fill(fill, modify_inputs, gradient_info);
apply_usvg_fill(fill, modify_inputs, graphite_gradient_stops);
}
if let Some(stroke) = path.stroke() {
apply_usvg_stroke(stroke, modify_inputs, node_transform);
@@ -955,21 +792,22 @@ fn apply_usvg_stroke(stroke: &usvg::Stroke, modify_inputs: &mut ModifyInputsCont
},
join_miter_limit: stroke.miterlimit().get() as f64,
align: StrokeAlign::Center,
paint_order: PaintOrder::StrokeAbove,
transform,
},
)
}
}
fn convert_gradient_spread(spread_method: usvg::SpreadMethod) -> GradientSpread {
fn convert_spread_method(spread_method: usvg::SpreadMethod) -> GradientSpreadMethod {
match spread_method {
usvg::SpreadMethod::Pad => GradientSpread::Pad,
usvg::SpreadMethod::Reflect => GradientSpread::Reflect,
usvg::SpreadMethod::Repeat => GradientSpread::Repeat,
usvg::SpreadMethod::Pad => GradientSpreadMethod::Pad,
usvg::SpreadMethod::Reflect => GradientSpreadMethod::Reflect,
usvg::SpreadMethod::Repeat => GradientSpreadMethod::Repeat,
}
}
fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, gradient_info: &SvgGradientInfo) {
fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, graphite_gradient_stops: &HashMap<String, GradientStops>) {
match &fill.paint() {
usvg::Paint::Color(color) => modify_inputs.fill_color_set(Some(usvg_color(*color, fill.opacity().get()))),
usvg::Paint::LinearGradient(linear) => {
@@ -979,9 +817,9 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
let direction = end - start;
let transform = DAffine2::from_cols(direction, direction.perp(), start);
let gradient_form = GradientForm::Linear;
let gradient_type = GradientType::Linear;
let gradient = match gradient_info.graphite_stops.get(linear.id()) {
let gradient = match graphite_gradient_stops.get(linear.id()) {
Some(graphite_stops) => graphite_stops.clone(),
None => {
let stops = linear.stops().iter().map(|stop| GradientStop {
@@ -989,16 +827,11 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
midpoint: 0.5,
color: usvg_color(stop.color(), stop.opacity().get()),
});
Gradient::new(stops)
GradientStops::new(stops)
}
};
// SVG interpolates between stops in gamma sRGB unless `color-interpolation` opts into linearRGB, carried explicitly rather than as the linear default
let settings = GradientSettings {
spread: convert_gradient_spread(linear.spread_method()),
space: gradient_info.spaces.get(linear.id()).copied().unwrap_or(GradientSpace::RgbGamma),
..Default::default()
};
modify_inputs.fill_gradient_set(gradient, gradient_form, settings, transform);
let spread_method = convert_spread_method(linear.spread_method());
modify_inputs.fill_gradient_set(gradient, gradient_type, spread_method, transform);
}
usvg::Paint::RadialGradient(radial) => {
let gradient_transform = usvg_transform(radial.transform());
@@ -1008,9 +841,9 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
let direction = end - start;
let transform = DAffine2::from_cols(direction, direction.perp(), start);
let gradient_form = GradientForm::Radial;
let gradient_type = GradientType::Radial;
let gradient = match gradient_info.graphite_stops.get(radial.id()) {
let gradient = match graphite_gradient_stops.get(radial.id()) {
Some(graphite_stops) => graphite_stops.clone(),
None => {
let stops = radial.stops().iter().map(|stop| GradientStop {
@@ -1018,213 +851,13 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
midpoint: 0.5,
color: usvg_color(stop.color(), stop.opacity().get()),
});
Gradient::new(stops)
GradientStops::new(stops)
}
};
let settings = GradientSettings {
spread: convert_gradient_spread(radial.spread_method()),
space: gradient_info.spaces.get(radial.id()).copied().unwrap_or(GradientSpace::RgbGamma),
..Default::default()
};
modify_inputs.fill_gradient_set(gradient, gradient_form, settings, transform);
let spread_method = convert_spread_method(radial.spread_method());
modify_inputs.fill_gradient_set(gradient, gradient_type, spread_method, transform);
}
usvg::Paint::Pattern(_) => warn!("SVG patterns are not currently supported"),
};
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn stroke_order_set_reorders_the_fill_and_stroke_nodes() {
use crate::messages::tool::common_functionality::graph_modification_utils::get_stroke_paint_order;
use crate::test_utils::test_prelude::*;
use graphene_std::vector::style::PaintOrder;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
let document = editor.active_document();
let layer = document.metadata().all_layers().next().unwrap();
let paint_order = get_stroke_paint_order(layer, &document.network_interface);
assert_eq!(paint_order, PaintOrder::StrokeAbove, "a fresh shape should stroke above its fill");
editor
.handle_message(GraphOperationMessage::StrokeOrderSet {
layer,
paint_order: PaintOrder::StrokeBelow,
})
.await;
let paint_order = get_stroke_paint_order(layer, &editor.active_document().network_interface);
assert_eq!(paint_order, PaintOrder::StrokeBelow, "the rewrite should move the stroke downstream of the fill");
editor
.handle_message(GraphOperationMessage::StrokeOrderSet {
layer,
paint_order: PaintOrder::StrokeAbove,
})
.await;
let paint_order = get_stroke_paint_order(layer, &editor.active_document().network_interface);
assert_eq!(paint_order, PaintOrder::StrokeAbove, "the rewrite should move the stroke back upstream of the fill");
}
#[tokio::test]
async fn a_node_inserted_between_the_fill_and_stroke_makes_the_order_swap_inapplicable() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::tool::common_functionality::graph_modification_utils::stroke_paint_order_applicable;
use crate::test_utils::test_prelude::*;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
let layer = editor.active_document().metadata().all_layers().next().unwrap();
assert!(
stroke_paint_order_applicable(layer, &editor.active_document().network_interface),
"a fresh shape's adjacent Fill and Stroke pair should be swappable"
);
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
let stroke_node_id = ModifyInputsContext::locate_node_in_layer_chain(&stroke_reference, layer, &editor.active_document().network_interface).unwrap();
let node_template = Box::new(resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).unwrap().default_node_template());
let passthrough_node_id = NodeId::new();
editor
.handle_message(NodeGraphMessage::InsertNode {
node_id: passthrough_node_id,
node_template,
})
.await;
editor
.handle_message(NodeGraphMessage::InsertNodeBetween {
node_id: passthrough_node_id,
input_connector: InputConnector::node_at_index(stroke_node_id, 0),
insert_node_input_index: 0,
})
.await;
assert!(
!stroke_paint_order_applicable(layer, &editor.active_document().network_interface),
"a node between the pair should gray the order radio out"
);
}
#[test]
fn color_interpolation_resolves_per_gradient_with_inheritance_and_style_priority() {
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" color-interpolation="linearRGB">
<defs>
<linearGradient id="inherited"/>
<linearGradient id="attribute" color-interpolation="sRGB"/>
<linearGradient id="styled" color-interpolation="sRGB" style="fill: red; color-interpolation: linearRGB"/>
<radialGradient id="auto" color-interpolation="auto"/>
</defs>
</svg>"##;
let spaces = extract_gradient_spaces(svg);
assert_eq!(spaces.get("inherited"), Some(&GradientSpace::RgbLinear), "an undeclared gradient should inherit from its ancestors");
assert_eq!(spaces.get("attribute"), Some(&GradientSpace::RgbGamma), "an sRGB declaration should beat the inherited linearRGB");
assert_eq!(spaces.get("styled"), Some(&GradientSpace::RgbLinear), "the inline style should beat the presentation attribute");
assert_eq!(
spaces.get("auto"),
Some(&GradientSpace::RgbGamma),
"auto should mean gamma like browsers treat it, not defer to ancestors"
);
}
#[test]
fn graphite_stop_extraction_keeps_real_stops_and_linearizes_their_colors() {
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:graphite="https://graphite.art">
<defs>
<linearGradient id="ramp">
<stop stop-color="#000000" graphite:midpoint="0.3" />
<stop offset="0.25" stop-color="#404040" />
<stop offset="0.5" stop-color="#808080" stop-opacity="0.5" graphite:midpoint="0.5" />
<stop offset="1" stop-color="#ffffff" graphite:midpoint="0.5" />
</linearGradient>
</defs>
</svg>"##;
let stops = extract_graphite_gradient_stops(svg);
let gradient = stops.get("ramp").expect("the tagged gradient should be recovered");
// The untagged stop is baked approximation residue, not authored data
assert_eq!(gradient.len(), 3, "only stops tagged with a midpoint should survive");
assert_eq!(gradient.positions(false), vec![0., 0.5, 1.]);
assert_eq!(gradient.midpoints(), vec![0.3, 0.5, 0.5]);
// Hex stop bytes are gamma-encoded, so the recovered color must lift them to linear light
assert_eq!(gradient.color(1), Some(Color::from_gamma_srgb_channels(128. / 255., 128. / 255., 128. / 255., 0.5)));
}
#[test]
fn color_interpolation_reads_style_blocks_with_selector_specificity() {
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg">
<style>
linearGradient { color-interpolation: linearRGB }
.classy { color-interpolation: sRGB }
#exact { color-interpolation: linearRGB }
</style>
<defs>
<linearGradient id="from-type-rule"/>
<linearGradient id="from-class-rule" class="classy"/>
<linearGradient id="exact" class="classy"/>
<linearGradient id="inline-beats-rules" class="classy" style="color-interpolation: linearRGB"/>
<linearGradient id="rule-beats-attribute" class="classy" color-interpolation="linearRGB"/>
</defs>
</svg>"##;
let spaces = extract_gradient_spaces(svg);
assert_eq!(spaces.get("from-type-rule"), Some(&GradientSpace::RgbLinear), "a type rule in a style block should reach the gradient");
assert_eq!(
spaces.get("from-class-rule"),
Some(&GradientSpace::RgbGamma),
"the class rule should outrank the type rule by specificity"
);
assert_eq!(spaces.get("exact"), Some(&GradientSpace::RgbLinear), "the ID rule should outrank the class rule");
assert_eq!(spaces.get("inline-beats-rules"), Some(&GradientSpace::RgbLinear), "the inline style should beat every style block rule");
assert_eq!(
spaces.get("rule-beats-attribute"),
Some(&GradientSpace::RgbGamma),
"a style block rule should beat the presentation attribute"
);
}
#[test]
fn repeated_and_important_declarations_resolve_by_cascade_order() {
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg">
<style>.forced { color-interpolation: linearRGB !important }</style>
<linearGradient id="last-declaration-wins" style="color-interpolation: sRGB; color-interpolation: linearRGB"/>
<linearGradient id="important-beats-later" style="color-interpolation: linearRGB !important; color-interpolation: sRGB"/>
<linearGradient id="important-rule-beats-inline" class="forced" style="color-interpolation: sRGB"/>
</svg>"##;
let spaces = extract_gradient_spaces(svg);
assert_eq!(
spaces.get("last-declaration-wins"),
Some(&GradientSpace::RgbLinear),
"the last of repeated inline declarations should win"
);
assert_eq!(
spaces.get("important-beats-later"),
Some(&GradientSpace::RgbLinear),
"an `!important` declaration should beat a later normal one"
);
assert_eq!(
spaces.get("important-rule-beats-inline"),
Some(&GradientSpace::RgbLinear),
"an `!important` style block rule should beat the inline style"
);
}
#[test]
fn color_interpolation_yields_nothing_when_never_declared() {
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg"><linearGradient id="plain"/></svg>"##;
assert!(
extract_gradient_spaces(svg).is_empty(),
"gradients without any declaration should fall back to the caller's gamma default"
);
}
}
@@ -14,26 +14,10 @@ pub fn update_transform(network_interface: &mut NodeNetworkInterface, node_id: &
let rotation = rotation.to_degrees();
let skew = DVec2::new(skew.atan().to_degrees(), 0.);
network_interface.set_input(
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::TranslationInput),
NodeInput::value(TaggedValue::DVec2(translation), false),
&[],
);
network_interface.set_input(
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::RotationInput),
NodeInput::value(TaggedValue::F64(rotation), false),
&[],
);
network_interface.set_input(
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::ScaleInput),
NodeInput::value(TaggedValue::DVec2(scale), false),
&[],
);
network_interface.set_input(
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::SkewInput),
NodeInput::value(TaggedValue::DVec2(skew), false),
&[],
);
network_interface.set_input(&InputConnector::node(*node_id, 1), NodeInput::value(TaggedValue::DVec2(translation), false), &[]);
network_interface.set_input(&InputConnector::node(*node_id, 2), NodeInput::value(TaggedValue::F64(rotation), false), &[]);
network_interface.set_input(&InputConnector::node(*node_id, 3), NodeInput::value(TaggedValue::DVec2(scale), false), &[]);
network_interface.set_input(&InputConnector::node(*node_id, 4), NodeInput::value(TaggedValue::DVec2(skew), false), &[]);
}
// TODO: This should be extracted from the graph at the location of the transform node.
@@ -1,26 +1,23 @@
use super::transform_utils;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{
ARTBOARD_DIMENSIONS_INPUT_INDEX, ARTBOARD_LOCATION_INPUT_INDEX, DefinitionIdentifier, resolve_document_node_type, resolve_network_node_type, resolve_proto_node_type,
};
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_network_node_type, resolve_proto_node_type};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{
ReplaceablePaintChain, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, replaceable_paint_chain,
};
use crate::messages::tool::common_functionality::graph_modification_utils::{get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input};
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graph_craft::{ProtoNodeIdentifier, list};
use graph_craft::{ProtoNodeIdentifier, concrete, descriptor};
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::list::List;
use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Image;
use graphene_std::subpath::Subpath;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
use graphene_std::vector::{Gradient, GradientRamp, PointId, Vector, VectorModification, VectorModificationType};
use graphene_std::{Artboard, Color, Graphic};
use graphene_std::vector::style::{GradientSpreadMethod, GradientType, Stroke};
use graphene_std::vector::{GradientStops, PointId, Vector, VectorModification, VectorModificationType};
use graphene_std::{Artboard, Color, Graphic, NodeInputDecleration};
#[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub enum TransformIn {
@@ -61,6 +58,72 @@ impl<'a> ModifyInputsContext<'a> {
Some(document)
}
/// Starts at any folder, or the output, and skips layer nodes based on insert_index. Non layer nodes are always skipped. Returns the post node InputConnector and pre node OutputConnector
/// Non layer nodes directly upstream of a layer are treated as part of that layer. See insert_index == 2 in the diagram
/// -----> Post node
/// | if insert_index == 0, return (Post node, Some(Layer1))
/// -> Layer1
/// ↑ if insert_index == 1, return (Layer1, Some(Layer2))
/// -> Layer2
/// ↑
/// -> NonLayerNode
/// ↑ if insert_index == 2, return (NonLayerNode, Some(Layer3))
/// -> Layer3
/// if insert_index == 3, return (Layer3, None)
pub fn get_post_node_with_index(network_interface: &NodeNetworkInterface, parent: LayerNodeIdentifier, insert_index: usize) -> InputConnector {
let mut post_node_input_connector = if parent == LayerNodeIdentifier::ROOT_PARENT {
InputConnector::Export(0)
} else {
InputConnector::node(parent.to_node(), 1)
};
// Skip layers based on skip_layer_nodes, which inserts the new layer at a certain index of the layer stack.
let mut current_index = 0;
// Set the post node to the layer node at insert_index
loop {
if current_index == insert_index {
break;
}
let next_node_in_stack_id = network_interface
.input_from_connector(&post_node_input_connector, &[])
.and_then(|input_from_connector| if let NodeInput::Node { node_id, .. } = input_from_connector { Some(node_id) } else { None });
if let Some(next_node_in_stack_id) = next_node_in_stack_id {
// Only increment index for layer nodes
if network_interface.is_layer(next_node_in_stack_id, &[]) {
current_index += 1;
}
// Input as a sibling to the Layer node above
post_node_input_connector = InputConnector::node(*next_node_in_stack_id, 0);
} else {
log::error!("Error getting post node: insert_index out of bounds");
break;
};
}
let layer_input_connector = post_node_input_connector;
// Sink post_node down to the end of the non layer chain that feeds into post_node, such that pre_node is the layer node at insert_index + 1, or None if insert_index is the last layer
loop {
let pre_node_output_connector = network_interface.upstream_output_connector(&post_node_input_connector, &[]);
match pre_node_output_connector {
Some(OutputConnector::Node { node_id: pre_node_id, .. }) if !network_interface.is_layer(&pre_node_id, &[]) => {
// Update post_node_input_connector for the next iteration
post_node_input_connector = InputConnector::node(pre_node_id, 0);
// Insert directly under layer if moving to the end of a layer stack that ends with a non layer node that does not have an exposed primary input
let primary_is_exposed = network_interface.input_from_connector(&post_node_input_connector, &[]).is_some_and(|input| input.is_exposed());
if !primary_is_exposed {
return layer_input_connector;
}
}
_ => break, // Break if pre_node_output_connector is None or if pre_node_id is a layer
}
}
post_node_input_connector
}
/// Creates a new layer and adds it to the document network. network_interface.move_layer_to_stack should be called after
pub fn create_layer(&mut self, new_id: NodeId) -> LayerNodeIdentifier {
let new_merge_node = resolve_network_node_type("Merge").expect("Merge node").default_node_template();
@@ -71,11 +134,11 @@ impl<'a> ModifyInputsContext<'a> {
/// Creates an artboard as the primary export for the document network.
pub fn create_artboard(&mut self, new_id: NodeId, location: DVec2, dimensions: DVec2, background: Color, clip: bool) -> LayerNodeIdentifier {
let artboard_node_template = resolve_network_node_type("Artboard").expect("Node").node_template_input_override([
Some(NodeInput::type_default(list!(Artboard), true)),
Some(NodeInput::type_default(list!(Graphic), true)),
Some(NodeInput::type_default(descriptor!(List<Artboard>), true)),
Some(NodeInput::type_default(descriptor!(List<Graphic>), true)),
Some(NodeInput::value(TaggedValue::DVec2(location), false)),
Some(NodeInput::value(TaggedValue::DVec2(dimensions), false)),
Some(NodeInput::value(TaggedValue::Color(background), false)),
Some(NodeInput::value(TaggedValue::Color(Some(background)), false)),
Some(NodeInput::value(TaggedValue::Bool(clip), false)),
]);
self.network_interface.insert_node(new_id, artboard_node_template, &[]);
@@ -86,7 +149,7 @@ impl<'a> ModifyInputsContext<'a> {
let boolean = resolve_proto_node_type(graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER)
.expect("Boolean node does not exist")
.node_template_input_override([
Some(NodeInput::type_default(list!(Graphic), true)),
Some(NodeInput::type_default(descriptor!(List<Graphic>), true)),
Some(NodeInput::value(TaggedValue::BooleanOperation(operation), false)),
]);
@@ -98,7 +161,7 @@ impl<'a> ModifyInputsContext<'a> {
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: f64) -> NodeId {
let blend = resolve_network_node_type("Blend")
.expect("Blend node does not exist")
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(count), false))]);
.node_template_input_override([Some(NodeInput::type_default(descriptor!(List<Graphic>), true)), Some(NodeInput::value(TaggedValue::F64(count), false))]);
let blend_id = NodeId::new();
self.network_interface.insert_node(blend_id, blend, &[]);
@@ -110,7 +173,7 @@ impl<'a> ModifyInputsContext<'a> {
pub fn insert_morph_data(&mut self, layer: LayerNodeIdentifier) -> NodeId {
let morph = resolve_proto_node_type(graphene_std::vector::morph::IDENTIFIER)
.expect("Morph node does not exist")
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
.node_template_input_override([Some(NodeInput::type_default(descriptor!(List<Graphic>), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
let morph_id = NodeId::new();
self.network_interface.insert_node(morph_id, morph, &[]);
@@ -234,41 +297,14 @@ impl<'a> ModifyInputsContext<'a> {
self.network_interface.move_node_to_chain_start(&fill_id, layer, &[], self.import);
}
pub fn insert_color_value(&mut self, color: Color, layer: LayerNodeIdentifier, attachment_input: InputConnector) -> NodeId {
pub fn insert_color_value(&mut self, color: Color, layer: LayerNodeIdentifier) {
let color_value = resolve_proto_node_type(graphene_std::math_nodes::color_value::IDENTIFIER)
.expect("Color Value node does not exist")
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::Color(color), false))]);
.node_template_input_override([Some(NodeInput::value(TaggedValue::None, false)), Some(NodeInput::value(TaggedValue::Color(Some(color)), false))]);
let color_value_id = NodeId::new();
self.network_interface.insert_node(color_value_id, color_value, &[]);
self.start_paint_chain(&color_value_id, layer, attachment_input);
color_value_id
}
/// Clear the whole-expanse paint one tool left on a layer so the other can start its own chain there.
/// Severing at the attachment detaches the layer from whatever the walk stopped at, which is the only part a node
/// the rest of the graph also draws from is subjected to, since such a node is never among those deleted.
fn clear_paint_chain(&mut self, paint_chain: &ReplaceablePaintChain) {
self.network_interface.disconnect_input(&paint_chain.attachment_input, &[]);
if !paint_chain.nodes.is_empty() {
self.network_interface.delete_nodes(paint_chain.nodes.clone(), false, &[]);
}
}
/// Wire a node that paints the layer's whole expanse into the start of its chain,
/// or past the 'Transform' nodes a blank layer already carries so those go on applying to the paint.
fn start_paint_chain(&mut self, node_id: &NodeId, layer: LayerNodeIdentifier, attachment_input: InputConnector) {
let layer_content_input = InputConnector::layer_secondary_input(layer.to_node());
if attachment_input == layer_content_input {
self.network_interface.move_node_to_chain_start(node_id, layer, &[], self.import);
return;
}
self.network_interface.set_input(&attachment_input, NodeInput::node(*node_id, 0), &[]);
self.network_interface.set_chain_position(node_id, &[]);
self.network_interface.move_node_to_chain_start(&color_value_id, layer, &[], self.import);
}
pub fn insert_image_data(&mut self, image: Image<Color>, layer: LayerNodeIdentifier) {
@@ -347,16 +383,6 @@ impl<'a> ModifyInputsContext<'a> {
self.existing_node_id(&DefinitionIdentifier::ProtoNode(reference), create_if_nonexistent)
}
/// The same as [`Self::existing_proto_node_id`], but yielding `None` on layers whose chain cannot host the node.
fn existing_chain_hosted_node_id(&mut self, reference: ProtoNodeIdentifier, create_if_nonexistent: bool) -> Option<NodeId> {
let output_layer = self.get_output_layer()?;
if !self.network_interface.layer_chain_hosts_node(&output_layer.to_node(), &[], &reference) {
return None;
}
self.existing_proto_node_id(reference, create_if_nonexistent)
}
/// Gets the node id of a document node with a specific reference that is upstream from the layer node, and optionally creates it if it does not exist.
fn existing_node_id(&mut self, reference: &DefinitionIdentifier, create_if_nonexistent: bool) -> Option<NodeId> {
// Start from the layer node or export
@@ -407,20 +433,17 @@ impl<'a> ModifyInputsContext<'a> {
return None;
};
// Without a secondary input there is no chain to hold the node, so inserting it would strand it at the graph origin
self.network_interface.input_from_connector(&InputConnector::layer_secondary_input(output_layer.to_node()), &[])?;
// If inserting a 'Path' node, insert a 'Combine Paths' node if the type is `Graphic`.
// If inserting a 'Path' node, insert a 'Flatten Path' node if the type is `Graphic`.
// TODO: Allow the 'Path' node to operate on `List` data by utilizing the reference (index or ID?) for each item.
if node_definition.identifier == "Path" {
let layer_input_type = self.network_interface.input_type(&InputConnector::layer_secondary_input(output_layer.to_node()), &[]);
if layer_input_type.compiled_element_name().as_deref() == Some("Graphic") {
let Some(combine_paths_definition) = resolve_proto_node_type(graphene_std::vector_nodes::combine_paths::IDENTIFIER) else {
log::error!("Combine Paths does not exist in ModifyInputsContext::existing_node_id");
let layer_input_type = self.network_interface.input_type(&InputConnector::node(output_layer.to_node(), 1), &[]);
if layer_input_type.compiled_nested_type() == Some(&concrete!(List<Graphic>)) {
let Some(flatten_path_definition) = resolve_proto_node_type(graphene_std::vector_nodes::flatten_path::IDENTIFIER) else {
log::error!("Flatten Path does not exist in ModifyInputsContext::existing_node_id");
return None;
};
let node_id = NodeId::new();
self.network_interface.insert_node(node_id, combine_paths_definition.default_node_template(), &[]);
self.network_interface.insert_node(node_id, flatten_path_definition.default_node_template(), &[]);
self.network_interface.move_node_to_chain_start(&node_id, output_layer, &[], self.import);
}
}
@@ -431,39 +454,28 @@ impl<'a> ModifyInputsContext<'a> {
}
pub fn fill_color_set(&mut self, color: Option<Color>) {
let existing_fill_node_id = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, false);
let Some(fill_node_id) = existing_fill_node_id.or_else(|| self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true)) else {
let Some(fill_node_id) = self.existing_proto_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
return;
};
let input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::PaintInput);
let backup_input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupColorInput);
let input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::INDEX);
let backup_input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupColorInput::INDEX);
// The backup remembers the last solid color, so the red-slash "none" choice leaves it untouched
if let Some(color) = color {
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
}
let fill_value = color.map_or_else(TaggedValue::no_paint, TaggedValue::Color);
self.set_input_with_refresh(input_connector, NodeInput::value(fill_value, false), false);
if existing_fill_node_id.is_none() {
self.restore_default_stroke_order();
}
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(color), false), false);
}
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: GradientForm, settings: GradientSettings, transform: DAffine2) {
let existing_fill_node_id = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, false);
let Some(fill_node_id) = existing_fill_node_id.or_else(|| self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true)) else {
pub fn fill_gradient_set(&mut self, gradient: GradientStops, gradient_type: GradientType, spread_method: GradientSpreadMethod, transform: DAffine2) {
let Some(fill_node_id) = self.existing_proto_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
return;
};
let backup_input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupGradientInput);
let backup_input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupGradientInput::INDEX);
let ramp = GradientRamp::from(gradient).with_settings(settings);
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::GradientRamp(ramp.clone()), false), true);
self.set_input_with_refresh(backup_input_connector, NodeInput::value(TaggedValue::Gradient(gradient.clone()), false), true);
// Skip the rerender on all but the last input so the whole update triggers a single graph run
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::PaintInput),
NodeInput::value(TaggedValue::GradientRamp(ramp), false),
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::INDEX),
NodeInput::value(TaggedValue::Gradient(gradient), false),
true,
);
@@ -473,63 +485,49 @@ impl<'a> ModifyInputsContext<'a> {
.document_network()
.nodes
.get(&fill_node_id)
.and_then(|node| node.input(graphene_std::vector::fill::TransformInput))
.and_then(|node| node.inputs.get(graphene_std::vector::fill::TransformInput::INDEX))
.is_some_and(|input| input.as_value().is_some());
if transform_is_value {
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::HasTransformInput),
NodeInput::value(TaggedValue::Bool(true), false),
true,
);
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput),
NodeInput::value(TaggedValue::DAffine2(transform), false),
InputConnector::node(fill_node_id, graphene_std::vector::fill::TransformInput::INDEX),
NodeInput::value(TaggedValue::OptionalDAffine2(Some(transform)), false),
true,
);
}
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::GradientFormInput),
NodeInput::value(TaggedValue::GradientForm(gradient_form), false),
false,
InputConnector::node(fill_node_id, graphene_std::vector::fill::GradientTypeInput::INDEX),
NodeInput::value(TaggedValue::GradientType(gradient_type), false),
true,
);
if existing_fill_node_id.is_none() {
self.restore_default_stroke_order();
}
}
/// A freshly created Fill node lands at the chain start, downstream of any Stroke node, where it would
/// paint over the stroke. This hops the stroke back downstream so it keeps painting above by default.
fn restore_default_stroke_order(&mut self) {
let Some(output_layer) = self.get_output_layer() else { return };
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
let Some(stroke_node_id) = Self::locate_node_in_layer_chain(&stroke_reference, output_layer, self.network_interface) else {
return;
};
set_stroke_paint_order(self.network_interface, &[], stroke_node_id, PaintOrder::StrokeAbove);
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::SpreadMethodInput::INDEX),
NodeInput::value(TaggedValue::GradientSpreadMethod(spread_method), false),
false,
);
}
pub fn blend_mode_set(&mut self, blend_mode: BlendMode) {
let Some(blend_node_id) = self.existing_chain_hosted_node_id(graphene_std::blending_nodes::blend_mode::IDENTIFIER, true) else {
let Some(blend_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::blend_mode::IDENTIFIER, true) else {
return;
};
let input_connector = InputConnector::node(blend_node_id, graphene_std::blending_nodes::blend_mode::BlendModeInput);
let input_connector = InputConnector::node(blend_node_id, graphene_std::blending_nodes::blend_mode::BlendModeInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::BlendMode(blend_mode), false), false);
}
pub fn opacity_set(&mut self, opacity: f64) {
let Some(opacity_node_id) = self.existing_chain_hosted_node_id(graphene_std::blending_nodes::opacity::IDENTIFIER, true) else {
let Some(opacity_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::opacity::IDENTIFIER, true) else {
return;
};
// Enable the `has_opacity` checkbox so the value is applied
self.set_input_with_refresh(
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::HasOpacityInput),
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::HasOpacityInput::INDEX),
NodeInput::value(TaggedValue::Bool(true), false),
false,
);
self.set_input_with_refresh(
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::OpacityInput),
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::OpacityInput::INDEX),
NodeInput::value(TaggedValue::F64(opacity * 100.), false),
false,
);
@@ -538,78 +536,47 @@ impl<'a> ModifyInputsContext<'a> {
pub fn opacity_fill_set(&mut self, fill: f64) {
// Reuse an existing Opacity node to avoid a redundant chain walk on slider drags
let identifier = graphene_std::blending_nodes::opacity::IDENTIFIER;
let existing = self.existing_chain_hosted_node_id(identifier.clone(), false);
let existing = self.existing_proto_node_id(identifier.clone(), false);
let existed = existing.is_some();
let Some(opacity_node_id) = existing.or_else(|| self.existing_chain_hosted_node_id(identifier, true)) else {
let Some(opacity_node_id) = existing.or_else(|| self.existing_proto_node_id(identifier, true)) else {
return;
};
// Freshly-created node defaults to opacity enabled; disable it so the fill slider works independently
if !existed {
self.set_input_with_refresh(
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::HasOpacityInput),
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::HasOpacityInput::INDEX),
NodeInput::value(TaggedValue::Bool(false), false),
false,
);
}
// Enable the `has_fill` checkbox so the value is applied
self.set_input_with_refresh(
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::HasFillInput),
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::HasFillInput::INDEX),
NodeInput::value(TaggedValue::Bool(true), false),
false,
);
self.set_input_with_refresh(
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::FillInput),
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::FillInput::INDEX),
NodeInput::value(TaggedValue::F64(fill * 100.), false),
false,
);
}
/// Update the chain's 'Color Value' node, or start a chain with one on an empty layer, painting the layer's whole expanse.
pub fn color_value_set(&mut self, color: Color) {
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
if let Some(node_id) = self.existing_proto_node_id_at(&target_input, graphene_std::math_nodes::color_value::IDENTIFIER, false) {
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::color_value::ColorInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(color), false), false);
return;
}
// The 'Color Value' node discards its primary input, so only a blank 'Merge' layer may start a chain with one,
// which any whole-expanse paint the other tool left behind is cleared off to become
let Some(paint_chain) = replaceable_paint_chain(output_layer, self.network_interface) else {
return;
};
self.clear_paint_chain(&paint_chain);
let color_value_id = self.insert_color_value(color, output_layer, paint_chain.attachment_input);
let input_connector = InputConnector::node(color_value_id, graphene_std::math_nodes::color_value::ColorInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(color), false), false);
}
/// Write the gradient stops to the 'Gradient Value' node feeding the layer.
pub fn gradient_stops_set(&mut self, stops: Gradient) {
pub fn gradient_stops_set(&mut self, stops: GradientStops) {
let Some(output_layer) = self.get_output_layer() else { return };
let gradient_value_id = match get_upstream_gradient_value_node_id(output_layer, self.network_interface) {
Some(id) => id,
None => {
let target = gradient_chain_target_input(output_layer, self.network_interface);
let starts_layer_chain = target == InputConnector::layer_secondary_input(output_layer.to_node());
let starts_layer_chain = target == InputConnector::node(output_layer.to_node(), 1);
// The 'Gradient Value' node discards its primary input, so only a blank 'Merge' layer may start a chain
// with one, which any whole-expanse paint the other tool left behind is cleared off to become
let paint_chain = if starts_layer_chain {
let Some(paint_chain) = replaceable_paint_chain(output_layer, self.network_interface) else {
log::error!("Refusing to start a gradient chain on anything but a blank 'Merge' layer");
return;
};
self.clear_paint_chain(&paint_chain);
Some(paint_chain)
} else {
None
};
// The Gradient Value node discards its primary input, so starting a chain ahead of existing layer content would drop that content; refuse instead
if starts_layer_chain && self.network_interface.upstream_output_connector(&target, &[]).is_some() {
log::error!("Refusing to start a gradient chain ahead of existing layer content");
return;
}
let Some(node_definition) = resolve_proto_node_type(graphene_std::math_nodes::gradient_value::IDENTIFIER) else {
return;
@@ -617,9 +584,9 @@ impl<'a> ModifyInputsContext<'a> {
let node_id = NodeId::new();
self.network_interface.insert_node(node_id, node_definition.default_node_template(), &[]);
if let Some(paint_chain) = paint_chain {
if starts_layer_chain {
// No Fill node: the new node starts the layer's chain
self.start_paint_chain(&node_id, output_layer, paint_chain.attachment_input);
self.network_interface.move_node_to_chain_start(&node_id, output_layer, &[], self.import);
} else {
// Feeding a Fill node's paint input: wire it up and place it one chain-width left and a step below the Fill
self.network_interface.set_input(&target, NodeInput::node(node_id, 0), &[]);
@@ -636,65 +603,8 @@ impl<'a> ModifyInputsContext<'a> {
}
};
// Only the stops are being replaced, so the ramp's other settings stay as the value node already holds them
let ramp = GradientRamp {
stops: (&stops).into(),
..self.gradient_value_ramp(gradient_value_id).unwrap_or_default()
};
let input_connector = InputConnector::node(gradient_value_id, graphene_std::math_nodes::gradient_value::GradientInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientRamp(ramp), false), false);
}
/// Update the last 'Gradient Positions' node in the chain when one exists, so on-canvas stop drags stay live even
/// though that node would otherwise override the stops value's own placement. Never inserts one: the stops value
/// carries placement itself, and these setter nodes are user-authored procedural overrides. A wired input is
/// procedural authorship too, so it is likewise left untouched.
pub fn gradient_positions_set(&mut self, positions: Vec<f64>) {
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::gradient_positions::IDENTIFIER;
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, false) else {
return;
};
let current_input = self
.network_interface
.document_network()
.nodes
.get(&node_id)
.and_then(|node| node.input(graphene_std::math_nodes::gradient_positions::PositionsInput));
if !current_input.is_some_and(|input| input.as_value().is_some()) {
return;
}
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_positions::PositionsInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(positions), false), false);
}
/// The 'Gradient Midpoints' counterpart of [`Self::gradient_positions_set`], likewise update-only.
pub fn gradient_midpoints_set(&mut self, midpoints: Vec<f64>) {
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::gradient_midpoints::IDENTIFIER;
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, false) else {
return;
};
let current_input = self
.network_interface
.document_network()
.nodes
.get(&node_id)
.and_then(|node| node.input(graphene_std::math_nodes::gradient_midpoints::MidpointsInput));
if !current_input.is_some_and(|input| input.as_value().is_some()) {
return;
}
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_midpoints::MidpointsInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(midpoints), false), false);
let input_connector = InputConnector::node(gradient_value_id, graphene_std::math_nodes::gradient_value::GradientInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Gradient(stops), false), false);
}
/// Update the transform to map the unit gradient ((0,0), (1, 0)) to the geometry's local space.
@@ -759,128 +669,69 @@ impl<'a> ModifyInputsContext<'a> {
self.responses.add(NodeGraphMessage::RunDocumentGraph);
}
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
/// Write the gradient type to the last 'Gradient Type' node in the chain, inserting one only when the value differs
/// from the default (`Linear`).
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
pub fn gradient_type_set(&mut self, gradient_type: GradientType) {
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
let create_if_nonexistent = gradient_form != GradientForm::default();
let identifier = graphene_std::math_nodes::gradient_type::IDENTIFIER;
let create_if_nonexistent = gradient_type != GradientType::default();
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
return;
};
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_type::GradientTypeInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientType(gradient_type), false), false);
}
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
pub fn gradient_spread_set(&mut self, gradient_spread: GradientSpread) {
/// Write the spread method to the last 'Spread Method' node in the chain, inserting one only when the value differs
/// from the default (`Pad`).
pub fn gradient_spread_method_set(&mut self, spread_method: GradientSpreadMethod) {
let Some(output_layer) = self.get_output_layer() else { return };
let Some(gradient_value_id) = get_upstream_gradient_value_node_id(output_layer, self.network_interface) else {
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::spread_method::IDENTIFIER;
let create_if_nonexistent = spread_method != GradientSpreadMethod::default();
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
return;
};
let Some(ramp) = self.gradient_value_ramp(gradient_value_id) else { return };
let ramp = GradientRamp { gradient_spread, ..ramp };
let input_connector = InputConnector::node(gradient_value_id, graphene_std::math_nodes::gradient_value::GradientInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientRamp(ramp), false), false);
}
/// The ramp currently held by a 'Gradient Value' node.
fn gradient_value_ramp(&self, gradient_value_id: NodeId) -> Option<GradientRamp> {
let node = self.network_interface.document_network().nodes.get(&gradient_value_id)?;
let TaggedValue::GradientRamp(ramp) = node.input(graphene_std::math_nodes::gradient_value::GradientInput)?.as_value()? else {
return None;
};
Some(ramp.clone())
}
/// Set the space on the chain's gradient value, which is where the ramp carries it. Never touches a
/// 'Gradient Space' node: that one is a user-authored procedural override, not something the tools manage.
pub fn gradient_space_set(&mut self, gradient_space: GradientSpace) {
let Some(output_layer) = self.get_output_layer() else { return };
let Some(gradient_value_id) = get_upstream_gradient_value_node_id(output_layer, self.network_interface) else {
return;
};
let Some(ramp) = self.gradient_value_ramp(gradient_value_id) else { return };
let ramp = GradientRamp { gradient_space, ..ramp };
let input_connector = InputConnector::node(gradient_value_id, graphene_std::math_nodes::gradient_value::GradientInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientRamp(ramp), false), false);
}
/// Set the cyclic wrap flag on the chain's gradient value, which is where the ramp carries it. This holds the existing
/// stops in place by reading their positions under the old flag, so batch it before any stops write rather than after one,
/// or it would reinterpret incoming stops already authored under the new flag.
pub fn gradient_cyclic_set(&mut self, gradient_cyclic: bool) {
let Some(output_layer) = self.get_output_layer() else { return };
let Some(gradient_value_id) = get_upstream_gradient_value_node_id(output_layer, self.network_interface) else {
return;
};
let Some(ramp) = self.gradient_value_ramp(gradient_value_id) else { return };
let ramp = ramp.with_cyclic(gradient_cyclic);
let input_connector = InputConnector::node(gradient_value_id, graphene_std::math_nodes::gradient_value::GradientInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientRamp(ramp), false), false);
}
/// Set the interpolation on the chain's gradient value, which is where the ramp carries it.
pub fn gradient_interpolation_set(&mut self, gradient_interpolation: GradientInterpolation) {
let Some(output_layer) = self.get_output_layer() else { return };
let Some(gradient_value_id) = get_upstream_gradient_value_node_id(output_layer, self.network_interface) else {
return;
};
let Some(ramp) = self.gradient_value_ramp(gradient_value_id) else { return };
let ramp = GradientRamp { gradient_interpolation, ..ramp };
let input_connector = InputConnector::node(gradient_value_id, graphene_std::math_nodes::gradient_value::GradientInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientRamp(ramp), false), false);
}
/// Set the hue direction on the chain's gradient value, which is where the ramp carries it.
pub fn gradient_hue_direction_set(&mut self, gradient_hue_direction: GradientHueDirection) {
let Some(output_layer) = self.get_output_layer() else { return };
let Some(gradient_value_id) = get_upstream_gradient_value_node_id(output_layer, self.network_interface) else {
return;
};
let Some(ramp) = self.gradient_value_ramp(gradient_value_id) else { return };
let ramp = GradientRamp { gradient_hue_direction, ..ramp };
let input_connector = InputConnector::node(gradient_value_id, graphene_std::math_nodes::gradient_value::GradientInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientRamp(ramp), false), false);
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::spread_method::SpreadMethodInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientSpreadMethod(spread_method), false), false);
}
pub fn clip_mode_toggle(&mut self, clip_mode: Option<bool>) {
let clip = !clip_mode.unwrap_or(false);
let Some(clip_node_id) = self.existing_chain_hosted_node_id(graphene_std::blending_nodes::clipping_mask::IDENTIFIER, true) else {
let Some(clip_node_id) = self.existing_proto_node_id(graphene_std::blending_nodes::clipping_mask::IDENTIFIER, true) else {
return;
};
let input_connector = InputConnector::node(clip_node_id, graphene_std::blending_nodes::clipping_mask::ClipInput);
let input_connector = InputConnector::node(clip_node_id, graphene_std::blending_nodes::clipping_mask::ClipInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Bool(clip), false), false);
}
pub fn stroke_set(&mut self, color: Option<Color>, stroke: Stroke) {
let Some(stroke_node_id) = self.existing_chain_hosted_node_id(graphene_std::vector::stroke::IDENTIFIER, true) else {
let Some(stroke_node_id) = self.existing_proto_node_id(graphene_std::vector::stroke::IDENTIFIER, true) else {
return;
};
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput);
self.set_input_with_refresh(input_connector, NodeInput::value(color.map_or_else(TaggedValue::no_paint, TaggedValue::Color), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Color(color), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeAlign(stroke.align), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::CapInput);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::CapInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeCap(stroke.cap), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::JoinInput);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::JoinInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeJoin(stroke.join), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::MiterLimitInput);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::MiterLimitInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintOrder(stroke.paint_order), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashLengthsInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(stroke.dash_lengths), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput::INDEX);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
}
@@ -981,11 +832,7 @@ impl<'a> ModifyInputsContext<'a> {
let Some(brush_node_id) = self.existing_proto_node_id(graphene_std::brush::brush::brush::IDENTIFIER, true) else {
return;
};
self.set_input_with_refresh(
InputConnector::node(brush_node_id, graphene_std::brush::brush::brush::TraceInput),
NodeInput::value(TaggedValue::BrushStrokes(strokes), false),
false,
);
self.set_input_with_refresh(InputConnector::node(brush_node_id, 1), NodeInput::value(TaggedValue::BrushStrokes(strokes), false), false);
}
pub fn resize_artboard(&mut self, location: DVec2, dimensions: DVec2) {
@@ -1004,16 +851,8 @@ impl<'a> ModifyInputsContext<'a> {
dimensions.y = -dimensions.y;
location.y -= dimensions.y;
}
self.set_input_with_refresh(
InputConnector::node_at_index(artboard_node_id, ARTBOARD_LOCATION_INPUT_INDEX),
NodeInput::value(TaggedValue::DVec2(location), false),
false,
);
self.set_input_with_refresh(
InputConnector::node_at_index(artboard_node_id, ARTBOARD_DIMENSIONS_INPUT_INDEX),
NodeInput::value(TaggedValue::DVec2(dimensions), false),
false,
);
self.set_input_with_refresh(InputConnector::node(artboard_node_id, 2), NodeInput::value(TaggedValue::DVec2(location), false), false);
self.set_input_with_refresh(InputConnector::node(artboard_node_id, 3), NodeInput::value(TaggedValue::DVec2(dimensions), false), false);
}
/// Set the input, refresh the Properties panel, and run the document graph if skip_rerender is false
@@ -1025,60 +864,3 @@ impl<'a> ModifyInputsContext<'a> {
}
}
}
/// The wires feeding off a node's primary output.
fn primary_output_consumers(network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], node_id: NodeId) -> Vec<InputConnector> {
network_interface
.outward_wires(network_path)
.and_then(|wires| wires.get(&OutputConnector::node(node_id, 0)).cloned())
.unwrap_or_default()
}
/// Swaps a chain's directly adjacent Stroke and Fill nodes when their order disagrees with the requested
/// paint order: both nodes append their cover, so the downstream one of the pair paints on top, following
/// the painter's algorithm. Without a fill wired directly to the stroke, nothing changes.
/// Returns whether the graph changed.
pub fn set_stroke_paint_order(network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], stroke_node_id: NodeId, paint_order: PaintOrder) -> bool {
let fill_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER);
let is_fill = |network_interface: &NodeNetworkInterface, node_id: &NodeId| network_interface.reference(node_id, network_path).as_ref() == Some(&fill_reference);
// Find the fill wired directly to the stroke on either side; the downstream one of the pair paints on top
let stroke_primary_source = match network_interface.input_from_connector(&InputConnector::node_at_index(stroke_node_id, 0), network_path) {
Some(NodeInput::Node { node_id, output_index: 0, .. }) => Some(*node_id),
_ => None,
};
let (fill_node_id, currently_above) = if let Some(source) = stroke_primary_source.filter(|source| is_fill(network_interface, source)) {
(source, true)
} else {
let consumers = primary_output_consumers(network_interface, network_path, stroke_node_id);
let fill_consumer = consumers.iter().find_map(|connector| match connector {
InputConnector::Node { node_id, input_index: 0 } if is_fill(network_interface, node_id) => Some(*node_id),
_ => None,
});
let Some(fill_node_id) = fill_consumer else { return false };
(fill_node_id, false)
};
if (paint_order == PaintOrder::StrokeAbove) == currently_above {
return false;
}
// Swap the pair in place: the downstream node takes the upstream one's source, consumers of the
// downstream node move over to the upstream one, and the wire linking the pair reverses direction
let (upstream, downstream) = if currently_above { (fill_node_id, stroke_node_id) } else { (stroke_node_id, fill_node_id) };
let Some(upstream_source) = network_interface.input_from_connector(&InputConnector::node_at_index(upstream, 0), network_path).cloned() else {
return false;
};
let downstream_consumers = primary_output_consumers(network_interface, network_path, downstream);
network_interface.set_input(&InputConnector::node_at_index(downstream, 0), upstream_source, network_path);
network_interface.set_input(&InputConnector::node_at_index(upstream, 0), NodeInput::node(downstream, 0), network_path);
for consumer in &downstream_consumers {
if matches!(consumer, InputConnector::Node { node_id, .. } if *node_id == upstream || *node_id == downstream) {
continue;
}
network_interface.set_input(consumer, NodeInput::node(upstream, 0), network_path);
}
true
}
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,7 @@
use super::DocumentNodeDefinition;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputMetadata, NodeTemplate, NodeTemplateImplementation, WidgetOverride};
use crate::messages::portfolio::document::utility_types::network_interface::{DocumentNodePersistentMetadata, InputMetadata, NodeTemplate, WidgetOverride};
use graph_craft::document::*;
use graphene_std::registry::*;
use graphene_std::*;
use std::collections::{HashMap, HashSet};
@@ -13,7 +14,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
let network_nodes = custom
.into_iter()
.filter_map(|definition| {
if let NodeTemplateImplementation::ProtoNode(proto_node_identifier) = &definition.node_template.implementation {
if let DocumentNodeImplementation::ProtoNode(proto_node_identifier) = &definition.node_template.document_node.implementation {
definitions_map.insert(DefinitionIdentifier::ProtoNode(proto_node_identifier.clone()), definition);
return None;
};
@@ -28,7 +29,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
// fallback when deriving `call_argument` so it reflects the impls actually registered, which will usually be `Context`.
let extended_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
let node_registry = NODE_REGISTRY.lock().unwrap();
let empty_implementations: Vec<(NodeConstructor, NodeIOTypes)> = Vec::new();
let empty_implementations: Vec<RegistryEntry> = Vec::new();
let context_type = concrete!(Context);
for (id, metadata) in NODE_METADATA.lock().unwrap().iter() {
let identifier = DefinitionIdentifier::ProtoNode(id.clone());
@@ -41,18 +42,17 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
fields,
description,
properties,
context_features,
..
} = metadata;
let implementations = node_registry.get(id).unwrap_or(&empty_implementations);
let first_node_io = implementations.first().map(|(_, node_io)| node_io).unwrap_or(const { &NodeIOTypes::empty() });
let first_node_io = implementations.first().map(|entry| &entry.io).unwrap_or(const { &NodeIOTypes::empty() });
let call_arguments: Vec<&Type> = if !implementations.is_empty() {
implementations.iter().map(|(_, io)| &io.call_argument).collect()
implementations.iter().map(|entry| &entry.io.call_argument).collect()
} else if let Some(impls) = extended_node_registry.get(id) {
impls.keys().map(|io| &io.call_argument).collect()
impls.iter().map(|entry| &entry.io.call_argument).collect()
} else {
Vec::new()
};
@@ -71,21 +71,29 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
DocumentNodeDefinition {
identifier: display_name,
node_template: NodeTemplate {
inputs,
call_argument: input_type.clone(),
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
context_features: ContextDependencies::from(context_features.as_slice()),
// TODO: Store information for input overrides in the node macro
input_metadata: fields
.iter()
.map(|f| match f.widget_override {
RegistryWidgetOverride::None => (f.name, f.description).into(),
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Hidden),
RegistryWidgetOverride::String(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::String(str.to_string())),
RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())),
})
.collect(),
..Default::default()
document_node: DocumentNode {
inputs,
call_argument: input_type.clone(),
implementation: DocumentNodeImplementation::ProtoNode(id.clone()),
visible: true,
skip_deduplication: false,
context_features: ContextDependencies::default(),
..Default::default()
},
persistent_node_metadata: DocumentNodePersistentMetadata {
// TODO: Store information for input overrides in the node macro
input_metadata: fields
.iter()
.map(|f| match f.widget_override {
RegistryWidgetOverride::None => (f.name, f.description).into(),
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Hidden),
RegistryWidgetOverride::String(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::String(str.to_string())),
RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())),
})
.collect(),
locked: false,
..Default::default()
},
},
category,
description: Cow::Borrowed(description),
@@ -96,14 +104,13 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
// Add the rest of the network nodes to the map and add the metadata for their internal protonodes
for mut network_node in network_nodes {
fill_proto_node_metadata(&mut network_node.node_template, &definitions_map);
traverse_node(&network_node.node_template.document_node, &mut network_node.node_template.persistent_node_metadata, &definitions_map);
// Set the reference to the node identifier
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
network_template.reference = Some(network_node.identifier.to_string());
if let Some(nested_metadata) = network_node.node_template.persistent_node_metadata.network_metadata.as_mut() {
nested_metadata.persistent_metadata.reference = Some(network_node.identifier.to_string());
// If it is not a merge node, then set the display name to the identifier/reference
if network_node.identifier != "Merge" {
network_node.node_template.display_name = network_node.identifier.to_string();
network_node.node_template.persistent_node_metadata.display_name = network_node.identifier.to_string();
}
}
definitions_map.insert(DefinitionIdentifier::Network(network_node.identifier.to_string()), network_node);
@@ -112,27 +119,27 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
definitions_map
}
/// Recursively fills each nested proto node's editor metadata from its definition, preserving only the authored position.
fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
match &mut node_template.implementation {
NodeTemplateImplementation::Network(network_template) => {
for nested_template in network_template.nodes.values_mut() {
fill_proto_node_metadata(nested_template, definitions_map);
/// Traverses a document node template and metadata in parallel to add metadata to the protonodes
fn traverse_node(node: &DocumentNode, node_metadata: &mut DocumentNodePersistentMetadata, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
match &node.implementation {
DocumentNodeImplementation::Network(node_network) => {
for (nested_node_id, nested_node) in node_network.nodes.iter() {
let nested_metadata = node_metadata.network_metadata.as_mut().unwrap().persistent_metadata.node_metadata.get_mut(nested_node_id).unwrap();
traverse_node(nested_node, &mut nested_metadata.persistent_metadata, definitions_map);
}
}
NodeTemplateImplementation::ProtoNode(id) => {
// If this lookup fails then the proto node id in the definition doesn't match what is generated by the macro
DocumentNodeImplementation::ProtoNode(id) => {
// Set all the metadata except the position to the proto node information from the macro
// TODO: Use options in the template to specify what you want to default and what you want to override
// If this fails then the proto node id in the definition doesn't match what is generated by the macro
let Some(definition) = definitions_map.get(&DefinitionIdentifier::ProtoNode(id.clone())) else {
// log::error!("Could not get definition for id {} when filling in protonode metadata for a custom node", id.clone());
return;
};
let definition_template = &definition.node_template;
node_template.display_name = definition_template.display_name.clone();
node_template.input_metadata = definition_template.input_metadata.clone();
node_template.output_names = definition_template.output_names.clone();
node_template.locked = definition_template.locked;
node_template.pinned = definition_template.pinned;
let mut new_metadata = definition.node_template.persistent_node_metadata.clone();
new_metadata.node_type_metadata = node_metadata.node_type_metadata.clone();
*node_metadata = new_metadata
}
NodeTemplateImplementation::Extract => {}
DocumentNodeImplementation::Extract => {}
}
}
@@ -157,7 +157,7 @@ pub enum NodeGraphMessage {
SetInputValue {
node_id: NodeId,
input_index: usize,
value: Box<TaggedValue>,
value: TaggedValue,
},
SetInput {
input_connector: InputConnector,
@@ -234,8 +234,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
x: (mid_point.x / 24.) as i32,
y: (mid_point.y / 24.) as i32,
});
let node_input_connector = InputConnector::primary_input(node_id);
let node_output_connector = OutputConnector::primary_output(node_id);
let node_input_connector = InputConnector::node(node_id, 0);
let node_output_connector = OutputConnector::node(node_id, 0);
responses.add(NodeGraphMessage::CreateWire {
output_connector,
input_connector: node_input_connector,
@@ -301,7 +301,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// A freshly added Text node carries no font, so give it the default font (registered like the Text tool does)
if node_type == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER) {
let font_resource_id = graph_craft::application_io::resource::ResourceId::new();
if let Some(font_input) = node_template.input_mut(graphene_std::text::text::FontInput) {
if let Some(font_input) = node_template.document_node.inputs.get_mut(graphene_std::text::text::FontInput::INDEX) {
*font_input = NodeInput::value(TaggedValue::Resource(font_resource_id), false);
}
responses.add(DocumentMessage::Resource(ResourceMessage::AddFont {
@@ -336,10 +336,10 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
};
// Ensure connection is to correct input of new node. If it does not have an input then do not connect
if let Some((input_index, _)) = node_template.inputs.iter().enumerate().find(|(_, input)| input.is_exposed()) {
if let Some((input_index, _)) = node_template.document_node.inputs.iter().enumerate().find(|(_, input)| input.is_exposed()) {
responses.add(NodeGraphMessage::CreateWire {
output_connector: *output_connector,
input_connector: InputConnector::node_at_index(node_id, input_index),
input_connector: InputConnector::node(node_id, input_index),
});
responses.add(NodeGraphMessage::RunDocumentGraph);
@@ -493,7 +493,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
*exposed = set_to_exposed;
}
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node_at_index(node_id, input_index),
input_connector: InputConnector::node(node_id, input_index),
input: node_input,
});
@@ -515,7 +515,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
return;
};
let encapsulating_connector = InputConnector::primary_input(*node_id);
let encapsulating_connector = InputConnector::node(*node_id, 0);
if !exposed {
network_interface.disconnect_input(&encapsulating_connector, network_path);
}
@@ -530,8 +530,19 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
network_interface.set_input(&encapsulating_connector, input, network_path);
// Disconnect all connections fed by the hidden import in the nested network
network_interface.disconnect_import_wires(0, breadcrumb_network_path);
let Some(outward_wires) = network_interface.outward_wires(breadcrumb_network_path) else {
log::error!("Could not get outward wires in remove_import");
return;
};
let Some(downstream_connections) = outward_wires.get(&OutputConnector::Import(0)).cloned() else {
log::error!("Could not get outward wires for import in remove_import");
return;
};
// Disconnect all connections in the encapsulating network
for downstream_connection in &downstream_connections {
network_interface.disconnect_input(downstream_connection, breadcrumb_network_path);
}
responses.add(NodeGraphMessage::UpdateImportsExports);
responses.add(NodeGraphMessage::SendWires);
@@ -554,7 +565,18 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// Disconnect all connections in the encapsulating network
if let Some((encapsulating_node, encapsulating_path)) = breadcrumb_network_path.split_last() {
network_interface.disconnect_output_wires(&OutputConnector::primary_output(*encapsulating_node), encapsulating_path);
let Some(outward_wires) = network_interface.outward_wires(encapsulating_path) else {
log::error!("Could not get outward wires in remove_import");
return;
};
let Some(downstream_connections) = outward_wires.get(&OutputConnector::node(*encapsulating_node, 0)).cloned() else {
log::error!("Could not get outward wires for import in remove_import");
return;
};
for downstream_connection in &downstream_connections {
network_interface.disconnect_input(downstream_connection, encapsulating_path);
}
}
responses.add(NodeGraphMessage::UpdateImportsExports);
@@ -596,7 +618,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// Ensure that nodes can be grouped by checking if there is an unselected node between selected nodes
for selected_node_id in &selected_node_ids {
for input_index in 0..network_interface.number_of_inputs(selected_node_id, breadcrumb_network_path) {
let input_connector = InputConnector::node_at_index(*selected_node_id, input_index);
let input_connector = InputConnector::node(*selected_node_id, input_index);
if let Some(upstream_deselected_node_id) = network_interface
.upstream_output_connector(&input_connector, breadcrumb_network_path)
.and_then(|output_connector| output_connector.node_id())
@@ -618,7 +640,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
for node_id in nodes_sorted_top_to_bottom {
for input_index in 0..network_interface.number_of_inputs(&node_id, breadcrumb_network_path) {
let current_input_connector = InputConnector::node_at_index(node_id, input_index);
let current_input_connector = InputConnector::node(node_id, input_index);
let Some(upstream_connector) = network_interface.upstream_output_connector(&current_input_connector, breadcrumb_network_path) else {
continue;
};
@@ -671,7 +693,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
return;
};
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
default_node_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
default_node_template.persistent_node_metadata.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
responses.add(DocumentMessage::AddTransaction);
responses.add(NodeGraphMessage::InsertNode {
node_id: encapsulating_node_id,
@@ -715,7 +737,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
for (input_index, output_connector) in input_connections.into_iter().enumerate() {
responses.add(NodeGraphMessage::CreateWire {
output_connector,
input_connector: InputConnector::node_at_index(encapsulating_node_id, input_index),
input_connector: InputConnector::node(encapsulating_node_id, input_index),
});
}
for (output_index, input_connectors) in output_connections.into_iter().enumerate() {
@@ -1157,8 +1179,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
data_type: self.wire_in_progress_type,
thick: false,
dashed: false,
is_list: false,
center_path_string: String::new(),
};
responses.add(FrontendMessage::UpdateWirePathInProgress { wire_path: Some(wire_path) });
}
@@ -1330,7 +1350,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.shift_without_push = false;
// Reset all offsets to end the rubber banding while dragging
network_interface.clear_drag_offsets(selection_network_path);
network_interface.unload_stack_dependents_y_offset(selection_network_path);
let Some(selected_nodes) = network_interface.selected_nodes_in_nested_network(selection_network_path) else {
log::error!("Could not get selected nodes in PointerUp");
return;
@@ -1359,7 +1379,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
.cloned()
.collect::<Vec<_>>()
{
network_interface.try_set_upstream_to_chain(&InputConnector::layer_secondary_input(layer), selection_network_path);
network_interface.try_set_upstream_to_chain(&InputConnector::node(layer, 1), selection_network_path);
}
responses.add(NodeGraphMessage::SendGraph);
@@ -1370,11 +1390,9 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// Check if a single node was dragged onto a wire and that the node was dragged onto the wire
if selected_nodes.selected_nodes_ref().len() == 1 && !self.begin_dragging {
let selected_node_id = selected_nodes.selected_nodes_ref()[0];
let has_primary_output_connection = network_interface.outward_wires(selection_network_path).is_some_and(|outward_wires| {
outward_wires
.get(&OutputConnector::primary_output(selected_node_id))
.is_some_and(|outward_wires| !outward_wires.is_empty())
});
let has_primary_output_connection = network_interface
.outward_wires(selection_network_path)
.is_some_and(|outward_wires| outward_wires.get(&OutputConnector::node(selected_node_id, 0)).is_some_and(|outward_wires| !outward_wires.is_empty()));
if !has_primary_output_connection {
let Some(network) = network_interface.nested_network(selection_network_path) else {
return;
@@ -1399,7 +1417,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// Prevent inserting on a link that is connected upstream to the selected node
for upstream_node in network_interface.upstream_flow_back_from_nodes(vec![selected_node_id], selection_network_path, network_interface::FlowType::UpstreamFlow) {
for input_index in 0..network_interface.number_of_inputs(&upstream_node, selection_network_path) {
wires_to_check.remove(&InputConnector::node_at_index(upstream_node, input_index));
wires_to_check.remove(&InputConnector::node(upstream_node, input_index));
}
}
@@ -1413,7 +1431,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
return None;
}
let (wire, _center_line, is_stack) = network_interface.vector_wire_from_input(&input, preferences.graph_wire_style, selection_network_path)?;
let (wire, is_stack) = network_interface.vector_wire_from_input(&input, preferences.graph_wire_style, selection_network_path)?;
let node_bbox = kurbo::Rect::new(node_bbox[0].x, node_bbox[0].y, node_bbox[1].x, node_bbox[1].y).to_path(DEFAULT_ACCURACY);
let inside = bezpath_is_inside_bezpath(&wire, &node_bbox, None, None);
@@ -1509,7 +1527,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
}
NodeGraphMessage::ShakeNode => {
let Some((drag_start, _)) = &mut self.drag_start else {
let Some(drag_start) = &self.drag_start else {
log::error!("Drag start should be initialized when shaking a node");
return;
};
@@ -1527,11 +1545,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
.transform_point2(viewport_location);
// Collect the distance to move the shaken nodes after the undo
let graph_delta = IVec2::new(((point.x - drag_start.start_x) / 24.).round() as i32, ((point.y - drag_start.start_y) / 24.).round() as i32);
// Keep the incremental rounding baseline in sync with the total shift reapplied below
drag_start.round_x = graph_delta.x;
drag_start.round_y = graph_delta.y;
let graph_delta = IVec2::new(((point.x - drag_start.0.start_x) / 24.).round() as i32, ((point.y - drag_start.0.start_y) / 24.).round() as i32);
// Undo to the state of the graph before shaking
responses.add(DocumentMessage::AbortTransaction);
@@ -1560,7 +1574,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
for selected_node in &all_selected_nodes {
// Handle inputs of selected node
for input_index in 0..network_interface.number_of_inputs(selected_node, selection_network_path) {
let input_connector = InputConnector::node_at_index(*selected_node, input_index);
let input_connector = InputConnector::node(*selected_node, input_index);
// Only disconnect inputs to non selected nodes
if network_interface
.upstream_output_connector(&input_connector, selection_network_path)
@@ -1571,13 +1585,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
let number_of_outputs = network_interface.number_of_outputs(selected_node, selection_network_path);
let mut first_deselected_upstream_output = network_interface.upstream_output_connector(&InputConnector::primary_input(*selected_node), selection_network_path);
let mut first_deselected_upstream_output = network_interface.upstream_output_connector(&InputConnector::node(*selected_node, 0), selection_network_path);
while let Some(OutputConnector::Node { node_id, .. }) = &first_deselected_upstream_output {
if !all_selected_nodes.contains(node_id) {
break;
}
first_deselected_upstream_output = network_interface.upstream_output_connector(&InputConnector::primary_input(*node_id), selection_network_path);
first_deselected_upstream_output = network_interface.upstream_output_connector(&InputConnector::node(*node_id, 0), selection_network_path);
}
let Some(outward_wires) = network_interface.outward_wires(selection_network_path) else {
@@ -1600,7 +1614,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// Handle reconnection
// Find first non selected upstream node by primary flow
if let Some(first_deselected_upstream_output) = first_deselected_upstream_output {
let Some(downstream_connections_to_first_output) = outward_wires.get(&OutputConnector::primary_output(*selected_node)).cloned() else {
let Some(downstream_connections_to_first_output) = outward_wires.get(&OutputConnector::node(*selected_node, 0)).cloned() else {
log::error!("Could not get downstream_connections_to_first_output in shake node");
return;
};
@@ -1712,13 +1726,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
continue;
};
// Expand the cull box by a grid cell so a node stays rendered until its connectors, which reach beyond its bounding box, also leave the viewport
let cull_margin = 24.;
if node_bbox[1].x + cull_margin >= document_bbox[0].x
&& node_bbox[0].x - cull_margin <= document_bbox[1].x
&& node_bbox[1].y + cull_margin >= document_bbox[0].y
&& node_bbox[0].y - cull_margin <= document_bbox[1].y
{
if node_bbox[1].x >= document_bbox[0].x && node_bbox[0].x <= document_bbox[1].x && node_bbox[1].y >= document_bbox[0].y && node_bbox[0].y <= document_bbox[1].y {
nodes.push(*node_id);
}
for error in &network_interface.resolved_types.node_graph_errors {
@@ -1734,7 +1742,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
responses.add(NodeGraphMessage::UpdateLayerPanel);
responses.add(DocumentMessage::DocumentStructureChanged);
responses.add(PropertiesPanelMessage::Refresh);
responses.add(EventMessage::GraphChanged);
if breadcrumb_network_path == selection_network_path && graph_view_overlay_open {
let nodes = self.collect_nodes(network_interface, breadcrumb_network_path);
self.frontend_nodes = nodes.iter().map(|node| node.id).collect();
@@ -1762,16 +1769,16 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
let is_text_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER));
let is_stroke_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER));
let is_fill_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER));
let is_fill_input = is_fill_node && input_index == graphene_std::vector::fill::PaintInput::INDEX;
let is_fill_input = is_fill_node && input_index == graphene_std::vector::fill::FillInput::INDEX;
let is_shape_generator_node = reference.as_ref().is_some_and(|r| {
[regular_polygon::IDENTIFIER, star::IDENTIFIER, arc::IDENTIFIER, spiral::IDENTIFIER, grid::IDENTIFIER, arrow::IDENTIFIER]
.into_iter()
.any(|id| *r == DefinitionIdentifier::ProtoNode(id))
});
let input = NodeInput::value(*value, false);
let input = NodeInput::value(value, false);
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node_at_index(node_id, input_index),
input_connector: InputConnector::node(node_id, input_index),
input,
});
responses.add(PropertiesPanelMessage::Refresh);
@@ -1797,7 +1804,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
network_interface.shift_selected_nodes(direction, self.shift_without_push, selection_network_path);
if !rubber_band {
network_interface.clear_drag_offsets(selection_network_path);
network_interface.unload_stack_dependents_y_offset(selection_network_path);
}
if graph_view_overlay_open {
@@ -2160,37 +2167,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
responses.add(NodeGraphMessage::SendGraph);
}
NodeGraphMessage::UpdateTypes { resolved_types, node_graph_errors } => {
// Hidden passthrough nodes let a wire borrow its color and rank from an upstream node, so any type change can restyle wires whose own node is unchanged.
// Compare each displayed wire's style (color, rank) across the update and unload only those that changed, so value-only recompiles keep their built wire paths.
let types_changed = !resolved_types.add.is_empty() || !resolved_types.remove.is_empty();
let wire_style = |network_interface: &mut NodeNetworkInterface, input: &InputConnector| {
network_interface.upstream_output_connector(input, breadcrumb_network_path).map(|output| {
let output_type = network_interface.output_type(&output, breadcrumb_network_path);
(output_type.displayed_type(), output_type.is_list())
})
};
let styles_before = types_changed.then(|| {
network_interface
.node_graph_input_connectors(breadcrumb_network_path)
.into_iter()
.map(|input| {
let style = wire_style(network_interface, &input);
(input, style)
})
.collect::<Vec<_>>()
});
network_interface.resolved_types.update(resolved_types, node_graph_errors);
if let Some(styles_before) = styles_before {
for (input, style_before) in styles_before {
if wire_style(network_interface, &input) != style_before {
network_interface.unload_wire(&input, breadcrumb_network_path);
}
}
}
responses.add(NodeGraphMessage::SendGraph);
}
NodeGraphMessage::UpdateActionButtons => {
if selection_network_path == breadcrumb_network_path {
@@ -2614,7 +2591,7 @@ impl NodeGraphMessageHandler {
.popover_layout({
let compatible_type = context
.network_interface
.upstream_output_connector(&InputConnector::layer_secondary_input(layer), &[])
.upstream_output_connector(&InputConnector::node(layer, 1), &[])
.and_then(|upstream_output| context.network_interface.output_type(&upstream_output, &[]).add_node_string());
let mut node_chooser = NodeCatalog::new();
@@ -2711,7 +2688,7 @@ impl NodeGraphMessageHandler {
};
let mut nodes = Vec::new();
for (node_id, visible) in network.nodes.iter().map(|(node_id, node)| (*node_id, node.visible)).collect::<Vec<_>>() {
let primary_input_connector = InputConnector::primary_input(node_id);
let primary_input_connector = InputConnector::node(node_id, 0);
let primary_input = if network_interface
.input_from_connector(&primary_input_connector, breadcrumb_network_path)
@@ -2722,10 +2699,10 @@ impl NodeGraphMessageHandler {
None
};
let exposed_inputs = (1..network_interface.number_of_inputs(&node_id, breadcrumb_network_path))
.filter_map(|input_index| network_interface.frontend_input_from_connector(&InputConnector::node_at_index(node_id, input_index), breadcrumb_network_path))
.filter_map(|input_index| network_interface.frontend_input_from_connector(&InputConnector::node(node_id, input_index), breadcrumb_network_path))
.collect();
let primary_output = network_interface.frontend_output_from_connector(&OutputConnector::primary_output(node_id), breadcrumb_network_path);
let primary_output = network_interface.frontend_output_from_connector(&OutputConnector::node(node_id, 0), breadcrumb_network_path);
let exposed_outputs = (1..network_interface.number_of_outputs(&node_id, breadcrumb_network_path))
.filter_map(|output_index| network_interface.frontend_output_from_connector(&OutputConnector::node(node_id, output_index), breadcrumb_network_path))
@@ -2853,7 +2830,7 @@ impl NodeGraphMessageHandler {
}))
);
let clippable = layer.can_be_clipped(network_interface.document_metadata()) && network_interface.layer_hosts_blending_nodes(&node_id, &[]);
let clippable = layer.can_be_clipped(network_interface.document_metadata());
let data = LayerPanelEntry {
id: node_id,
File diff suppressed because it is too large. Load diff
@@ -1,5 +1,10 @@
use graph_craft::document::NodeId;
use graphene_std::{Type, simplify_identifier_name};
use graph_craft::document::value::TaggedValue;
use graphene_std::Type;
use graphene_std::list::List;
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::vector::Vector;
use graphene_std::{Artboard, Graphic};
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
@@ -19,22 +24,20 @@ pub enum FrontendGraphDataType {
impl FrontendGraphDataType {
pub fn from_type(input: &Type) -> Self {
// Color a wire by its element type, peeling a rank-0 `Item` or rank-1 `List` wrapper (and a whole-list `Bundle` cell) so all ranks share the element's color
let nested_type = input.nested_type();
let element = match nested_type.bundle_element_name() {
Some(bundle_element) => simplify_identifier_name(bundle_element),
None => nested_type.list_element().unwrap_or(nested_type).identifier_name(),
};
match element.as_str() {
"Vector" => Self::Vector,
"Graphic" => Self::Graphic,
"Artboard" => Self::Artboard,
"Color" => Self::Color,
"Gradient" => Self::Gradient,
"String" => Self::Typography,
"f64" | "f32" | "u32" | "u64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
raster if raster.starts_with("Raster") => Self::Raster,
match TaggedValue::from_type_or_none(input) {
TaggedValue::U32(_) | TaggedValue::U64(_) | TaggedValue::F32(_) | TaggedValue::F64(_) | TaggedValue::DVec2(_) | TaggedValue::F64Array(_) | TaggedValue::DAffine2(_) => Self::Number,
TaggedValue::Color(_) => Self::Color,
TaggedValue::LegacyGradient(_) | TaggedValue::Gradient(_) => Self::Gradient,
TaggedValue::String(_) => Self::Typography,
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) => Self::Graphic,
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) => Self::Artboard,
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Raster<CPU>>>()) => Self::Raster,
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) => Self::Vector,
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<String>>()) => Self::Typography,
_ => Self::General,
},
_ => Self::General,
}
}
@@ -5,7 +5,7 @@ use crate::messages::prelude::*;
use glam::DVec2;
use graphene_std::color::SRGBA8;
use graphene_std::renderer::Quad;
use graphene_std::vector::style::FillChoice;
use graphene_std::vector::style::FillChoiceUI;
fn grid_overlay_rectangular(document: &DocumentMessageHandler, overlay_context: &mut OverlayContext, spacing: DVec2) {
let origin = document.snapping_state.grid.origin;
@@ -274,7 +274,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
Separator::new(SeparatorStyle::Related).widget_instance(),
]);
color_widgets.push(
ColorInput::new(FillChoice::<SRGBA8>::Solid(SRGBA8::from_hex_str(&grid.color).unwrap_or(SRGBA8::BLACK)))
ColorInput::new(FillChoiceUI::Solid(SRGBA8::from_hex_str(&grid.color).unwrap_or(SRGBA8::BLACK)))
.tooltip_label("Grid Display Color")
.allow_none(false)
.on_update(update_val::<ColorInput, _>(grid, |grid, color| {
@@ -2,14 +2,16 @@ use super::utility_types::{DrawHandles, OverlayContext};
use crate::consts::HIDE_HANDLE_DISTANCE;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
pub use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
use crate::messages::portfolio::fonts::FALLBACK_FONT_RESOURCE;
use crate::messages::tool::common_functionality::shape_editor::{SelectedLayerState, ShapeState};
use crate::messages::tool::tool_messages::tool_prelude::DocumentMessageHandler;
use glam::{DAffine2, DVec2};
use graphene_std::subpath::{Bezier, BezierHandles};
use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
use graphene_std::vector::misc::ManipulatorPointId;
use graphene_std::vector::{PointId, SegmentId, Vector};
use std::collections::HashMap;
use std::sync::{LazyLock, Mutex};
#[cfg(target_family = "wasm")]
use wasm_bindgen::JsCast;
@@ -220,6 +222,24 @@ pub fn path_endpoint_overlays(document: &DocumentMessageHandler, shape_editor: &
}
}
pub static GLOBAL_TEXT_CONTEXT: LazyLock<Mutex<TextContext>> = LazyLock::new(|| Mutex::new(TextContext::default()));
pub fn text_width(text: &str, font_size: f64) -> f64 {
let typesetting = TypesettingConfig {
font_size,
line_height_ratio: 1.2,
letter_spacing: 0.,
letter_tilt: 0.,
max_width: None,
max_height: None,
align: TextAlign::AlignLeft,
};
let mut text_context = GLOBAL_TEXT_CONTEXT.lock().expect("Failed to lock global text context");
let bounds = text_context.bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
bounds.x
}
pub fn hex_to_rgba_u8(hex: &str) -> [u8; 4] {
let hex = hex.trim().trim_start_matches('#');
if hex.len() != 6 && hex.len() != 8 {
@@ -3,12 +3,11 @@ use crate::consts::{
COLOR_OVERLAY_YELLOW_DULL, COMPASS_ROSE_ARROW_SIZE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_MAIN_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER, DOWEL_PIN_RADIUS,
GRADIENT_MIDPOINT_DIAMOND_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE, PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
};
use crate::messages::portfolio::document::overlays::utility_functions::hex_to_rgba_u8;
use crate::messages::portfolio::document::overlays::utility_functions::{GLOBAL_TEXT_CONTEXT, hex_to_rgba_u8};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::fonts::FALLBACK_FONT_RESOURCE;
use crate::messages::prelude::Message;
use crate::messages::prelude::ViewportMessageHandler;
use crate::messages::tool::common_functionality::shapes::shape_utility::format_rounded;
use core::borrow::Borrow;
use core::f64::consts::{FRAC_PI_2, PI, TAU};
use glam::{DAffine2, DVec2};
@@ -16,7 +15,7 @@ use graphene_std::ATTR_TRANSFORM;
use graphene_std::list::List;
use graphene_std::math::quad::Quad;
use graphene_std::subpath::{self, Subpath};
use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::vector::click_target::ClickTargetType;
use graphene_std::vector::misc::point_to_dvec2;
use graphene_std::vector::{PointId, SegmentId, Vector};
@@ -1117,17 +1116,17 @@ impl OverlayContextInternal {
align: TextAlign::AlignLeft,
};
// Lay out the text once, taking its dimensions and vector paths from the same thread-local context pass
let (text_size, text_list) = TextContext::with_thread_local(|text_context| {
let text_size = text_context.bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
let text_list = text_context.to_path(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
(text_size, text_list)
});
// Get text dimensions directly from layout
let mut text_context = GLOBAL_TEXT_CONTEXT.lock().expect("Failed to lock global text context");
let text_size = text_context.bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
let text_width = text_size.x;
let text_height = text_size.y;
// Create a rect from the size (assuming text starts at origin)
let text_bounds = kurbo::Rect::new(0., 0., text_width, text_height);
// Convert text to vector paths for rendering
let text_list = text_context.to_path(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
// Calculate position based on pivot
let mut position = DVec2::ZERO;
match pivot[0] {
@@ -1190,7 +1189,7 @@ impl OverlayContextInternal {
let width = match typed_string {
Some(ref typed_string) => typed_string,
None => &format_rounded(translation.x, 2),
None => &format!("{:.2}", translation.x).trim_end_matches('0').trim_end_matches('.').to_string(),
};
let x_transform = DAffine2::from_translation((quad.top_left() + quad.top_right()) / 2.);
self.text(width, COLOR_OVERLAY_BLUE, None, x_transform, 4., [Pivot::Middle, Pivot::End]);
@@ -1201,7 +1200,7 @@ impl OverlayContextInternal {
let height = match typed_string {
Some(ref typed_string) => typed_string,
None => &format_rounded(translation.y, 2),
None => &format!("{:.2}", translation.y).trim_end_matches('0').trim_end_matches('.').to_string(),
};
let y_transform = DAffine2::from_translation((quad.top_left() + quad.bottom_left()) / 2.);
let height_pivot = if translation.x > -1e-3 { Pivot::Start } else { Pivot::End };
@@ -7,7 +7,6 @@ use crate::consts::{
};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::prelude::Message;
use crate::messages::tool::common_functionality::shapes::shape_utility::format_rounded;
use crate::messages::viewport::ViewportMessageHandler;
use core::borrow::Borrow;
use core::f64::consts::{FRAC_PI_2, PI, TAU};
@@ -1091,7 +1090,7 @@ impl OverlayContext {
let width = match typed_string {
Some(ref typed_string) => typed_string,
None => &format_rounded(translation.x, 2),
None => &format!("{:.2}", translation.x).trim_end_matches('0').trim_end_matches('.').to_string(),
};
let x_transform = DAffine2::from_translation((quad.top_left() + quad.top_right()) / 2.);
self.text(width, COLOR_OVERLAY_BLUE, None, x_transform, 4., [Pivot::Middle, Pivot::End]);
@@ -1102,7 +1101,7 @@ impl OverlayContext {
let height = match typed_string {
Some(ref typed_string) => typed_string,
None => &format_rounded(translation.y, 2),
None => &format!("{:.2}", translation.y).trim_end_matches('0').trim_end_matches('.').to_string(),
};
let y_transform = DAffine2::from_translation((quad.top_left() + quad.bottom_left()) / 2.);
let height_pivot = if translation.x > -1e-3 { Pivot::Start } else { Pivot::End };
@@ -16,7 +16,6 @@ use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{StorageMetadataView, build_interface_from_storage};
use crate::test_utils::test_prelude::*;
use graphene_std::NodeParameter;
use graphene_std::vector::style::RenderMode;
/// Every node addressable in `original` resolves identically through the round-tripped interface:
@@ -709,171 +708,3 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
// Autosaving the undone state still round-trips cleanly (no drift panic).
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
}
/// The document's single Fill node, as `(network_path, node_id)`.
fn find_fill_node(document: &DocumentMessageHandler) -> (Vec<graph_craft::document::NodeId>, graph_craft::document::NodeId) {
node_paths(&document.network_interface)
.into_iter()
.find(|(network_path, node_id)| {
let Some(network) = document.network_interface.nested_network(network_path) else { return false };
network.nodes[node_id].implementation == graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER)
})
.expect("the document should contain a Fill node")
}
/// The stored paint value of the document's single Fill node.
fn fill_paint_value(document: &DocumentMessageHandler) -> graph_craft::document::value::TaggedValue {
let (network_path, node_id) = find_fill_node(document);
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
let input = network.nodes[&node_id].input(graphene_std::vector::fill::PaintInput).expect("Fill should have a paint input");
input.as_value().expect("the paint input should hold a value").clone()
}
#[tokio::test]
async fn none_fill_survives_document_reopen() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
// Pick the red-slash "none" paint, stored the same way as the Fill widget's None choice
let (_, fill_node_id) = find_fill_node(editor.active_document());
editor
.handle_message(NodeGraphMessage::SetInputValue {
node_id: fill_node_id,
input_index: graphene_std::vector::fill::PaintInput::INDEX,
value: graph_craft::document::value::TaggedValue::no_paint().into(),
})
.await;
assert!(fill_paint_value(editor.active_document()).is_no_paint(), "the None pick should store as no_paint");
// Reopen through the editor's real open path, which runs the document migrations
let serialized = editor.active_document().serialize_document();
editor
.handle_message(PortfolioMessage::OpenDocumentFile {
document_name: None,
document_path: None,
document_serialized_content: serialized,
})
.await;
let reopened_paint = fill_paint_value(editor.active_document());
assert!(reopened_paint.is_no_paint(), "a none fill should survive reopening, but the stored paint became {reopened_paint:?}");
}
#[tokio::test]
async fn legacy_four_input_fill_migrates_to_the_split_transform_shape() {
use graph_craft::document::value::TaggedValue;
// A minimal master-era document: a 4-input Fill (content, fill: wired, backup color, backup gradient) fed by another node
const LEGACY_DOCUMENT: &str = r#"{"network_interface":{"network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[1,{"inputs":[{"Value":{"tagged_value":{"GraphicGroup":{"instance":[],"transform":[],"alpha_blending":[],"source_node_id":[]}},"exposed":true}},{"Node":{"node_id":2,"output_index":0,"lambda":false}},{"Value":{"tagged_value":{"OptionalColor":null},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"stops":[[0.0,{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],[1.0,{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]],"gradient_type":"Linear","start":[0.0,0.5],"end":[1.0,0.5],"transform":[1.0,0.0,0.0,1.0,0.0,0.0]}},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"GradientStops":[[0.0,{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}],[1.0,{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::ops::SampleGradientNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]},"network_metadata":{"persistent_metadata":{"node_metadata":[[1,{"persistent_metadata":{"reference":"Fill","display_name":"","input_properties":[{"input_data":{"input_name":"Vector Data"},"widget_override":null},{"input_data":{"input_name":"Fill"},"widget_override":null},{"input_data":{"input_name":"Backup Color"},"widget_override":null},{"input_data":{"input_name":"Backup Gradient"},"widget_override":null}],"output_names":["Future<Instances<VectorData>>"],"has_primary_output":true,"locked":false,"pinned":false,"node_type_metadata":{"Node":{"position":{"Absolute":[0,0]}}},"network_metadata":null}}],[2,{"persistent_metadata":{"reference":"Sample Gradient","display_name":"","input_properties":[{"input_data":{"input_name":"Primary"},"widget_override":null},{"input_data":{"input_name":"Gradient"},"widget_override":null},{"input_data":{"input_name":"Position"},"widget_override":null}],"output_names":["Future<Color>"],"has_primary_output":true,"locked":false,"pinned":false,"node_type_metadata":{"Node":{"position":{"Absolute":[-20,0]}}},"network_metadata":null}}]],"previewing":"No","navigation_metadata":{"node_graph_ptz":{"pan":[0.0,0.0],"tilt":0.0,"zoom":1.0,"flip":false},"node_graph_to_viewport":[1.0,0.0,0.0,1.0,0.0,0.0],"node_graph_top_right":[0.0,0.0]},"selection_undo_history":[],"selection_redo_history":[]}}},"collapsed":[],"name":"legacy_fill.graphite","commit_hash":"0000000000000000000000000000000000000000","document_ptz":{"pan":[0.0,0.0],"tilt":0.0,"zoom":1.0,"flip":false},"document_mode":"DesignMode","view_mode":"Normal","overlays_visibility_settings":{"all":true,"artboard_name":true,"compass_rose":true,"quick_measurement":true,"transform_measurement":true,"transform_cage":true,"hover_outline":true,"selection_outline":true,"pivot":true,"path":true,"anchors":true,"handles":true},"rulers_visible":true,"snapping_state":{"snapping_enabled":true,"grid_snapping":false,"artboards":true,"tolerance":8.0,"bounding_box":{"center_point":true,"corner_point":true,"edge_midpoint":true,"align_with_edges":true,"distribute_evenly":true},"path":{"anchor_point":true,"line_midpoint":true,"along_path":true,"normal_to_path":true,"tangent_to_path":true,"path_intersection_point":true,"align_with_anchor_point":true,"perpendicular_from_endpoint":true},"grid":{"origin":[0.0,0.0],"grid_type":{"Rectangular":{"spacing":[1.0,1.0]}},"grid_color":{"red":0.6,"green":0.6,"blue":0.6,"alpha":1.0},"dot_display":false}},"graph_view_overlay_open":false,"graph_fade_artwork_percentage":80.0}"#;
// Deserializing alone must succeed, so a failure below is attributable to the migrations
DocumentMessageHandler::deserialize_document(LEGACY_DOCUMENT).expect("the legacy document should deserialize");
let mut editor = EditorTestUtils::create();
editor
.handle_message(PortfolioMessage::OpenDocumentFile {
document_name: None,
document_path: None,
document_serialized_content: LEGACY_DOCUMENT.to_string(),
})
.await;
let document = editor.active_document();
let (network_path, node_id) = find_fill_node(document);
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
let fill_node = &network.nodes[&node_id];
assert_eq!(fill_node.inputs.len(), 7, "the legacy Fill should upgrade to the 7-input shape");
let paint = fill_node.input(graphene_std::vector::fill::PaintInput);
assert!(
matches!(paint, Some(graph_craft::document::NodeInput::Node { .. })),
"the wired legacy fill should keep its connection, but became {paint:?}"
);
let has_transform = fill_node.input_value(graphene_std::vector::fill::HasTransformInput);
assert!(
matches!(has_transform, Some(TaggedValue::Bool(_))),
"the has-transform input should hold a bool, but became {has_transform:?}"
);
let transform = fill_node.input_value(graphene_std::vector::fill::TransformInput);
assert!(
matches!(transform, Some(TaggedValue::DAffine2(_))),
"the transform input should hold a matrix, but became {transform:?}"
);
// The Evaluate Gradient parameter held the tuple-form stops, which parse as the ramp value with even positions elided
let evaluate_gradient_node = &network.nodes[&graph_craft::document::NodeId(2)];
let stops = evaluate_gradient_node.input_value(graphene_std::math_nodes::evaluate_gradient::GradientInput);
let Some(TaggedValue::GradientRamp(ramp)) = stops else {
panic!("the legacy stops parameter should become a gradient ramp value, but became {stops:?}");
};
assert_eq!(
ramp.gradient_space,
graphene_std::vector::style::GradientSpace::RgbGamma,
"a legacy document's ramps should deserialize with the explicit gamma interpolation"
);
let stops = graphene_std::vector::Gradient::from(ramp);
assert_eq!(stops.len(), 2);
assert!(!stops.has_position_attribute(), "even legacy tuple positions should elide rather than materialize");
}
#[tokio::test]
async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
use graph_craft::document::value::TaggedValue;
use graphene_std::vector::style::GradientSpread;
// A minimal document from the era when the gradient spread was the Fill node's own sixth input (tagged `GradientSpreadMethod`), here set to Repeat
const EIGHT_INPUT_DOCUMENT: &str = r#"{"network_interface":{"network":{"exports":[{"Node":{"node_id":1,"output_index":0,"lambda":false}}],"nodes":[[1,{"inputs":[{"Value":{"tagged_value":{"GraphicGroup":{"instance":[],"transform":[],"alpha_blending":[],"source_node_id":[]}},"exposed":true}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]}}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0}]}}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Repeat"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"manual_composition":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<graphene_core::context::OwnedContextImpl>>","alias":null}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]},"network_metadata":{"persistent_metadata":{"node_metadata":[[1,{"persistent_metadata":{"reference":"Fill","display_name":"","input_properties":[{"input_data":{"input_name":"Content"},"widget_override":null},{"input_data":{"input_name":"Fill"},"widget_override":null},{"input_data":{"input_name":"Backup Color"},"widget_override":null},{"input_data":{"input_name":"Backup Gradient"},"widget_override":null},{"input_data":{"input_name":"Gradient Type"},"widget_override":null},{"input_data":{"input_name":"Spread Method"},"widget_override":null},{"input_data":{"input_name":"Has Transform"},"widget_override":null},{"input_data":{"input_name":"Transform"},"widget_override":null}],"output_names":[""],"has_primary_output":true,"locked":false,"pinned":false,"node_type_metadata":{"Node":{"position":{"Absolute":[0,0]}}},"network_metadata":null}}]],"previewing":"No","navigation_metadata":{"node_graph_ptz":{"pan":[0.0,0.0],"tilt":0.0,"zoom":1.0,"flip":false},"node_graph_to_viewport":[1.0,0.0,0.0,1.0,0.0,0.0],"node_graph_top_right":[0.0,0.0]},"selection_undo_history":[],"selection_redo_history":[]}}},"collapsed":[],"name":"eight_input_fill.graphite","commit_hash":"0000000000000000000000000000000000000000","document_ptz":{"pan":[0.0,0.0],"tilt":0.0,"zoom":1.0,"flip":false},"document_mode":"DesignMode","view_mode":"Normal","overlays_visibility_settings":{"all":true,"artboard_name":true,"compass_rose":true,"quick_measurement":true,"transform_measurement":true,"transform_cage":true,"hover_outline":true,"selection_outline":true,"pivot":true,"path":true,"anchors":true,"handles":true},"rulers_visible":true,"snapping_state":{"snapping_enabled":true,"grid_snapping":false,"artboards":true,"tolerance":8.0,"bounding_box":{"center_point":true,"corner_point":true,"edge_midpoint":true,"align_with_edges":true,"distribute_evenly":true},"path":{"anchor_point":true,"line_midpoint":true,"along_path":true,"normal_to_path":true,"tangent_to_path":true,"path_intersection_point":true,"align_with_anchor_point":true,"perpendicular_from_endpoint":true},"grid":{"origin":[0.0,0.0],"grid_type":{"Rectangular":{"spacing":[1.0,1.0]}},"grid_color":{"red":0.6,"green":0.6,"blue":0.6,"alpha":1.0},"dot_display":false}},"graph_view_overlay_open":false,"graph_fade_artwork_percentage":80.0}"#;
// Deserializing alone must succeed, so a failure below is attributable to the migrations
DocumentMessageHandler::deserialize_document(EIGHT_INPUT_DOCUMENT).expect("the eight-input document should deserialize");
let mut editor = EditorTestUtils::create();
editor
.handle_message(PortfolioMessage::OpenDocumentFile {
document_name: None,
document_path: None,
document_serialized_content: EIGHT_INPUT_DOCUMENT.to_string(),
})
.await;
let document = editor.active_document();
let (network_path, node_id) = find_fill_node(document);
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
let fill_node = &network.nodes[&node_id];
assert_eq!(fill_node.inputs.len(), 7, "the eight-input Fill should fold down to the 7-input shape");
let paint = fill_node.input_value(graphene_std::vector::fill::PaintInput);
let Some(TaggedValue::GradientRamp(ramp)) = paint else {
panic!("the fill input should keep its gradient ramp value, but became {paint:?}");
};
assert_eq!(ramp.gradient_spread, GradientSpread::Repeat, "the spread input's value should fold into the fill ramp");
assert_eq!(
ramp.gradient_space,
graphene_std::vector::style::GradientSpace::RgbGamma,
"a legacy document's ramps should deserialize with the explicit gamma interpolation"
);
let backup = fill_node.input_value(graphene_std::vector::fill::BackupGradientInput);
let Some(TaggedValue::GradientRamp(backup_ramp)) = backup else {
panic!("the backup gradient input should keep its gradient ramp value, but became {backup:?}");
};
assert_eq!(backup_ramp.gradient_spread, GradientSpread::Repeat, "the spread input's value should fold into the backup ramp");
assert_eq!(
backup_ramp.gradient_space,
graphene_std::vector::style::GradientSpace::RgbGamma,
"the backup ramp should carry the explicit gamma interpolation too"
);
let has_transform = fill_node.input_value(graphene_std::vector::fill::HasTransformInput);
assert!(
matches!(has_transform, Some(TaggedValue::Bool(false))),
"the has-transform input should shift down intact, but became {has_transform:?}"
);
let transform = fill_node.input_value(graphene_std::vector::fill::TransformInput);
assert!(
matches!(transform, Some(TaggedValue::DAffine2(_))),
"the transform input should shift down intact, but became {transform:?}"
);
}
@@ -20,6 +20,29 @@ pub fn load_demo(file_name: &str) -> DocumentMessageHandler {
DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {path}: {e:?}"))
}
/// Dev tool for the flip: runs each demo through the full open-time migration and writes the
/// re-saved form into the directory named by `DEMO_OUT`, so the CLI can render migrated copies
/// while the checked-in originals stay pristine until the flip's re-save.
#[test]
#[ignore = "dev tool: set DEMO_OUT and run explicitly"]
fn migrate_demo_artwork_into_demo_out() {
use crate::messages::portfolio::document_migration::{document_migration_reset_node_definition, document_migration_string_preprocessing, document_migration_upgrades};
let out_dir = std::env::var("DEMO_OUT").expect("set DEMO_OUT to the output directory");
for entry in std::fs::read_dir("../demo-artwork").unwrap() {
let path = entry.unwrap().path();
if path.extension().and_then(|extension| extension.to_str()) != Some("graphite") {
continue;
}
let content = std::fs::read_to_string(&path).unwrap();
let content = document_migration_string_preprocessing(content);
let reset = document_migration_reset_node_definition(&content);
let mut document = DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {}: {e:?}", path.display()));
document_migration_upgrades(&mut document, reset);
let out = format!("{out_dir}/{}", path.file_name().unwrap().to_string_lossy());
std::fs::write(out, document.serialize_document()).unwrap();
}
}
/// Walk every node in every nested network and collect `(network_path, local_id)` pairs, so a test can
/// iterate every node addressable from the metadata side.
pub fn node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)> {
@@ -6,7 +6,8 @@ use crate::messages::portfolio::document::utility_types::network_interface::Flow
use crate::messages::tool::common_functionality::graph_modification_utils;
use glam::{DAffine2, DVec2};
use graph_craft::document::NodeId;
use graphene_std::Appearance;
use graphene_std::Graphic;
use graphene_std::list::List;
use graphene_std::math::quad::Quad;
use graphene_std::subpath;
use graphene_std::transform::Footprint;
@@ -40,8 +41,12 @@ pub struct DocumentMetadata {
/// Vector data keyed by layer ID, used as fallback when no Path node exists.
/// This provides accurate SegmentIds for layers without explicit Path nodes.
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Vector>>,
/// Per-layer `ATTR_APPEARANCE` attribute, exposed so message handlers can read paint information that lives on the list.
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
/// Per-layer `ATTR_FILL` attribute, exposed so message handlers can read paint
/// information that lives on the list.
pub layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>,
/// Per-layer `ATTR_STROKE` attribute, exposed so message handlers can read
/// stroke paint information that lives on the list.
pub layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>,
/// Transform from document space to viewport space.
pub document_to_viewport: DAffine2,
}
@@ -228,15 +233,10 @@ impl DocumentMetadata {
/// stroke geometry when the layer is a vector with a stroke style. Falls back to the click-target-based
/// bounds for non-vector layers (groups, raster, text, color, gradient).
pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
if let Some(vector) = self.layer_vector_data.get(&layer) {
let stroke = self
.layer_appearance_attributes
.get(&layer)
.and_then(|appearance| appearance.first_coverage_of(graphene_std::Cover::Stroke))
.map(graphene_std::Coverage::stroke_params);
if let Some(bounds) = vector.stroke_inclusive_bounding_box_with_transform(self.transform_to_document(layer), stroke.as_ref()) {
return Some(bounds);
}
if let Some(vector) = self.layer_vector_data.get(&layer)
&& let Some(bounds) = vector.stroke_inclusive_bounding_box_with_transform(self.transform_to_document(layer))
{
return Some(bounds);
}
self.bounding_box_document(layer)
}
@@ -3,6 +3,5 @@ pub mod error;
pub mod misc;
pub mod network_interface;
pub mod nodes;
pub mod text_metrics;
pub mod transformation;
pub mod wires;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,403 +0,0 @@
use super::{InputConnector, OutputConnector, Previewing, RootNode, TransactionStatus};
use crate::messages::portfolio::document::node_graph::utility_types::Direction;
use crate::test_utils::test_prelude::*;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::uuid::NodeId;
fn assert_invariants(editor: &EditorTestUtils, context: &str) {
let violations = editor.active_document().network_interface.validate_invariants();
assert!(violations.is_empty(), "Invariant violations {context}:\n{}", violations.join("\n"));
}
fn rectangle_definition() -> DefinitionIdentifier {
DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)
}
fn new_artboard_message(id: NodeId) -> GraphOperationMessage {
GraphOperationMessage::NewArtboard {
id,
location: DVec2::ZERO,
dimensions: DVec2::new(400., 300.),
background: Color::WHITE,
clip: false,
}
}
#[tokio::test]
async fn invariants_hold_through_basic_editing_flow() {
let mut editor = EditorTestUtils::create();
// This test covers the interface's structural invariants. The storage dual-write is out of its scope and asserted by the storage round-trip tests.
editor.editor.handle_message(PreferencesMessage::ValidateStorageRoundTrip { enabled: false });
editor.new_document().await;
assert_invariants(&editor, "after opening a new document");
editor.handle_message(new_artboard_message(NodeId::new())).await;
assert_invariants(&editor, "after creating an artboard");
let rectangle = editor.create_node_by_name(rectangle_definition()).await;
assert_invariants(&editor, "after creating a node");
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![rectangle] }).await;
editor.handle_message(NodeGraphMessage::DeleteSelectedNodes { delete_children: true }).await;
assert_invariants(&editor, "after deleting the node");
editor.handle_message(DocumentMessage::Undo).await;
assert_invariants(&editor, "after undo");
editor.handle_message(DocumentMessage::Redo).await;
assert_invariants(&editor, "after redo");
}
#[tokio::test]
async fn deleting_a_node_with_children_prunes_them_from_the_selection() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let parent = editor.create_node_by_name(rectangle_definition()).await;
let child = editor.create_node_by_name(rectangle_definition()).await;
let network_interface = &mut editor.active_document_mut().network_interface;
assert!(network_interface.number_of_inputs(&parent, &[]) >= 2, "Test needs a secondary input to wire the child into");
// Wire the child into the parent's secondary input so it is a sole dependent, then select both and delete only the parent
network_interface.set_input(&InputConnector::node_at_index(parent, 1), NodeInput::node(child, 0), &[]);
network_interface.selected_nodes_mut(&[]).unwrap().set_selected_nodes(vec![parent, child]);
network_interface.delete_nodes(vec![parent], true, &[]);
assert!(network_interface.document_network().nodes.is_empty(), "Both the parent and its sole-dependent child should be deleted");
let remaining_selection = network_interface.selected_nodes_mut(&[]).unwrap().selected_nodes().copied().collect::<Vec<_>>();
assert!(remaining_selection.is_empty(), "Deleted children should be pruned from the selection, found {remaining_selection:?}");
assert_invariants(&editor, "after deleting a node with children");
}
#[tokio::test]
async fn deleting_a_node_keeps_children_shared_with_other_nodes() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let parent = editor.create_node_by_name(rectangle_definition()).await;
let sibling = editor.create_node_by_name(rectangle_definition()).await;
let shared_child = editor.create_node_by_name(rectangle_definition()).await;
let network_interface = &mut editor.active_document_mut().network_interface;
// Wire the same child into the secondary inputs of both nodes, then delete only the parent along with its children
network_interface.set_input(&InputConnector::node_at_index(parent, 1), NodeInput::node(shared_child, 0), &[]);
network_interface.set_input(&InputConnector::node_at_index(sibling, 1), NodeInput::node(shared_child, 0), &[]);
network_interface.delete_nodes(vec![parent], true, &[]);
let nodes = &network_interface.document_network().nodes;
assert!(!nodes.contains_key(&parent), "The deleted node itself should be gone");
assert!(nodes.contains_key(&shared_child), "A child shared with another node is not a sole dependent and should survive");
assert!(nodes.contains_key(&sibling), "The unrelated sibling should survive");
assert_invariants(&editor, "after deleting a node with a shared child");
}
#[tokio::test]
async fn cyclic_connection_is_rejected_without_side_effects() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let a = editor.create_node_by_name(rectangle_definition()).await;
let b = editor.create_node_by_name(rectangle_definition()).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_input(&InputConnector::node_at_index(a, 1), NodeInput::node(b, 0), &[]);
// Attempt to complete a cycle inside a transaction: the edit must be rejected without marking the transaction as modified
network_interface.start_transaction();
let input_before = network_interface.input_from_connector(&InputConnector::node_at_index(b, 1), &[]).cloned();
network_interface.set_input(&InputConnector::node_at_index(b, 1), NodeInput::node(a, 0), &[]);
let input_after = network_interface.input_from_connector(&InputConnector::node_at_index(b, 1), &[]).cloned();
assert_eq!(input_before, input_after, "A rejected cyclic connection should leave the input unchanged");
assert_eq!(
network_interface.transaction_status(),
TransactionStatus::Started,
"A rejected cyclic connection should not mark the transaction as modified"
);
network_interface.finish_transaction();
assert_invariants(&editor, "after rejecting a cyclic connection");
}
#[tokio::test]
async fn toggling_preview_on_a_disconnected_export() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.disconnect_input(&InputConnector::Export(0), &[]);
// Previewing a node while the export is disconnected is a preview with nothing to restore
network_interface.toggle_preview(node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None });
let export = network_interface.input_from_connector(&InputConnector::Export(0), &[]);
assert_eq!(export.and_then(|input| input.as_node()), Some(node), "The previewed node should be wired to the export");
// Ending the preview restores the disconnected export
network_interface.toggle_preview(node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
let export = network_interface.input_from_connector(&InputConnector::Export(0), &[]);
assert!(export.is_some_and(|input| input.as_node().is_none()), "Ending the preview should disconnect the export again");
assert_invariants(&editor, "after toggling preview twice");
}
#[tokio::test]
async fn artboard_identity_is_independent_of_scene_connectivity() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let network_interface = &mut editor.active_document_mut().network_interface;
assert!(network_interface.is_artboard(&artboard, &[]));
assert!(!network_interface.all_artboards().is_empty());
// Disconnecting the artboard from the export keeps its identity but removes it from the scene's artboards
network_interface.disconnect_input(&InputConnector::Export(0), &[]);
assert!(network_interface.is_artboard(&artboard, &[]), "Artboard identity should survive disconnection");
assert!(network_interface.all_artboards().is_empty(), "Disconnected artboards should not count as scene artboards");
assert_invariants(&editor, "after disconnecting an artboard");
}
#[tokio::test]
async fn selection_history_is_not_serialized() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node] }).await;
let serialized = editor.active_document().serialize_document();
assert!(!serialized.contains("selection_undo_history"), "Selection history should not be persisted into saved documents");
assert!(!serialized.contains("selection_redo_history"), "Selection history should not be persisted into saved documents");
}
fn merge_definition() -> DefinitionIdentifier {
DefinitionIdentifier::Network("Merge".to_string())
}
#[tokio::test]
async fn layer_stacking_follows_wiring() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let upper = editor.create_node_by_name_at(merge_definition(), 20, 10).await;
let lower = editor.create_node_by_name_at(merge_definition(), 20, 16).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_to_node_or_layer(&upper, &[], true);
network_interface.set_to_node_or_layer(&lower, &[], true);
assert!(network_interface.is_layer(&upper, &[]) && network_interface.is_layer(&lower, &[]));
assert!(network_interface.is_absolute(&lower, &[]));
// Wiring a layer into the bottom input of another layer converts it to stack positioning at its current visual spot
let lower_position_before = network_interface.position(&lower, &[]).expect("Lower layer should have a position");
network_interface.create_wire(&OutputConnector::primary_output(lower), &InputConnector::primary_input(upper), &[]);
assert!(network_interface.is_stack(&lower, &[]), "A layer feeding the bottom of a layer should be stack positioned");
let stacked_position = network_interface.position(&lower, &[]).expect("Stacked layer should have a position");
assert_eq!(stacked_position.y, lower_position_before.y, "Stacking should preserve the layer's vertical position");
// Disconnecting converts the layer back to absolute positioning without moving it
network_interface.disconnect_input(&InputConnector::primary_input(upper), &[]);
assert!(network_interface.is_absolute(&lower, &[]), "A disconnected stack layer should return to absolute positioning");
assert_eq!(network_interface.position(&lower, &[]), Some(stacked_position), "Unstacking should not move the layer");
assert_invariants(&editor, "after stacking and unstacking a layer");
}
#[tokio::test]
async fn chain_membership_follows_wiring() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let layer = editor.create_node_by_name_at(merge_definition(), 20, 10).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 15, 10).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_to_node_or_layer(&layer, &[], true);
// A node wired into a layer's secondary input from the same row, within chain distance, joins the chain
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::layer_secondary_input(layer), &[]);
assert!(
network_interface.is_chain(&node, &[]),
"A node feeding a layer's secondary input from chain range should become a chain node"
);
// Disconnecting breaks the chain and the node becomes absolute at its chain spot
let chained_y = network_interface.position(&node, &[]).expect("Chained node should have a position").y;
network_interface.disconnect_input(&InputConnector::layer_secondary_input(layer), &[]);
assert!(!network_interface.is_chain(&node, &[]), "Disconnecting should break the chain");
assert!(network_interface.is_absolute(&node, &[]));
assert_eq!(network_interface.position(&node, &[]).map(|position| position.y), Some(chained_y));
assert_invariants(&editor, "after forming and breaking a chain");
}
#[tokio::test]
async fn move_layer_to_stack_builds_the_layer_stack() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let first = editor.create_node_by_name_at(merge_definition(), 0, 30).await;
let second = editor.create_node_by_name_at(merge_definition(), 0, 40).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_to_node_or_layer(&first, &[], true);
network_interface.set_to_node_or_layer(&second, &[], true);
let artboard_layer = LayerNodeIdentifier::new(artboard, network_interface);
let first_layer = LayerNodeIdentifier::new(first, network_interface);
let second_layer = LayerNodeIdentifier::new(second, network_interface);
network_interface.move_layer_to_stack(first_layer, artboard_layer, 0, &[]);
let children = artboard_layer.children(network_interface.document_metadata()).collect::<Vec<_>>();
assert_eq!(children, vec![first_layer], "The first moved layer should become the artboard's only child");
network_interface.move_layer_to_stack(second_layer, artboard_layer, 1, &[]);
let children = artboard_layer.children(network_interface.document_metadata()).collect::<Vec<_>>();
assert_eq!(children, vec![first_layer, second_layer], "The second layer should be inserted below the first");
assert!(network_interface.is_stack(&second, &[]), "A layer below a sibling should be stack positioned");
assert_invariants(&editor, "after moving two layers into an artboard");
}
#[tokio::test]
async fn drag_offsets_do_not_outlive_programmatic_shifts() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let first = editor.create_node_by_name_at(merge_definition(), 0, 30).await;
let second = editor.create_node_by_name_at(merge_definition(), 0, 40).await;
let third = editor.create_node_by_name_at(merge_definition(), 0, 50).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_to_node_or_layer(&first, &[], true);
network_interface.set_to_node_or_layer(&second, &[], true);
network_interface.set_to_node_or_layer(&third, &[], true);
let artboard_layer = LayerNodeIdentifier::new(artboard, network_interface);
network_interface.move_layer_to_stack(LayerNodeIdentifier::new(first, network_interface), artboard_layer, 0, &[]);
network_interface.move_layer_to_stack(LayerNodeIdentifier::new(second, network_interface), artboard_layer, 1, &[]);
network_interface.move_layer_to_stack(LayerNodeIdentifier::new(third, network_interface), artboard_layer, 2, &[]);
// Making room while inserting into the stack pushes neighbors with drag-offset bookkeeping that must not outlive the operation
for node_id in [first, second, third] {
assert_eq!(network_interface.drag_offset(&node_id, &[]), 0, "Inserting into a stack should not leave a drag offset on {node_id}");
}
// Deleting the middle layer collapses the stack upward, which must also leave no offsets behind
network_interface.delete_nodes(vec![second], false, &[]);
assert_eq!(network_interface.drag_offset(&third, &[]), 0, "Collapsing the deleted layer's space should not leave a drag offset");
// A later nudge must move the survivor by exactly one unit, without replaying any restore toward its pre-collapse position
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![third] }).await;
let network_interface = &editor.active_document().network_interface;
let before = network_interface.position(&third, &[]).expect("Surviving layer should have a position");
editor
.handle_message(NodeGraphMessage::ShiftSelectedNodes {
direction: Direction::Down,
rubber_band: false,
})
.await;
let network_interface = &editor.active_document().network_interface;
let after = network_interface.position(&third, &[]).expect("Surviving layer should have a position");
assert_eq!(after.y - before.y, 1, "A single nudge should move the layer exactly one unit");
assert_invariants(&editor, "after stack pushes, a delete collapse, and a nudge");
}
#[tokio::test]
async fn signature_edits_keep_parallel_metadata_in_sync() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let merge = editor.create_node_by_name_at(merge_definition(), 0, 0).await;
let path = vec![merge];
let network_interface = &mut editor.active_document_mut().network_interface;
let initial_imports = network_interface.number_of_imports(&path);
let initial_exports = network_interface.number_of_exports(&path);
network_interface.add_import(TaggedValue::None, true, -1, "Extra import", "", &path);
assert_eq!(network_interface.number_of_imports(&path), initial_imports + 1);
assert_invariants(&editor, "after adding an import");
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.add_export(TaggedValue::None, -1, "Extra export", &path);
assert_eq!(network_interface.number_of_exports(&path), initial_exports + 1);
assert_invariants(&editor, "after adding an export");
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.reorder_import(initial_imports, 0, &path);
assert_invariants(&editor, "after reordering an import to the front");
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.remove_import(0, &path);
assert_eq!(network_interface.number_of_imports(&path), initial_imports);
assert_invariants(&editor, "after removing the reordered import");
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.remove_export(initial_exports, &path);
assert_eq!(network_interface.number_of_exports(&path), initial_exports);
assert_invariants(&editor, "after removing the added export");
}
#[tokio::test]
async fn toggle_preview_transitions_with_a_connected_export() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
let network_interface = &mut editor.active_document_mut().network_interface;
let export_node = |network_interface: &super::NodeNetworkInterface| network_interface.input_from_connector(&InputConnector::Export(0), &[]).and_then(|input| input.as_node());
assert_eq!(export_node(network_interface), Some(artboard));
// Previewing a node remembers the artboard as the connection to restore
network_interface.toggle_preview(node, &[]);
assert_eq!(export_node(network_interface), Some(node));
assert_eq!(
network_interface.previewing(&[]),
Previewing::Yes {
root_node_to_restore: Some(RootNode { node_id: artboard, output_index: 0 })
}
);
// Toggling the previewed node again restores the artboard connection
network_interface.toggle_preview(node, &[]);
assert_eq!(export_node(network_interface), Some(artboard));
assert_eq!(network_interface.previewing(&[]), Previewing::No);
// Toggling the restore node while previewing promotes it to the export with nothing left to restore
network_interface.toggle_preview(node, &[]);
network_interface.toggle_preview(artboard, &[]);
assert_eq!(export_node(network_interface), Some(artboard));
assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None });
// Toggling it once more ends the preview by disconnecting the export entirely
network_interface.toggle_preview(artboard, &[]);
assert_eq!(export_node(network_interface), None);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
assert_invariants(&editor, "after cycling through the preview states");
}
@@ -72,6 +72,7 @@ impl From<DocumentNodePersistentMetadataPropertiesRow> for DocumentNodePersisten
input_name: properties_row.input_name,
input_description: properties_row.input_description,
},
..Default::default()
})
}
DocumentNodePersistentMetadataHasPrimaryOutput {
@@ -1,452 +0,0 @@
use super::{DocumentNodeMetadata, DocumentNodePersistentMetadata, LayerPosition, NodePosition, NodeTypePersistentMetadata};
use document_graph_storage::attr::node as node_attr;
use document_graph_storage::from_runtime::{ConversionError, DeclarationBytes};
use document_graph_storage::{AttributeDelta, Attributes, Implementation, NoMetadata, PathResolver, Position, Registry, RegistryDelta, ScopedConversion, TimeStamp};
use document_graph_storage::{convert_resource_entry, encode_input_ui_attributes, encode_node_ui_attributes, node_value_resource_refs, value_resource_ref};
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry};
use graph_craft::document::NodeId;
use graph_craft::runtime_delta::RuntimeDelta;
use std::collections::HashSet;
/// A [`RuntimeDelta`] extended with the editor-only change kind: a wholesale copy of a node's
/// persistent metadata, which storage diffs against the working registry so minimal attribute ops
/// fall out. The compiler consumes only the `Graph` variant.
#[derive(Debug, Clone, PartialEq)]
pub enum EditorDelta {
Graph(RuntimeDelta),
/// The copy includes the metadata of everything nested under the node, so one delta covers a
/// group and its contents.
NodeMetadata {
network_path: Vec<NodeId>,
node_id: NodeId,
metadata: Box<DocumentNodePersistentMetadata>,
},
}
pub struct ConstructedOps {
pub ops: Vec<RegistryDelta>,
pub declaration_bytes: DeclarationBytes,
}
/// Constructs the storage ops for one gesture's deltas, in delta order. Removal closures and
/// resource liveness are computed against the whole batch, since several removals in one gesture
/// can jointly orphan a resource that each alone would not. Op timestamps are placeholders,
/// re-stamped by the staging clock.
pub fn construct_batch(deltas: &[EditorDelta], working: &Registry, resources: &ResourceRegistry, peer: document_graph_storage::PeerId) -> Result<ConstructedOps, ConversionError> {
let resolver = PathResolver::new(peer);
let mut ops = Vec::new();
let mut declaration_bytes = DeclarationBytes::new();
let mut batch_removed_nodes = Vec::new();
let mut batch_removed_networks = Vec::new();
let mut batch_added_resources = HashSet::new();
for delta in deltas {
if let EditorDelta::Graph(RuntimeDelta::RemoveNode { network_path, node_id } | RuntimeDelta::ReplaceNode { network_path, node_id, .. }) = delta {
collect_removal_closure(resolver.node_id(network_path, *node_id), working, &mut batch_removed_nodes, &mut batch_removed_networks);
}
}
batch_removed_nodes.sort();
batch_removed_nodes.dedup();
batch_removed_networks.sort();
batch_removed_networks.dedup();
for delta in deltas {
delta.construct(working, resources, peer, &resolver, &batch_removed_nodes, &mut batch_added_resources, &mut ops, &mut declaration_bytes)?;
}
construct_resource_removals(&batch_removed_nodes, working, &mut ops);
Ok(ConstructedOps { ops, declaration_bytes })
}
impl EditorDelta {
#[allow(clippy::too_many_arguments)]
fn construct(
&self,
working: &Registry,
resources: &ResourceRegistry,
peer: document_graph_storage::PeerId,
resolver: &PathResolver,
batch_removed_nodes: &[document_graph_storage::NodeId],
batch_added_resources: &mut HashSet<ResourceId>,
ops: &mut Vec<RegistryDelta>,
declaration_bytes: &mut DeclarationBytes,
) -> Result<(), ConversionError> {
match self {
EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, node }) => {
construct_structural_additions(network_path, *node_id, node, working, resources, peer, batch_added_resources, ops, declaration_bytes)?;
}
EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => {
construct_removals(resolver.node_id(network_path, *node_id), working, ops);
construct_structural_additions(network_path, *node_id, node, working, resources, peer, batch_added_resources, ops, declaration_bytes)?;
}
EditorDelta::Graph(RuntimeDelta::RemoveNode { network_path, node_id }) => {
construct_removals(resolver.node_id(network_path, *node_id), working, ops);
}
EditorDelta::Graph(RuntimeDelta::SetVisibility { network_path, node_id, visible }) => {
ops.push(RegistryDelta::ChangeNodeAttribute {
id: resolver.node_id(network_path, *node_id),
delta: AttributeDelta {
key: node_attr::VISIBLE.to_string(),
value: (!visible).then_some(serde_json::Value::Bool(false)),
},
});
}
EditorDelta::Graph(RuntimeDelta::SetInput {
network_path,
node_id,
input_index,
input,
}) => {
ops.push(RegistryDelta::ChangeNodeInput {
id: resolver.node_id(network_path, *node_id),
index: (*input_index).try_into().map_err(|_| ConversionError::IndexOverflow(*input_index))?,
new_input: resolver.convert_input_at(input, network_path)?,
});
}
EditorDelta::Graph(RuntimeDelta::SetExport { network_path, export_index, input }) => {
ops.push(RegistryDelta::SetNetworkExport {
id: resolver.network_id(network_path),
index: (*export_index).try_into().map_err(|_| ConversionError::IndexOverflow(*export_index))?,
export: Some(resolver.convert_input_at(input, network_path)?),
});
}
EditorDelta::NodeMetadata { network_path, node_id, metadata } => {
construct_metadata_changes(network_path, *node_id, metadata, working, resolver, ops)?;
}
}
let _ = batch_removed_nodes;
Ok(())
}
}
/// Converts through the same encoders as a whole-document conversion, with `NoMetadata` as the
/// source: ui attributes arrive via the gesture's paired `NodeMetadata` delta.
#[allow(clippy::too_many_arguments)]
fn construct_structural_additions(
network_path: &[NodeId],
node_id: NodeId,
node: &graph_craft::document::DocumentNode,
working: &Registry,
resources: &ResourceRegistry,
peer: document_graph_storage::PeerId,
batch_added_resources: &mut HashSet<ResourceId>,
ops: &mut Vec<RegistryDelta>,
declaration_bytes: &mut DeclarationBytes,
) -> Result<(), ConversionError> {
let mut scoped = ScopedConversion::new(&NoMetadata, peer);
let mut scratch = Registry::default();
scoped.convert_node_at(&mut scratch, network_path, node_id, node, true)?;
declaration_bytes.extend(scoped.finish());
let mut networks: Vec<_> = scratch.networks.iter().collect();
networks.sort_by_key(|(id, _)| **id);
for (id, network) in networks {
ops.push(RegistryDelta::AddNetwork { id: *id, network: network.clone() });
}
let mut nodes: Vec<_> = scratch.node_instances.iter().collect();
nodes.sort_by_key(|(id, _)| **id);
for (id, node) in nodes {
ops.push(RegistryDelta::AddNode { id: *id, node: node.clone() });
}
let mut new_resources: Vec<_> = scratch.resources.iter().filter(|(id, _)| !working.resources.contains_key(id)).collect();
new_resources.sort_by_key(|(id, _)| **id);
for (id, entry) in new_resources {
if batch_added_resources.insert(*id) {
ops.push(RegistryDelta::AddResource { id: *id, entry: entry.clone() });
}
}
let mut tagged: Vec<ResourceId> = scratch.node_instances.values().flat_map(node_value_resource_refs).collect();
tagged.sort();
tagged.dedup();
for id in tagged {
if !working.resources.contains_key(&id)
&& !scratch.resources.contains_key(&id)
&& !batch_added_resources.contains(&id)
&& let Some(entry) = convert_resource_entry(resources, id, peer)?
{
batch_added_resources.insert(id);
ops.push(RegistryDelta::AddResource { id, entry });
}
}
Ok(())
}
fn construct_metadata_changes(
network_path: &[NodeId],
node_id: NodeId,
metadata: &DocumentNodePersistentMetadata,
working: &Registry,
resolver: &PathResolver,
ops: &mut Vec<RegistryDelta>,
) -> Result<(), ConversionError> {
let source = MetadataCopySource {
anchor_path: network_path,
anchor_id: node_id,
metadata,
};
let mut pending = vec![(network_path.to_vec(), node_id, metadata)];
while let Some((path, id, node_metadata)) = pending.pop() {
let global_id = resolver.node_id(&path, id);
let working_node = working.node_instances.get(&global_id);
let mut encoded = Attributes::new();
encode_node_ui_attributes(&mut encoded, &source, &path, id, TimeStamp::ORIGIN)?;
for delta in ui_attribute_deltas(working_node.map(|node| node.attributes()), &encoded) {
ops.push(RegistryDelta::ChangeNodeAttribute { id: global_id, delta });
}
for input_index in 0..node_metadata.input_metadata.len() {
let mut encoded = Attributes::new();
encode_input_ui_attributes(&mut encoded, &source, &path, id, input_index, TimeStamp::ORIGIN)?;
let current = working_node.and_then(|node| node.inputs().get(input_index)).map(|slot| &slot.attributes);
for delta in ui_attribute_deltas(current, &encoded) {
ops.push(RegistryDelta::ChangeNodeInputAttribute {
id: global_id,
index: input_index.try_into().map_err(|_| ConversionError::IndexOverflow(input_index))?,
delta,
});
}
}
if let Some(network_metadata) = &node_metadata.network_metadata {
let mut nested_path = path.clone();
nested_path.push(id);
let network_id = resolver.network_id(&nested_path);
let target = network_metadata.persistent_metadata.reference.clone().map(serde_json::Value::String);
let current = working
.networks
.get(&network_id)
.and_then(|network| network.attributes.get(node_attr::ui::REFERENCE))
.map(|value| value.value.clone());
if current != target {
ops.push(RegistryDelta::ChangeNetworkAttribute {
id: network_id,
delta: AttributeDelta {
key: node_attr::ui::REFERENCE.to_string(),
value: target,
},
});
}
for (child_id, child) in &network_metadata.persistent_metadata.node_metadata {
pending.push((nested_path.clone(), *child_id, &child.persistent_metadata));
}
}
}
Ok(())
}
/// Minimal ops transforming the `ui::`-prefixed subset of `current` into `encoded`, comparing
/// values only, since timestamps are re-stamped at staging.
fn ui_attribute_deltas(current: Option<&Attributes>, encoded: &Attributes) -> Vec<AttributeDelta> {
let owned = |key: &str| key.starts_with("ui::");
let mut deltas = Vec::new();
if let Some(current) = current {
for key in current.keys() {
if owned(key) && !encoded.contains_key(key) {
deltas.push(AttributeDelta { key: key.clone(), value: None });
}
}
}
for (key, value) in encoded {
let unchanged = current.and_then(|current| current.get(key)).is_some_and(|existing| existing.value == value.value);
if !unchanged {
deltas.push(AttributeDelta {
key: key.clone(),
value: Some(value.value.clone()),
});
}
}
deltas.sort_by(|a, b| a.key.cmp(&b.key));
deltas
}
fn construct_removals(node_id: document_graph_storage::NodeId, working: &Registry, ops: &mut Vec<RegistryDelta>) {
let mut removed_nodes = Vec::new();
let mut removed_networks = Vec::new();
collect_removal_closure(node_id, working, &mut removed_nodes, &mut removed_networks);
removed_nodes.sort();
removed_networks.sort();
for id in &removed_nodes {
ops.push(RegistryDelta::RemoveNode {
id: *id,
snapshot: working.node_instances[id].clone(),
});
}
for id in &removed_networks {
ops.push(RegistryDelta::RemoveNetwork {
id: *id,
snapshot: working.networks[id].clone(),
});
}
}
/// Emits removals for resources referenced only by the batch's removed nodes, checked after every
/// removal is known.
fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::NodeId], working: &Registry, ops: &mut Vec<RegistryDelta>) {
let removed_node_set: HashSet<_> = batch_removed_nodes.iter().copied().collect();
let mut candidates: Vec<ResourceId> = batch_removed_nodes
.iter()
.flat_map(|id| {
let node = &working.node_instances[id];
let declaration = match node.implementation() {
Implementation::ProtoNode(declaration) => Some(*declaration),
Implementation::Network(_) => None,
};
declaration.into_iter().chain(node_value_resource_refs(node))
})
.collect();
candidates.sort();
candidates.dedup();
for candidate in candidates {
let still_referenced = working
.node_instances
.iter()
.filter(|(id, _)| !removed_node_set.contains(id))
.any(|(_, node)| matches!(node.implementation(), Implementation::ProtoNode(declaration) if *declaration == candidate) || node_value_resource_refs(node).any(|id| id == candidate))
|| working
.networks
.values()
.any(|network| network.exports.iter().any(|slot| slot.target.as_ref().and_then(value_resource_ref) == Some(candidate)));
if !still_referenced && let Some(entry) = working.resources.get(&candidate) {
ops.push(RegistryDelta::RemoveResource {
id: candidate,
snapshot: entry.clone(),
});
}
}
}
fn collect_removal_closure(node_id: document_graph_storage::NodeId, working: &Registry, nodes: &mut Vec<document_graph_storage::NodeId>, networks: &mut Vec<document_graph_storage::NetworkId>) {
let Some(node) = working.node_instances.get(&node_id) else { return };
nodes.push(node_id);
if let &Implementation::Network(network_id) = node.implementation() {
networks.push(network_id);
for (child_id, child) in &working.node_instances {
if child.network() == network_id {
collect_removal_closure(*child_id, working, nodes, networks);
}
}
}
}
/// Serves a metadata copy as the [`document_graph_storage::NodeMetadataSource`] for its own
/// encoding, resolving requested paths relative to the anchor node the copy was taken from.
struct MetadataCopySource<'a> {
anchor_path: &'a [NodeId],
anchor_id: NodeId,
metadata: &'a DocumentNodePersistentMetadata,
}
impl MetadataCopySource<'_> {
fn metadata_for(&self, metadata_path: &[NodeId], node_id: NodeId) -> Option<&DocumentNodePersistentMetadata> {
let relative = metadata_path.strip_prefix(self.anchor_path)?;
let (mut current, rest) = match relative.split_first() {
None => return (node_id == self.anchor_id).then_some(self.metadata),
Some((first, rest)) if *first == self.anchor_id => (self.metadata, rest),
Some(_) => return None,
};
for step in rest {
current = child_metadata(current, *step)?;
}
child_metadata(current, node_id)
}
}
fn child_metadata(metadata: &DocumentNodePersistentMetadata, child_id: NodeId) -> Option<&DocumentNodePersistentMetadata> {
metadata
.network_metadata
.as_ref()
.and_then(|network| network.persistent_metadata.node_metadata.get(&child_id))
.map(|child: &DocumentNodeMetadata| &child.persistent_metadata)
}
impl document_graph_storage::NodeMetadataSource for MetadataCopySource<'_> {
fn position(&self, metadata_path: &[NodeId], node_id: NodeId) -> Option<Position> {
match &self.metadata_for(metadata_path, node_id)?.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer) => Some(match layer.position {
LayerPosition::Absolute(offset) => Position::Absolute([offset.x, offset.y]),
LayerPosition::Stack(offset) => Position::Stack(offset),
}),
NodeTypePersistentMetadata::Node(node) => Some(match *node.position() {
NodePosition::Absolute(offset) => Position::Absolute([offset.x, offset.y]),
NodePosition::Chain => Position::Chain,
}),
}
}
fn is_layer(&self, metadata_path: &[NodeId], node_id: NodeId) -> bool {
self.metadata_for(metadata_path, node_id)
.is_some_and(|metadata| matches!(metadata.node_type_metadata, NodeTypePersistentMetadata::Layer(_)))
}
fn display_name(&self, metadata_path: &[NodeId], node_id: NodeId) -> Option<&str> {
self.metadata_for(metadata_path, node_id).map(|metadata| metadata.display_name.as_str())
}
fn locked(&self, metadata_path: &[NodeId], node_id: NodeId) -> bool {
self.metadata_for(metadata_path, node_id).is_some_and(|metadata| metadata.locked)
}
fn pinned(&self, metadata_path: &[NodeId], node_id: NodeId) -> bool {
self.metadata_for(metadata_path, node_id).is_some_and(|metadata| metadata.pinned)
}
fn output_names(&self, metadata_path: &[NodeId], node_id: NodeId) -> Vec<String> {
self.metadata_for(metadata_path, node_id).map(|metadata| metadata.output_names.clone()).unwrap_or_default()
}
fn input_name(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> Option<&str> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.map(|input| input.persistent_metadata.input_name.as_str())
}
fn input_description(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> Option<&str> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.map(|input| input.persistent_metadata.input_description.as_str())
}
fn widget_override(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> Option<&str> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.and_then(|input| input.persistent_metadata.widget_override.as_deref())
}
fn input_data(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> std::collections::HashMap<String, serde_json::Value> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.map(|input| input.persistent_metadata.input_data.clone())
.unwrap_or_default()
}
fn reference(&self, network_path: &[NodeId]) -> Option<&str> {
let (owner_path, owner_id) = network_path.split_last().map(|(last, rest)| (rest, *last))?;
self.metadata_for(owner_path, owner_id)?
.network_metadata
.as_ref()
.and_then(|network| network.persistent_metadata.reference.as_deref())
}
}
@@ -1,241 +0,0 @@
use super::InputConnector;
use super::editor_delta::{EditorDelta, construct_batch};
use super::storage_metadata::StorageMetadataView;
use crate::test_utils::test_prelude::*;
use document_graph_storage::delta::compute_deltas;
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graph_craft::runtime_delta::RuntimeDelta;
use graphene_std::uuid::NodeId;
const PEER: PeerId = PeerId(7);
fn rectangle_definition() -> DefinitionIdentifier {
DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)
}
fn convert(editor: &EditorTestUtils) -> Registry {
let document = editor.active_document();
Registry::convert_from_runtime(
document.network_interface.document_network(),
&StorageMetadataView::new(&document.network_interface),
&document.resources.registry,
PEER,
)
.expect("conversion should succeed")
.registry
}
fn construct(editor: &EditorTestUtils, deltas: &[EditorDelta], working: &Registry) -> Vec<RegistryDelta> {
construct_batch(deltas, working, &editor.active_document().resources.registry, PEER)
.expect("construction should succeed")
.ops
}
fn node_metadata_delta(editor: &EditorTestUtils, node_id: NodeId) -> EditorDelta {
let metadata = editor
.active_document()
.network_interface
.node_metadata(&node_id, &[])
.expect("node metadata should exist")
.persistent_metadata
.clone();
EditorDelta::NodeMetadata {
network_path: Vec::new(),
node_id,
metadata: Box::new(metadata),
}
}
fn assert_same_stored_effect(working: &Registry, constructed: Vec<RegistryDelta>, diffed: Vec<RegistryDelta>, at: &str) {
let baseline = compute_deltas(&Registry::default(), working);
let mut from_construction = Session::with_peer(PEER);
from_construction.stage_computed_ops(baseline.clone()).expect("baseline should stage");
from_construction.stage_computed_ops(constructed).expect("constructed ops should stage");
let mut from_diff = Session::with_peer(PEER);
from_diff.stage_computed_ops(baseline).expect("baseline should stage");
from_diff.stage_computed_ops(diffed).expect("diffed ops should stage");
assert!(
from_construction.registry().value_equal(from_diff.registry()),
"Constructed ops must produce the same stored state as the whole-document diff: {at}\nresidual: {:#?}",
compute_deltas(from_construction.registry(), from_diff.registry())
);
}
#[tokio::test]
async fn set_input_value_constructs_the_exact_diff_op() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
let input = NodeInput::value(TaggedValue::F64(42.), false);
editor.active_document_mut().network_interface.set_input(&InputConnector::node(node, 1), input.clone(), &[]);
let delta = EditorDelta::Graph(RuntimeDelta::SetInput {
network_path: Vec::new(),
node_id: node,
input_index: 1,
input,
});
let constructed = construct(&editor, std::slice::from_ref(&delta), &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_eq!(constructed, diffed, "A value edit should construct exactly the diff's op");
}
#[tokio::test]
async fn wiring_and_export_edits_construct_the_exact_diff_ops() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let a = editor.create_node_by_name(rectangle_definition()).await;
let b = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
let wire = NodeInput::node(b, 0);
editor.active_document_mut().network_interface.set_input(&InputConnector::node(a, 1), wire.clone(), &[]);
let delta = EditorDelta::Graph(RuntimeDelta::SetInput {
network_path: Vec::new(),
node_id: a,
input_index: 1,
input: wire,
});
let constructed = construct(&editor, std::slice::from_ref(&delta), &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_eq!(constructed, diffed, "A wiring edit should construct exactly the diff's op");
let working = convert(&editor);
let export = NodeInput::node(a, 0);
editor.active_document_mut().network_interface.set_input(&InputConnector::Export(0), export.clone(), &[]);
let delta = EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: Vec::new(),
export_index: 0,
input: export,
});
let constructed = construct(&editor, std::slice::from_ref(&delta), &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_eq!(constructed, diffed, "An export edit should construct exactly the diff's op");
}
#[tokio::test]
async fn adding_a_node_as_structure_plus_metadata_matches_the_diff() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let working = convert(&editor);
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template();
let node_id = NodeId(0xDE17A);
let (document_node, metadata) = template.clone().into_parts();
editor.active_document_mut().network_interface.insert_node(node_id, template, &[]);
let deltas = [
EditorDelta::Graph(RuntimeDelta::AddNode {
network_path: Vec::new(),
node_id,
node: Box::new(document_node),
}),
EditorDelta::NodeMetadata {
network_path: Vec::new(),
node_id,
metadata: Box::new(metadata),
},
];
let constructed = construct(&editor, &deltas, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "node addition");
}
#[tokio::test]
async fn metadata_edits_construct_the_exact_diff_ops() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
{
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&node, "Renamed".to_string(), &[]);
network_interface.set_visibility(&node, &[], false);
network_interface.set_locked(&node, &[], true);
network_interface.set_pinned(&node, &[], true);
network_interface.shift_node(&node, glam::IVec2::new(3, 5), &[]);
}
let deltas = [
node_metadata_delta(&editor, node),
EditorDelta::Graph(RuntimeDelta::SetVisibility {
network_path: Vec::new(),
node_id: node,
visible: false,
}),
];
let constructed = construct(&editor, &deltas, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_eq!(constructed, diffed, "Metadata edits should construct exactly the diff's attribute ops");
}
#[tokio::test]
async fn removing_a_nested_network_node_matches_the_diff() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
let before: Vec<NodeId> = editor.active_document().network_interface.document_network().nodes.keys().copied().collect();
let working = convert(&editor);
let group = editor
.active_document()
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(node.implementation, graph_craft::document::DocumentNodeImplementation::Network(_)))
.map(|(id, _)| *id)
.expect("the group should be a network node");
editor.active_document_mut().network_interface.delete_nodes(vec![group], true, &[]);
let network = editor.active_document().network_interface.document_network().clone();
let mut deltas: Vec<EditorDelta> = before
.iter()
.filter(|id| !network.nodes.contains_key(id))
.map(|id| {
EditorDelta::Graph(RuntimeDelta::RemoveNode {
network_path: Vec::new(),
node_id: *id,
})
})
.collect();
for (index, export) in network.exports.iter().enumerate() {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: Vec::new(),
export_index: index,
input: export.clone(),
}));
}
for (node_id, node) in &network.nodes {
for (index, input) in node.inputs.iter().enumerate() {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInput {
network_path: Vec::new(),
node_id: *node_id,
input_index: index,
input: input.clone(),
}));
}
}
let constructed = construct(&editor, &deltas, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "nested network removal");
}
@@ -1,380 +0,0 @@
use super::*;
// Helper functions for mutable getters
impl NodeNetworkInterface {
pub fn upstream_chain_nodes(&self, network_path: &[NodeId]) -> Vec<NodeId> {
let Some(selected_nodes) = self.selected_nodes_in_nested_network(network_path) else {
log::error!("Could not get selected nodes in upstream_chain_nodes");
return Vec::new();
};
let mut all_selected_nodes = selected_nodes.selected_nodes().cloned().collect::<Vec<_>>();
for selected_node_id in selected_nodes.selected_nodes() {
if self.is_layer(selected_node_id, network_path) {
let unique_upstream_chain = self
.upstream_flow_back_from_nodes(vec![*selected_node_id], network_path, FlowType::HorizontalFlow)
.skip(1)
.take_while(|node_id| self.is_chain(node_id, network_path))
.filter(|upstream_node| all_selected_nodes.iter().all(|new_selected_node| new_selected_node != upstream_node))
.collect::<Vec<_>>();
all_selected_nodes.extend(unique_upstream_chain);
}
}
all_selected_nodes
}
pub fn collect_frontend_click_targets(&self, network_path: &[NodeId]) -> FrontendClickTargets {
let mut all_node_click_targets = Vec::new();
let mut connector_click_targets = Vec::new();
let mut icon_click_targets = Vec::new();
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in collect_frontend_click_targets");
return FrontendClickTargets::default();
};
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
self.with_import_export_ports(network_path, |import_export_click_targets| {
for port in import_export_click_targets.click_targets() {
if let ClickTargetType::Subpath(subpath) = port.target_type() {
connector_click_targets.push(subpath.to_bezpath().to_svg());
}
}
});
nodes.into_iter().for_each(|node_id| {
self.with_node_click_targets(&node_id, network_path, |node_click_targets| {
let mut node_path = String::new();
if let ClickTargetType::Subpath(subpath) = node_click_targets.node_click_target.target_type() {
node_path.push_str(subpath.to_bezpath().to_svg().as_str())
}
all_node_click_targets.push((node_id, node_path));
for port in node_click_targets.port_click_targets.click_targets() {
if let ClickTargetType::Subpath(subpath) = port.target_type() {
connector_click_targets.push(subpath.to_bezpath().to_svg());
}
}
if let NodeTypeClickTargets::Layer(layer_metadata) = &node_click_targets.node_type_metadata {
// Visibility button (eye icon)
if let ClickTargetType::Subpath(subpath) = layer_metadata.visibility_click_target.target_type() {
icon_click_targets.push(subpath.to_bezpath().to_svg());
}
// Lock button (padlock icon), only when the layer is locked
if let Some(lock_click_target) = &layer_metadata.lock_click_target
&& let ClickTargetType::Subpath(subpath) = lock_click_target.target_type()
{
icon_click_targets.push(subpath.to_bezpath().to_svg());
}
// Drag grip (dotted symbol)
if let ClickTargetType::Subpath(subpath) = layer_metadata.grip_click_target.target_type() {
icon_click_targets.push(subpath.to_bezpath().to_svg());
}
}
});
});
let mut layer_click_targets = Vec::new();
let mut node_click_targets = Vec::new();
all_node_click_targets.into_iter().for_each(|(node_id, path)| {
if self.is_layer(&node_id, network_path) {
layer_click_targets.push(path);
} else {
node_click_targets.push(path);
}
});
let bounds = self.all_nodes_bounding_box(network_path).unwrap_or([DVec2::ZERO, DVec2::ZERO]);
let rect = Subpath::<PointId>::new_rectangle(bounds[0], bounds[1]);
let all_nodes_bounding_box = rect.to_bezpath().to_svg();
let mut modify_import_export = Vec::new();
self.with_modify_import_export(network_path, |modify_import_export_click_targets| {
for click_target in modify_import_export_click_targets
.remove_imports_exports
.click_targets()
.chain(modify_import_export_click_targets.reorder_imports_exports.click_targets())
{
if let ClickTargetType::Subpath(subpath) = click_target.target_type() {
modify_import_export.push(subpath.to_bezpath().to_svg());
}
}
});
FrontendClickTargets {
node_click_targets,
layer_click_targets,
connector_click_targets,
icon_click_targets,
all_nodes_bounding_box,
modify_import_export,
}
}
pub fn set_document_to_viewport_transform(&mut self, transform: DAffine2) {
self.document_metadata.document_to_viewport = transform;
}
pub fn is_eligible_to_be_layer(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
self.query(network_path, "is_eligible_to_be_layer", |view| view.is_eligible_to_be_layer(node_id)).unwrap_or_default()
}
pub fn node_graph_ptz(&self, network_path: &[NodeId]) -> Option<&PTZ> {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in node_graph_ptz_mut");
return None;
};
Some(&network_metadata.persistent_metadata.navigation_metadata.node_graph_ptz)
}
pub fn node_graph_ptz_mut(&mut self, network_path: &[NodeId]) -> Option<&mut PTZ> {
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
log::error!("Could not get nested network_metadata in node_graph_ptz_mut");
return None;
};
Some(&mut network_metadata.persistent_metadata.navigation_metadata.node_graph_ptz)
}
// TODO: Optimize getting click target intersections from click by using a spacial data structure like a quadtree instead of linear search
/// Click target getter methods
pub fn node_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<NodeId> {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in node_from_click");
return None;
};
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get nested network in node_from_click");
return None;
};
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
let nodes = network.nodes.keys().copied().collect::<Vec<_>>();
let clicked_nodes = nodes
.iter()
.filter(|node_id| {
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
transient_node_metadata.node_click_target.intersect_point_no_stroke(point)
}) == Some(true)
})
.cloned()
.collect::<Vec<_>>();
// Since nodes are placed on top of layer chains, find the first non layer node that was clicked, and if there way no non layer nodes clicked, then find the first layer node that was clicked
clicked_nodes
.iter()
.find_map(|node_id| {
let Some(node_metadata) = self.network_metadata(network_path)?.persistent_metadata.node_metadata.get(node_id) else {
log::error!("Could not get node_metadata for node {node_id}");
return None;
};
if !node_metadata.persistent_metadata.is_layer() { Some(*node_id) } else { None }
})
.or_else(|| clicked_nodes.into_iter().next())
}
pub fn layer_click_target_from_click(&self, click: DVec2, click_target_type: LayerClickTargetTypes, network_path: &[NodeId]) -> Option<NodeId> {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in visibility_from_click");
return None;
};
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get nested network in visibility_from_click");
return None;
};
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
let node_ids: Vec<_> = network.nodes.keys().copied().collect();
node_ids
.iter()
.filter_map(|node_id| {
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
if let NodeTypeClickTargets::Layer(layer) = &transient_node_metadata.node_type_metadata {
match click_target_type {
LayerClickTargetTypes::Visibility => layer.visibility_click_target.intersect_point_no_stroke(point).then_some(*node_id),
LayerClickTargetTypes::Lock => layer.lock_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
LayerClickTargetTypes::Grip => layer.grip_click_target.intersect_point_no_stroke(point).then_some(*node_id),
LayerClickTargetTypes::Name => layer.name_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
}
} else {
None
}
})
.flatten()
})
.next()
}
pub fn input_connector_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<InputConnector> {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in input_connector_from_click");
return None;
};
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get nested network in input_connector_from_click");
return None;
};
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
network
.nodes
.keys()
.copied()
.collect::<Vec<_>>()
.iter()
.filter_map(|node_id| {
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
transient_node_metadata
.port_click_targets
.clicked_input_port_from_point(point)
.map(|port| InputConnector::node_at_index(*node_id, port))
})
.flatten()
})
.next()
.or_else(|| {
self.with_import_export_ports(network_path, |import_export_ports| import_export_ports.clicked_input_port_from_point(point).map(InputConnector::Export))
.flatten()
})
}
pub fn output_connector_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<OutputConnector> {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in output_connector_from_click");
return None;
};
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get nested network in output_connector_from_click");
return None;
};
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
let nodes = network.nodes.keys().copied().collect::<Vec<_>>();
nodes
.iter()
.filter_map(|node_id| {
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
transient_node_metadata
.port_click_targets
.clicked_output_port_from_point(point)
.map(|output_index| OutputConnector::node(*node_id, output_index))
})
.flatten()
})
.next()
.or_else(|| {
self.with_import_export_ports(network_path, |import_export_ports| {
import_export_ports.clicked_output_port_from_point(point).map(OutputConnector::Import)
})
.flatten()
})
}
pub fn input_position(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<DVec2> {
match input_connector {
InputConnector::Node { node_id, input_index } => self
.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
transient_node_metadata.port_click_targets.input_port_position(*input_index)
})
.flatten(),
InputConnector::Export(export_index) => self
.with_import_export_ports(network_path, |import_export_ports| import_export_ports.input_port_position(*export_index))
.flatten(),
}
}
pub fn output_position(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<DVec2> {
match output_connector {
OutputConnector::Node { node_id, output_index } => self
.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
transient_node_metadata.port_click_targets.output_port_position(*output_index)
})
.flatten(),
OutputConnector::Import(import_index) => self
.with_import_export_ports(network_path, |import_export_ports| import_export_ports.output_port_position(*import_index))
.flatten(),
}
}
/// Get the combined bounding box of the click targets of the selected nodes in the node graph in viewport space
pub fn selected_nodes_bounding_box_viewport(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
// Always get the bounding box for nodes in the currently viewed network
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in selected_nodes_bounding_box_viewport");
return None;
};
let node_graph_to_viewport = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport;
self.selected_nodes_bounding_box(network_path)
.map(|[a, b]| [node_graph_to_viewport.transform_point2(a), node_graph_to_viewport.transform_point2(b)])
}
pub fn selected_layers_artwork_bounding_box_viewport(&self) -> Option<[DVec2; 2]> {
self.selected_nodes()
.0
.iter()
.filter(|node| self.is_layer(node, &[]))
.filter_map(|layer| self.document_metadata.bounding_box_viewport(LayerNodeIdentifier::new(*layer, self)))
.reduce(Quad::combine_bounds)
}
pub fn selected_unlocked_layers_bounding_box_viewport(&self) -> Option<[DVec2; 2]> {
self.selected_nodes()
.0
.iter()
.filter(|node| self.is_layer(node, &[]) && !self.is_locked(node, &[]))
.filter_map(|layer| self.document_metadata.bounding_box_viewport(LayerNodeIdentifier::new(*layer, self)))
.reduce(Quad::combine_bounds)
}
/// Get the combined bounding box of the click targets of the selected nodes in the node graph in layer space
pub fn selected_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
let Some(selected_nodes) = self.selected_nodes_in_nested_network(network_path) else {
log::error!("Could not get selected nodes in selected_nodes_bounding_box_viewport");
return None;
};
selected_nodes
.selected_nodes()
.cloned()
.collect::<Vec<_>>()
.iter()
.filter_map(|node_id| self.node_bounding_box(node_id, network_path))
.reduce(graphene_std::renderer::Quad::combine_bounds)
}
/// Gets the bounding box in viewport coordinates for each node in the node graph
pub fn graph_bounds_viewport_space(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
let bounds = self.all_nodes_bounding_box(network_path)?;
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in graph_bounds_viewport_space");
return None;
};
let bounding_box_subpath = Subpath::<PointId>::new_rectangle(bounds[0], bounds[1]);
bounding_box_subpath.bounding_box_with_transform(network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport)
}
pub fn collect_layer_widths(&self, network_path: &[NodeId]) -> (HashMap<NodeId, u32>, HashMap<NodeId, u32>, HashMap<NodeId, bool>) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in collect_layer_widths");
return (HashMap::new(), HashMap::new(), HashMap::new());
};
let nodes = network_metadata
.persistent_metadata
.node_metadata
.keys()
.filter_map(|node_id| if self.is_layer(node_id, network_path) { Some(*node_id) } else { None })
.collect::<Vec<_>>();
let layer_widths = nodes
.iter()
.filter_map(|node_id| self.layer_width(node_id, network_path).map(|layer_width| (*node_id, layer_width)))
.collect::<HashMap<NodeId, u32>>();
let chain_widths = nodes.iter().map(|node_id| (*node_id, self.chain_width(node_id, network_path))).collect::<HashMap<NodeId, u32>>();
let has_left_input_wire = nodes
.iter()
.map(|node_id| {
(
*node_id,
!self
.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow)
.skip(1)
.all(|node_id| self.is_chain(&node_id, network_path)),
)
})
.collect::<HashMap<NodeId, bool>>();
(layer_widths, chain_widths, has_left_input_wire)
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -3,8 +3,12 @@ use std::collections::{HashMap, HashSet};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNodeImplementation, InlineRust, NodeInput};
use graph_craft::proto::{GraphErrorType, GraphErrors};
use graph_craft::{ProtoNodeIdentifier, Type, concrete};
use graph_craft::{Type, concrete};
use graphene_std::list::List;
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::uuid::NodeId;
use graphene_std::vector::Vector;
use graphene_std::{Artboard, Graphic};
use interpreted_executor::dynamic_executor::{NodeTypes, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::node_registry::NODE_REGISTRY;
@@ -52,27 +56,28 @@ impl TypeSource {
return FrontendGraphDataType::Invalid;
};
match self.compiled_nested_type() {
Some(nested_type) => FrontendGraphDataType::from_type(nested_type),
Some(nested_type) => match TaggedValue::from_type_or_none(nested_type) {
TaggedValue::U32(_) | TaggedValue::U64(_) | TaggedValue::F32(_) | TaggedValue::F64(_) | TaggedValue::DVec2(_) | TaggedValue::F64Array(_) | TaggedValue::DAffine2(_) => {
FrontendGraphDataType::Number
}
TaggedValue::Color(_) => FrontendGraphDataType::Color,
TaggedValue::LegacyGradient(_) | TaggedValue::Gradient(_) => FrontendGraphDataType::Gradient,
TaggedValue::String(_) => FrontendGraphDataType::Typography,
// Types whose `TaggedValue` variant has been removed are routed through `TypeDefault` and identified by the descriptor's type name.
TaggedValue::TypeDefault(td) => match td.name.as_ref() {
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Graphic>>()) => FrontendGraphDataType::Graphic,
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Artboard>>()) => FrontendGraphDataType::Artboard,
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Raster<CPU>>>()) => FrontendGraphDataType::Raster,
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) => FrontendGraphDataType::Vector,
n if n == graphene_std::core_types::normalize_type_name(std::any::type_name::<List<String>>()) => FrontendGraphDataType::Typography,
_ => FrontendGraphDataType::General,
},
_ => FrontendGraphDataType::General,
},
None => FrontendGraphDataType::General,
}
}
/// Whether the compiled type is a rank-1 `List<T>`, as opposed to a rank-0 `Item<T>` or a bare value.
/// A bundled cell carrying a whole list displays as the list it carries.
pub fn is_list(&self) -> bool {
self.compiled_nested_type().is_some_and(|ty| matches!(ty, Type::List(_)) || ty.bundle_element_name().is_some())
}
/// The element type with any rank-0 `Item` or rank-1 `List` wrapper peeled, so semantic type checks can be rank-agnostic.
pub fn compiled_element_type(&self) -> Option<&Type> {
Some(element_of(self.compiled_nested_type()?))
}
/// The identifier name of [`Self::compiled_element_type`].
pub fn compiled_element_name(&self) -> Option<String> {
Some(self.compiled_element_type()?.identifier_name())
}
pub fn compiled_nested_type(&self) -> Option<&Type> {
match self {
TypeSource::Compiled(compiled_type) => Some(compiled_type.nested_type()),
@@ -109,16 +114,8 @@ impl TypeSource {
}
}
/// Peels any `Fn`/`Future` wrapper, then any rank-0 `Item` or rank-1 `List` wrapper, down to the element type.
fn element_of(ty: &Type) -> &Type {
match ty.nested_type() {
Type::Item(element) | Type::List(element) => element.as_ref(),
other => other,
}
}
impl NodeNetworkInterface {
fn input_has_error(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> bool {
fn input_has_error(&mut self, input_connector: &InputConnector, network_path: &[NodeId]) -> bool {
match input_connector {
InputConnector::Node { node_id, input_index } => {
let Some(implementation) = self.implementation(node_id, network_path) else {
@@ -128,10 +125,10 @@ impl NodeNetworkInterface {
let node_path = [network_path, &[*node_id]].concat();
match implementation {
DocumentNodeImplementation::Network(_) => {
let outward_wires = self.with_outward_wires(&node_path, |map| map.get(&OutputConnector::Import(*input_index)).cloned()).flatten();
let Some(outward_wires) = outward_wires else { return false };
outward_wires.iter().any(|connector| match connector {
InputConnector::Node { node_id, input_index } => self.input_has_error(&InputConnector::node_at_index(*node_id, *input_index), &node_path),
let Some(map) = self.outward_wires(&node_path) else { return false };
let Some(outward_wires) = map.get(&OutputConnector::Import(*input_index)) else { return false };
outward_wires.clone().iter().any(|connector| match connector {
InputConnector::Node { node_id, input_index } => self.input_has_error(&InputConnector::node(*node_id, *input_index), &node_path),
InputConnector::Export(_) => false,
})
}
@@ -150,7 +147,7 @@ impl NodeNetworkInterface {
}
}
pub fn input_type_not_invalid(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> TypeSource {
pub fn input_type_not_invalid(&mut self, input_connector: &InputConnector, network_path: &[NodeId]) -> TypeSource {
let Some(input) = self.input_from_connector(input_connector, network_path) else {
return TypeSource::Error("Could not get input from connector");
};
@@ -168,7 +165,7 @@ impl NodeNetworkInterface {
let Some((encapsulating_node, encapsulating_path)) = network_path.split_last() else {
return TypeSource::Error("Could not get type of import in document network since it has no imports");
};
self.input_type(&InputConnector::node_at_index(*encapsulating_node, *import_index), encapsulating_path)
self.input_type(&InputConnector::node(*encapsulating_node, *import_index), encapsulating_path)
}
NodeInput::Scope(_) => TypeSource::Compiled(concrete!(())),
NodeInput::Reflection(document_node_metadata) => TypeSource::Compiled(document_node_metadata.ty()),
@@ -176,42 +173,9 @@ impl NodeNetworkInterface {
}
}
/// Whether the given node has a registered implementation accepting the layer chain's element type as its content input.
/// A chain awaiting compilation has no resolved type yet, so only a known-wrong type or a type error locks the layer out.
pub fn layer_chain_hosts_node(&self, node_id: &NodeId, network_path: &[NodeId], node: &ProtoNodeIdentifier) -> bool {
let secondary_input = InputConnector::layer_secondary_input(*node_id);
if !self.input_from_connector(&secondary_input, network_path).is_some_and(|input| input.is_exposed()) {
return false;
}
let chain_type = self.input_type(&secondary_input, network_path);
match chain_type.compiled_element_type() {
Some(element) => {
let Some(implementations) = NODE_REGISTRY.get(node) else {
log::error!("Proto node {node:?} not found in the node registry, in layer_chain_hosts_node");
return false;
};
implementations.keys().any(|node_io| node_io.inputs.first().is_some_and(|content| element_of(content) == element))
}
None => !matches!(chain_type, TypeSource::Invalid),
}
}
/// Whether the blending nodes (blend mode, opacity, clipping mask) can be spliced into this layer's chain.
pub fn layer_hosts_blending_nodes(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
// Blend Mode stands in for the trio since they share one implementations list
self.layer_chain_hosts_node(node_id, network_path, &graphene_std::blending_nodes::blend_mode::IDENTIFIER)
}
/// Whether the Fill and Stroke nodes can be spliced into this layer's chain.
pub fn layer_hosts_paint_nodes(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
// Fill stands in for both since they share one implementations list
self.layer_chain_hosts_node(node_id, network_path, &graphene_std::vector_nodes::fill::IDENTIFIER)
}
/// Get the [`TypeSource`] for any InputConnector.
/// If the input is not compiled, then an Unknown or default from the definition is returned.
pub fn input_type(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> TypeSource {
pub fn input_type(&mut self, input_connector: &InputConnector, network_path: &[NodeId]) -> TypeSource {
// First check if there is an error with this node or any protonodes it is connected to
if self.input_has_error(input_connector, network_path) {
return TypeSource::Invalid;
@@ -220,7 +184,7 @@ impl NodeNetworkInterface {
}
/// Gets the default tagged value for an input. If its not compiled, then it tries to get a valid type. If there are no valid types, then it picks a random implementation.
pub fn tagged_value_from_input(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> TaggedValue {
pub fn tagged_value_from_input(&mut self, input_connector: &InputConnector, network_path: &[NodeId]) -> TaggedValue {
let guaranteed_type = match self.input_type(input_connector, network_path) {
TypeSource::Compiled(compiled) => compiled,
TypeSource::TaggedValue(value) => value,
@@ -242,24 +206,11 @@ impl NodeNetworkInterface {
concrete!(())
}
};
// A List-typed default drops to its Item counterpart (when that has a default value and the connector accepts rank 0),
// since a stored Item default can promote back onto a List connector but a stored List default can never return to rank 0
if let Some(element) = guaranteed_type.nested_type().list_element()
&& let Some(item_type) = self
.potential_valid_input_types(input_connector, network_path)
.into_iter()
.find(|ty| matches!(ty.nested_type(), Type::Item(item_element) if item_element.as_ref() == element))
&& let Some(item_default) = TaggedValue::from_type(&item_type)
{
return item_default;
}
TaggedValue::from_type_or_none(&guaranteed_type)
}
/// A list of all valid input types for this specific node.
pub fn potential_valid_input_types(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Vec<Type> {
pub fn potential_valid_input_types(&mut self, input_connector: &InputConnector, network_path: &[NodeId]) -> Vec<Type> {
let InputConnector::Node { node_id, input_index } = input_connector else {
// An export can have any type connected to it
return vec![graph_craft::generic!(T)];
@@ -271,15 +222,17 @@ impl NodeNetworkInterface {
match implementation {
DocumentNodeImplementation::Network(_) => {
let nested_path = [network_path, &[*node_id]].concat();
let inputs_from_import = self
.with_outward_wires(&nested_path, |outward_wires| outward_wires.get(&OutputConnector::Import(*input_index)).cloned())
.flatten();
let Some(inputs_from_import) = inputs_from_import else {
let Some(outward_wires) = self.outward_wires(&nested_path) else {
log::error!("Could not get outward wires in potential_valid_input_types");
return Vec::new();
};
let Some(inputs_from_import) = outward_wires.get(&OutputConnector::Import(*input_index)) else {
log::error!("Could not get inputs from import in potential_valid_input_types");
return Vec::new();
};
let intersection: HashSet<Type> = inputs_from_import
.clone()
.iter()
.map(|input_connector| self.potential_valid_input_types(input_connector, &nested_path).into_iter().collect::<HashSet<_>>())
.fold(None, |acc: Option<HashSet<Type>>, set| match acc {
@@ -300,11 +253,12 @@ impl NodeNetworkInterface {
};
let number_of_inputs = self.number_of_inputs(node_id, network_path);
implementations
.keys()
.filter_map(|node_io| {
.iter()
.filter_map(|entry| {
let node_io = &entry.io;
// Check if this NodeIOTypes implementation is valid for the other inputs
let valid_implementation = (0..number_of_inputs).filter(|iterator_index| iterator_index != input_index).all(|iterator_index| {
let input_type = self.input_type_not_invalid(&InputConnector::node_at_index(*node_id, iterator_index), network_path);
let input_type = self.input_type_not_invalid(&InputConnector::node(*node_id, iterator_index), network_path);
// TODO: Fix type checking for different call arguments
// For example a node input of (Footprint) -> Vector would not be compatible with a node that is called with () and returns Vector
node_io.inputs.get(iterator_index).map(|ty| ty.nested_type()) == input_type.compiled_nested_type()
@@ -323,7 +277,7 @@ impl NodeNetworkInterface {
}
/// Performs a downstream traversal to ensure input type will work in the full context of the graph.
pub fn complete_valid_input_types(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Vec<Type> {
pub fn complete_valid_input_types(&mut self, input_connector: &InputConnector, network_path: &[NodeId]) -> Vec<Type> {
match input_connector {
InputConnector::Node { node_id, input_index } => {
let Some(implementation) = self.implementation(node_id, network_path) else {
@@ -337,17 +291,18 @@ impl NodeNetworkInterface {
log::error!("Protonode {proto_node_identifier:?} not found in registry in complete_valid_input_types");
return Vec::new();
};
let valid_output_types = self.valid_output_types(&OutputConnector::primary_output(*node_id), network_path);
let valid_output_types = self.valid_output_types(&OutputConnector::node(*node_id, 0), network_path);
implementations
.keys()
.filter_map(|node_io| {
.iter()
.filter_map(|entry| {
let node_io = &entry.io;
if !valid_output_types.iter().any(|output_type| output_type.nested_type() == node_io.return_value.nested_type()) {
return None;
}
let valid_inputs = (0..node_io.inputs.len()).filter(|iterator_index| iterator_index != input_index).all(|iterator_index| {
let input_type = self.input_type_not_invalid(&InputConnector::node_at_index(*node_id, iterator_index), network_path);
let input_type = self.input_type_not_invalid(&InputConnector::node(*node_id, iterator_index), network_path);
match input_type.compiled_nested_type() {
Some(input_type) => node_io.inputs.get(iterator_index).is_some_and(|node_io_input_type| node_io_input_type.nested_type() == input_type),
None => true,
@@ -370,31 +325,22 @@ impl NodeNetworkInterface {
log::error!("Protonode {render_node:?} not found in registry");
return Vec::new();
};
implementations.keys().map(|types| types.inputs[1].clone()).collect()
implementations.iter().map(|entry| entry.io.inputs[1].clone()).collect()
}
}
}
}
}
pub fn output_type(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> TypeSource {
pub fn output_type(&mut self, output_connector: &OutputConnector, network_path: &[NodeId]) -> TypeSource {
match output_connector {
OutputConnector::Node { node_id, output_index } => {
// A hidden node is replaced by a passthrough during flattening, so its output carries its primary input's type
if *output_index == 0 && !self.is_visible(node_id, network_path) {
return self.input_type(&InputConnector::primary_input(*node_id), network_path);
}
// First try iterating upstream to the first protonode and try get its compiled type
let Some(implementation) = self.implementation(node_id, network_path) else {
return TypeSource::Error("Could not get implementation");
};
match implementation {
DocumentNodeImplementation::Network(_) => self.input_type(&InputConnector::Export(*output_index), &[network_path, &[*node_id]].concat()),
// The compiler removes passthrough nodes so they resolve no type of their own, but their output carries their primary input's type
DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::ops::passthrough::IDENTIFIER => {
self.input_type(&InputConnector::primary_input(*node_id), network_path)
}
DocumentNodeImplementation::ProtoNode(_) => match self.resolved_types.types.get(&[network_path, &[*node_id]].concat()) {
Some(resolved_type) => TypeSource::Compiled(resolved_type.output.clone()),
None => TypeSource::Unknown,
@@ -406,7 +352,7 @@ impl NodeNetworkInterface {
let Some((encapsulating_node, encapsulating_path)) = network_path.split_last() else {
return TypeSource::Error("Cannot get import type in document network since it has no imports");
};
let mut input_type = self.input_type(&InputConnector::node_at_index(*encapsulating_node, *import_index), encapsulating_path);
let mut input_type = self.input_type(&InputConnector::node(*encapsulating_node, *import_index), encapsulating_path);
if matches!(input_type, TypeSource::Invalid) {
input_type = TypeSource::Unknown
}
@@ -416,14 +362,18 @@ impl NodeNetworkInterface {
}
/// The valid output types are all types that are valid for each downstream connection.
fn valid_output_types(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Vec<Type> {
let inputs_from_import = self.with_outward_wires(network_path, |outward_wires| outward_wires.get(output_connector).cloned()).flatten();
let Some(inputs_from_import) = inputs_from_import else {
fn valid_output_types(&mut self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Vec<Type> {
let Some(outward_wires) = self.outward_wires(network_path) else {
log::error!("Could not get outward wires in valid_output_types");
return Vec::new();
};
let Some(inputs_from_import) = outward_wires.get(output_connector) else {
log::error!("Could not get inputs from import in valid_output_types");
return Vec::new();
};
let intersection = inputs_from_import
.clone()
.iter()
.map(|input_connector| self.potential_valid_input_types(input_connector, network_path).into_iter().collect::<HashSet<_>>())
.fold(None, |acc: Option<HashSet<Type>>, set| match acc {
@@ -387,5 +387,6 @@ fn input_metadata_entry_to_runtime(entry: InputMetadataEntry) -> InputMetadata {
widget_override: entry.widget_override,
input_data: entry.input_data,
},
..Default::default()
}
}
@@ -1,190 +0,0 @@
use super::*;
impl NodeNetworkInterface {
pub fn compute_modified_vector(&self, layer: LayerNodeIdentifier) -> Option<Vector> {
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self);
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))
&& let Some(vector) = self.document_metadata.vector_modify.get(&path_node)
{
let mut modified = vector.clone();
let path_node = self.document_network().nodes.get(&path_node);
let modification_input = path_node.and_then(|node: &DocumentNode| node.inputs.get(1)).and_then(|input| input.as_value());
if let Some(TaggedValue::VectorModification(modification)) = modification_input {
modification.apply(&mut modified);
}
return Some(modified);
}
self.document_metadata.layer_vector_data.get(&layer).map(|arc| arc.as_ref().clone())
}
/// The vector geometry an upstream Path node would surface for editing.
/// This is the result of `compute_modified_vector`, but only if a visible 'Path' node is actually upstream.
/// Useful for tool overlays and snap target collection usages that want to match the Path tool's view
/// (e.g. the pre-solidified centerline for a Solidify Stroke layer) and otherwise do nothing.
pub fn upstream_path_node_vector(&self, layer: LayerNodeIdentifier) -> Option<Vector> {
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self);
graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))?;
self.compute_modified_vector(layer)
}
/// Outline targets for the Select tool's hover/selection overlay, mirroring the Path tool's view.
/// Returns `Some` when an upstream Path node exists so the outline matches what the Path tool edits
/// (e.g. the pre-solidified centerline for a Solidify Stroke layer); returns `None` otherwise so the
/// caller can fall back to the layer's recorded `outlines`/`click_targets`.
pub fn path_aware_outline_targets(&self, layer: LayerNodeIdentifier) -> Option<Vec<ClickTargetType>> {
let vector = self.upstream_path_node_vector(layer)?;
let mut targets = Vec::new();
let subpaths: Vec<Subpath<PointId>> = vector.stroke_bezier_paths().collect();
if !subpaths.is_empty() {
targets.push(ClickTargetType::CompoundPath(subpaths));
}
for &point_id in vector.point_domain.ids() {
if !vector.any_connected(point_id) {
let position = vector.point_domain.position_from_id(point_id).unwrap_or_default();
targets.push(ClickTargetType::FreePoint(FreePoint::new(point_id, position)));
}
}
Some(targets)
}
/// Loads the structure of layer nodes from a node graph.
pub fn load_structure(&mut self) {
self.document_metadata.structure = HashMap::from_iter([(LayerNodeIdentifier::ROOT_PARENT, NodeRelations::default())]);
// Only load structure if there is a root node
let Some(root_node) = self.root_node(&[]) else { return };
let Some(first_root_layer) = self
.upstream_flow_back_from_nodes(vec![root_node.node_id], &[], FlowType::PrimaryFlow)
.find_map(|node_id| if self.is_layer(&node_id, &[]) { Some(LayerNodeIdentifier::new(node_id, self)) } else { None })
else {
return;
};
// Should refer to output node
let mut awaiting_horizontal_flow = vec![(first_root_layer.to_node(), first_root_layer)];
let mut awaiting_primary_flow = vec![];
while let Some((horizontal_root_node_id, mut parent_layer_node)) = awaiting_horizontal_flow.pop() {
let horizontal_flow_iter = self.upstream_flow_back_from_nodes(vec![horizontal_root_node_id], &[], FlowType::HorizontalFlow);
let mut children = Vec::new();
// Special handling for the root layer, since it should not be skipped
if horizontal_root_node_id == first_root_layer.to_node() {
for current_node_id in horizontal_flow_iter {
if self.is_layer(&current_node_id, &[]) {
let current_layer_node = LayerNodeIdentifier::new(current_node_id, self);
if !self.document_metadata.structure.contains_key(&current_layer_node) {
if current_node_id == first_root_layer.to_node() {
awaiting_primary_flow.push((current_node_id, LayerNodeIdentifier::ROOT_PARENT));
children.push((LayerNodeIdentifier::ROOT_PARENT, current_layer_node));
} else {
awaiting_primary_flow.push((current_node_id, parent_layer_node));
children.push((parent_layer_node, current_layer_node));
}
parent_layer_node = current_layer_node;
}
}
}
} else {
// Skip the horizontal_root_node_id node
for current_node_id in horizontal_flow_iter.skip(1) {
if self.is_layer(&current_node_id, &[]) {
let current_layer_node = LayerNodeIdentifier::new(current_node_id, self);
if !self.document_metadata.structure.contains_key(&current_layer_node) {
awaiting_primary_flow.push((current_node_id, parent_layer_node));
children.push((parent_layer_node, current_layer_node));
parent_layer_node = current_layer_node;
}
}
}
}
for (parent, child) in children {
parent.push_child(&mut self.document_metadata, child);
}
while let Some((primary_root_node_id, parent_layer_node)) = awaiting_primary_flow.pop() {
let primary_flow_iter = self.upstream_flow_back_from_nodes(vec![primary_root_node_id], &[], FlowType::PrimaryFlow);
// Skip the primary_root_node_id node
let mut children = Vec::new();
for current_node_id in primary_flow_iter.skip(1) {
if self.is_layer(&current_node_id, &[]) {
// Create a new layer for the top of each stack, and add it as a child to the previous parent
let current_layer_node = LayerNodeIdentifier::new(current_node_id, self);
if !self.document_metadata.structure.contains_key(&current_layer_node) {
children.push(current_layer_node);
// The layer nodes for the horizontal flow is itself
awaiting_horizontal_flow.push((current_node_id, current_layer_node));
}
}
}
for child in children {
parent_layer_node.push_child(&mut self.document_metadata, child);
}
}
}
let nodes: HashSet<NodeId> = self.document_network().nodes.keys().cloned().collect::<HashSet<_>>();
self.document_metadata.upstream_footprints.retain(|node, _| nodes.contains(node));
self.document_metadata.local_transforms.retain(|node, _| nodes.contains(node));
self.document_metadata.vector_modify.retain(|node, _| nodes.contains(node));
self.document_metadata.click_targets.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
self.document_metadata.outlines.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
self.document_metadata.text_frames.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
}
/// Update the cached transforms of the layers
pub fn update_transforms(&mut self, upstream_footprints: HashMap<NodeId, Footprint>, local_transforms: HashMap<NodeId, DAffine2>) {
self.document_metadata.upstream_footprints = upstream_footprints;
self.document_metadata.local_transforms = local_transforms;
}
/// Update the cached first item's source id of the layers
pub fn update_first_element_source_id(&mut self, new: HashMap<NodeId, Option<NodeId>>) {
self.document_metadata.first_element_source_ids = new;
}
/// Update the cached click targets of the layers
pub fn update_click_targets(&mut self, new_click_targets: HashMap<LayerNodeIdentifier, Vec<Arc<ClickTarget>>>) {
self.document_metadata.click_targets = new_click_targets;
}
/// Update the cached source-geometry outline targets of the layers
pub fn update_outlines(&mut self, new_outlines: HashMap<LayerNodeIdentifier, Vec<Arc<ClickTarget>>>) {
self.document_metadata.outlines = new_outlines;
}
/// Update the cached per-layer 'Text' node text frames in row-local space (as `DAffine2`
/// mapping the unit square onto the frame).
pub fn update_text_frames(&mut self, new_text_frames: HashMap<LayerNodeIdentifier, DAffine2>) {
self.document_metadata.text_frames = new_text_frames;
}
/// Update the cached clip targets of the layers
pub fn update_clip_targets(&mut self, new_clip_targets: HashSet<NodeId>) {
self.document_metadata.clip_targets = new_clip_targets;
}
/// Update the vector modify of the layers
pub fn update_vector_modify(&mut self, new_vector_modify: HashMap<NodeId, Vector>) {
self.document_metadata.vector_modify = new_vector_modify;
}
/// Update the layer vector data (for layers without Path nodes)
pub fn update_vector_data(&mut self, new_layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Vector>>) {
self.document_metadata.layer_vector_data = new_layer_vector_data;
}
/// Update the per-layer `ATTR_APPEARANCE` snapshot.
pub fn update_appearance_attributes(&mut self, new_layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>) {
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
}
}
@@ -1,320 +0,0 @@
use super::*;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::concrete;
use graphene_std::Context;
// PartialEq required by message handlers
/// All persistent editor and Graphene data for a node, unified into a single flat shape.
/// Used to author node definitions, pass nodes through the editor, and serialize them for the clipboard.
///
/// [`Self::into_parts`] and [`Self::from_parts`] are the only places this is split into (or joined from) the
/// [`DocumentNode`] and [`DocumentNodePersistentMetadata`] halves stored by the network interface, so the parallel-tree
/// storage invariants hold by construction for every node built from a template.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(from = "NodeTemplateParts", into = "NodeTemplateParts")]
pub struct NodeTemplate {
/// The graph data inputs to the node. Kept the same length as `input_metadata` by [`Self::normalize_input_metadata`] and [`Self::into_parts`].
pub inputs: Vec<NodeInput>,
/// Type of the argument which this node can be evaluated with.
pub call_argument: Type,
/// A nested network of templates, a proto node identifier, or the Extract tag.
pub implementation: NodeTemplateImplementation,
/// Represents the eye icon for hiding/showing the node in the graph UI.
pub visible: bool,
/// Prevents identical proto nodes from being deduplicated during compilation, e.g. for monitor nodes.
pub skip_deduplication: bool,
/// List of Extract and Inject annotations for the Context.
pub context_features: ContextDependencies,
/// A name chosen by the user for this instance of the node. Empty indicates no given name, in which case the implementation name is displayed in italics.
pub display_name: String,
/// Metadata to override the properties panel widgets for each input. Kept the same length as `inputs`.
pub input_metadata: Vec<InputMetadata>,
pub output_names: Vec<String>,
/// Represents the lock icon for locking/unlocking the node in the graph UI.
pub locked: bool,
/// Indicates that the node will be shown in the Properties panel when it would otherwise be empty.
pub pinned: bool,
/// Whether the node is displayed as a left-to-right node or bottom-to-top layer, along with its position.
pub node_type_metadata: NodeTypePersistentMetadata,
}
impl NodeTemplate {
/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
self.inputs.get(P::INDEX)
}
/// Mutable access to the input slot named by the given parameter symbol, mirroring [`DocumentNode::input_mut`].
pub fn input_mut<P: graphene_std::NodeParameter>(&mut self, _parameter: P) -> Option<&mut NodeInput> {
self.inputs.get_mut(P::INDEX)
}
}
impl Default for NodeTemplate {
fn default() -> Self {
Self {
inputs: Vec::new(),
call_argument: concrete!(Context),
implementation: NodeTemplateImplementation::default(),
visible: true,
skip_deduplication: false,
context_features: ContextDependencies::default(),
display_name: String::new(),
input_metadata: Vec::new(),
output_names: Vec::new(),
locked: false,
pinned: false,
node_type_metadata: NodeTypePersistentMetadata::default(),
}
}
}
/// The implementation of a [`NodeTemplate`], mirroring [`DocumentNodeImplementation`] but carrying unified templates for nested network nodes.
// Templates are transient authoring objects, so the Network variant's size is not worth the authoring noise of boxing
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq)]
pub enum NodeTemplateImplementation {
Network(NodeNetworkTemplate),
ProtoNode(ProtoNodeIdentifier),
Extract,
}
impl Default for NodeTemplateImplementation {
fn default() -> Self {
NodeTemplateImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER)
}
}
/// A nested network within a [`NodeTemplate`], holding each nested node as a unified template alongside the network-level persistent metadata.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct NodeNetworkTemplate {
pub exports: Vec<NodeInput>,
pub nodes: HashMap<NodeId, NodeTemplate>,
pub scope_injections: HashMap<String, (NodeId, Type)>,
/// The identifier of the [`DocumentNodeDefinition`] this network was instantiated from, if unmodified.
///
/// [`DocumentNodeDefinition`]: crate::messages::portfolio::document::node_graph::document_node_definitions::DocumentNodeDefinition
pub reference: Option<String>,
/// The display order of pinned nodes in the Properties panel.
pub pinned_node_order: Vec<NodeId>,
pub previewing: Previewing,
pub navigation_metadata: NavigationMetadata,
}
impl NodeTemplate {
/// Joins a [`DocumentNode`] and its persistent metadata into the unified template shape. Missing nested metadata is filled with defaults.
pub fn from_parts(document_node: DocumentNode, persistent_node_metadata: DocumentNodePersistentMetadata) -> Self {
let DocumentNode {
inputs,
call_argument,
implementation,
visible,
skip_deduplication,
context_features,
original_location: _,
} = document_node;
let DocumentNodePersistentMetadata {
display_name,
input_metadata,
output_names,
locked,
pinned,
node_type_metadata,
network_metadata,
} = persistent_node_metadata;
let implementation = match implementation {
DocumentNodeImplementation::Network(network) => {
let mut nested_persistent = network_metadata.map(|metadata| metadata.persistent_metadata).unwrap_or_default();
// Pair each nested node with its metadata by ID, recursively
let mut nodes = HashMap::with_capacity(network.nodes.len());
for (node_id, node) in network.nodes {
let node_persistent_metadata = nested_persistent.node_metadata.remove(&node_id).map(|metadata| metadata.persistent_metadata).unwrap_or_default();
nodes.insert(node_id, NodeTemplate::from_parts(node, node_persistent_metadata));
}
NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: network.exports,
nodes,
scope_injections: network.scope_injections.into_iter().collect(),
reference: nested_persistent.reference,
pinned_node_order: nested_persistent.pinned_node_order,
previewing: nested_persistent.previewing,
navigation_metadata: nested_persistent.navigation_metadata,
})
}
DocumentNodeImplementation::ProtoNode(identifier) => NodeTemplateImplementation::ProtoNode(identifier),
DocumentNodeImplementation::Extract => NodeTemplateImplementation::Extract,
};
NodeTemplate {
inputs,
call_argument,
implementation,
visible,
skip_deduplication,
context_features,
display_name,
input_metadata,
output_names,
locked,
pinned,
node_type_metadata,
}
}
/// Splits the template into the [`DocumentNode`] and [`DocumentNodePersistentMetadata`] halves stored by the network interface.
pub fn into_parts(self) -> (DocumentNode, DocumentNodePersistentMetadata) {
let NodeTemplate {
inputs,
call_argument,
implementation,
visible,
skip_deduplication,
context_features,
display_name,
mut input_metadata,
output_names,
locked,
pinned,
node_type_metadata,
} = self;
let (implementation, network_metadata) = implementation.into_parts();
// The stored metadata invariant requires exactly one input metadata entry per input
input_metadata.resize_with(inputs.len(), InputMetadata::default);
let document_node = DocumentNode {
inputs,
call_argument,
implementation,
visible,
skip_deduplication,
context_features,
original_location: Default::default(),
};
let persistent_node_metadata = DocumentNodePersistentMetadata {
display_name,
input_metadata,
output_names,
locked,
pinned,
node_type_metadata,
network_metadata,
};
(document_node, persistent_node_metadata)
}
/// Resizes `input_metadata` to match `inputs` at every nesting level, filling gaps with defaults.
pub fn normalize_input_metadata(&mut self) {
self.input_metadata.resize_with(self.inputs.len(), InputMetadata::default);
if let NodeTemplateImplementation::Network(network_template) = &mut self.implementation {
for nested_template in network_template.nodes.values_mut() {
nested_template.normalize_input_metadata();
}
}
}
/// Normalizes the stored types at every nesting level via [`DocumentNode::normalize_stored_types`], round-tripping through the split halves to reuse its logic.
pub fn normalize_stored_types(&mut self) {
let (mut document_node, persistent_node_metadata) = std::mem::take(self).into_parts();
document_node.normalize_stored_types();
*self = NodeTemplate::from_parts(document_node, persistent_node_metadata);
}
}
impl NodeTemplateImplementation {
/// Splits into the [`DocumentNodeImplementation`] and the nested network metadata stored alongside it.
pub fn into_parts(self) -> (DocumentNodeImplementation, Option<NodeNetworkMetadata>) {
match self {
NodeTemplateImplementation::Network(network_template) => {
let NodeNetworkTemplate {
exports,
nodes,
scope_injections,
reference,
pinned_node_order,
previewing,
navigation_metadata,
} = network_template;
// Split each nested template into its two halves, recursively
let mut network = NodeNetwork {
exports,
scope_injections: scope_injections.into_iter().collect(),
..Default::default()
};
let mut node_metadata = HashMap::with_capacity(nodes.len());
for (node_id, node_template) in nodes {
let (document_node, persistent_metadata) = node_template.into_parts();
network.nodes.insert(node_id, document_node);
node_metadata.insert(
node_id,
DocumentNodeMetadata {
persistent_metadata,
transient_metadata: Default::default(),
},
);
}
let network_metadata = NodeNetworkMetadata {
persistent_metadata: NodeNetworkPersistentMetadata {
reference,
node_metadata,
pinned_node_order,
previewing,
navigation_metadata,
selection_undo_history: Default::default(),
selection_redo_history: Default::default(),
},
transient_metadata: Default::default(),
};
(DocumentNodeImplementation::Network(network), Some(network_metadata))
}
NodeTemplateImplementation::ProtoNode(identifier) => (DocumentNodeImplementation::ProtoNode(identifier), None),
NodeTemplateImplementation::Extract => (DocumentNodeImplementation::Extract, None),
}
}
}
/// Collects resource IDs referenced by a template and its nested networks.
pub fn collect_template_resources(template: &NodeTemplate, out: &mut HashSet<ResourceId>) {
for input in &template.inputs {
collect_input_resource(input, out);
}
if let NodeTemplateImplementation::Network(network_template) = &template.implementation {
for export in &network_template.exports {
collect_input_resource(export, out);
}
for nested_template in network_template.nodes.values() {
collect_template_resources(nested_template, out);
}
}
}
/// The legacy two-tree shape of [`NodeTemplate`], kept as its serde representation so serialized clipboard data round-trips across versions.
#[derive(serde::Serialize, serde::Deserialize)]
struct NodeTemplateParts {
document_node: DocumentNode,
persistent_node_metadata: DocumentNodePersistentMetadata,
}
impl From<NodeTemplateParts> for NodeTemplate {
fn from(parts: NodeTemplateParts) -> Self {
NodeTemplate::from_parts(parts.document_node, parts.persistent_node_metadata)
}
}
impl From<NodeTemplate> for NodeTemplateParts {
fn from(template: NodeTemplate) -> Self {
let (document_node, persistent_node_metadata) = template.into_parts();
NodeTemplateParts {
document_node,
persistent_node_metadata,
}
}
}
@@ -1,866 +0,0 @@
use super::*;
use graphene_std::ParameterRef;
#[derive(PartialEq)]
pub enum FlowType {
/// Iterate over all upstream nodes (inclusive) from every input (the primary and all secondary).
UpstreamFlow,
/// Iterate over nodes (inclusive) connected to the primary input.
PrimaryFlow,
/// Iterate over the secondary input (inclusive) for layer nodes and primary input for non layer nodes.
HorizontalFlow,
/// Same as horizontal flow, but only iterates over connections to primary outputs
HorizontalPrimaryOutputFlow,
/// Upstream flow starting from the either the node (inclusive) or secondary input of the layer (not inclusive).
LayerChildrenUpstreamFlow,
}
/// Iterate over upstream nodes. The behavior changes based on the `flow_type` that's set.
/// - [`FlowType::UpstreamFlow`]: iterates over all upstream nodes from every input (the primary and all secondary).
/// - [`FlowType::PrimaryFlow`]: iterates along the horizontal inputs of nodes, so in the case of a node chain `a -> b -> c`, this would yield `c, b, a` if we started from `c`.
/// - [`FlowType::HorizontalFlow`]: iterates over the secondary input for layer nodes and primary input for non layer nodes.
/// - [`FlowType::LayerChildrenUpstreamFlow`]: iterates over all upstream nodes from the secondary input of the node.
pub(crate) struct FlowIter<'a> {
pub(crate) stack: Vec<NodeId>,
pub(crate) network: &'a NodeNetwork,
pub(crate) network_metadata: &'a NodeNetworkMetadata,
pub(crate) flow_type: FlowType,
}
impl Iterator for FlowIter<'_> {
type Item = NodeId;
fn next(&mut self) -> Option<Self::Item> {
loop {
let node_id = self.stack.pop()?;
if let (Some(document_node), Some(node_metadata)) = (self.network.nodes.get(&node_id), self.network_metadata.persistent_metadata.node_metadata.get(&node_id)) {
let skip = if matches!(self.flow_type, FlowType::HorizontalFlow | FlowType::HorizontalPrimaryOutputFlow) && node_metadata.persistent_metadata.is_layer() {
1
} else {
0
};
let take = if self.flow_type == FlowType::UpstreamFlow { u32::MAX as usize } else { 1 };
let inputs = document_node.inputs.iter().skip(skip).take(take);
let node_ids = inputs.filter_map(|input| match input {
NodeInput::Node { output_index, .. } if self.flow_type == FlowType::HorizontalPrimaryOutputFlow && *output_index != 0 => None,
NodeInput::Node { node_id, .. } => Some(node_id),
_ => None,
});
self.stack.extend(node_ids);
return Some(node_id);
}
}
}
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ImportOrExport {
Import(usize),
Export(usize),
}
/// The primary input (index 0) of any node: a chain node's horizontal wire continuing from the left, or a layer's vertical stack wire from the sibling rendered below it.
pub const PRIMARY_INPUT_INDEX: usize = 0;
/// The secondary input (index 1) of a layer-shaped node: the horizontal wire from the left, carrying the node chain or child stack that the layer renders.
pub const LAYER_SECONDARY_INPUT_INDEX: usize = 1;
/// The primary output (index 0) of a node, which most nodes expose as their only output.
pub const PRIMARY_OUTPUT_INDEX: usize = 0;
/// Represents an input connector with index based on the [`DocumentNode::inputs`] index, not the visible input index
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum InputConnector {
#[serde(rename = "node")]
Node {
#[serde(rename = "nodeId")]
node_id: NodeId,
#[serde(rename = "inputIndex")]
input_index: usize,
},
#[serde(rename = "export")]
Export(usize),
}
impl Default for InputConnector {
fn default() -> Self {
InputConnector::Export(0)
}
}
impl InputConnector {
/// Reference a node's input by its parameter symbol, e.g. `InputConnector::node(node_id, stroke::WeightInput)`, or by an erased [`ParameterRef`] chosen at runtime.
pub fn node(node_id: NodeId, parameter: impl Into<ParameterRef>) -> Self {
InputConnector::Node {
node_id,
input_index: parameter.into().input_index,
}
}
/// Reference a node's primary input: a chain node's continuation from the left, or a layer's stack wire from the bottom.
pub fn primary_input(node_id: NodeId) -> Self {
InputConnector::Node {
node_id,
input_index: PRIMARY_INPUT_INDEX,
}
}
/// Reference a layer-shaped node's secondary input, the wire from the left carrying the content that the layer renders.
pub fn layer_secondary_input(node_id: NodeId) -> Self {
InputConnector::Node {
node_id,
input_index: LAYER_SECONDARY_INPUT_INDEX,
}
}
/// Reference a node's input by a runtime index, for genuinely dynamic cases like clicked ports, input enumeration, and document upgrades.
pub fn node_at_index(node_id: NodeId, input_index: usize) -> Self {
InputConnector::Node { node_id, input_index }
}
pub fn input_index(&self) -> usize {
match self {
InputConnector::Node { input_index, .. } => *input_index,
InputConnector::Export(input_index) => *input_index,
}
}
pub fn node_id(&self) -> Option<NodeId> {
match self {
InputConnector::Node { node_id, .. } => Some(*node_id),
_ => None,
}
}
}
/// Represents an output connector
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum OutputConnector {
#[serde(rename = "node")]
Node {
#[serde(rename = "nodeId")]
node_id: NodeId,
#[serde(rename = "outputIndex")]
output_index: usize,
},
#[serde(rename = "import")]
Import(usize),
}
impl Default for OutputConnector {
fn default() -> Self {
OutputConnector::Import(0)
}
}
impl OutputConnector {
pub fn node(node_id: NodeId, output_index: usize) -> Self {
OutputConnector::Node { node_id, output_index }
}
/// Reference a node's primary (first) output.
pub fn primary_output(node_id: NodeId) -> Self {
OutputConnector::Node {
node_id,
output_index: PRIMARY_OUTPUT_INDEX,
}
}
pub fn index(&self) -> usize {
match self {
OutputConnector::Node { output_index, .. } => *output_index,
OutputConnector::Import(output_index) => *output_index,
}
}
pub fn node_id(&self) -> Option<NodeId> {
match self {
OutputConnector::Node { node_id, .. } => Some(*node_id),
_ => None,
}
}
pub fn from_input(input: &NodeInput) -> Option<Self> {
match input {
NodeInput::Import { import_index, .. } => Some(Self::Import(*import_index)),
NodeInput::Node { node_id, output_index, .. } => Some(Self::node(*node_id, *output_index)),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct Ports {
pub(crate) input_ports: Vec<(usize, ClickTarget)>,
pub(crate) output_ports: Vec<(usize, ClickTarget)>,
}
impl Default for Ports {
fn default() -> Self {
Self::new()
}
}
impl Ports {
pub fn new() -> Ports {
Ports {
input_ports: Vec::new(),
output_ports: Vec::new(),
}
}
pub fn click_targets(&self) -> impl Iterator<Item = &ClickTarget> {
self.input_ports
.iter()
.map(|(_, click_target)| click_target)
.chain(self.output_ports.iter().map(|(_, click_target)| click_target))
}
pub fn input_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> {
self.input_ports.iter()
}
pub fn output_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> {
self.output_ports.iter()
}
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
let subpath = Subpath::new_ellipse(center - DVec2::new(8., 8.), center + DVec2::new(8., 8.));
self.insert_custom_input_port(input_index, ClickTarget::new_with_subpath(subpath, 0.));
}
pub(crate) fn insert_custom_input_port(&mut self, input_index: usize, click_target: ClickTarget) {
self.input_ports.push((input_index, click_target));
}
pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
let subpath = Subpath::new_ellipse(center - DVec2::new(8., 8.), center + DVec2::new(8., 8.));
self.insert_custom_output_port(output_index, ClickTarget::new_with_subpath(subpath, 0.));
}
pub(crate) fn insert_custom_output_port(&mut self, output_index: usize, click_target: ClickTarget) {
self.output_ports.push((output_index, click_target));
}
pub(crate) fn insert_node_input(&mut self, input_index: usize, row_index: usize, node_top_left: DVec2) {
// The center of the click target is always 24 px down from the top left corner of the node
let center = node_top_left + DVec2::new(0., 24. + 24. * row_index as f64);
self.insert_input_port_at_center(input_index, center);
}
pub(crate) fn insert_node_output(&mut self, output_index: usize, node_top_left: DVec2) {
// The center of the click target is always 24 px down from the top left corner of the node
let center = node_top_left + DVec2::new(5. * 24., 24. + 24. * output_index as f64);
self.insert_output_port_at_center(output_index, center);
}
pub(crate) fn insert_layer_input(&mut self, input_index: usize, node_top_left: DVec2) {
let center = if input_index == 0 {
node_top_left + DVec2::new(2. * 24., 24. * 2. + 8.)
} else {
node_top_left + DVec2::new(0., 24. * 1.)
};
self.insert_input_port_at_center(input_index, center);
}
pub(crate) fn insert_layer_output(&mut self, node_top_left: DVec2) {
// The center of the click target is always 24 px down from the top left corner of the node
let center = node_top_left + DVec2::new(2. * 24., -8.);
self.insert_output_port_at_center(0, center);
}
pub fn clicked_input_port_from_point(&self, point: DVec2) -> Option<usize> {
self.input_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
}
pub fn clicked_output_port_from_point(&self, point: DVec2) -> Option<usize> {
self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
}
pub fn input_port_position(&self, index: usize) -> Option<DVec2> {
self.input_ports
.iter()
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
}
pub fn output_port_position(&self, index: usize) -> Option<DVec2> {
self.output_ports
.iter()
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
}
}
#[derive(PartialEq, Debug, Clone, Copy, Hash, Default, serde::Serialize, serde::Deserialize)]
pub struct RootNode {
pub node_id: NodeId,
pub output_index: usize,
}
impl RootNode {
pub fn to_connector(&self) -> OutputConnector {
OutputConnector::Node {
node_id: self.node_id,
output_index: self.output_index,
}
}
}
#[derive(PartialEq, Debug, Clone, Copy, Hash, Default, serde::Serialize, serde::Deserialize)]
pub enum Previewing {
/// If there is a node to restore the connection to the export for, then it is stored in the option.
/// Otherwise, nothing gets restored and the primary export is disconnected.
Yes { root_node_to_restore: Option<RootNode> },
#[default]
No,
}
/// All fields in NetworkMetadata should automatically be updated by using the network interface API. If a field is none then it should be calculated based on the network state.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct NodeNetworkMetadata {
pub persistent_metadata: NodeNetworkPersistentMetadata,
#[serde(skip)]
pub transient_metadata: NodeNetworkTransientMetadata,
}
impl Clone for NodeNetworkMetadata {
fn clone(&self) -> Self {
NodeNetworkMetadata {
persistent_metadata: self.persistent_metadata.clone(),
transient_metadata: Default::default(),
}
}
}
impl PartialEq for NodeNetworkMetadata {
fn eq(&self, other: &Self) -> bool {
self.persistent_metadata == other.persistent_metadata
}
}
impl NodeNetworkMetadata {
pub fn nested_metadata(&self, nested_path: &[NodeId]) -> Option<&Self> {
let mut network_metadata = Some(self);
for segment in nested_path {
network_metadata = network_metadata
.and_then(|network| network.persistent_metadata.node_metadata.get(segment))
.and_then(|node| node.persistent_metadata.network_metadata.as_ref());
}
network_metadata
}
/// Get the mutable nested network given by the path of node ids
pub fn nested_metadata_mut(&mut self, nested_path: &[NodeId]) -> Option<&mut Self> {
let mut network_metadata = Some(self);
for segment in nested_path {
network_metadata = network_metadata
.and_then(|network: &mut NodeNetworkMetadata| network.persistent_metadata.node_metadata.get_mut(segment))
.and_then(|node| node.persistent_metadata.network_metadata.as_mut());
}
network_metadata
}
}
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct NodeNetworkPersistentMetadata {
/// The identifier for the node definition created for custom network nodes in [`DocumentNodeDefinition`].
/// It is only used to associate network nodes with their definition. Protonodes use their ProtonodeIdentifier.
/// The reference is removed once the node is modified, since the node now stores its own implementation and inputs.
/// TODO: Used during serialization/deserialization to prevent storing implementation or inputs (and possible other fields) if they are the same as the definition.
/// TODO: Implement node versioning so that references to old nodes can be updated to the new node definition.
pub reference: Option<String>,
/// Node metadata must exist for every document node in the network
#[serde(serialize_with = "graphene_std::vector::serialize_hashmap", deserialize_with = "graphene_std::vector::deserialize_hashmap")]
pub node_metadata: HashMap<NodeId, DocumentNodeMetadata>,
/// The display order of pinned nodes in the Properties panel (shown when nothing is selected in this network), keyed by node ID.
#[serde(default)]
pub pinned_node_order: Vec<NodeId>,
/// Cached metadata for each node, which is calculated when adding a node to node_metadata
/// Indicates whether the network is currently rendered with a particular node that is previewed, and if so, which connection should be restored when the preview ends.
pub previewing: Previewing,
// Stores the transform and navigation state for the network
pub navigation_metadata: NavigationMetadata,
/// Stack of selection snapshots for previous history states. Session state that is not persisted into saved documents.
#[serde(skip)]
pub selection_undo_history: VecDeque<SelectedNodes>,
/// Stack of selection snapshots for future history states.
#[serde(skip)]
pub selection_redo_history: VecDeque<SelectedNodes>,
}
/// A lazily computed cache slot whose load and read paths work through &self, with interior mutability guarding the stored value.
#[derive(Debug, Clone)]
pub(crate) struct TransientCache<T>(std::cell::RefCell<Option<T>>);
impl<T> Default for TransientCache<T> {
fn default() -> Self {
TransientCache(std::cell::RefCell::new(None))
}
}
impl<T> TransientCache<T> {
pub(crate) fn is_loaded(&self) -> bool {
self.0.borrow().is_some()
}
pub(crate) fn store(&self, value: T) {
*self.0.borrow_mut() = Some(value);
}
pub(crate) fn unload(&self) {
*self.0.borrow_mut() = None;
}
/// Runs `read` on the cached value if it is loaded.
pub(crate) fn with_loaded<R>(&self, read: impl FnOnce(&T) -> R) -> Option<R> {
self.0.borrow().as_ref().map(read)
}
/// Direct access without runtime borrow tracking, for callers already holding exclusive access.
pub(crate) fn get_loaded_mut(&mut self) -> Option<&mut T> {
self.0.get_mut().as_mut()
}
}
/// If some network calculation is too slow to compute for every usage, cache the data here
#[derive(Debug, Default, Clone)]
pub struct NodeNetworkTransientMetadata {
pub selected_nodes: SelectedNodes,
/// Sole dependents of the top of the stacks of all selected nodes. Used to determine which nodes are checked for collision when shifting.
/// The LayerOwner is used to determine whether the collided node should be shifted, or the layer that owns it.
pub(crate) stack_dependents: TransientCache<HashMap<NodeId, LayerOwner>>,
/// Cache for the bounding box around all nodes in node graph space.
pub(crate) all_nodes_bounding_box: TransientCache<[DVec2; 2]>,
/// Cache for all outward wire connections
pub(crate) outward_wires: TransientCache<HashMap<OutputConnector, Vec<InputConnector>>>,
/// All export connector click targets
pub(crate) import_export_ports: TransientCache<Ports>,
/// Click targets for adding, removing, and moving import/export ports
pub(crate) modify_import_export: TransientCache<ModifyImportExportClickTarget>,
/// Cached wire SVG paths per input connector, where an entry's presence means that wire is loaded.
pub(crate) wires: std::cell::RefCell<HashMap<InputConnector, WirePathUpdate>>,
/// Drag-session state: how far each unowned stack dependent has been pushed vertically from its resting position. Cleared when the drag ends.
pub(crate) drag_offsets: std::cell::RefCell<HashMap<NodeId, i32>>,
}
#[derive(Debug, Clone)]
pub struct ModifyImportExportClickTarget {
// Subtract icon that appears when hovering over an import/export
pub remove_imports_exports: Ports,
// Grip drag icon that appears when hovering over an import/export
pub reorder_imports_exports: Ports,
}
#[derive(Debug, Clone)]
pub struct NetworkEdgeDistance {
/// The viewport pixel distance between the left edge of the node graph and the exports.
pub exports_to_edge_distance: DVec2,
/// The viewport pixel distance between the left edge of the node graph and the imports.
pub imports_to_edge_distance: DVec2,
}
#[derive(Debug, Clone)]
pub enum LayerOwner {
// Used to get the layer that should be shifted when there is a collision.
Layer(NodeId),
None,
}
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct DocumentNodeMetadata {
#[serde(deserialize_with = "deserialize_node_persistent_metadata")]
pub persistent_metadata: DocumentNodePersistentMetadata,
#[serde(skip)]
pub transient_metadata: DocumentNodeTransientMetadata,
}
impl Clone for DocumentNodeMetadata {
fn clone(&self) -> Self {
DocumentNodeMetadata {
persistent_metadata: self.persistent_metadata.clone(),
transient_metadata: Default::default(),
}
}
}
impl PartialEq for DocumentNodeMetadata {
fn eq(&self, other: &Self) -> bool {
self.persistent_metadata == other.persistent_metadata
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct NumberInputSettings {
pub unit: Option<String>,
pub min: Option<f64>,
pub max: Option<f64>,
pub step: Option<f64>,
pub mode: NumberInputMode,
pub range_min: Option<f64>,
pub range_max: Option<f64>,
pub is_integer: bool,
pub blank_assist: bool,
}
impl Default for NumberInputSettings {
fn default() -> Self {
NumberInputSettings {
unit: None,
min: None,
max: None,
step: None,
mode: NumberInputMode::default(),
range_min: None,
range_max: None,
is_integer: false,
blank_assist: true,
}
}
}
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct Vec2InputSettings {
pub x: String,
pub y: String,
pub unit: String,
pub min: Option<f64>,
pub is_integer: bool,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum WidgetOverride {
None,
Hidden,
String(String),
Number(NumberInputSettings),
Vec2(Vec2InputSettings),
Custom(String),
}
// TODO: Custom deserialization/serialization to ensure number of properties row matches number of node inputs
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct InputPersistentMetadata {
/// A general datastore than can store key value pairs of any types for any input
/// Each instance of the input node needs to store its own data, since it can lose the reference to its
/// node definition if the node signature is modified by the user. For example adding/removing/renaming an import/export of a network node.
#[serde(serialize_with = "graphene_std::vector::serialize_hashmap_as_sorted_object")]
pub input_data: HashMap<String, Value>,
// An input can override a widget, which would otherwise be automatically generated from the type
// The string is the identifier to the widget override function stored in INPUT_OVERRIDES
pub widget_override: Option<String>,
/// An empty input name means to use the type as the name.
pub input_name: String,
/// Displayed as the tooltip description.
pub input_description: String,
}
impl InputPersistentMetadata {
pub fn with_name(mut self, input_name: &str) -> Self {
self.input_name = input_name.to_string();
self
}
pub fn with_override(mut self, widget_override: WidgetOverride) -> Self {
match widget_override {
// Uses the default widget for the type
WidgetOverride::None => {
self.widget_override = None;
}
WidgetOverride::Hidden => {
self.widget_override = Some("hidden".to_string());
}
WidgetOverride::String(string_properties) => {
self.input_data.insert("string_properties".to_string(), Value::String(string_properties));
self.widget_override = Some("string".to_string());
}
WidgetOverride::Number(mut number_properties) => {
if let Some(unit) = number_properties.unit.take() {
self.input_data.insert("unit".to_string(), json!(unit));
}
if let Some(min) = number_properties.min.take() {
self.input_data.insert("min".to_string(), json!(min));
}
if let Some(max) = number_properties.max.take() {
self.input_data.insert("max".to_string(), json!(max));
}
if let Some(step) = number_properties.step.take() {
self.input_data.insert("step".to_string(), json!(step));
}
if let Some(range_min) = number_properties.range_min.take() {
self.input_data.insert("range_min".to_string(), json!(range_min));
}
if let Some(range_max) = number_properties.range_max.take() {
self.input_data.insert("range_max".to_string(), json!(range_max));
}
self.input_data.insert("mode".to_string(), json!(number_properties.mode));
self.input_data.insert("is_integer".to_string(), Value::Bool(number_properties.is_integer));
self.input_data.insert("blank_assist".to_string(), Value::Bool(number_properties.blank_assist));
self.widget_override = Some("number".to_string());
}
WidgetOverride::Vec2(vec2_properties) => {
self.input_data.insert("x".to_string(), json!(vec2_properties.x));
self.input_data.insert("y".to_string(), json!(vec2_properties.y));
self.input_data.insert("unit".to_string(), json!(vec2_properties.unit));
self.input_data.insert("is_integer".to_string(), Value::Bool(vec2_properties.is_integer));
if let Some(min) = vec2_properties.min {
self.input_data.insert("min".to_string(), json!(min));
}
self.widget_override = Some("vec2".to_string());
}
WidgetOverride::Custom(lambda_name) => {
self.widget_override = Some(lambda_name);
}
};
self
}
pub fn with_description(mut self, description: &str) -> Self {
self.input_description = description.to_string();
self
}
}
/// Persistent metadata for each node in the network, which must be included when creating, serializing, and deserializing saving a node.
#[derive(Default, Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DocumentNodePersistentMetadata {
/// A name chosen by the user for this instance of the node. Empty indicates no given name, in which case the implementation name is displayed to the user in italics.
#[serde(default)]
pub display_name: String,
/// Stores metadata to override the properties in the properties panel for each input. These can either be generated automatically based on the type, or with a custom function.
/// Must match the length of node inputs
pub input_metadata: Vec<InputMetadata>,
pub output_names: Vec<String>,
/// Represents the lock icon for locking/unlocking the node in the graph UI. When locked, a node cannot be moved in the graph UI.
#[serde(default)]
pub locked: bool,
/// Indicates that the node will be shown in the Properties panel when it would otherwise be empty, letting a user easily edit its properties by just deselecting everything.
#[serde(default)]
pub pinned: bool,
/// Metadata that is specific to either nodes or layers, which are chosen states for displaying as a left-to-right node or bottom-to-top layer.
/// All fields in NodeTypePersistentMetadata should automatically be updated by using the network interface API
pub node_type_metadata: NodeTypePersistentMetadata,
/// This should always be Some for nodes with a [`DocumentNodeImplementation::Network`], and none for [`DocumentNodeImplementation::ProtoNode`]
pub network_metadata: Option<NodeNetworkMetadata>,
}
impl DocumentNodePersistentMetadata {
pub fn is_layer(&self) -> bool {
matches!(self.node_type_metadata, NodeTypePersistentMetadata::Layer(_))
}
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct InputMetadata {
pub persistent_metadata: InputPersistentMetadata,
}
impl PartialEq for InputMetadata {
fn eq(&self, other: &Self) -> bool {
self.persistent_metadata == other.persistent_metadata
}
}
impl From<(&str, &str)> for InputMetadata {
fn from(input_name_and_description: (&str, &str)) -> Self {
InputMetadata {
persistent_metadata: InputPersistentMetadata::default()
.with_name(input_name_and_description.0)
.with_description(input_name_and_description.1),
}
}
}
impl InputMetadata {
pub fn with_name_description_override(input_name: &str, description: &str, widget_override: WidgetOverride) -> Self {
InputMetadata {
persistent_metadata: InputPersistentMetadata::default().with_name(input_name).with_description(description).with_override(widget_override),
}
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum NodeTypePersistentMetadata {
Layer(LayerPersistentMetadata),
Node(NodePersistentMetadata),
}
impl Default for NodeTypePersistentMetadata {
fn default() -> Self {
NodeTypePersistentMetadata::node(IVec2::ZERO)
}
}
impl NodeTypePersistentMetadata {
pub fn node(position: IVec2) -> NodeTypePersistentMetadata {
NodeTypePersistentMetadata::Node(NodePersistentMetadata {
position: NodePosition::Absolute(position),
})
}
pub fn layer(position: IVec2) -> NodeTypePersistentMetadata {
NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Absolute(position),
})
}
}
/// All fields in LayerMetadata should automatically be updated by using the network interface API
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct LayerPersistentMetadata {
/// Stores the position of a layer node, which can either be Absolute or Stack
pub position: LayerPosition,
}
impl PartialEq for LayerPersistentMetadata {
fn eq(&self, other: &Self) -> bool {
self.position == other.position
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct NodePersistentMetadata {
/// Stores the position of a non layer node, which can either be Absolute or Chain
pub(crate) position: NodePosition,
}
impl NodePersistentMetadata {
pub fn new(position: NodePosition) -> Self {
Self { position }
}
pub fn position(&self) -> &NodePosition {
&self.position
}
}
/// A layer can either be position as Absolute or in a Stack
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum LayerPosition {
// Position of the node in grid spaces
Absolute(IVec2),
// A layer is in a Stack when it feeds into the bottom input of a layer. The Y position stores the vertical distance between the layer and its upstream sibling/parent.
Stack(u32),
}
/// A node can either be position as Absolute or in a Chain
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum NodePosition {
// Position of the node in grid spaces
Absolute(IVec2),
// In a chain the position is based on the number of nodes to the first layer node
Chain,
}
/// Cached metadata that should be calculated when creating a node, and should be recalculated when modifying a node property that affects one of the cached fields.
#[derive(Debug, Default, Clone)]
pub struct DocumentNodeTransientMetadata {
// The click targets are stored as a single struct since it is very rare for only one to be updated, and recomputing all click targets in one function is more efficient than storing them separately.
pub(crate) click_targets: TransientCache<DocumentNodeClickTargets>,
/// All nodes that should be moved when this layer is moved, kept here since only layers own nodes.
pub(crate) owned_nodes: TransientCache<HashSet<NodeId>>,
/// Width in grid units from the left edge of the layer's thumbnail to its left end, cached since text measurement is slow. Only loaded for layers.
pub(crate) layer_width: TransientCache<u32>,
}
#[derive(Debug, Clone)]
pub struct DocumentNodeClickTargets {
/// In order to keep the displayed position of the node in sync with the click target, the displayed position of a node is derived from the top left of the click target
/// Ensure node_click_target is kept in sync when modifying a node property that changes its size. Currently this is alias, inputs, is_layer, and metadata
pub node_click_target: ClickTarget,
/// Stores all port click targets in node graph space.
pub port_click_targets: Ports,
// Click targets that are specific to either nodes or layers, which are chosen states for displaying as a left-to-right node or bottom-to-top layer.
pub node_type_metadata: NodeTypeClickTargets,
}
#[derive(Debug, Clone)]
pub enum NodeTypeClickTargets {
Layer(Box<LayerClickTargets>),
Node, // No transient click targets are stored exclusively for nodes
}
/// All fields in TransientLayerMetadata should automatically be updated by using the network interface API
#[derive(Debug, Clone)]
pub struct LayerClickTargets {
/// Cache for all visibility buttons. Should be automatically updated when update_click_target is called
pub visibility_click_target: ClickTarget,
/// Cache for the lock icon button, only present when the layer is locked.
pub lock_click_target: Option<ClickTarget>,
/// Cache for the grip icon, which is next to the visibility button.
pub grip_click_target: ClickTarget,
/// Cache for the layer's display-name text bounds. Used to detect double-click rename and
/// to skip the drill-into-subgraph behavior when the click lands on the name itself.
/// `None` for layers whose display name is empty.
pub name_click_target: Option<ClickTarget>,
}
pub enum LayerClickTargetTypes {
Visibility,
Lock,
Grip,
Name,
// Preview,
}
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct NavigationMetadata {
/// The current pan, and zoom state of the viewport's view of the node graph.
/// Ensure `DocumentMessage::UpdateDocumentTransform` is called when the pan, zoom, or transform changes.
pub node_graph_ptz: PTZ,
// TODO: Eventually remove once te click targets are extracted from the native render
/// Transform from node graph space to viewport space.
pub node_graph_to_viewport: DAffine2,
// TODO: Eventually remove once the import/export positions are extracted from the native render
/// The width of the node graph in viewport space
#[serde(default)]
pub node_graph_width: f64,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum TransactionStatus {
Started,
Modified,
#[default]
Finished,
}
/// How [`NodeNetworkInterface::is_sole_dependent`] should treat a downstream connector it encounters.
#[derive(Clone, Copy, Debug)]
pub(crate) enum SoleDependentStep {
/// The downstream path ends here, inside the dependent set.
Terminate,
/// Keep walking downstream through this node.
Continue,
/// The path leaves the dependent set, so the candidate is not a sole dependent.
Escape,
}
pub(crate) fn collect_network_resources(network: &NodeNetwork, out: &mut HashSet<ResourceId>) {
for export in &network.exports {
collect_input_resource(export, out);
}
for node in network.nodes.values() {
collect_node_resources(node, out);
}
}
/// Collects resource IDs referenced by a node and its nested networks.
pub fn collect_node_resources(node: &DocumentNode, out: &mut HashSet<ResourceId>) {
for input in &node.inputs {
collect_input_resource(input, out);
}
if let DocumentNodeImplementation::Network(nested) = &node.implementation {
collect_network_resources(nested, out);
}
}
/// Records the resource ID held by a value input, covering node inputs and export slots alike.
pub(crate) fn collect_input_resource(input: &NodeInput, out: &mut HashSet<ResourceId>) {
if let NodeInput::Value { tagged_value, .. } = input
&& let TaggedValue::Resource(id) = &**tagged_value
{
out.insert(*id);
}
}
@@ -1,103 +0,0 @@
use super::{NodeNetworkInterface, NodeNetworkMetadata};
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
impl NodeNetworkInterface {
/// Checks the structural invariants between the document network and its parallel metadata tree at every nesting level.
/// Returns a description of each violation found, or an empty list if the interface is internally consistent.
/// Intended for tests and debugging; violations indicate a desync bug in the mutation methods, not a user error.
// O(nodes + wires) summed across all nesting levels, plus an acyclicity walk per network
pub fn validate_invariants(&self) -> Vec<String> {
let mut violations = Vec::new();
validate_network(self.document_network(), &self.network_metadata, &mut Vec::new(), 0, &mut violations);
violations
}
}
fn validate_network(network: &NodeNetwork, network_metadata: &NodeNetworkMetadata, path: &mut Vec<NodeId>, import_count: usize, violations: &mut Vec<String>) {
let node_metadata = &network_metadata.persistent_metadata.node_metadata;
// The network and its metadata tree must contain exactly the same set of nodes
for node_id in network.nodes.keys() {
if !node_metadata.contains_key(node_id) {
violations.push(format!("Node {node_id} in network {path:?} has no metadata entry"));
}
}
for node_id in node_metadata.keys() {
if !network.nodes.contains_key(node_id) {
violations.push(format!("Metadata entry {node_id} in network {path:?} has no corresponding node"));
}
}
// The pinned display order may only reference existing nodes
for node_id in &network_metadata.persistent_metadata.pinned_node_order {
if !network.nodes.contains_key(node_id) {
violations.push(format!("Pinned node order in network {path:?} references nonexistent node {node_id}"));
}
}
// Every wire must reference an existing endpoint within this network
let validate_input = |input: &NodeInput, location: &str, violations: &mut Vec<String>| match input {
NodeInput::Node { node_id, output_index, .. } => match network.nodes.get(node_id) {
None => violations.push(format!("{location} in network {path:?} references nonexistent node {node_id}")),
Some(target) if *output_index >= target.implementation.output_count() => {
violations.push(format!("{location} in network {path:?} references nonexistent output {output_index} of node {node_id}"));
}
_ => {}
},
NodeInput::Import { import_index, .. } if *import_index >= import_count => {
violations.push(format!("{location} in network {path:?} references nonexistent import {import_index} of {import_count}"));
}
_ => {}
};
for (node_id, node) in &network.nodes {
for input in &node.inputs {
validate_input(input, &format!("Input of node {node_id}"), violations);
}
}
for (export_index, export) in network.exports.iter().enumerate() {
validate_input(export, &format!("Export {export_index}"), violations);
}
if !network.is_acyclic() {
violations.push(format!("Network {path:?} contains a cycle"));
}
for (node_id, node) in &network.nodes {
let Some(metadata) = node_metadata.get(node_id) else { continue };
let persistent = &metadata.persistent_metadata;
// Input metadata is a parallel array to the node's inputs and the lengths must stay in sync
if persistent.input_metadata.len() != node.inputs.len() {
violations.push(format!(
"Node {node_id} in network {path:?} has {} inputs but {} input metadata entries",
node.inputs.len(),
persistent.input_metadata.len()
));
}
// Nested network metadata must exist exactly for nodes implemented as networks
match (&node.implementation, &persistent.network_metadata) {
(DocumentNodeImplementation::Network(nested_network), Some(nested_metadata)) => {
if persistent.output_names.len() != nested_network.exports.len() {
violations.push(format!(
"Node {node_id} in network {path:?} has {} exports but {} output names",
nested_network.exports.len(),
persistent.output_names.len()
));
}
path.push(*node_id);
validate_network(nested_network, nested_metadata, path, node.inputs.len(), violations);
path.pop();
}
(DocumentNodeImplementation::Network(_), None) => {
violations.push(format!("Network node {node_id} in network {path:?} is missing its nested network metadata"));
}
(_, Some(_)) => {
violations.push(format!("Non-network node {node_id} in network {path:?} has nested network metadata"));
}
(_, None) => {}
}
}
}
@@ -1,415 +0,0 @@
use super::*;
/// A failure to resolve part of the network or its metadata, returned by [`NetworkView`] accessors.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum NetworkError {
#[error("Network not found at path {path:?}")]
NetworkNotFound { path: Vec<NodeId> },
#[error("Node {node_id} not found")]
NodeNotFound { node_id: NodeId },
#[error("Node metadata for {node_id} not found")]
NodeMetadataNotFound { node_id: NodeId },
#[error("Nested network metadata for node {node_id} not found")]
NestedMetadataNotFound { node_id: NodeId },
#[error("Input {connector:?} not found")]
InputNotFound { connector: InputConnector },
#[error("The document network has no encapsulating node")]
NoEncapsulatingNode,
}
/// A read cursor over one network nesting level, resolving the network and its parallel metadata once instead of per query.
/// Obtained from [`NodeNetworkInterface::view`]; accessors return typed errors that callers at the message boundary may log.
#[derive(Clone, Copy)]
pub struct NetworkView<'a, 'p> {
pub(crate) interface: &'a NodeNetworkInterface,
pub(crate) path: &'p [NodeId],
pub(crate) network: &'a NodeNetwork,
pub(crate) metadata: &'a NodeNetworkMetadata,
}
impl NodeNetworkInterface {
/// Resolves a read cursor for the network at `network_path`, walking the nested network and metadata trees once.
pub fn view<'a, 'p>(&'a self, network_path: &'p [NodeId]) -> Result<NetworkView<'a, 'p>, NetworkError> {
let network = self
.document_network()
.nested_network(network_path)
.ok_or_else(|| NetworkError::NetworkNotFound { path: network_path.to_vec() })?;
let metadata = self
.document_network_metadata()
.nested_metadata(network_path)
.ok_or_else(|| NetworkError::NetworkNotFound { path: network_path.to_vec() })?;
Ok(NetworkView {
interface: self,
path: network_path,
network,
metadata,
})
}
}
impl<'a, 'p> NetworkView<'a, 'p> {
pub fn network_metadata(&self) -> &'a NodeNetworkMetadata {
self.metadata
}
pub fn node(&self, node_id: &NodeId) -> Result<&'a DocumentNode, NetworkError> {
self.network.nodes.get(node_id).ok_or(NetworkError::NodeNotFound { node_id: *node_id })
}
pub fn node_metadata(&self, node_id: &NodeId) -> Result<&'a DocumentNodeMetadata, NetworkError> {
self.metadata
.persistent_metadata
.node_metadata
.get(node_id)
.ok_or(NetworkError::NodeMetadataNotFound { node_id: *node_id })
}
pub fn input(&self, input_connector: &InputConnector) -> Result<&'a NodeInput, NetworkError> {
let input = match input_connector {
InputConnector::Node { node_id, input_index } => self.node(node_id)?.inputs.get(*input_index),
InputConnector::Export(export_index) => self.network.exports.get(*export_index),
};
input.ok_or(NetworkError::InputNotFound { connector: *input_connector })
}
/// The view over the network which contains this network's encapsulating node, or an error in the document network.
pub fn encapsulating(&self) -> Result<NetworkView<'a, 'p>, NetworkError> {
let (_, encapsulating_path) = self.path.split_last().ok_or(NetworkError::NoEncapsulatingNode)?;
self.interface.view(encapsulating_path)
}
/// The node which encapsulates this network, or an error in the document network.
pub fn encapsulating_node(&self) -> Result<&'a DocumentNode, NetworkError> {
let (node_id, _) = self.path.split_last().ok_or(NetworkError::NoEncapsulatingNode)?;
self.encapsulating()?.node(node_id)
}
/// The metadata of the node which encapsulates this network, or an error in the document network.
pub fn encapsulating_node_metadata(&self) -> Result<&'a DocumentNodeMetadata, NetworkError> {
let (node_id, _) = self.path.split_last().ok_or(NetworkError::NoEncapsulatingNode)?;
self.encapsulating()?.node_metadata(node_id)
}
pub fn implementation(&self, node_id: &NodeId) -> Result<&'a DocumentNodeImplementation, NetworkError> {
Ok(&self.node(node_id)?.implementation)
}
pub fn reference(&self, node_id: &NodeId) -> Result<Option<DefinitionIdentifier>, NetworkError> {
match self.implementation(node_id)? {
DocumentNodeImplementation::Network(_) => {
let node_metadata = self.node_metadata(node_id)?;
let network_metadata = node_metadata
.persistent_metadata
.network_metadata
.as_ref()
.ok_or(NetworkError::NestedMetadataNotFound { node_id: *node_id })?;
Ok(network_metadata.persistent_metadata.reference.clone().map(DefinitionIdentifier::Network))
}
DocumentNodeImplementation::ProtoNode(protonode_id) => Ok(Some(DefinitionIdentifier::ProtoNode(protonode_id.clone()))),
_ => Ok(None),
}
}
pub fn is_layer(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
Ok(self.node_metadata(node_id)?.persistent_metadata.is_layer())
}
/// Whether the node is an Artboard node by identity, regardless of whether it currently participates in the scene.
pub fn is_artboard(&self, node_id: &NodeId) -> bool {
self.reference(node_id)
.ok()
.flatten()
.is_some_and(|reference| reference == DefinitionIdentifier::Network("Artboard".into()))
}
/// Whether the node is a Merge node by identity, regardless of whether it currently participates in the scene.
pub fn is_merge(&self, node_id: &NodeId) -> bool {
self.reference(node_id)
.ok()
.flatten()
.is_some_and(|reference| reference == DefinitionIdentifier::Network("Merge".into()))
}
/// The uneditable name in the Properties panel which represents the function name of the node implementation.
pub fn implementation_name(&self, node_id: &NodeId) -> String {
self.reference(node_id)
.ok()
.flatten()
.map(|identifier| identifier.implementation_name_from_identifier())
.unwrap_or("Custom Node".to_string())
}
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
pub fn display_name(&self, node_id: &NodeId) -> String {
let display_name = self.node_metadata(node_id).map(|metadata| metadata.persistent_metadata.display_name.clone()).unwrap_or_default();
if display_name.is_empty() {
if self.is_layer(node_id).unwrap_or_default() {
"Untitled Layer".to_string()
} else {
// TODO: Have this displayed in italics in the UI
self.implementation_name(node_id)
}
} else {
display_name
}
}
/// The current selection of this network, filtered to nodes that still exist.
pub fn selected_nodes(&self) -> SelectedNodes {
self.metadata
.persistent_metadata
.selection_undo_history
.back()
.cloned()
.unwrap_or_default()
.filtered_selected_nodes(|node_id| self.metadata.persistent_metadata.node_metadata.contains_key(node_id))
}
pub fn primary_input_connected_to_layer(&self, node_id: &NodeId) -> bool {
self.input(&InputConnector::primary_input(*node_id))
.ok()
.and_then(|input| input.as_node())
.is_some_and(|upstream_id| self.is_layer(&upstream_id).unwrap_or_default())
}
/// Whether the node's signature fits the layer form: one output, at most two exposed leading inputs, and no exposed parameters.
pub fn is_eligible_to_be_layer(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
let node = self.node(node_id)?;
let input_count = node.inputs.iter().take(2).filter(|input| input.is_exposed()).count();
let parameters_hidden = node.inputs.iter().skip(2).all(|input| !input.is_exposed());
let output_count = self.number_of_outputs(node_id)?;
Ok(!self.hidden_primary_output(node_id)? && output_count == 1 && (input_count <= 2) && parameters_hidden)
}
pub fn is_locked(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
Ok(self.node_metadata(node_id)?.persistent_metadata.locked)
}
pub fn is_pinned(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
Ok(self.node_metadata(node_id)?.persistent_metadata.pinned)
}
pub fn is_visible(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
Ok(self.node(node_id)?.visible)
}
pub fn is_absolute(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
Ok(match &self.node_metadata(node_id)?.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer_metadata) => matches!(layer_metadata.position, LayerPosition::Absolute(_)),
NodeTypePersistentMetadata::Node(node_metadata) => matches!(node_metadata.position, NodePosition::Absolute(_)),
})
}
pub fn is_chain(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
Ok(match &self.node_metadata(node_id)?.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Node(node_metadata) => matches!(node_metadata.position, NodePosition::Chain),
_ => false,
})
}
pub fn is_stack(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
Ok(match &self.node_metadata(node_id)?.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer_metadata) => matches!(layer_metadata.position, LayerPosition::Stack(_)),
_ => false,
})
}
pub fn number_of_inputs(&self, node_id: &NodeId) -> Result<usize, NetworkError> {
Ok(self.node(node_id)?.inputs.len())
}
pub fn number_of_displayed_inputs(&self, node_id: &NodeId) -> Result<usize, NetworkError> {
Ok(self.node(node_id)?.inputs.iter().filter(|input| input.is_exposed()).count())
}
pub fn number_of_outputs(&self, node_id: &NodeId) -> Result<usize, NetworkError> {
Ok(match self.implementation(node_id)? {
DocumentNodeImplementation::Network(nested_network) => nested_network.exports.len(),
_ => 1,
})
}
/// The number of imports as defined by the encapsulating node's input count, or zero for the document network.
pub fn number_of_imports(&self) -> usize {
self.encapsulating_node().map_or(0, |node| node.inputs.len())
}
pub fn number_of_exports(&self) -> usize {
self.network.exports.len()
}
pub fn has_primary_input(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
Ok(self.input(&InputConnector::primary_input(*node_id)).is_ok_and(|input| input.is_exposed()))
}
pub fn hidden_primary_output(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
Ok(match self.implementation(node_id)? {
DocumentNodeImplementation::Network(network) => network.exports.first().is_none_or(|input| !input.is_exposed()),
_ => false,
})
}
pub fn hidden_primary_export(&self) -> bool {
let Some((node_id, _)) = self.path.split_last() else { return false };
self.encapsulating().and_then(|parent| parent.hidden_primary_output(node_id)).unwrap_or(false)
}
pub fn hidden_primary_import(&self) -> bool {
self.encapsulating_node().is_ok_and(|node| node.inputs.first().is_some_and(|input| !input.is_exposed()))
}
pub fn previewing(&self) -> Previewing {
self.metadata.persistent_metadata.previewing
}
/// The root node (the node that the solid line is connected to), or None if no nodes are connected to the output.
pub fn root_node(&self) -> Option<RootNode> {
match &self.metadata.persistent_metadata.previewing {
Previewing::Yes { root_node_to_restore } => *root_node_to_restore,
Previewing::No => self.network.exports.first().and_then(|export| {
if let NodeInput::Node { node_id, output_index, .. } = export {
Some(RootNode {
node_id: *node_id,
output_index: *output_index,
})
} else {
None
}
}),
}
}
pub fn input_data(&self, node_id: &NodeId, index: usize, key: &str) -> Result<Option<&'a Value>, NetworkError> {
Ok(self.persistent_input_metadata(node_id, index)?.input_data.get(key))
}
pub fn persistent_input_metadata(&self, node_id: &NodeId, index: usize) -> Result<&'a InputPersistentMetadata, NetworkError> {
let metadata = self.node_metadata(node_id)?;
let input_metadata = metadata.persistent_metadata.input_metadata.get(index).ok_or(NetworkError::InputNotFound {
connector: InputConnector::node_at_index(*node_id, index),
})?;
Ok(&input_metadata.persistent_metadata)
}
pub fn upstream_output_connector(&self, input_connector: &InputConnector) -> Result<Option<OutputConnector>, NetworkError> {
Ok(OutputConnector::from_input(self.input(input_connector)?))
}
/// Whether the node reaches the exports by following wires downstream.
// O(nodes + wires) reachability walk
pub fn connected_to_output(&self, target_node_id: &NodeId) -> bool {
if self
.network
.exports
.iter()
.any(|export| if let NodeInput::Node { node_id, .. } = export { node_id == target_node_id } else { false })
{
return true;
}
let mut stack = self
.network
.exports
.iter()
.filter_map(|output| if let NodeInput::Node { node_id, .. } = output { self.network.nodes.get(node_id) } else { None })
.collect::<Vec<_>>();
let mut already_visited = HashSet::new();
already_visited.extend(
self.network
.exports
.iter()
.filter_map(|output| if let NodeInput::Node { node_id, .. } = output { Some(node_id) } else { None }),
);
while let Some(node) = stack.pop() {
for input in &node.inputs {
if let &NodeInput::Node { node_id: upstream_id, .. } = input {
if already_visited.contains(&upstream_id) {
continue;
}
if upstream_id == *target_node_id {
return true;
}
let Some(upstream_node) = self.network.nodes.get(&upstream_id) else { continue };
already_visited.insert(upstream_id);
stack.push(upstream_node);
}
}
}
false
}
/// An iterator of all nodes connected to the given nodes by the flow type, traversing backwards upstream from the given nodes' inputs.
pub(crate) fn upstream_flow(&self, mut node_ids: Vec<NodeId>, mut flow_type: FlowType) -> FlowIter<'a> {
if matches!(flow_type, FlowType::LayerChildrenUpstreamFlow) {
node_ids = node_ids
.iter()
.filter_map(|node_id| {
if self.is_layer(node_id).unwrap_or_default() {
self.network.nodes.get(node_id).and_then(|node| node.inputs.get(1)).and_then(|input| input.as_node())
} else {
Some(*node_id)
}
})
.collect::<Vec<_>>();
flow_type = FlowType::UpstreamFlow;
};
FlowIter {
stack: node_ids,
network: self.network,
network_metadata: self.metadata,
flow_type,
}
}
/// The distance in grid cells from the layer to the end of its chain, or zero for a layer with no chain.
pub fn chain_width(&self, node_id: &NodeId) -> u32 {
if self.number_of_displayed_inputs(node_id).unwrap_or_default() > 1 {
let mut last_chain_node_distance = 0_u32;
for (index, node_id) in self.upstream_flow(vec![*node_id], FlowType::HorizontalPrimaryOutputFlow).skip(1).enumerate() {
if self.is_chain(&node_id).unwrap_or_default() {
last_chain_node_distance = (index as u32) + 1;
} else {
return last_chain_node_distance * NODE_CHAIN_WIDTH as u32 + 1;
}
}
last_chain_node_distance * NODE_CHAIN_WIDTH as u32 + 1
} else {
// A layer with no secondary input has no chain
0
}
}
/// The given network's pinned nodes in display order: pinning appends, dragging rearranges, and any not yet recorded go last.
pub fn ordered_pinned_nodes(&self) -> Vec<NodeId> {
let order = &self.metadata.persistent_metadata.pinned_node_order;
let is_pinned = |node_id: &NodeId| self.is_pinned(node_id).unwrap_or_default();
// Follow the saved order, keeping only nodes that still exist and are still pinned
let mut pinned_nodes = order
.iter()
.copied()
.filter(|node_id| self.network.nodes.contains_key(node_id) && is_pinned(node_id))
.collect::<Vec<_>>();
// Append any pinned nodes missing from the saved order at the end
let mut unordered = self.network.nodes.keys().copied().filter(|node_id| is_pinned(node_id) && !order.contains(node_id)).collect::<Vec<_>>();
unordered.sort();
pinned_nodes.extend(unordered);
pinned_nodes
}
/// Create a node template from an existing node.
pub fn create_node_template(&self, node_id: &NodeId) -> Result<NodeTemplate, NetworkError> {
let node = self.node(node_id)?;
let node_metadata = self.node_metadata(node_id)?;
Ok(NodeTemplate::from_parts(node.clone(), node_metadata.persistent_metadata.clone()))
}
}
@@ -1,16 +0,0 @@
use crate::messages::portfolio::fonts::FALLBACK_FONT_RESOURCE;
use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
pub fn text_width(text: &str, font_size: f64) -> f64 {
let typesetting = TypesettingConfig {
font_size,
line_height_ratio: 1.2,
letter_spacing: 0.,
letter_tilt: 0.,
max_width: None,
max_height: None,
align: TextAlign::AlignLeft,
};
TextContext::with_thread_local(|text_context| text_context.bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting, false).x)
}
@@ -12,12 +12,6 @@ pub struct WirePath {
pub data_type: FrontendGraphDataType,
pub thick: bool,
pub dashed: bool,
// A rank-1 `List<T>` wire renders as a doubled-up pair of parallel lines to distinguish it from a rank-0 `Item<T>` wire
#[serde(rename = "isList")]
pub is_list: bool,
// A thick wire's center line reaches past the wire into the cleaved connector slots, so it needs its own longer path; empty otherwise
#[serde(rename = "centerPathString")]
pub center_path_string: String,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -63,19 +57,6 @@ impl GraphWireStyle {
pub fn build_vector_wire(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool, graph_wire_style: GraphWireStyle) -> BezPath {
let grid_spacing = 24.;
// A thick layer-stack wire (vertical at both ends) is skipped across a single straight grid cell where its connectors
// already meet, and otherwise trimmed 3px inward at each end since it overshoots the connectors.
let (output_position, input_position) = if vertical_out && vertical_in {
if thick_wire_spans_single_cell(output_position, input_position) {
return BezPath::new();
}
let trim = 3. * (input_position.y - output_position.y).signum();
(output_position + DVec2::new(0., trim), input_position - DVec2::new(0., trim))
} else {
(output_position, input_position)
};
match graph_wire_style {
GraphWireStyle::Direct => {
let horizontal_gap = (output_position.x - input_position.x).abs();
@@ -120,31 +101,6 @@ pub fn build_vector_wire(output_position: DVec2, input_position: DVec2, vertical
}
}
fn thick_wire_spans_single_cell(output_position: DVec2, input_position: DVec2) -> bool {
let grid_spacing = 24.;
(output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= grid_spacing
}
/// The center line that cleaves a thick layer-stack wire. Its ends reach past the wire (1.5px toward the output
/// connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires.
pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> BezPath {
if !(vertical_out && vertical_in) || thick_wire_spans_single_cell(output_position, input_position) {
return BezPath::new();
}
// The 8px wire trims 3px at each end; the center line trims less so it reaches further into the cleaved slots
let sign = (input_position.y - output_position.y).signum();
let output_trim = 1.5;
let input_trim = 1.;
let start = output_position + DVec2::new(0., output_trim * sign);
let end = input_position - DVec2::new(0., input_trim * sign);
let mut center_line = BezPath::new();
center_line.move_to(dvec2_to_point(start));
center_line.line_to(dvec2_to_point(end));
center_line
}
fn straight_wire_path(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> Vec<IVec2> {
let grid_spacing = 24;
let line_width = 2;
File diff suppressed because it is too large. Load diff
@@ -912,7 +912,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
let Some((downstream_node, input_index)) = document
.network_interface
.outward_wires(&[])
.and_then(|outward_wires| outward_wires.get(&OutputConnector::primary_output(layer.to_node())))
.and_then(|outward_wires| outward_wires.get(&OutputConnector::node(layer.to_node(), 0)))
.and_then(|outward_wires| outward_wires.first())
.and_then(|input_connector| input_connector.node_id().map(|node_id| (node_id, input_connector.input_index())))
else {
@@ -6,8 +6,7 @@ use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::utility_types::DocumentToolData;
use graphene_std::Color;
use graphene_std::color::SRGBA8;
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::style::{FillChoice, FillChoiceUI, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
/// Color selector widgets seen in [`LayoutTarget::ToolOptions`] bar.
pub struct ToolColorOptions {
@@ -86,8 +85,8 @@ impl ToolColorOptions {
// In the mixed state (`fill_choice` is `None`) the dash overlay covers the swatch, so the underlying widget value just drives the picker's initial position.
// `FillChoice::None` gives it a neutral starting point.
let mixed_color = self.fill_choice.is_none();
// Convert the internal linear-light `FillChoice` to the JS-boundary `FillChoice<SRGBA8>` (with `SRGBA8` colors) for the widget value.
let widget_value = FillChoice::<SRGBA8>::from(self.fill_choice.as_ref().unwrap_or(&FillChoice::None));
// Convert the internal linear-light `FillChoice` to the JS-boundary `FillChoiceUI` (with `SRGBA8` colors) for the widget value.
let widget_value = FillChoiceUI::from(self.fill_choice.as_ref().unwrap_or(&FillChoice::None));
let mixed_enabled = self.enabled.is_none();
// In the mixed-enabled state the underlying `checked` value is hidden behind the indeterminate dash.
// The frontend's click handler sends `true` when the user resolves the mixed state by clicking.
@@ -125,9 +124,6 @@ pub struct DrawingToolState {
pub miter_limit: Option<f64>,
/// Paint order from the selection. `None` = mixed.
pub paint_order: Option<PaintOrder>,
/// Whether any selected layer has a lone adjacent Fill/Stroke pair for the paint order to swap.
/// Stays true with an empty selection, where the radio still sets the default for new shapes.
pub paint_order_applicable: bool,
/// Dash lengths from the selection. `None` = mixed.
pub dash_lengths: Option<Vec<f64>>,
/// Dash offset from the selection. `None` = mixed.
@@ -153,7 +149,6 @@ impl DrawingToolState {
stroke_join: Some(StrokeJoin::default()),
miter_limit: Some(4.),
paint_order: Some(PaintOrder::default()),
paint_order_applicable: true,
dash_lengths: Some(Vec::new()),
dash_offset: Some(0.),
last_synced_selection: Vec::new(),
@@ -187,21 +182,13 @@ impl DrawingToolState {
cap: self.stroke_cap.unwrap_or_default(),
join: self.stroke_join.unwrap_or_default(),
join_miter_limit: self.miter_limit.unwrap_or(4.),
paint_order: self.paint_order.unwrap_or_default(),
dash_lengths: self.effective_dash_lengths(),
dash_offset: self.dash_offset.unwrap_or(0.),
transform: glam::DAffine2::IDENTITY,
};
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
}
/// Queues the paint order rewrite for a freshly created `layer`. The order is the relative position of the
/// Stroke and Fill nodes in the chain, so this must run after both the stroke and fill have been applied.
pub fn apply_stroke_order_to_new_layer(&self, layer: LayerNodeIdentifier, responses: &mut VecDeque<Message>) {
let paint_order = self.paint_order.unwrap_or_default();
if paint_order != PaintOrder::default() {
responses.add(GraphOperationMessage::StrokeOrderSet { layer, paint_order });
}
}
}
/// Builds a `FillChoice::Solid` from a color.
@@ -316,23 +303,14 @@ pub fn sync_drawing_state(drawing: &mut DrawingToolState, natural_fill_enabled:
/// Reads the stroke proto-node inputs (align, cap, join, miter limit, paint order, dash lengths, dash offset) across the selection and updates
/// the matching fields on `drawing`. Each field becomes `None` (mixed) when selected strokes disagree. With no selection, fields are left as-is.
fn sync_stroke_options(drawing: &mut DrawingToolState, document: &DocumentMessageHandler) -> bool {
let layers = graph_modification_utils::paintable_selected_layers(document);
// The order radio only swaps a layer's lone adjacent Fill/Stroke pair, so it grays out when no selected
// layer has one; with nothing selected it still sets the default order for new shapes
let paint_order_applicable = layers.is_empty() || layers.iter().any(|&layer| graph_modification_utils::stroke_paint_order_applicable(layer, &document.network_interface));
let mut applicability_changed = false;
if drawing.paint_order_applicable != paint_order_applicable {
drawing.paint_order_applicable = paint_order_applicable;
applicability_changed = true;
}
let strokes: Vec<_> = layers
.into_iter()
let strokes: Vec<_> = document
.network_interface
.selected_nodes()
.selected_layers_except_artboards(&document.network_interface)
.filter_map(|layer| graph_modification_utils::get_stroke_options(layer, &document.network_interface))
.collect();
if strokes.is_empty() {
return applicability_changed;
return false;
}
fn unanimous<T: PartialEq + Clone>(values: impl IntoIterator<Item = T>) -> Option<T> {
@@ -349,7 +327,7 @@ fn sync_stroke_options(drawing: &mut DrawingToolState, document: &DocumentMessag
let new_dash_lengths = unanimous(strokes.iter().map(|s| &s.dash_lengths)).cloned();
let new_dash_offset = unanimous(strokes.iter().map(|s| s.dash_offset));
let mut changed = applicability_changed;
let mut changed = false;
if drawing.stroke_align != new_align {
drawing.stroke_align = new_align;
@@ -412,9 +390,14 @@ pub fn sync_fill_only(fill: &mut ToolColorOptions, natural_fill_enabled: bool, f
}
}
/// True if at least one selected layer can take paint, making the swatches edit the selection instead of the tool's own colors.
pub fn has_paintable_selection(document: &DocumentMessageHandler) -> bool {
!graph_modification_utils::paintable_selected_layers(document).is_empty()
/// True if at least one (non-artboard) layer is currently selected.
pub fn has_selection(document: &DocumentMessageHandler) -> bool {
document
.network_interface
.selected_nodes()
.selected_layers_except_artboards(&document.network_interface)
.next()
.is_some()
}
/// Applies a user-picked fill (gradient or solid). With a selection, writes to the layers; with none, pushes a solid to the swap-routed working color slot.
@@ -427,7 +410,7 @@ pub fn apply_fill_only_color_pick(fill: &mut ToolColorOptions, fill_choice: Fill
fill.fill_choice = Some(fill_choice.clone());
fill.enabled = Some(true);
fill.tracks_working_color = false;
if has_paintable_selection(document) {
if has_selection(document) {
if document.network_interface.transaction_status() == TransactionStatus::Finished {
responses.add(DocumentMessage::StartTransaction);
}
@@ -442,7 +425,7 @@ pub fn apply_stroke_color_pick(drawing: &mut DrawingToolState, color: Option<Col
drawing.stroke.fill_choice = Some(color.map_or(FillChoice::None, FillChoice::Solid));
drawing.stroke.enabled = Some(true);
drawing.stroke.tracks_working_color = false;
if has_paintable_selection(document) {
if has_selection(document) {
if document.network_interface.transaction_status() == TransactionStatus::Finished {
responses.add(DocumentMessage::StartTransaction);
}
@@ -463,7 +446,7 @@ pub fn apply_fill_enabled(drawing: &mut DrawingToolState, enabled: bool, global:
/// Single-slot variant of [`apply_fill_enabled`]. `working_color` is the fallback used when re-ticking or unticking from a mixed state.
pub fn apply_fill_only_enabled(fill: &mut ToolColorOptions, enabled: bool, working_color: Color, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
fill.enabled = Some(enabled);
if has_paintable_selection(document) {
if has_selection(document) {
responses.add(DocumentMessage::AddTransaction);
}
if enabled {
@@ -487,7 +470,7 @@ pub fn apply_fill_only_enabled(fill: &mut ToolColorOptions, enabled: bool, worki
/// Toggles the stroke checkbox: mirrors [`apply_fill_enabled`].
pub fn apply_stroke_enabled(drawing: &mut DrawingToolState, enabled: bool, global: &DocumentToolData, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
drawing.stroke.enabled = Some(enabled);
if has_paintable_selection(document) {
if has_selection(document) {
responses.add(DocumentMessage::AddTransaction);
}
if enabled {
@@ -509,7 +492,7 @@ pub fn apply_stroke_enabled(drawing: &mut DrawingToolState, enabled: bool, globa
/// Applies a user-edited stroke weight to the selection, also persisting it as the no-selection default.
pub fn apply_line_weight(drawing: &mut DrawingToolState, line_weight: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
drawing.line_weight = Some(line_weight);
if !has_paintable_selection(document) {
if !has_selection(document) {
drawing.default_line_weight = line_weight;
}
graph_modification_utils::set_stroke_weight_for_selected_layers(line_weight, document, responses);
@@ -523,7 +506,7 @@ pub fn apply_working_colors(drawing: &mut DrawingToolState, global: &DocumentToo
/// Refreshes a single swatch from the given working color, subject to the rules in [`apply_working_colors`].
pub fn refresh_slot_working_color(slot: &mut ToolColorOptions, working_color: Color, document: &DocumentMessageHandler) {
if slot.fill_choice.is_some() && (!has_paintable_selection(document) || slot.tracks_working_color) {
if slot.fill_choice.is_some() && (!has_selection(document) || slot.tracks_working_color) {
slot.fill_choice = Some(solid(working_color));
}
}
@@ -540,7 +523,7 @@ pub fn reset_colors_on_deactivation(drawing: &mut DrawingToolState, global: &Doc
pub fn swap_fill_and_stroke(drawing: &mut DrawingToolState, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
drawing.colors_swapped = !drawing.colors_swapped;
if has_paintable_selection(document) {
if has_selection(document) {
responses.add(DocumentMessage::AddTransaction);
}
@@ -555,7 +538,7 @@ pub fn swap_fill_and_stroke(drawing: &mut DrawingToolState, document: &DocumentM
drawing.fill.tracks_working_color = new_fill_tracks;
drawing.stroke.tracks_working_color = new_stroke_tracks;
if has_paintable_selection(document) {
if has_selection(document) {
// Apply to layers only when we have a concrete value (`None` means mixed, no single value to broadcast).
if drawing.fill.is_active()
&& let Some(choice) = new_fill
@@ -595,7 +578,7 @@ pub enum WeightSyncOutcome {
/// Inspects the selection and returns how the weight widget should update.
pub fn compute_weight_sync(document: &DocumentMessageHandler) -> WeightSyncOutcome {
let layers = graph_modification_utils::paintable_selected_layers(document);
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
if layers.is_empty() {
return WeightSyncOutcome::NoSelection;
@@ -11,7 +11,6 @@ use crate::messages::tool::common_functionality::shapes::shape_utility::{extract
use glam::{DAffine2, DVec2};
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::ParameterRef;
use std::collections::VecDeque;
use std::f64::consts::FRAC_PI_2;
@@ -148,13 +147,7 @@ impl RadiusHandle {
pub fn update_inner_radius(&mut self, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque<Message>, drag_start: DVec2) {
let Some(layer) = self.layer else { return };
// This gizmo serves both Circle and Arc layers, so resolve which node is present to know whose radius parameter to write
let (node_id, radius_parameter) = if let Some(node_id) = graph_modification_utils::get_circle_id(layer, &document.network_interface) {
(node_id, ParameterRef::from(graphene_std::vector::generator_nodes::circle::RadiusInput))
} else if let Some(node_id) = get_arc_id(layer, &document.network_interface) {
(node_id, ParameterRef::from(graphene_std::vector::generator_nodes::arc::RadiusInput))
} else {
let Some(node_id) = graph_modification_utils::get_circle_id(layer, &document.network_interface).or(get_arc_id(layer, &document.network_interface)) else {
return;
};
let Some(current_radius) = extract_circle_radius(layer, document).or(extract_arc_parameters(Some(layer), document).map(|(r, _, _, _)| r)) else {
@@ -172,7 +165,7 @@ impl RadiusHandle {
self.previous_mouse_position = input.mouse.position;
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, radius_parameter),
input_connector: InputConnector::node(node_id, 1),
input: NodeInput::value(TaggedValue::F64(current_radius + net_delta), false),
});
responses.add(NodeGraphMessage::RunDocumentGraph);
@@ -13,7 +13,7 @@ use crate::messages::tool::common_functionality::shapes::shape_utility::extract_
use glam::{DAffine2, DVec2};
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::ParameterRef;
use graphene_std::NodeInputDecleration;
use graphene_std::vector::misc::{GridType, dvec2_to_point, get_line_endpoints};
use kurbo::{Line, ParamCurveNearest, Rect};
use std::collections::VecDeque;
@@ -123,7 +123,7 @@ impl RowColumnGizmo {
let transform = self.transform_grid(dimensions_delta, self.spacing, grid_type, angles, viewport);
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, self.gizmo_type.parameter()),
input_connector: InputConnector::node(node_id, self.gizmo_type.index()),
input: NodeInput::value(TaggedValue::U32((self.initial_dimension() as i32 + dimensions_to_add).max(1) as u32), false),
});
@@ -411,13 +411,13 @@ impl RowColumnGizmoType {
}
}
fn parameter(&self) -> ParameterRef {
fn index(&self) -> usize {
use graphene_std::vector::generator_nodes::grid::*;
match self {
RowColumnGizmoType::Top | RowColumnGizmoType::Bottom => RowsInput.into(),
RowColumnGizmoType::Left | RowColumnGizmoType::Right => ColumnsInput.into(),
RowColumnGizmoType::None => panic!("RowColumnGizmoType::None does not reference a grid input"),
RowColumnGizmoType::Top | RowColumnGizmoType::Bottom => RowsInput::INDEX,
RowColumnGizmoType::Left | RowColumnGizmoType::Right => ColumnsInput::INDEX,
RowColumnGizmoType::None => panic!("RowColumnGizmoType::None does not have a mouse_icon"),
}
}
@@ -13,7 +13,6 @@ use crate::messages::tool::common_functionality::shapes::shape_utility::{extract
use glam::{DAffine2, DVec2};
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::ParameterRef;
use std::collections::VecDeque;
use std::f64::consts::TAU;
@@ -195,20 +194,14 @@ impl NumberOfPointsDial {
let net_delta = (delta.length() / 25.).round() * sign;
let Some(layer) = self.layer else { return };
// This dial serves both Star and Polygon layers, so resolve which node is present to know whose sides parameter to write
let (node_id, sides_parameter) = if let Some(node_id) = graph_modification_utils::get_star_id(layer, &document.network_interface) {
(node_id, ParameterRef::from(graphene_std::vector::generator_nodes::star::SidesInput))
} else if let Some(node_id) = graph_modification_utils::get_polygon_id(layer, &document.network_interface) {
(node_id, ParameterRef::from(graphene_std::vector::generator_nodes::regular_polygon::SidesInput))
} else {
let Some(node_id) = graph_modification_utils::get_star_id(layer, &document.network_interface).or(graph_modification_utils::get_polygon_id(layer, &document.network_interface)) else {
return;
};
let new_point_count = ((self.initial_points as i32) + (net_delta as i32)).max(3);
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, sides_parameter),
input_connector: InputConnector::node(node_id, 1),
input: NodeInput::value(TaggedValue::U32(new_point_count as u32), false),
});
responses.add(NodeGraphMessage::RunDocumentGraph);
@@ -8,14 +8,12 @@ use crate::messages::portfolio::document::{overlays::utility_types::OverlayConte
use crate::messages::prelude::FrontendMessage;
use crate::messages::prelude::Responses;
use crate::messages::prelude::{DocumentMessageHandler, InputPreprocessorMessageHandler, NodeGraphMessage};
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
use crate::messages::tool::common_functionality::graph_modification_utils::{self, NodeGraphLayer};
use crate::messages::tool::common_functionality::shapes::shape_utility::{draw_snapping_ticks, extract_polygon_parameters, polygon_outline, polygon_vertex_position, star_outline};
use crate::messages::tool::common_functionality::shapes::shape_utility::{extract_star_parameters, star_vertex_position};
use glam::DVec2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::ParameterRef;
use graphene_std::vector::generator_nodes::{regular_polygon, star};
use std::collections::VecDeque;
use std::f64::consts::{FRAC_1_SQRT_2, FRAC_PI_4, PI, SQRT_2};
@@ -32,8 +30,7 @@ pub enum PointRadiusHandleState {
pub struct PointRadiusHandle {
pub layer: Option<LayerNodeIdentifier>,
point: u32,
/// The radius parameter the hovered or dragged handle writes to: a star's first or second radius, or a polygon's radius.
radius_parameter: Option<ParameterRef>,
radius_index: usize,
snap_radii: Vec<f64>,
initial_radius: f64,
handle_state: PointRadiusHandleState,
@@ -66,11 +63,7 @@ impl PointRadiusHandle {
let viewport = document.metadata().transform_to_viewport(layer);
for i in 0..2 * sides {
let (radius, radius_parameter) = if i % 2 == 0 {
(radius1, ParameterRef::from(star::Radius1Input))
} else {
(radius2, ParameterRef::from(star::Radius2Input))
};
let (radius, radius_index) = if i % 2 == 0 { (radius1, 2) } else { (radius2, 3) };
let point = star_vertex_position(viewport, i as i32, sides, radius1, radius2);
let center = viewport.transform_point2(DVec2::ZERO);
@@ -80,10 +73,10 @@ impl PointRadiusHandle {
}
if point.distance(mouse_position) < 5. {
self.snap_radii = Self::calculate_snap_radii(document, layer, &radius_parameter);
self.radius_parameter = Some(radius_parameter);
self.radius_index = radius_index;
self.layer = Some(layer);
self.point = i;
self.snap_radii = Self::calculate_snap_radii(document, layer, radius_index);
self.initial_radius = radius;
responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Default });
self.update_state(PointRadiusHandleState::Hover);
@@ -107,7 +100,7 @@ impl PointRadiusHandle {
}
if point.distance(mouse_position) < 5. {
self.radius_parameter = Some(regular_polygon::RadiusInput.into());
self.radius_index = 2;
self.layer = Some(layer);
self.point = i;
self.snap_radii.clear();
@@ -336,20 +329,21 @@ impl PointRadiusHandle {
}
}
fn calculate_snap_radii(document: &DocumentMessageHandler, layer: LayerNodeIdentifier, radius_parameter: &ParameterRef) -> Vec<f64> {
fn calculate_snap_radii(document: &DocumentMessageHandler, layer: LayerNodeIdentifier, radius_index: usize) -> Vec<f64> {
let mut snap_radii = Vec::new();
let Some(parameters) = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(star::IDENTIFIER) else {
let Some(node_inputs) = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::star::IDENTIFIER))
else {
return snap_radii;
};
let (Some(&TaggedValue::F64(radius_1)), Some(&TaggedValue::F64(radius_2))) = (parameters.value(star::Radius1Input), parameters.value(star::Radius2Input)) else {
let (Some(&TaggedValue::F64(radius_1)), Some(&TaggedValue::F64(radius_2))) = (node_inputs[2].as_value(), node_inputs[3].as_value()) else {
return snap_radii;
};
let other_radius = if *radius_parameter == ParameterRef::from(star::Radius2Input) { radius_1 } else { radius_2 };
let other_radius = if radius_index == 3 { radius_1 } else { radius_2 };
let Some(&TaggedValue::U32(sides)) = parameters.value(star::SidesInput) else {
let Some(&TaggedValue::U32(sides)) = node_inputs[1].as_value() else {
return snap_radii;
};
@@ -421,15 +415,14 @@ impl PointRadiusHandle {
pub fn update_inner_radius(&mut self, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque<Message>, drag_start: DVec2) {
let Some(layer) = self.layer else { return };
let Some(radius_parameter) = self.radius_parameter.clone() else { return };
// The stored parameter names the node it belongs to (Star or Polygon), so locate that same node on the layer
let Some(node_id) = NodeGraphLayer::new(layer, &document.network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(radius_parameter.node_identifier.clone())) else {
let Some(node_id) = graph_modification_utils::get_star_id(layer, &document.network_interface).or(graph_modification_utils::get_polygon_id(layer, &document.network_interface)) else {
return;
};
let viewport_transform = document.network_interface.document_metadata().transform_to_viewport(layer);
let center = viewport_transform.transform_point2(DVec2::ZERO);
let radius_index = self.radius_index;
let original_radius = self.initial_radius;
@@ -443,7 +436,7 @@ impl PointRadiusHandle {
self.update_state(PointRadiusHandleState::Dragging);
self.check_if_radius_flipped(original_radius, new_radius, document, layer, &radius_parameter);
self.check_if_radius_flipped(original_radius, new_radius, document, layer, radius_index);
if let Some((index, snapped_delta)) = self.check_snapping(new_radius, original_radius) {
net_delta = snapped_delta;
@@ -451,28 +444,29 @@ impl PointRadiusHandle {
}
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, radius_parameter),
input_connector: InputConnector::node(node_id, radius_index),
input: NodeInput::value(TaggedValue::F64(original_radius + net_delta), false),
});
responses.add(NodeGraphMessage::RunDocumentGraph);
}
fn check_if_radius_flipped(&mut self, original_radius: f64, new_radius: f64, document: &DocumentMessageHandler, layer: LayerNodeIdentifier, radius_parameter: &ParameterRef) {
let Some(parameters) = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(star::IDENTIFIER) else {
fn check_if_radius_flipped(&mut self, original_radius: f64, new_radius: f64, document: &DocumentMessageHandler, layer: LayerNodeIdentifier, radius_index: usize) {
let Some(node_inputs) = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::star::IDENTIFIER))
else {
return;
};
let (Some(&TaggedValue::F64(radius_1)), Some(&TaggedValue::F64(radius_2))) = (parameters.value(star::Radius1Input), parameters.value(star::Radius2Input)) else {
let (Some(&TaggedValue::F64(radius_1)), Some(&TaggedValue::F64(radius_2))) = (node_inputs[2].as_value(), node_inputs[3].as_value()) else {
return;
};
let other_radius = if *radius_parameter == ParameterRef::from(star::Radius2Input) { radius_1 } else { radius_2 };
let other_radius = if radius_index == 3 { radius_1 } else { radius_2 };
let flipped = (other_radius.is_sign_positive() && original_radius.is_sign_negative() && new_radius.is_sign_positive())
|| (other_radius.is_sign_negative() && original_radius.is_sign_positive() && new_radius.is_sign_negative());
if flipped {
self.snap_radii = Self::calculate_snap_radii(document, layer, radius_parameter);
self.snap_radii = Self::calculate_snap_radii(document, layer, radius_index);
}
}
}
@@ -12,6 +12,7 @@ use crate::messages::tool::common_functionality::shapes::spiral_shape::calculate
use glam::DVec2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::NodeInputDecleration;
use graphene_std::subpath::{calculate_growth_factor, spiral_point};
use graphene_std::vector::misc::SpiralType;
use std::collections::VecDeque;
@@ -189,15 +190,15 @@ impl SpiralTurns {
let new_outer_radius = (self.initial_outer_radius + outer_radius_change * sign).max(0.1);
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, StartAngleInput),
input_connector: InputConnector::node(node_id, StartAngleInput::INDEX),
input: NodeInput::value(TaggedValue::F64(self.initial_start_angle + total_delta), false),
});
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, TurnsInput),
input_connector: InputConnector::node(node_id, TurnsInput::INDEX),
input: NodeInput::value(TaggedValue::F64(new_turns), false),
});
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, OuterRadiusInput),
input_connector: InputConnector::node(node_id, OuterRadiusInput::INDEX),
input: NodeInput::value(TaggedValue::F64(new_outer_radius), false),
});
}
@@ -206,11 +207,11 @@ impl SpiralTurns {
let new_outer_radius = (self.initial_outer_radius + outer_radius_change).max(0.1);
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, TurnsInput),
input_connector: InputConnector::node(node_id, TurnsInput::INDEX),
input: NodeInput::value(TaggedValue::F64(new_turns), false),
});
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, OuterRadiusInput),
input_connector: InputConnector::node(node_id, OuterRadiusInput::INDEX),
input: NodeInput::value(TaggedValue::F64(new_outer_radius), false),
});
}
@@ -332,11 +332,11 @@ impl SweepAngleGizmo {
self.snap_angles = Self::calculate_snap_angles();
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::arc::StartAngleInput),
input_connector: InputConnector::node(node_id, 2),
input: NodeInput::value(TaggedValue::F64(start_angle), false),
});
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::arc::SweepAngleInput),
input_connector: InputConnector::node(node_id, 3),
input: NodeInput::value(TaggedValue::F64(sweep_angle), false),
});
@@ -1,21 +1,21 @@
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{self, DefinitionIdentifier};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeNetworkInterface, NodeTemplate, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeNetworkInterface, NodeTemplate};
use crate::messages::prelude::*;
use glam::{DAffine2, DVec2};
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, NodeId, NodeInput};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_std::Color;
use graphene_std::NodeInputDecleration;
use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Image;
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
use graphene_std::subpath::Subpath;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::misc::ManipulatorPointId;
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
use graphene_std::vector::{Gradient, GradientForm, GradientRamp, GradientSettings, PointId, SegmentId, VectorModificationType};
use graphene_std::{NodeParameter, ParameterRef};
use graphene_std::vector::{GradientSpreadMethod, GradientStops, GradientType, PointId, SegmentId, VectorModificationType};
use std::collections::VecDeque;
/// Returns the ID of the first Spline node in the horizontal flow which is not followed by a `Path` node, or `None` if none exists.
@@ -92,29 +92,29 @@ pub fn merge_layers(document: &DocumentMessageHandler, first_layer: LayerNodeIde
parent: first_layer,
});
responses.add(NodeGraphMessage::ConnectUpstreamOutputToInput {
downstream_input: InputConnector::layer_secondary_input(second_layer.to_node()),
input_connector: InputConnector::layer_secondary_input(merge_node_id),
downstream_input: InputConnector::node(second_layer.to_node(), 1),
input_connector: InputConnector::node(merge_node_id, 1),
});
responses.add(NodeGraphMessage::DeleteNodes {
node_ids: vec![second_layer.to_node()],
delete_children: false,
});
// Add a Combine Paths node after the merge
let combine_paths_node_id = NodeId::new();
let combine_paths_node = document_node_definitions::resolve_proto_node_type(graphene_std::vector::combine_paths::IDENTIFIER)
.expect("Failed to create combine paths node")
// Add a Flatten Path node after the merge
let flatten_node_id = NodeId::new();
let flatten_node = document_node_definitions::resolve_proto_node_type(graphene_std::vector::flatten_path::IDENTIFIER)
.expect("Failed to create flatten node")
.default_node_template();
responses.add(NodeGraphMessage::InsertNode {
node_id: combine_paths_node_id,
node_template: Box::new(combine_paths_node),
node_id: flatten_node_id,
node_template: Box::new(flatten_node),
});
responses.add(NodeGraphMessage::MoveNodeToChainStart {
node_id: combine_paths_node_id,
node_id: flatten_node_id,
parent: first_layer,
});
// Add a path node after the combine paths node
// Add a path node after the flatten node
let path_node_id = NodeId::new();
let path_node = document_node_definitions::resolve_network_node_type("Path")
.expect("Failed to create path node")
@@ -250,7 +250,9 @@ pub fn new_custom(id: NodeId, nodes: Vec<(NodeId, NodeTemplate)>, parent: LayerN
pub fn get_origin(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<DVec2> {
use graphene_std::transform_nodes::transform::*;
if let TaggedValue::DVec2(origin) = NodeGraphLayer::new(layer, network_interface).parameter_value(TranslationInput)? {
if let TaggedValue::DVec2(origin) =
NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER), TranslationInput::INDEX)?
{
Some(*origin)
} else {
None
@@ -272,196 +274,64 @@ pub fn get_viewport_center(layer: LayerNodeIdentifier, network_interface: &NodeN
pub fn get_fill_node_id_with_direct_fill_input(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
let fill_node = network_interface.document_network().nodes.get(&fill_node_id)?;
matches!(fill_node.input(graphene_std::vector::fill::PaintInput)?, NodeInput::Value { .. }).then_some(fill_node_id)
matches!(fill_node.inputs.get(graphene_std::vector::fill::FillInput::INDEX)?, NodeInput::Value { .. }).then_some(fill_node_id)
}
/// Determine the input connector where the gradient chain enters the layer.
/// Returns Fill's fill input if the layer has a "Fill" node, otherwise returns the layer's content input.
pub fn gradient_chain_target_input(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> InputConnector {
if let Some(fill_node_id) = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER)) {
InputConnector::node(fill_node_id, graphene_std::vector::fill::PaintInput)
InputConnector::node(fill_node_id, graphene_std::vector::fill::FillInput::INDEX)
} else {
InputConnector::layer_secondary_input(layer.to_node())
InputConnector::node(layer.to_node(), 1)
}
}
/// Try to find the paint value node feeding a 'Fill' node, or a layer directly.
fn get_upstream_paint_value_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface, identifier: ProtoNodeIdentifier) -> Option<NodeId> {
/// Try to find a "Gradient Value" node that is connected to a "Fill" node, or to a layer directly.
pub fn get_upstream_gradient_value_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
let target_input = gradient_chain_target_input(layer, network_interface);
let walk_from = network_interface.upstream_output_connector(&target_input, &[])?.node_id()?;
let reference = DefinitionIdentifier::ProtoNode(identifier);
network_interface
.upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow)
.take_while(|node_id| !network_interface.is_layer(node_id, &[]))
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&reference))
}
/// Try to find a 'Gradient Value' node that is connected to a 'Fill' node, or to a layer directly.
pub fn get_upstream_gradient_value_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
get_upstream_paint_value_node_id(layer, network_interface, graphene_std::math_nodes::gradient_value::IDENTIFIER)
}
/// A whole-expanse paint to clear off a 'Merge' layer so a paint tool can start its own chain there.
pub struct ReplaceablePaintChain {
/// Where the fresh paint attaches, which is also the link severed to reach it.
pub attachment_input: InputConnector,
/// The paint's nodes, ordered downstream to upstream, empty when there is nothing to clear away.
pub nodes: Vec<NodeId>,
}
/// The whole-expanse paint on a 'Merge' layer that a paint tool may take over, or `None`
/// when the layer isn't one or its chain holds anything the tools didn't put there.
/// The walk stops at the first node the rest of the graph also draws from, since repainting through it would change
/// what those other consumers see, and it passes through 'Transform' nodes so a swap keeps the layer's placement.
pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<ReplaceablePaintChain> {
if !network_interface.is_merge(&layer.to_node(), &[]) {
return None;
}
// A generator discards its primary input, so the chain ends at whichever one is reached
let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
let setters = [
graphene_std::math_nodes::gradient_form::IDENTIFIER,
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
];
let mut nodes = Vec::new();
let mut input = InputConnector::layer_secondary_input(layer.to_node());
// Trails the walk over the 'Transform' nodes that survive, then holds still once the paint to clear away begins
let mut attachment_input = input;
while let Some(upstream) = network_interface.upstream_output_connector(&input, &[]) {
let node_id = upstream.node_id()?;
// Arriving here means this layer consumes the node, so a further consumer makes it shared
let shared = network_interface
.with_outward_wires(&[], |outward_wires| outward_wires.get(&OutputConnector::primary_output(node_id)).is_some_and(|inputs| inputs.len() > 1))
.unwrap_or(true);
if shared {
break;
}
let Some(DefinitionIdentifier::ProtoNode(identifier)) = network_interface.reference(&node_id, &[]) else {
return None;
};
if identifier == graphene_std::transform_nodes::transform::IDENTIFIER {
input = InputConnector::primary_input(node_id);
if nodes.is_empty() {
attachment_input = input;
}
continue;
}
let generator = generators.contains(&identifier);
if !generator && !setters.contains(&identifier) {
return None;
}
nodes.push(node_id);
if generator {
break;
}
input = InputConnector::primary_input(node_id);
}
Some(ReplaceablePaintChain { attachment_input, nodes })
}
/// Try to find a 'Color Value' node that is connected to a 'Fill' node, or to a layer directly.
pub fn get_upstream_color_value_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
get_upstream_paint_value_node_id(layer, network_interface, graphene_std::math_nodes::color_value::IDENTIFIER)
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_value::IDENTIFIER)))
}
/// Get the node connected to Fill's fill input, if any.
pub fn get_fill_input_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
let fill_node = network_interface.document_network().nodes.get(&fill_node_id)?;
let NodeInput::Node { node_id, .. } = fill_node.input(graphene_std::vector::fill::PaintInput)? else {
let NodeInput::Node { node_id, .. } = fill_node.inputs.get(graphene_std::vector::fill::FillInput::INDEX)? else {
return None;
};
Some(*node_id)
}
/// The ramp held by the 'Gradient Value' node feeding a layer's chain, which carries the whole-ramp settings.
fn get_chain_source_gradient_ramp(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<&GradientRamp> {
let gradient_value_node = network_interface.document_network().nodes.get(&get_upstream_gradient_value_node_id(layer, network_interface)?)?;
let TaggedValue::GradientRamp(ramp) = gradient_value_node.input(graphene_std::math_nodes::gradient_value::GradientInput)?.as_value()? else {
return None;
};
Some(ramp)
}
/// The whole-ramp settings baked into the 'Gradient Value' node feeding a layer's chain.
pub fn get_chain_source_gradient_settings(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<GradientSettings> {
Some(get_chain_source_gradient_ramp(layer, network_interface)?.into())
}
/// Get the gradient stops of a layer, if any.
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<GradientStops> {
// Try to find the gradient stops value that is created by a Fill node first
if let Some(fill_node_id) = get_fill_node_id_with_direct_fill_input(layer, network_interface) {
return network_interface
.document_network()
.nodes
.get(&fill_node_id)
.and_then(|node| node.input(graphene_std::vector::fill::PaintInput))
.and_then(|node| node.inputs.get(graphene_std::vector::fill::FillInput::INDEX))
.and_then(|input| input.as_value())
.and_then(|value| if let TaggedValue::GradientRamp(ramp) = value { Some(Gradient::from(ramp)) } else { None });
.and_then(|value| if let TaggedValue::Gradient(gradient) = value { Some(gradient.clone()) } else { None });
}
let gradient_value_node = network_interface.document_network().nodes.get(&get_upstream_gradient_value_node_id(layer, network_interface)?)?;
let TaggedValue::GradientRamp(ramp) = gradient_value_node.input(graphene_std::math_nodes::gradient_value::GradientInput)?.as_value()? else {
let TaggedValue::Gradient(stops) = gradient_value_node.inputs.get(graphene_std::math_nodes::gradient_value::GradientInput::INDEX)?.as_value()? else {
return None;
};
let mut stops = Gradient::from(ramp);
// The chain's stop placement comes from the closest-to-layer 'Gradient Positions'/'Gradient Midpoints' nodes,
// matching the runtime where each later node overwrites the whole attribute
let target_input = gradient_chain_target_input(layer, network_interface);
let walk_from = network_interface.upstream_output_connector(&target_input, &[])?.node_id()?;
let positions_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_positions::IDENTIFIER);
let midpoints_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_midpoints::IDENTIFIER);
let (mut positions_pending, mut midpoints_pending) = (true, true);
for node_id in network_interface
.upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow)
.take_while(|node_id| !network_interface.is_layer(node_id, &[]))
{
let Some(reference) = network_interface.reference(&node_id, &[]) else { continue };
let node = network_interface.document_network().nodes.get(&node_id);
if positions_pending && reference == positions_reference {
positions_pending = false;
if let Some(TaggedValue::F64Array(positions)) = node
.and_then(|node| node.input(graphene_std::math_nodes::gradient_positions::PositionsInput))
.and_then(|input| input.as_value())
{
stops.set_positions(positions);
}
} else if midpoints_pending && reference == midpoints_reference {
midpoints_pending = false;
if let Some(TaggedValue::F64Array(midpoints)) = node
.and_then(|node| node.input(graphene_std::math_nodes::gradient_midpoints::MidpointsInput))
.and_then(|input| input.as_value())
{
stops.set_midpoints(midpoints);
}
}
}
Some(stops)
Some(stops.clone())
}
/// Compute the transform from a gradient's local space to viewport space for the given layer. For a `List<Gradient>`
/// Compute the transform from a gradient's local space to viewport space for the given layer. For a `List<GradientStops>`
/// layer this is the layer's incoming footprint transform; for a Fill-owned gradient value it composes the layer's viewport
/// transform with the [0,1]² → bounding-box mapping.
pub fn gradient_to_viewport_transform(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> glam::DAffine2 {
pub fn gradient_space_transform(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> glam::DAffine2 {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
let metadata = network_interface.document_metadata();
@@ -477,14 +347,6 @@ pub fn gradient_to_viewport_transform(layer: LayerNodeIdentifier, network_interf
metadata.transform_to_viewport(layer)
}
/// Tooltip description for a "Reverse Direction" gradient button, phrased for the given Gradient Form.
pub fn reverse_direction_tooltip_description(gradient_form: GradientForm) -> &'static str {
match gradient_form {
GradientForm::Radial => "Reverse which end the gradient radiates from.",
GradientForm::Linear => "Swap the start and end points of the gradient line.",
}
}
/// True when start→end (mapped through `transform` into viewport space) points predominantly rightward. For purely
/// vertical lines we fall back to a stable tiebreaker on (x + y) so the choice doesn't flicker between equal alternatives.
pub fn gradient_orientation_rightward(transform: glam::DAffine2) -> bool {
@@ -499,10 +361,11 @@ pub fn gradient_orientation_rightward(transform: glam::DAffine2) -> bool {
/// Get the current fill of a layer from the closest "Fill" node.
pub fn get_fill_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Color> {
let TaggedValue::Color(color) = NodeGraphLayer::new(layer, network_interface).parameter_value(graphene_std::vector::fill::PaintInput)? else {
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
let &TaggedValue::Color(color) = inputs.get(graphene_std::vector::fill::FillInput::INDEX)?.as_value()? else {
return None;
};
Some(*color)
color
}
/// Get the current blend mode of a layer from the closest upstream "Blend Mode" node.
@@ -608,35 +471,42 @@ pub fn get_text<'a>(
fonts: &FontsMessageHandler,
resources: &ResourceMessageHandler,
) -> Option<(&'a String, Font, TypesettingConfig)> {
use graphene_std::text::text;
let parameters = NodeGraphLayer::new(layer, network_interface).find_node_parameters(text::IDENTIFIER)?;
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER))?;
let Some(TaggedValue::String(text)) = parameters.value(text::TextInput) else { return None };
let font = match parameters.value(text::FontInput) {
let Some(TaggedValue::String(text)) = inputs.get(graphene_std::text::text::TextInput::INDEX)?.as_value() else {
return None;
};
let font = match inputs.get(graphene_std::text::text::FontInput::INDEX)?.as_value() {
Some(TaggedValue::Resource(resource_id)) => fonts.id_font(resources, *resource_id).unwrap_or_default(),
_ => Font::default(),
};
let Some(&TaggedValue::F64(font_size)) = parameters.value(text::SizeInput) else { return None };
let Some(&TaggedValue::F64(line_height_ratio)) = parameters.value(text::LineHeightInput) else {
let Some(&TaggedValue::F64(font_size)) = inputs.get(graphene_std::text::text::SizeInput::INDEX)?.as_value() else {
return None;
};
let Some(&TaggedValue::F64(letter_spacing)) = parameters.value(text::LetterSpacingInput) else {
let Some(&TaggedValue::F64(line_height_ratio)) = inputs.get(graphene_std::text::text::LineHeightInput::INDEX)?.as_value() else {
return None;
};
let Some(&TaggedValue::Bool(has_max_width)) = parameters.value(text::HasMaxWidthInput) else {
let Some(&TaggedValue::F64(letter_spacing)) = inputs.get(graphene_std::text::text::LetterSpacingInput::INDEX)?.as_value() else {
return None;
};
let Some(&TaggedValue::F64(max_width)) = parameters.value(text::MaxWidthInput) else { return None };
let Some(&TaggedValue::Bool(has_max_height)) = parameters.value(text::HasMaxHeightInput) else {
let Some(&TaggedValue::Bool(has_max_width)) = inputs.get(graphene_std::text::text::HasMaxWidthInput::INDEX)?.as_value() else {
return None;
};
let Some(&TaggedValue::F64(max_height)) = parameters.value(text::MaxHeightInput) else {
let Some(&TaggedValue::F64(max_width)) = inputs.get(graphene_std::text::text::MaxWidthInput::INDEX)?.as_value() else {
return None;
};
let Some(&TaggedValue::F64(letter_tilt)) = parameters.value(text::LetterTiltInput) else {
let Some(&TaggedValue::Bool(has_max_height)) = inputs.get(graphene_std::text::text::HasMaxHeightInput::INDEX)?.as_value() else {
return None;
};
let Some(&TaggedValue::F64(max_height)) = inputs.get(graphene_std::text::text::MaxHeightInput::INDEX)?.as_value() else {
return None;
};
let Some(&TaggedValue::F64(letter_tilt)) = inputs.get(graphene_std::text::text::LetterTiltInput::INDEX)?.as_value() else {
return None;
};
let Some(&TaggedValue::TextAlign(align)) = inputs.get(graphene_std::text::text::AlignInput::INDEX)?.as_value() else {
return None;
};
let Some(&TaggedValue::TextAlign(align)) = parameters.value(text::AlignInput) else { return None };
let typesetting = TypesettingConfig {
font_size,
@@ -651,7 +521,8 @@ pub fn get_text<'a>(
}
pub fn get_stroke_width(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<f64> {
if let TaggedValue::F64(width) = NodeGraphLayer::new(layer, network_interface).parameter_value(graphene_std::vector::stroke::WeightInput)? {
let weight_node_input_index = graphene_std::vector::stroke::WeightInput::INDEX;
if let TaggedValue::F64(width) = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER), weight_node_input_index)? {
Some(*width)
} else {
None
@@ -673,31 +544,36 @@ pub struct StrokeOptionsState {
/// Reads the non-color stroke option inputs from a layer's Stroke proto node. Returns `None` when the layer has no Stroke node.
/// Inputs that aren't a static value (e.g. wired to another node) fall back to per-field defaults so the layer still participates in the sync.
pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<StrokeOptionsState> {
use graphene_std::vector::stroke;
let parameters = NodeGraphLayer::new(layer, network_interface).find_node_parameters(stroke::IDENTIFIER)?;
let stroke = &DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
let layer_view = NodeGraphLayer::new(layer, network_interface);
layer_view.upstream_node_id_from_name(stroke)?;
let read = |index: usize| layer_view.find_input(stroke, index);
let align = match parameters.value(stroke::AlignInput) {
let align = match read(graphene_std::vector::stroke::AlignInput::INDEX) {
Some(TaggedValue::StrokeAlign(value)) => *value,
_ => StrokeAlign::default(),
};
let cap = match parameters.value(stroke::CapInput) {
let cap = match read(graphene_std::vector::stroke::CapInput::INDEX) {
Some(TaggedValue::StrokeCap(value)) => *value,
_ => StrokeCap::default(),
};
let join = match parameters.value(stroke::JoinInput) {
let join = match read(graphene_std::vector::stroke::JoinInput::INDEX) {
Some(TaggedValue::StrokeJoin(value)) => *value,
_ => StrokeJoin::default(),
};
let miter_limit = match parameters.value(stroke::MiterLimitInput) {
let miter_limit = match read(graphene_std::vector::stroke::MiterLimitInput::INDEX) {
Some(TaggedValue::F64(value)) => *value,
_ => 4.,
};
let paint_order = get_stroke_paint_order(layer, network_interface);
let dash_lengths = match parameters.value(stroke::DashPatternInput) {
Some(TaggedValue::DashPattern(lengths)) => lengths.clone(),
let paint_order = match read(graphene_std::vector::stroke::PaintOrderInput::INDEX) {
Some(TaggedValue::PaintOrder(value)) => *value,
_ => PaintOrder::default(),
};
let dash_lengths = match read(graphene_std::vector::stroke::DashLengthsInput::INDEX) {
Some(TaggedValue::F64Array(value)) => value.clone(),
_ => Vec::new(),
};
let dash_offset = match parameters.value(stroke::DashOffsetInput) {
let dash_offset = match read(graphene_std::vector::stroke::DashOffsetInput::INDEX) {
Some(TaggedValue::F64(value)) => *value,
_ => 0.,
};
@@ -718,78 +594,27 @@ pub fn get_stroke_id(layer: LayerNodeIdentifier, network_interface: &NodeNetwork
NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER))
}
/// Whether the paint order swap can act on the layer: exactly one Fill and one Stroke node in its chain,
/// wired directly together. Extra paint nodes make the swap unreliable, since a cover replaced in place
/// keeps the slot in the paint order that its upstream sibling established.
pub fn stroke_paint_order_applicable(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> bool {
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
let fill_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER);
let mut strokes = Vec::new();
let mut fills = Vec::new();
let node_graph_layer = NodeGraphLayer::new(layer, network_interface);
for node_id in node_graph_layer
.horizontal_layer_flow()
.take_while(|&node_id| node_id == layer.to_node() || !network_interface.is_layer(&node_id, &[]))
{
let reference = network_interface.reference(&node_id, &[]);
if reference.as_ref() == Some(&stroke_reference) {
strokes.push(node_id);
} else if reference.as_ref() == Some(&fill_reference) {
fills.push(node_id);
}
}
let (&[stroke_node_id], &[fill_node_id]) = (strokes.as_slice(), fills.as_slice()) else {
return false;
};
let primary_source = |node_id: NodeId| match network_interface.input_from_connector(&InputConnector::node_at_index(node_id, 0), &[]) {
Some(NodeInput::Node { node_id, output_index: 0, .. }) => Some(*node_id),
_ => None,
};
primary_source(stroke_node_id) == Some(fill_node_id) || primary_source(fill_node_id) == Some(stroke_node_id)
}
/// The paint order of a layer's stroke, read from the chain topology: both the Fill and Stroke nodes append
/// their cover, so the more downstream of the two paints on top, following the painter's algorithm.
pub fn get_stroke_paint_order(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> PaintOrder {
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
let fill_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER);
// The flow iterates downstream to upstream, so the first of the pair encountered is the one painting on top
let mut stroke_position = None;
let mut fill_position = None;
let node_graph_layer = NodeGraphLayer::new(layer, network_interface);
for (position, node_id) in node_graph_layer
.horizontal_layer_flow()
.take_while(|&node_id| node_id == layer.to_node() || !network_interface.is_layer(&node_id, &[]))
.enumerate()
{
let reference = network_interface.reference(&node_id, &[]);
if reference.as_ref() == Some(&stroke_reference) {
stroke_position.get_or_insert(position);
} else if reference.as_ref() == Some(&fill_reference) {
fill_position.get_or_insert(position);
}
}
match stroke_position.zip(fill_position) {
Some((stroke_position, fill_position)) if fill_position < stroke_position => PaintOrder::StrokeBelow,
_ => PaintOrder::StrokeAbove,
}
/// Stroke weight of the first selected non-artboard layer, used by tool control bars to mirror the selection's weight.
/// Returns `Some(0.)` if the layer has no Stroke node so the widget reads "0 px", and `None` only when no layer is selected.
pub fn first_selected_stroke_weight(document: &DocumentMessageHandler) -> Option<f64> {
document
.network_interface
.selected_nodes()
.selected_layers_except_artboards(&document.network_interface)
.next()
.map(|layer| get_stroke_width(layer, &document.network_interface).unwrap_or(0.))
}
/// Writes the weight back to every selected non-artboard layer's stroke. Layers with an existing stroke just have their
/// `WeightInput` updated; layers without one get a fresh stroke node added (defaulting to a black stroke with the new
/// weight) only when the new weight is nonzero, so changing back to 0 doesn't keep adding empty strokes.
pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
for layer in paintable_selected_layers(document) {
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
for layer in layers {
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
responses.add(NodeGraphMessage::SetInputValue {
node_id,
input_index: graphene_std::vector::stroke::WeightInput::INDEX,
value: TaggedValue::F64(weight).into(),
});
let input_index = graphene_std::vector::stroke::WeightInput::INDEX;
let value = TaggedValue::F64(weight);
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
} else if weight > 0. {
let color = Some(Color::BLACK);
let stroke = graphene_std::vector::style::Stroke::default().with_weight(weight);
@@ -800,9 +625,9 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
/// A Fill node's decoded gradient inputs, with the transform kept in its raw form (not yet baked into `start`/`end`).
pub struct FillNodeGradient {
pub stops: Gradient,
pub gradient_form: GradientForm,
pub settings: GradientSettings,
pub stops: GradientStops,
pub gradient_type: GradientType,
pub spread_method: GradientSpreadMethod,
pub transform: DAffine2,
/// Whether the transform input holds a plain value (so it may be written to) rather than a wire.
pub transform_is_value: bool,
@@ -812,39 +637,36 @@ pub struct FillNodeGradient {
pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOnce() -> [DVec2; 2]) -> Option<FillNodeGradient> {
use graphene_std::vector::fill;
let TaggedValue::GradientRamp(ramp) = fill_node.input(fill::PaintInput)?.as_value()? else {
let TaggedValue::Gradient(stops) = fill_node.inputs.get(fill::FillInput::INDEX)?.as_value()? else {
return None;
};
let settings = GradientSettings::from(ramp);
let stops = Gradient::from(ramp);
let gradient_form = match fill_node.input(fill::GradientFormInput).and_then(|input| input.as_value()) {
Some(&TaggedValue::GradientForm(value)) => value,
_ => GradientForm::default(),
let gradient_type = match fill_node.inputs.get(fill::GradientTypeInput::INDEX).and_then(|input| input.as_value()) {
Some(&TaggedValue::GradientType(value)) => value,
_ => GradientType::default(),
};
let has_transform = matches!(fill_node.input(fill::HasTransformInput).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
let transform_input = fill_node.input(fill::TransformInput).and_then(|input| input.as_value());
let transform = match (has_transform, transform_input) {
(true, Some(&TaggedValue::DAffine2(value))) => value,
(false, _) => initial_gradient_transform_for_bounding_box(bounding_box()),
let spread_method = match fill_node.inputs.get(fill::SpreadMethodInput::INDEX).and_then(|input| input.as_value()) {
Some(&TaggedValue::GradientSpreadMethod(value)) => value,
_ => GradientSpreadMethod::default(),
};
let transform_input = fill_node.inputs.get(fill::TransformInput::INDEX).and_then(|input| input.as_value());
let transform = match transform_input {
Some(&TaggedValue::OptionalDAffine2(value)) => value.unwrap_or_else(|| initial_gradient_transform_for_bounding_box(bounding_box())),
_ => DAffine2::IDENTITY,
};
Some(FillNodeGradient {
stops,
gradient_form,
settings,
stops: stops.clone(),
gradient_type,
spread_method,
transform,
transform_is_value: transform_input.is_some(),
})
}
/// Returns the stroke color from a layer's upstream Stroke node.
pub fn get_stroke_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Option<Color>> {
let tagged = NodeGraphLayer::new(layer, network_interface).parameter_value(graphene_std::vector::stroke::PaintInput)?;
match tagged {
TaggedValue::Color(color) => Some(Some(*color)),
value if value.is_no_paint() => Some(None),
_ => None,
}
let color_index = graphene_std::vector::stroke::PaintInput::INDEX;
let tagged = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER), color_index)?;
if let TaggedValue::Color(color) = tagged { Some(*color) } else { None }
}
/// Aggregated fill state across all selected non-artboard layers.
@@ -863,21 +685,12 @@ pub struct SelectedStrokeState {
pub optional_color: Option<Option<Color>>,
}
/// The selected layers (artboards excluded) whose chains can host Fill and Stroke nodes.
/// The tool options bar's paint widgets treat these as the whole selection, so other layers act as if unselected.
pub fn paintable_selected_layers(document: &DocumentMessageHandler) -> Vec<LayerNodeIdentifier> {
let selected_nodes = document.network_interface.selected_nodes();
selected_nodes
.selected_layers_except_artboards(&document.network_interface)
.filter(|layer| document.network_interface.layer_hosts_paint_nodes(&layer.to_node(), &[]))
.collect()
}
/// Reads the fill state across all selected non-artboard layers, including whether their enabled states or colors differ.
/// "Enabled" tracks node attachment: a layer counts as enabled whenever a Fill node is attached, even when that fill's value is the no-paint choice.
/// Unticked means there is no Fill node. Returns `None` only when no paintable layer is selected.
/// "Enabled" tracks node attachment: a layer counts as enabled whenever a Fill node is attached, even when that fill's value is [`FillChoice::None`].
/// Unticked means there is no Fill node. Returns `None` only when no layer is selected.
pub fn selected_fill_state(document: &DocumentMessageHandler) -> Option<SelectedFillState> {
let mut per_layer = paintable_selected_layers(document).into_iter().map(|layer| {
let selected_nodes = document.network_interface.selected_nodes();
let mut per_layer = selected_nodes.selected_layers_except_artboards(&document.network_interface).map(|layer| {
let Some(fill_node_id) = get_fill_id(layer, &document.network_interface) else {
return (false, FillChoice::None);
};
@@ -885,10 +698,9 @@ pub fn selected_fill_state(document: &DocumentMessageHandler) -> Option<Selected
let fill_choice = (|| {
let fill_node = document.network_interface.document_network().nodes.get(&fill_node_id)?;
match fill_node.input(graphene_std::vector::fill::PaintInput)?.as_value()? {
TaggedValue::Color(color) => Some(FillChoice::Solid(*color)),
TaggedValue::GradientRamp(ramp) => Some(FillChoice::Gradient(ramp.clone())),
value if value.is_no_paint() => Some(FillChoice::None),
match fill_node.inputs.get(graphene_std::vector::fill::FillInput::INDEX)?.as_value()? {
&TaggedValue::Color(color) => Some(color.map_or(FillChoice::None, FillChoice::Solid)),
TaggedValue::Gradient(stops) => Some(FillChoice::Gradient(stops.clone())),
_ => None,
}
})()
@@ -928,7 +740,8 @@ pub fn selected_fill_state(document: &DocumentMessageHandler) -> Option<Selected
/// "Enabled" tracks node attachment: a layer counts as enabled whenever a Stroke node is attached, even when that stroke's color is `None`.
/// Unticked means there is no Stroke node. Returns `None` only when no layer is selected.
pub fn selected_stroke_state(document: &DocumentMessageHandler) -> Option<SelectedStrokeState> {
let mut per_layer = paintable_selected_layers(document).into_iter().map(|layer| {
let selected_nodes = document.network_interface.selected_nodes();
let mut per_layer = selected_nodes.selected_layers_except_artboards(&document.network_interface).map(|layer| {
if get_stroke_id(layer, &document.network_interface).is_none() {
return (false, None);
}
@@ -965,30 +778,38 @@ pub fn selected_stroke_state(document: &DocumentMessageHandler) -> Option<Select
/// Sets the fill on all selected non-artboard layers, preserving gradient transform data when the layer already has a gradient fill.
pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
for layer in paintable_selected_layers(document) {
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
for layer in layers {
match &fill_choice {
FillChoice::None => responses.add(GraphOperationMessage::FillColorSet { layer, color: None }),
FillChoice::Solid(color) => responses.add(GraphOperationMessage::FillColorSet { layer, color: Some(*color) }),
FillChoice::Gradient(ramp) => {
use graphene_std::vector::fill;
let fill_parameters = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(fill::IDENTIFIER);
FillChoice::Gradient(stops) => {
let fill_node = NodeGraphLayer::new(layer, &document.network_interface)
.upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))
.and_then(|id| document.network_interface.document_network().nodes.get(&id));
let gradient_form = match fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::GradientFormInput)) {
Some(TaggedValue::GradientForm(value)) => *value,
_ => GradientForm::default(),
let read = |index: usize| fill_node.and_then(|node| node.inputs.get(index)).and_then(|input| input.as_value());
let gradient_type = match read(graphene_std::vector::fill::GradientTypeInput::INDEX) {
Some(TaggedValue::GradientType(value)) => *value,
_ => GradientType::default(),
};
let has_transform = matches!(fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::HasTransformInput)), Some(TaggedValue::Bool(true)));
let transform = match (has_transform, fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::TransformInput))) {
(true, Some(TaggedValue::DAffine2(value))) => *value,
(false, _) => initial_gradient_transform_for_bounding_box(document.network_interface.document_metadata().nonzero_bounding_box(layer)),
let spread_method = match read(graphene_std::vector::fill::SpreadMethodInput::INDEX) {
Some(TaggedValue::GradientSpreadMethod(value)) => *value,
_ => GradientSpreadMethod::default(),
};
let transform = match read(graphene_std::vector::fill::TransformInput::INDEX) {
Some(TaggedValue::OptionalDAffine2(value)) => {
value.unwrap_or_else(|| initial_gradient_transform_for_bounding_box(document.network_interface.document_metadata().nonzero_bounding_box(layer)))
}
_ => DAffine2::IDENTITY,
};
responses.add(GraphOperationMessage::FillGradientSet {
layer,
gradient: Gradient::from(ramp),
gradient_form,
gradient_settings: ramp.into(),
gradient: stops.clone(),
gradient_type,
spread_method,
transform,
});
}
@@ -1000,13 +821,12 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
/// the provided `weight`, so picking any color (including `None`) from an unticked stroke control bar entry both attaches
/// the Stroke node and applies the chosen color.
pub fn set_stroke_color_for_selected_layers(color: Option<Color>, weight: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
for layer in paintable_selected_layers(document) {
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
for layer in layers {
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
responses.add(NodeGraphMessage::SetInputValue {
node_id,
input_index: graphene_std::vector::stroke::PaintInput::INDEX,
value: color.map_or_else(TaggedValue::no_paint, TaggedValue::Color).into(),
});
let input_index = graphene_std::vector::stroke::PaintInput::INDEX;
let value = TaggedValue::Color(color);
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
} else {
let stroke = graphene_std::vector::style::Stroke::new(weight);
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
@@ -1016,7 +836,8 @@ pub fn set_stroke_color_for_selected_layers(color: Option<Color>, weight: f64, d
/// Removes the Fill node from all selected non-artboard layers.
pub fn remove_fill_for_selected_layers(document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
for layer in paintable_selected_layers(document) {
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
for layer in layers {
if let Some(node_id) = get_fill_id(layer, &document.network_interface) {
responses.add(NodeGraphMessage::DeleteNodes {
node_ids: vec![node_id],
@@ -1030,7 +851,8 @@ pub fn remove_fill_for_selected_layers(document: &DocumentMessageHandler, respon
/// Removes the Stroke node from all selected non-artboard layers.
pub fn remove_stroke_for_selected_layers(document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
for layer in paintable_selected_layers(document) {
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
for layer in layers {
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
responses.add(NodeGraphMessage::DeleteNodes {
node_ids: vec![node_id],
@@ -1042,26 +864,28 @@ pub fn remove_stroke_for_selected_layers(document: &DocumentMessageHandler, resp
responses.add(NodeGraphMessage::SendGraph);
}
/// Reads the given parameter from its proto node on the first selected non-artboard layer that has one.
/// Reads a specific input from the matching proto node on the first selected non-artboard layer that has one.
/// Used by tool control bars to mirror per-shape parameters (sides, arc type, turns, etc.) from the selection
/// into the control bar's input widget state without each call site re-implementing the layer iteration.
pub fn first_selected_parameter(document: &DocumentMessageHandler, parameter: impl Into<ParameterRef>) -> Option<&TaggedValue> {
let parameter = parameter.into();
let identifier = DefinitionIdentifier::ProtoNode(parameter.node_identifier);
pub fn first_selected_proto_node_input(document: &DocumentMessageHandler, identifier: graph_craft::ProtoNodeIdentifier, input_index: usize) -> Option<&TaggedValue> {
let identifier = DefinitionIdentifier::ProtoNode(identifier);
document
.network_interface
.selected_nodes()
.selected_layers_except_artboards(&document.network_interface)
.find_map(|layer| NodeGraphLayer::new(layer, &document.network_interface).find_input(&identifier, parameter.input_index))
.find_map(|layer| NodeGraphLayer::new(layer, &document.network_interface).find_input(&identifier, input_index))
}
/// Writes a value to the given parameter on its proto node for every selected non-artboard layer that has one.
/// Writes a value to a specific input on the matching proto node of every selected non-artboard layer that has one.
/// Used by tool control bars to push per-shape parameter changes back onto all selected layers of that shape.
/// The parameter symbol locates the node, so the value can never land on the right index of the wrong node.
pub fn set_parameter_for_selected_layers(document: &DocumentMessageHandler, parameter: impl Into<ParameterRef>, value: TaggedValue, responses: &mut VecDeque<Message>) {
let parameter = parameter.into();
let identifier = DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone());
pub fn set_proto_node_input_for_selected_layers(
document: &DocumentMessageHandler,
identifier: graph_craft::ProtoNodeIdentifier,
input_index: usize,
value: TaggedValue,
responses: &mut VecDeque<Message>,
) {
let identifier = DefinitionIdentifier::ProtoNode(identifier);
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
@@ -1071,8 +895,8 @@ pub fn set_parameter_for_selected_layers(document: &DocumentMessageHandler, para
};
responses.add(NodeGraphMessage::SetInputValue {
node_id,
input_index: parameter.input_index,
value: value.clone().into(),
input_index,
value: value.clone(),
});
}
}
@@ -1142,60 +966,18 @@ impl<'a> NodeGraphLayer<'a> {
.and_then(|node_id| self.network_interface.document_network().nodes.get(&node_id).map(|node| &node.inputs))
}
/// Find a specific input of a node within the layer's primary flow.
/// Prefer [`Self::parameter_value`] where the input is statically known; this remains for network nodes and runtime-chosen indices.
/// Find a specific input of a node within the layer's primary flow
pub fn find_input(&self, identifier: &DefinitionIdentifier, index: usize) -> Option<&'a TaggedValue> {
// TODO: Find a better way to accept a node input rather than using its index (which is quite unclear and fragile)
self.find_node_inputs(identifier)?.get(index)?.as_value()
}
/// The stored value of the given parameter on the matching proto node in the layer's primary flow, if that node exists and the input holds a value.
/// The parameter symbol names both the node and the input, so the two can never disagree.
/// For reading several parameters of the same node, prefer [`Self::find_node_parameters`] so the upstream flow is walked only once.
pub fn parameter_value(&self, parameter: impl Into<ParameterRef>) -> Option<&'a TaggedValue> {
let parameter = parameter.into();
self.find_input(&DefinitionIdentifier::ProtoNode(parameter.node_identifier), parameter.input_index)
}
/// Find a proto node in the layer's primary flow and return its inputs for reading by parameter symbol, walking upstream only once.
pub fn find_node_parameters(&self, identifier: ProtoNodeIdentifier) -> Option<ProtoNodeParameters<'a>> {
let inputs = self.find_node_inputs(&DefinitionIdentifier::ProtoNode(identifier.clone()))?;
Some(ProtoNodeParameters { identifier, inputs })
}
/// Check if a layer is a raster layer
pub fn is_raster_layer(layer: LayerNodeIdentifier, network_interface: &mut NodeNetworkInterface) -> bool {
let layer_input_type = network_interface.input_type(&InputConnector::layer_secondary_input(layer.to_node()), &[]);
let layer_input_type = network_interface.input_type(&InputConnector::node(layer.to_node(), 1), &[]);
matches!(layer_input_type.compiled_element_name().as_deref(), Some("Raster<CPU>" | "Raster<GPU>"))
}
}
/// The inputs of a proto node located by [`NodeGraphLayer::find_node_parameters`], read by parameter symbol without re-walking the layer's upstream flow per read.
pub struct ProtoNodeParameters<'a> {
identifier: ProtoNodeIdentifier,
inputs: &'a [NodeInput],
}
impl<'a> ProtoNodeParameters<'a> {
/// The input slot of the given parameter, or `None` if the parameter belongs to a different node than this view was built from.
pub fn input(&self, parameter: impl Into<ParameterRef>) -> Option<&'a NodeInput> {
let parameter = parameter.into();
// A mismatched symbol would otherwise read whatever sits at that index on the wrong node, so crash under tests but only log and read nothing in the running app
if parameter.node_identifier != self.identifier {
let message = format!("A parameter of {} was read from the inputs of {}", parameter.node_identifier, self.identifier);
if cfg!(test) {
panic!("{message}")
}
log::error!("{message}");
return None;
}
self.inputs.get(parameter.input_index)
}
/// The stored value of the given parameter, if that input currently holds a value rather than a wire.
pub fn value(&self, parameter: impl Into<ParameterRef>) -> Option<&'a TaggedValue> {
self.input(parameter)?.as_value()
// A leveled wire is typed by its element; depth rides the layout.
let compiled = layer_input_type.compiled_nested_type();
compiled == Some(&concrete!(Raster<CPU>)) || compiled == Some(&concrete!(Raster<GPU>))
}
}
@@ -421,7 +421,7 @@ impl ShapeState {
(point.as_handle().is_some() && self.ignore_handles) || (point.as_anchor().is_some() && self.ignore_anchors)
}
/// Applies a dummy vector modification to the layer. In the case where a group containing some vector data is selected, this triggers the creation of a Combine Paths node.
/// Applies a dummy vector modification to the layer. In the case where a group containing some vector data is selected, this triggers the creation of a «Flatten Path» node.
fn add_dummy_modification_to_trigger_graph_reorganization(layer: LayerNodeIdentifier, start_point: PointId, _end_point: PointId, responses: &mut VecDeque<Message>) {
// Apply a zero-delta to one of the points to trigger reorganization
let dummy_modification = VectorModificationType::ApplyPointDelta {
@@ -172,7 +172,7 @@ impl Arc {
let radius = radius / viewport_zoom(document);
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::arc::RadiusInput),
input_connector: InputConnector::node(node_id, 1),
input: NodeInput::value(TaggedValue::F64(radius), false),
});
@@ -67,7 +67,7 @@ impl Arrow {
let document_to_viewport = document.metadata().document_to_viewport;
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::arrow::ArrowToInput),
input_connector: InputConnector::node(node_id, 1),
input: NodeInput::value(TaggedValue::DVec2(arrow_to), false),
});
let downstream = document.metadata().downstream_transform_to_viewport(layer);
@@ -106,7 +106,7 @@ impl Circle {
let radius: f64 = if dimensions.x > dimensions.y { dimensions.y / 2. } else { dimensions.x / 2. };
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::circle::RadiusInput),
input_connector: InputConnector::node(node_id, 1),
input: NodeInput::value(TaggedValue::F64(radius), false),
});
@@ -37,11 +37,11 @@ impl Ellipse {
let radius = ((start - end) / 2. / viewport_zoom(document)).abs();
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::ellipse::RadiusXInput),
input_connector: InputConnector::node(node_id, 1),
input: NodeInput::value(TaggedValue::F64(radius.x), false),
});
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::ellipse::RadiusYInput),
input_connector: InputConnector::node(node_id, 2),
input: NodeInput::value(TaggedValue::F64(radius.y), false),
});
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), DVec2::ONE));
@@ -75,8 +75,8 @@ mod test_ellipse {
let node_graph_layer = NodeGraphLayer::new(layer, &document.network_interface);
let ellipse_node = node_graph_layer.upstream_node_id_from_protonode(ellipse::IDENTIFIER)?;
Some(ResolvedEllipse {
radius_x: instrumented.grab_ranked_input::<ellipse::RadiusXInput, f64>(&vec![ellipse_node], &editor.runtime).unwrap(),
radius_y: instrumented.grab_ranked_input::<ellipse::RadiusYInput, f64>(&vec![ellipse_node], &editor.runtime).unwrap(),
radius_x: instrumented.grab_protonode_input::<ellipse::RadiusXInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
radius_y: instrumented.grab_protonode_input::<ellipse::RadiusYInput>(&vec![ellipse_node], &editor.runtime).unwrap(),
transform: document.metadata().transform_to_document(layer),
})
})
@@ -11,6 +11,7 @@ use crate::messages::tool::common_functionality::shapes::shape_utility::ShapeGiz
use crate::messages::tool::tool_messages::tool_prelude::*;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::NodeInputDecleration;
use graphene_std::vector::misc::GridType;
use std::collections::VecDeque;
@@ -118,14 +119,14 @@ impl Grid {
// Set dimensions/spacing
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, SpacingInput),
input_connector: InputConnector::node(node_id, SpacingInput::<f64>::INDEX),
input: NodeInput::value(TaggedValue::DVec2(dimensions), false),
});
// Set angle for isometric grids
if let Some(angle_deg) = angle {
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, AnglesInput),
input_connector: InputConnector::node(node_id, AnglesInput::INDEX),
input: NodeInput::value(TaggedValue::DVec2(DVec2::splat(angle_deg)), false),
});
}
@@ -73,7 +73,7 @@ impl Line {
let line_to = document_points[1] - document_points[0];
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::line::LineToInput),
input_connector: InputConnector::node(node_id, 1),
input: NodeInput::value(TaggedValue::DVec2(line_to), false),
});
let document_to_viewport = document.metadata().document_to_viewport;
@@ -147,7 +147,7 @@ impl Polygon {
};
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::regular_polygon::RadiusInput),
input_connector: InputConnector::node(node_id, 2),
input: NodeInput::value(TaggedValue::F64(radius), false),
});
@@ -180,7 +180,7 @@ impl Polygon {
});
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::regular_polygon::SidesInput),
input_connector: InputConnector::node(node_id, 1),
input: NodeInput::value(TaggedValue::U32(new_dimension), false),
});
responses.add(NodeGraphMessage::RunDocumentGraph);
@@ -37,11 +37,11 @@ impl Rectangle {
let size = ((start - end) / viewport_zoom(document)).abs();
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::rectangle::WidthInput),
input_connector: InputConnector::node(node_id, 1),
input: NodeInput::value(TaggedValue::F64(size.x), false),
});
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::rectangle::HeightInput),
input_connector: InputConnector::node(node_id, 2),
input: NodeInput::value(TaggedValue::F64(size.y), false),
});
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), DVec2::ONE));
@@ -16,6 +16,7 @@ use crate::messages::tool::utility_types::*;
use glam::{DAffine2, DMat2, DVec2};
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::NodeInputDecleration;
use graphene_std::subpath::{self, Subpath};
use graphene_std::vector::click_target::ClickTargetType;
use graphene_std::vector::misc::{ArcType, GridType, SpiralType, dvec2_to_point};
@@ -213,7 +214,7 @@ pub fn update_radius_sign(end: DVec2, start: DVec2, layer: LayerNodeIdentifier,
let new_layer = NodeGraphLayer::new(layer, &document.network_interface);
if new_layer
.parameter_value(graphene_std::vector::generator_nodes::regular_polygon::SidesInput)
.find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::regular_polygon::IDENTIFIER), 1)
.unwrap_or(&TaggedValue::U32(0))
.to_u32()
% 2 == 1
@@ -223,14 +224,14 @@ pub fn update_radius_sign(end: DVec2, start: DVec2, layer: LayerNodeIdentifier,
};
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(polygon_node_id, graphene_std::vector::generator_nodes::regular_polygon::RadiusInput),
input_connector: InputConnector::node(polygon_node_id, 2),
input: NodeInput::value(TaggedValue::F64(sign_num * 0.5), false),
});
return;
}
if new_layer
.parameter_value(graphene_std::vector::generator_nodes::star::SidesInput)
.find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::star::IDENTIFIER), 1)
.unwrap_or(&TaggedValue::U32(0))
.to_u32()
% 2 == 1
@@ -240,11 +241,11 @@ pub fn update_radius_sign(end: DVec2, start: DVec2, layer: LayerNodeIdentifier,
};
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(star_node_id, graphene_std::vector::generator_nodes::star::Radius1Input),
input_connector: InputConnector::node(star_node_id, 2),
input: NodeInput::value(TaggedValue::F64(sign_num * 0.5), false),
});
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(star_node_id, graphene_std::vector::generator_nodes::star::Radius2Input),
input_connector: InputConnector::node(star_node_id, 3),
input: NodeInput::value(TaggedValue::F64(sign_num * 0.25), false),
});
}
@@ -352,7 +353,7 @@ pub fn extract_arc_parameters(layer: Option<LayerNodeIdentifier>, document: &Doc
pub fn extract_spiral_parameters(layer: LayerNodeIdentifier, document: &DocumentMessageHandler) -> Option<(SpiralType, f64, f64, f64, f64, f64)> {
use graphene_std::vector::generator_nodes::spiral::*;
let parameters = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(IDENTIFIER)?;
let node_inputs = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::spiral::IDENTIFIER))?;
let (
Some(&TaggedValue::SpiralType(spiral_type)),
@@ -362,12 +363,12 @@ pub fn extract_spiral_parameters(layer: LayerNodeIdentifier, document: &Document
Some(&TaggedValue::F64(turns)),
Some(&TaggedValue::F64(angle_resolution)),
) = (
parameters.value(SpiralTypeInput),
parameters.value(StartAngleInput),
parameters.value(InnerRadiusInput),
parameters.value(OuterRadiusInput),
parameters.value(TurnsInput),
parameters.value(AngularResolutionInput),
node_inputs.get(SpiralTypeInput::INDEX)?.as_value(),
node_inputs.get(StartAngleInput::INDEX)?.as_value(),
node_inputs.get(InnerRadiusInput::INDEX)?.as_value(),
node_inputs.get(OuterRadiusInput::INDEX)?.as_value(),
node_inputs.get(TurnsInput::INDEX)?.as_value(),
node_inputs.get(AngularResolutionInput::INDEX)?.as_value(),
)
else {
return None;
@@ -570,37 +571,7 @@ pub fn wrap_to_tau(angle: f64) -> f64 {
}
pub fn format_rounded(value: f64, precision: usize) -> String {
// Denoised values within floating point noise of zero (including -0) display as unsigned zero, unless the precision is fine enough to display them
let value = round_away_float_noise(value);
let value = if value.abs() < f64::min(1e-12, 0.5 * 10_f64.powi(-(precision as i32))) { 0. } else { value };
let formatted = format!("{value:.precision$}");
// Trailing zeros are trimmed only when the display is exact, so a truncated value keeps its decimal places (like "0.00" or "3.10") to indicate the truncation
if formatted.parse::<f64>() == Ok(value) {
formatted.trim_end_matches('0').trim_end_matches('.').to_string()
} else {
formatted
}
}
/// Recovers the intended number from floating point imprecision noise when that can be done reliably, e.g. 0.30000000000000004 -> 0.3.
/// Rounding to each significant digit count from 1 to 12, the first candidate within a relative 1e-13 of the original is accepted.
/// Actual high-precision values (like 0.3333333333333333) never pass the tolerance and are returned unchanged.
pub fn round_away_float_noise(value: f64) -> f64 {
if value == 0. || !value.is_finite() {
return if value == 0. { 0. } else { value };
}
let exponent = value.abs().log10().floor() as i32;
for significant_digits in 1..=12 {
let scale = 10_f64.powi(significant_digits - 1 - exponent);
let rounded = (value * scale).round() / scale;
if ((rounded - value) / value).abs() < 1e-13 {
return rounded;
}
}
value
format!("{value:.precision$}").trim_end_matches('0').trim_end_matches('.').to_string()
}
/// Gives the approximated angle to display in degrees, given an angle in degrees.
@@ -628,92 +599,17 @@ pub fn calculate_arc_text_transform(angle: f64, offset_angle: f64, center: DVec2
pub fn extract_grid_parameters(layer: LayerNodeIdentifier, document: &DocumentMessageHandler) -> Option<(GridType, DVec2, u32, u32, DVec2)> {
use graphene_std::vector::generator_nodes::grid::*;
let parameters = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(IDENTIFIER)?;
let node_inputs = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::grid::IDENTIFIER))?;
let (Some(&TaggedValue::GridType(grid_type)), Some(&TaggedValue::DVec2(spacing)), Some(&TaggedValue::U32(columns)), Some(&TaggedValue::U32(rows)), Some(&TaggedValue::DVec2(angles))) = (
parameters.value(GridTypeInput),
parameters.value(SpacingInput),
parameters.value(ColumnsInput),
parameters.value(RowsInput),
parameters.value(AnglesInput),
node_inputs.get(GridTypeInput::INDEX)?.as_value(),
node_inputs.get(SpacingInput::<f64>::INDEX)?.as_value(),
node_inputs.get(ColumnsInput::INDEX)?.as_value(),
node_inputs.get(RowsInput::INDEX)?.as_value(),
node_inputs.get(AnglesInput::INDEX)?.as_value(),
) else {
return None;
};
Some((grid_type, spacing, columns, rows, angles))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_away_float_noise_snaps_noisy_values() {
assert_eq!(round_away_float_noise(0.1 + 0.2), 0.3);
assert_eq!(round_away_float_noise(0.3000000000000012), 0.3);
assert_eq!(round_away_float_noise(2.99999999999993), 3.);
assert_eq!(round_away_float_noise(45.00000000000001), 45.);
}
#[test]
fn round_away_float_noise_keeps_honest_values() {
assert_eq!(round_away_float_noise(1. / 3.), 1. / 3.);
assert_eq!(round_away_float_noise(0.2394023940209349), 0.2394023940209349);
assert_eq!(round_away_float_noise(0.25), 0.25);
assert_eq!(round_away_float_noise(-17.5), -17.5);
}
#[test]
fn round_away_float_noise_keeps_deliberate_values_with_zero_runs() {
assert_eq!(round_away_float_noise(0.30000005), 0.30000005);
assert_eq!(round_away_float_noise(0.3000000000001), 0.3000000000001);
assert_eq!(round_away_float_noise(1.00000001), 1.00000001);
assert_eq!(round_away_float_noise(2.9999993), 2.9999993);
}
#[test]
fn round_away_float_noise_normalizes_zero() {
let result = round_away_float_noise(-0.);
assert_eq!(result, 0.);
assert!(result.is_sign_positive());
}
#[test]
fn format_rounded_trims_trailing_zeros_when_exact() {
assert_eq!(format_rounded(0.25, 2), "0.25");
assert_eq!(format_rounded(3.1, 2), "3.1");
assert_eq!(format_rounded(45., 2), "45");
}
#[test]
fn format_rounded_keeps_decimal_places_when_truncated() {
assert_eq!(format_rounded(0.0003, 2), "0.00");
assert_eq!(format_rounded(-0.0003, 2), "-0.00");
assert_eq!(format_rounded(0.0003, 3), "0.000");
assert_eq!(format_rounded(3.10001, 2), "3.10");
assert_eq!(format_rounded(45.001, 2), "45.00");
assert_eq!(format_rounded(std::f64::consts::PI, 2), "3.14");
}
#[test]
fn format_rounded_denoises_before_judging_exactness() {
assert_eq!(format_rounded(29.999999999999996, 2), "30");
assert_eq!(format_rounded(45.00000000000001, 2), "45");
}
#[test]
fn format_rounded_shows_true_and_noise_zeros_plainly() {
assert_eq!(format_rounded(0., 2), "0");
assert_eq!(format_rounded(-0., 2), "0");
assert_eq!(format_rounded(1e-15, 2), "0");
assert_eq!(format_rounded(-1e-15, 2), "0");
}
#[test]
fn format_rounded_keeps_tiny_values_at_displayable_precision() {
assert_eq!(format_rounded(5e-13, 20), "0.0000000000005");
assert_eq!(format_rounded(-5e-13, 20), "-0.0000000000005");
assert_eq!(format_rounded(0., 20), "0");
assert_eq!(format_rounded(-0., 20), "0");
}
}
@@ -14,6 +14,7 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
use glam::DAffine2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::NodeInputDecleration;
use graphene_std::subpath::{calculate_growth_factor, spiral_point};
use graphene_std::vector::misc::SpiralType;
use std::collections::VecDeque;
@@ -139,11 +140,12 @@ impl Spiral {
return;
};
let Some(parameters) = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(graphene_std::vector::generator_nodes::spiral::IDENTIFIER) else {
let Some(node_inputs) = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::spiral::IDENTIFIER))
else {
return;
};
let Some(&TaggedValue::SpiralType(spiral_type)) = parameters.value(SpiralTypeInput) else {
let Some(&TaggedValue::SpiralType(spiral_type)) = node_inputs.get(SpiralTypeInput::INDEX).unwrap().as_value() else {
return;
};
@@ -155,7 +157,7 @@ impl Spiral {
responses.add(window_aligned_transform_set(document, layer, viewport_drag_start, DVec2::ONE));
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, OuterRadiusInput),
input_connector: InputConnector::node(node_id, OuterRadiusInput::INDEX),
input: NodeInput::value(TaggedValue::F64(new_radius), false),
});
}
@@ -165,7 +167,8 @@ impl Spiral {
pub fn update_turns(decrease: bool, layer: LayerNodeIdentifier, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
use graphene_std::vector::generator_nodes::spiral::*;
let Some(parameters) = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(graphene_std::vector::generator_nodes::spiral::IDENTIFIER) else {
let Some(node_inputs) = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::spiral::IDENTIFIER))
else {
return;
};
@@ -173,7 +176,7 @@ impl Spiral {
return;
};
let Some(&TaggedValue::F64(mut turns)) = parameters.value(TurnsInput) else {
let Some(&TaggedValue::F64(mut turns)) = node_inputs.get(TurnsInput::INDEX).unwrap().as_value() else {
return;
};
@@ -188,7 +191,7 @@ impl Spiral {
});
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, TurnsInput),
input_connector: InputConnector::node(node_id, TurnsInput::INDEX),
input: NodeInput::value(TaggedValue::F64(turns), false),
});
}
@@ -152,12 +152,12 @@ impl Star {
};
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::star::Radius1Input),
input_connector: InputConnector::node(node_id, 2),
input: NodeInput::value(TaggedValue::F64(radius), false),
});
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::star::Radius2Input),
input_connector: InputConnector::node(node_id, 3),
input: NodeInput::value(TaggedValue::F64(radius / 2.), false),
});
@@ -3,6 +3,7 @@ use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::color_selector::{DrawingToolState, apply_line_weight};
use crate::messages::tool::common_functionality::graph_modification_utils;
use graph_craft::document::value::TaggedValue;
use graphene_std::NodeInputDecleration;
use graphene_std::choice_type::ChoiceTypeStatic;
use graphene_std::vector::style::{PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
@@ -64,9 +65,7 @@ where
if has_dash {
rows.push(LayoutGroup::row(dash_offset_row(drawing.dash_offset, to_message.clone())));
}
// An inapplicable order (no Fill/Stroke pair to reorder) grays out and highlights no entry, since the synced value is only a fallback
let paint_order = drawing.paint_order.filter(|_| drawing.paint_order_applicable);
rows.push(LayoutGroup::row(enum_radio_row::<PaintOrder, _>("Order", paint_order, !drawing.paint_order_applicable, {
rows.push(LayoutGroup::row(enum_radio_row::<PaintOrder, _>("Order", drawing.paint_order, false, {
let to_message = to_message.clone();
move |value| to_message(StrokeOptionsUpdate::PaintOrder(value))
})));
@@ -125,9 +124,19 @@ where
E: ChoiceTypeStatic + 'static,
F: Fn(E) -> Message + 'static + Send + Sync + Clone,
{
let entries = RadioEntryData::list_from_choice_type(to_message)
.into_iter()
.map(|entry| entry.on_commit(|_| DocumentMessage::StartTransaction.into()))
let entries = E::list()
.iter()
.flat_map(|section| section.iter())
.map(|(value, meta)| {
let to_message = to_message.clone();
let value = *value;
let entry = RadioEntryData::new(meta.name)
.tooltip_label(meta.label)
.tooltip_description(meta.description.unwrap_or_default())
.on_update(move |_| to_message(value))
.on_commit(|_| DocumentMessage::StartTransaction.into());
if let Some(icon) = meta.icon { entry.icon(icon) } else { entry.label(meta.label) }
})
.collect();
vec![
TextLabel::new(label_text).table_align(true).widget_instance(),
@@ -180,40 +189,39 @@ where
pub fn apply_stroke_align(drawing: &mut DrawingToolState, align: StrokeAlign, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
drawing.stroke_align = Some(align);
graph_modification_utils::set_parameter_for_selected_layers(document, graphene_std::vector::stroke::AlignInput, TaggedValue::StrokeAlign(align), responses);
set_stroke_input_for_selected(document, graphene_std::vector::stroke::AlignInput::INDEX, TaggedValue::StrokeAlign(align), responses);
}
pub fn apply_stroke_cap(drawing: &mut DrawingToolState, cap: StrokeCap, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
drawing.stroke_cap = Some(cap);
graph_modification_utils::set_parameter_for_selected_layers(document, graphene_std::vector::stroke::CapInput, TaggedValue::StrokeCap(cap), responses);
set_stroke_input_for_selected(document, graphene_std::vector::stroke::CapInput::INDEX, TaggedValue::StrokeCap(cap), responses);
}
pub fn apply_stroke_join(drawing: &mut DrawingToolState, join: StrokeJoin, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
drawing.stroke_join = Some(join);
graph_modification_utils::set_parameter_for_selected_layers(document, graphene_std::vector::stroke::JoinInput, TaggedValue::StrokeJoin(join), responses);
set_stroke_input_for_selected(document, graphene_std::vector::stroke::JoinInput::INDEX, TaggedValue::StrokeJoin(join), responses);
}
pub fn apply_miter_limit(drawing: &mut DrawingToolState, limit: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
drawing.miter_limit = Some(limit);
graph_modification_utils::set_parameter_for_selected_layers(document, graphene_std::vector::stroke::MiterLimitInput, TaggedValue::F64(limit), responses);
set_stroke_input_for_selected(document, graphene_std::vector::stroke::MiterLimitInput::INDEX, TaggedValue::F64(limit), responses);
}
pub fn apply_paint_order(drawing: &mut DrawingToolState, order: PaintOrder, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
drawing.paint_order = Some(order);
// A mixed selection only grays the radio out when no layer can take the swap, so skip the ones that can't
for layer in graph_modification_utils::paintable_selected_layers(document) {
if graph_modification_utils::stroke_paint_order_applicable(layer, &document.network_interface) {
responses.add(GraphOperationMessage::StrokeOrderSet { layer, paint_order: order });
}
}
set_stroke_input_for_selected(document, graphene_std::vector::stroke::PaintOrderInput::INDEX, TaggedValue::PaintOrder(order), responses);
}
pub fn apply_dash_lengths(drawing: &mut DrawingToolState, lengths: Vec<f64>, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
drawing.dash_lengths = Some(lengths.clone());
graph_modification_utils::set_parameter_for_selected_layers(document, graphene_std::vector::stroke::DashPatternInput, TaggedValue::DashPattern(lengths), responses);
set_stroke_input_for_selected(document, graphene_std::vector::stroke::DashLengthsInput::INDEX, TaggedValue::F64Array(lengths), responses);
}
pub fn apply_dash_offset(drawing: &mut DrawingToolState, offset: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
drawing.dash_offset = Some(offset);
graph_modification_utils::set_parameter_for_selected_layers(document, graphene_std::vector::stroke::DashOffsetInput, TaggedValue::F64(offset), responses);
set_stroke_input_for_selected(document, graphene_std::vector::stroke::DashOffsetInput::INDEX, TaggedValue::F64(offset), responses);
}
fn set_stroke_input_for_selected(document: &DocumentMessageHandler, input_index: usize, value: TaggedValue, responses: &mut VecDeque<Message>) {
graph_modification_utils::set_proto_node_input_for_selected_layers(document, graphene_std::vector::stroke::IDENTIFIER, input_index, value, responses);
}
@@ -11,7 +11,9 @@ use crate::messages::tool::common_functionality::transformation_cage::SelectedEd
use crate::messages::tool::tool_messages::path_tool::PathOverlayMode;
use crate::messages::tool::utility_types::ToolType;
use glam::{DAffine2, DVec2};
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graphene_std::list::List;
use graphene_std::renderer::Quad;
use graphene_std::subpath::{Bezier, BezierHandles};
use graphene_std::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table;
@@ -566,11 +568,11 @@ pub fn make_path_editable_is_allowed(network_interface: &mut NodeNetworkInterfac
}
for _ in selected_layers {}
// Must be a vector layer, at either rank
// Must be a layer of type List<Vector>
let node_id = NodeGraphLayer::new(first_layer, network_interface).horizontal_layer_flow().nth(1)?;
let output_type = network_interface.output_type(&OutputConnector::primary_output(node_id), &[]);
if output_type.compiled_element_name().as_deref() != Some("Vector") {
let output_type = network_interface.output_type(&OutputConnector::node(node_id, 0), &[]);
if output_type.compiled_nested_type() != Some(&concrete!(List<Vector>)) {
return None;
}
@@ -574,15 +574,22 @@ mod test_artboard {
use graphene_std::Artboard;
use graphene_std::list::List;
/// A leveled wire introspects as its whole legacy list, so each `extend`
/// occurrence yields one list rather than one element.
async fn get_artboards(editor: &mut EditorTestUtils) -> List<Artboard> {
let instrumented = match editor.eval_graph().await {
Ok(instrumented) => instrumented,
Err(e) => panic!("Failed to evaluate graph: {e}"),
};
instrumented
.grab_all_input::<graphene_std::graphic::extend::NewInput, List<Artboard>>(&editor.runtime)
.flatten()
.collect()
let mut artboards = List::new();
for list in instrumented.grab_all_input_level::<graphene_std::graphic::extend::NewInput<Artboard>, Artboard>(&editor.runtime) {
for index in 0..list.len() {
if let Some(item) = list.clone_item(index) {
artboards.push(item);
}
}
}
artboards
}
#[derive(Debug, PartialEq)]
@@ -9,9 +9,8 @@ use graph_craft::document::NodeId;
use graph_craft::document::value::TaggedValue;
use graphene_std::Color;
use graphene_std::brush::brush_stroke::{BrushInputSample, BrushStroke, BrushStyle};
use graphene_std::color::SRGBA8;
use graphene_std::raster::BlendMode;
use graphene_std::vector::style::FillChoice;
use graphene_std::vector::style::{FillChoice, FillChoiceUI};
const BRUSH_MAX_SIZE: f64 = 5000.;
@@ -105,7 +104,7 @@ impl ToolMetadata for BrushTool {
impl LayoutHolder for BrushTool {
fn layout(&self) -> Layout {
let mut widgets = vec![
ColorInput::new(FillChoice::<SRGBA8>::from(self.options.color.fill_choice.as_ref().unwrap_or(&FillChoice::None)))
ColorInput::new(FillChoiceUI::from(self.options.color.fill_choice.as_ref().unwrap_or(&FillChoice::None)))
.mixed(self.options.color.fill_choice.is_none())
.narrow(true)
.on_update(|color: &ColorInput| {
@@ -1,14 +1,10 @@
use super::tool_prelude::*;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
use crate::messages::tool::common_functionality::color_selector::solid;
use crate::messages::tool::common_functionality::graph_modification_utils::{NodeGraphLayer, get_upstream_color_value_node_id, gradient_chain_target_input, replaceable_paint_chain};
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
use graphene_std::color::SRGBA8;
use graphene_std::raster::color::Color;
use graphene_std::subpath::Subpath;
use graphene_std::vector::PointId;
use graphene_std::vector::style::FillChoice;
use graphene_std::vector::style::FillChoiceUI;
#[derive(Default, ExtractField)]
pub struct FillTool {
@@ -48,7 +44,7 @@ impl ToolMetadata for FillTool {
impl LayoutHolder for FillTool {
fn layout(&self) -> Layout {
let widgets = vec![
ColorInput::new(FillChoice::<SRGBA8>::from(&solid(self.primary_color)))
ColorInput::new(FillChoiceUI::from(&solid(self.primary_color)))
.narrow(true)
.on_update(|color: &ColorInput| {
FillToolMessage::SetColor {
@@ -144,16 +140,10 @@ impl Fsm for FillToolFsmState {
let use_secondary = input.keyboard.get(Key::Shift as usize);
let preview_color = if use_secondary { global_tool_data.secondary_color } else { global_tool_data.primary_color };
// Pattern the layer the fill would land on, over its whole expanse when the color is its entire content
if let Some(layer) = fill_target_layer(document, input, viewport) {
// Get the layer the user is hovering over
if let Some(layer) = document.click(input, viewport) {
let color_hex = SRGBA8::from(preview_color).to_css_hex();
if paints_whole_expanse(layer, &document.network_interface) {
let expanse = whole_expanse_rect(layer, document, overlay_context.viewport.size().into_dvec2());
overlay_context.fill_path_pattern(std::iter::once(expanse), DAffine2::IDENTITY, &color_hex);
} else {
overlay_context.fill_path_pattern(document.metadata().layer_outline(layer), document.metadata().transform_to_viewport(layer), &color_hex);
}
overlay_context.fill_path_pattern(document.metadata().layer_outline(layer), document.metadata().transform_to_viewport(layer), &color_hex);
}
self
@@ -164,11 +154,9 @@ impl Fsm for FillToolFsmState {
self
}
(FillToolFsmState::Ready, color_event) => {
let Some(layer_identifier) = fill_target_layer(document, input, viewport) else { return self };
// A whole-expanse color chain (existing, or newly started on a blank layer) routes to its 'Color Value' node; geometry gets its Fill set
let route_to_color_chain = routes_to_color_chain(layer_identifier, &document.network_interface);
let Some(layer_identifier) = document.click(input, viewport) else {
return self;
};
// If the layer is a raster layer, don't fill it, wait till the flood fill tool is implemented
if NodeGraphLayer::is_raster_layer(layer_identifier, &mut document.network_interface) {
return self;
@@ -180,14 +168,10 @@ impl Fsm for FillToolFsmState {
};
responses.add(DocumentMessage::AddTransaction);
if route_to_color_chain {
responses.add(GraphOperationMessage::ColorValueSet { layer: layer_identifier, color });
} else {
responses.add(GraphOperationMessage::FillColorSet {
layer: layer_identifier,
color: Some(color),
});
}
responses.add(GraphOperationMessage::FillColorSet {
layer: layer_identifier,
color: Some(color),
});
FillToolFsmState::Filling
}
@@ -218,58 +202,24 @@ impl Fsm for FillToolFsmState {
}
}
/// Whether the fill lands on the layer's 'Color Value' node rather than on geometry's Fill, which includes taking over
/// a layer the Gradient tool painted, since a whole-expanse gradient gives way to a solid color.
fn routes_to_color_chain(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> bool {
get_upstream_color_value_node_id(layer, network_interface).is_some() || replaceable_paint_chain(layer, network_interface).is_some()
}
/// The layer the fill acts on: the one under the cursor, or else a selected layer painted through a color chain,
/// since blank layers and whole-expanse colors render no clickable geometry.
fn fill_target_layer(document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, viewport: &ViewportMessageHandler) -> Option<LayerNodeIdentifier> {
document.click(input, viewport).or_else(|| {
document
.network_interface
.selected_nodes()
.selected_visible_layers(&document.network_interface)
.find(|&layer| routes_to_color_chain(layer, &document.network_interface))
})
}
/// Whether the color is the layer's whole content rather than paint applied to its geometry, meaning there is no
/// outline to pattern and the preview covers the layer's whole expanse instead.
fn paints_whole_expanse(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> bool {
gradient_chain_target_input(layer, network_interface) == InputConnector::layer_secondary_input(layer.to_node()) && routes_to_color_chain(layer, network_interface)
}
/// The viewport-space area a whole-expanse color paints: the artboard containing the layer, since the color fills it,
/// or else the visible viewport for a layer living outside any artboard.
fn whole_expanse_rect(layer: LayerNodeIdentifier, document: &DocumentMessageHandler, viewport_size: DVec2) -> Subpath<PointId> {
let containing_artboard = layer
.ancestors(document.metadata())
.find(|&ancestor| ancestor != LayerNodeIdentifier::ROOT_PARENT && document.network_interface.is_artboard(&ancestor.to_node(), &[]));
match containing_artboard.and_then(|artboard| document.metadata().bounding_box_viewport(artboard)) {
Some([min, max]) => Subpath::new_rectangle(min, max),
None => Subpath::new_rectangle(DVec2::ZERO, viewport_size),
}
}
#[cfg(test)]
mod test_fill {
pub use crate::test_utils::test_prelude::*;
use graphene_std::color::SRGBA8;
use graphene_std::list::Item;
use graphene_std::vector::fill;
// The Fill tool writes solid colors, whose stored values the input monitor records as `Item<Color>` wires
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Item<Color>> {
/// Paint inputs are single-typed now, so the monitored wire carries the
/// colors themselves and the `Graphic` conversion sits downstream of it.
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Color> {
let instrumented = match editor.eval_graph().await {
Ok(instrumented) => instrumented,
Err(e) => panic!("Failed to evaluate graph: {e}"),
};
instrumented.grab_all_input::<fill::PaintInput, Item<Color>>(&editor.runtime).collect()
instrumented
.grab_all_input_level::<fill::FillInput, Color>(&editor.runtime)
.flat_map(|list| list.iter_element_values().cloned().collect::<Vec<_>>())
.collect()
}
#[tokio::test]
@@ -299,8 +249,7 @@ mod test_fill {
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
let fills = get_fills(&mut editor).await;
assert_eq!(fills.len(), 1);
let color = fills.first().unwrap().element();
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::GREEN));
assert_eq!(SRGBA8::from(fills[0]), SRGBA8::from(Color::GREEN));
}
#[tokio::test]
@@ -312,305 +261,6 @@ mod test_fill {
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::SHIFT).await;
let fills = get_fills(&mut editor).await;
assert_eq!(fills.len(), 1);
let color = fills.first().unwrap().element();
assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::YELLOW));
}
#[tokio::test]
async fn blank_layer_gets_whole_expanse_color() {
use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_color_value_node_id;
use graph_craft::document::NodeId;
use graph_craft::document::value::TaggedValue;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor
.handle_message(GraphOperationMessage::NewCustomLayer {
id: NodeId::new(),
nodes: Vec::new(),
parent: LayerNodeIdentifier::ROOT_PARENT,
insert_index: 0,
})
.await;
let layer = editor.active_document().metadata().all_layers().next().unwrap();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
editor.select_primary_color(Color::GREEN).await;
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
let document = editor.active_document();
let color_value_id = get_upstream_color_value_node_id(layer, &document.network_interface).expect("the fill should start a Color Value chain");
let color_input = document
.network_interface
.document_network()
.nodes
.get(&color_value_id)
.and_then(|node| node.input(graphene_std::math_nodes::color_value::ColorInput))
.and_then(|input| input.as_value());
assert!(matches!(color_input, Some(TaggedValue::Color(color)) if *color == Color::GREEN));
}
#[tokio::test]
async fn replaces_a_whole_expanse_gradient_with_a_solid_color() {
use crate::messages::tool::common_functionality::graph_modification_utils::{get_upstream_color_value_node_id, get_upstream_gradient_value_node_id};
use graph_craft::document::NodeId;
use graph_craft::document::value::TaggedValue;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor
.handle_message(GraphOperationMessage::NewCustomLayer {
id: NodeId::new(),
nodes: Vec::new(),
parent: LayerNodeIdentifier::ROOT_PARENT,
insert_index: 0,
})
.await;
let layer = editor.active_document().metadata().all_layers().next().unwrap();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
// Paint the layer's whole expanse with a gradient, which the Fill tool then takes over
editor.drag_tool(ToolType::Gradient, 0., 0., 100., 0., ModifierKeys::empty()).await;
assert!(get_upstream_gradient_value_node_id(layer, &editor.active_document().network_interface).is_some());
editor.select_primary_color(Color::GREEN).await;
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
let document = editor.active_document();
let color_value_id = get_upstream_color_value_node_id(layer, &document.network_interface).expect("the fill should start a Color Value chain");
let color_input = document
.network_interface
.document_network()
.nodes
.get(&color_value_id)
.and_then(|node| node.input(graphene_std::math_nodes::color_value::ColorInput))
.and_then(|input| input.as_value());
assert!(matches!(color_input, Some(TaggedValue::Color(color)) if *color == Color::GREEN));
// The replaced gradient nodes are gone from the graph rather than left orphaned
let gradient_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_value::IDENTIFIER);
let leftover_gradient_nodes = document
.network_interface
.document_network()
.nodes
.keys()
.filter(|node_id| document.network_interface.reference(node_id, &[]).as_ref() == Some(&gradient_reference))
.count();
assert_eq!(leftover_gradient_nodes, 0, "the gradient it replaced should be deleted");
}
#[tokio::test]
async fn replacing_a_shared_gradient_leaves_it_for_its_other_layer() {
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use crate::messages::tool::common_functionality::graph_modification_utils::{get_upstream_color_value_node_id, get_upstream_gradient_value_node_id};
use graph_craft::document::NodeId;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let painted_id = NodeId::new();
let sharing_id = NodeId::new();
for id in [painted_id, sharing_id] {
editor
.handle_message(GraphOperationMessage::NewCustomLayer {
id,
nodes: Vec::new(),
parent: LayerNodeIdentifier::ROOT_PARENT,
insert_index: 0,
})
.await;
}
let (painted, sharing) = (LayerNodeIdentifier::new_unchecked(painted_id), LayerNodeIdentifier::new_unchecked(sharing_id));
// Give one layer a whole-expanse gradient, then wire that same 'Gradient Value' node into the other layer
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![painted_id] }).await;
editor.drag_tool(ToolType::Gradient, 0., 0., 100., 0., ModifierKeys::empty()).await;
let gradient_value_id = get_upstream_gradient_value_node_id(painted, &editor.active_document().network_interface).expect("the drag should start a gradient chain");
editor
.active_document_mut()
.network_interface
.create_wire(&OutputConnector::primary_output(gradient_value_id), &InputConnector::layer_secondary_input(sharing_id), &[]);
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![painted_id] }).await;
editor.select_primary_color(Color::GREEN).await;
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
let document = editor.active_document();
assert!(
get_upstream_color_value_node_id(painted, &document.network_interface).is_some(),
"the filled layer should get its own Color Value chain"
);
assert!(
document.network_interface.document_network().nodes.contains_key(&gradient_value_id),
"a gradient the rest of the graph still draws from must not be deleted"
);
assert_eq!(
get_upstream_gradient_value_node_id(sharing, &document.network_interface),
Some(gradient_value_id),
"the other layer should keep its gradient"
);
}
#[tokio::test]
async fn replacing_a_gradient_shared_through_a_transform_leaves_the_other_layer_alone() {
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use crate::messages::tool::common_functionality::graph_modification_utils::{get_fill_node_id_with_direct_fill_input, get_upstream_color_value_node_id, get_upstream_gradient_value_node_id};
use graph_craft::document::NodeId;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// An ellipse layer whose Fill is painted by the same chain that fills the blank layer's whole expanse
editor.drag_tool(ToolType::Ellipse, 0., 0., 100., 100., ModifierKeys::empty()).await;
let ellipse = editor.active_document().metadata().all_layers().next().unwrap();
let painted_id = NodeId::new();
editor
.handle_message(GraphOperationMessage::NewCustomLayer {
id: painted_id,
nodes: Vec::new(),
parent: LayerNodeIdentifier::ROOT_PARENT,
insert_index: 0,
})
.await;
let painted = LayerNodeIdentifier::new_unchecked(painted_id);
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![painted_id] }).await;
// Nudging leaves a 'Transform' node, and the gradient drag paints through it
editor
.handle_message(DocumentMessage::NudgeSelectedLayers {
delta_x: 10.,
delta_y: 0.,
resize: Key::Shift,
resize_opposite: Key::Alt,
})
.await;
editor.drag_tool(ToolType::Gradient, 0., 0., 100., 0., ModifierKeys::empty()).await;
let gradient_value_id = get_upstream_gradient_value_node_id(painted, &editor.active_document().network_interface).expect("the drag should start a gradient chain");
let shared_transform_id = editor
.active_document()
.network_interface
.upstream_output_connector(&InputConnector::layer_secondary_input(painted_id), &[])
.and_then(|output| output.node_id())
.expect("the nudge should leave a Transform node feeding the layer");
// Branch that same Transform into the ellipse's Fill, so both layers draw from it
let ellipse_fill_id = get_fill_node_id_with_direct_fill_input(ellipse, &editor.active_document().network_interface).expect("the ellipse should have a Fill node");
editor.active_document_mut().network_interface.create_wire(
&OutputConnector::primary_output(shared_transform_id),
&InputConnector::node(ellipse_fill_id, graphene_std::vector::fill::PaintInput),
&[],
);
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![painted_id] }).await;
editor.select_primary_color(Color::GREEN).await;
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
let document = editor.active_document();
assert!(
get_upstream_color_value_node_id(painted, &document.network_interface).is_some(),
"the filled layer should get its own Color Value chain"
);
assert!(
document.network_interface.document_network().nodes.contains_key(&gradient_value_id),
"the gradient still painting the ellipse must not be deleted"
);
assert_eq!(
document
.network_interface
.upstream_output_connector(&InputConnector::node(ellipse_fill_id, graphene_std::vector::fill::PaintInput), &[])
.and_then(|output| output.node_id()),
Some(shared_transform_id),
"the ellipse should keep being painted by the shared chain"
);
assert_eq!(
get_upstream_gradient_value_node_id(ellipse, &document.network_interface),
Some(gradient_value_id),
"the ellipse's fill should still resolve to the gradient"
);
}
#[tokio::test]
async fn nudged_blank_layer_keeps_its_transform() {
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_color_value_node_id;
use graph_craft::document::NodeId;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor
.handle_message(GraphOperationMessage::NewCustomLayer {
id: NodeId::new(),
nodes: Vec::new(),
parent: LayerNodeIdentifier::ROOT_PARENT,
insert_index: 0,
})
.await;
let layer = editor.active_document().metadata().all_layers().next().unwrap();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
// Nudging an empty layer leaves a 'Transform' node in its chain, even though the layer still paints nothing
editor
.handle_message(DocumentMessage::NudgeSelectedLayers {
delta_x: 10.,
delta_y: 0.,
resize: Key::Shift,
resize_opposite: Key::Alt,
})
.await;
let layer_content_input = InputConnector::layer_secondary_input(layer.to_node());
let transform_id = editor
.active_document()
.network_interface
.upstream_output_connector(&layer_content_input, &[])
.and_then(|output| output.node_id())
.expect("the nudge should leave a Transform node feeding the layer");
editor.select_primary_color(Color::GREEN).await;
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
let network_interface = &editor.active_document().network_interface;
let color_value_id = get_upstream_color_value_node_id(layer, network_interface).expect("the fill should start a Color Value chain");
assert_eq!(
network_interface.upstream_output_connector(&layer_content_input, &[]).and_then(|output| output.node_id()),
Some(transform_id),
"the Transform node should still feed the layer"
);
assert_eq!(
network_interface
.upstream_output_connector(&InputConnector::primary_input(transform_id), &[])
.and_then(|output| output.node_id()),
Some(color_value_id),
"the color should be painted through the preserved Transform node"
);
}
#[tokio::test]
async fn node_displayed_as_layer_gets_no_color_chain() {
use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_color_value_node_id;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// A generator node displayed as a layer looks empty from the outside, but its secondary input is a parameter of its own
let rectangle = editor
.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER))
.await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_to_node_or_layer(&rectangle, &[], true);
let layer = LayerNodeIdentifier::new(rectangle, network_interface);
network_interface.move_layer_to_stack(layer, LayerNodeIdentifier::ROOT_PARENT, 0, &[]);
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![rectangle] }).await;
assert!(editor.active_document().metadata().all_layers().any(|other| other == layer), "the node should sit in the layer stack");
editor.select_primary_color(Color::GREEN).await;
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
let document = editor.active_document();
assert!(
get_upstream_color_value_node_id(layer, &document.network_interface).is_none(),
"only a 'Merge' layer may have a whole-expanse color chain started on it"
);
assert_eq!(SRGBA8::from(fills[0]), SRGBA8::from(Color::YELLOW));
}
}
Loaded 100 of 315 files, more files were not shown because too many files have changed in this diff. Show more